]> git.proxmox.com Git - ceph.git/blob - ceph/src/s3select/rapidjson/thirdparty/gtest/googlemock/include/gmock/gmock-matchers.h
bump version to 19.2.0-pve1
[ceph.git] / ceph / src / s3select / rapidjson / thirdparty / gtest / googlemock / include / gmock / gmock-matchers.h
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 // Author: wan@google.com (Zhanyong Wan)
31
32 // Google Mock - a framework for writing C++ mock classes.
33 //
34 // This file implements some commonly used argument matchers. More
35 // matchers can be defined by the user implementing the
36 // MatcherInterface<T> interface if necessary.
37
38 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
39 #define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
40
41 #include <math.h>
42 #include <algorithm>
43 #include <iterator>
44 #include <limits>
45 #include <ostream> // NOLINT
46 #include <sstream>
47 #include <string>
48 #include <utility>
49 #include <vector>
50 #include "gtest/gtest.h"
51 #include "gmock/internal/gmock-internal-utils.h"
52 #include "gmock/internal/gmock-port.h"
53
54 #if GTEST_HAS_STD_INITIALIZER_LIST_
55 # include <initializer_list> // NOLINT -- must be after gtest.h
56 #endif
57
58 namespace testing {
59
60 // To implement a matcher Foo for type T, define:
61 // 1. a class FooMatcherImpl that implements the
62 // MatcherInterface<T> interface, and
63 // 2. a factory function that creates a Matcher<T> object from a
64 // FooMatcherImpl*.
65 //
66 // The two-level delegation design makes it possible to allow a user
67 // to write "v" instead of "Eq(v)" where a Matcher is expected, which
68 // is impossible if we pass matchers by pointers. It also eases
69 // ownership management as Matcher objects can now be copied like
70 // plain values.
71
72 // MatchResultListener is an abstract class. Its << operator can be
73 // used by a matcher to explain why a value matches or doesn't match.
74 //
75 // TODO(wan@google.com): add method
76 // bool InterestedInWhy(bool result) const;
77 // to indicate whether the listener is interested in why the match
78 // result is 'result'.
79 class MatchResultListener {
80 public:
81 // Creates a listener object with the given underlying ostream. The
82 // listener does not own the ostream, and does not dereference it
83 // in the constructor or destructor.
84 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
85 virtual ~MatchResultListener() = 0; // Makes this class abstract.
86
87 // Streams x to the underlying ostream; does nothing if the ostream
88 // is NULL.
89 template <typename T>
90 MatchResultListener& operator<<(const T& x) {
91 if (stream_ != NULL)
92 *stream_ << x;
93 return *this;
94 }
95
96 // Returns the underlying ostream.
97 ::std::ostream* stream() { return stream_; }
98
99 // Returns true iff the listener is interested in an explanation of
100 // the match result. A matcher's MatchAndExplain() method can use
101 // this information to avoid generating the explanation when no one
102 // intends to hear it.
103 bool IsInterested() const { return stream_ != NULL; }
104
105 private:
106 ::std::ostream* const stream_;
107
108 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
109 };
110
111 inline MatchResultListener::~MatchResultListener() {
112 }
113
114 // An instance of a subclass of this knows how to describe itself as a
115 // matcher.
116 class MatcherDescriberInterface {
117 public:
118 virtual ~MatcherDescriberInterface() {}
119
120 // Describes this matcher to an ostream. The function should print
121 // a verb phrase that describes the property a value matching this
122 // matcher should have. The subject of the verb phrase is the value
123 // being matched. For example, the DescribeTo() method of the Gt(7)
124 // matcher prints "is greater than 7".
125 virtual void DescribeTo(::std::ostream* os) const = 0;
126
127 // Describes the negation of this matcher to an ostream. For
128 // example, if the description of this matcher is "is greater than
129 // 7", the negated description could be "is not greater than 7".
130 // You are not required to override this when implementing
131 // MatcherInterface, but it is highly advised so that your matcher
132 // can produce good error messages.
133 virtual void DescribeNegationTo(::std::ostream* os) const {
134 *os << "not (";
135 DescribeTo(os);
136 *os << ")";
137 }
138 };
139
140 // The implementation of a matcher.
141 template <typename T>
142 class MatcherInterface : public MatcherDescriberInterface {
143 public:
144 // Returns true iff the matcher matches x; also explains the match
145 // result to 'listener' if necessary (see the next paragraph), in
146 // the form of a non-restrictive relative clause ("which ...",
147 // "whose ...", etc) that describes x. For example, the
148 // MatchAndExplain() method of the Pointee(...) matcher should
149 // generate an explanation like "which points to ...".
150 //
151 // Implementations of MatchAndExplain() should add an explanation of
152 // the match result *if and only if* they can provide additional
153 // information that's not already present (or not obvious) in the
154 // print-out of x and the matcher's description. Whether the match
155 // succeeds is not a factor in deciding whether an explanation is
156 // needed, as sometimes the caller needs to print a failure message
157 // when the match succeeds (e.g. when the matcher is used inside
158 // Not()).
159 //
160 // For example, a "has at least 10 elements" matcher should explain
161 // what the actual element count is, regardless of the match result,
162 // as it is useful information to the reader; on the other hand, an
163 // "is empty" matcher probably only needs to explain what the actual
164 // size is when the match fails, as it's redundant to say that the
165 // size is 0 when the value is already known to be empty.
166 //
167 // You should override this method when defining a new matcher.
168 //
169 // It's the responsibility of the caller (Google Mock) to guarantee
170 // that 'listener' is not NULL. This helps to simplify a matcher's
171 // implementation when it doesn't care about the performance, as it
172 // can talk to 'listener' without checking its validity first.
173 // However, in order to implement dummy listeners efficiently,
174 // listener->stream() may be NULL.
175 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
176
177 // Inherits these methods from MatcherDescriberInterface:
178 // virtual void DescribeTo(::std::ostream* os) const = 0;
179 // virtual void DescribeNegationTo(::std::ostream* os) const;
180 };
181
182 namespace internal {
183
184 // Converts a MatcherInterface<T> to a MatcherInterface<const T&>.
185 template <typename T>
186 class MatcherInterfaceAdapter : public MatcherInterface<const T&> {
187 public:
188 explicit MatcherInterfaceAdapter(const MatcherInterface<T>* impl)
189 : impl_(impl) {}
190 virtual ~MatcherInterfaceAdapter() { delete impl_; }
191
192 virtual void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
193
194 virtual void DescribeNegationTo(::std::ostream* os) const {
195 impl_->DescribeNegationTo(os);
196 }
197
198 virtual bool MatchAndExplain(const T& x,
199 MatchResultListener* listener) const {
200 return impl_->MatchAndExplain(x, listener);
201 }
202
203 private:
204 const MatcherInterface<T>* const impl_;
205
206 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatcherInterfaceAdapter);
207 };
208
209 } // namespace internal
210
211 // A match result listener that stores the explanation in a string.
212 class StringMatchResultListener : public MatchResultListener {
213 public:
214 StringMatchResultListener() : MatchResultListener(&ss_) {}
215
216 // Returns the explanation accumulated so far.
217 std::string str() const { return ss_.str(); }
218
219 // Clears the explanation accumulated so far.
220 void Clear() { ss_.str(""); }
221
222 private:
223 ::std::stringstream ss_;
224
225 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
226 };
227
228 namespace internal {
229
230 struct AnyEq {
231 template <typename A, typename B>
232 bool operator()(const A& a, const B& b) const { return a == b; }
233 };
234 struct AnyNe {
235 template <typename A, typename B>
236 bool operator()(const A& a, const B& b) const { return a != b; }
237 };
238 struct AnyLt {
239 template <typename A, typename B>
240 bool operator()(const A& a, const B& b) const { return a < b; }
241 };
242 struct AnyGt {
243 template <typename A, typename B>
244 bool operator()(const A& a, const B& b) const { return a > b; }
245 };
246 struct AnyLe {
247 template <typename A, typename B>
248 bool operator()(const A& a, const B& b) const { return a <= b; }
249 };
250 struct AnyGe {
251 template <typename A, typename B>
252 bool operator()(const A& a, const B& b) const { return a >= b; }
253 };
254
255 // A match result listener that ignores the explanation.
256 class DummyMatchResultListener : public MatchResultListener {
257 public:
258 DummyMatchResultListener() : MatchResultListener(NULL) {}
259
260 private:
261 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
262 };
263
264 // A match result listener that forwards the explanation to a given
265 // ostream. The difference between this and MatchResultListener is
266 // that the former is concrete.
267 class StreamMatchResultListener : public MatchResultListener {
268 public:
269 explicit StreamMatchResultListener(::std::ostream* os)
270 : MatchResultListener(os) {}
271
272 private:
273 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
274 };
275
276 // An internal class for implementing Matcher<T>, which will derive
277 // from it. We put functionalities common to all Matcher<T>
278 // specializations here to avoid code duplication.
279 template <typename T>
280 class MatcherBase {
281 public:
282 // Returns true iff the matcher matches x; also explains the match
283 // result to 'listener'.
284 bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
285 MatchResultListener* listener) const {
286 return impl_->MatchAndExplain(x, listener);
287 }
288
289 // Returns true iff this matcher matches x.
290 bool Matches(GTEST_REFERENCE_TO_CONST_(T) x) const {
291 DummyMatchResultListener dummy;
292 return MatchAndExplain(x, &dummy);
293 }
294
295 // Describes this matcher to an ostream.
296 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
297
298 // Describes the negation of this matcher to an ostream.
299 void DescribeNegationTo(::std::ostream* os) const {
300 impl_->DescribeNegationTo(os);
301 }
302
303 // Explains why x matches, or doesn't match, the matcher.
304 void ExplainMatchResultTo(GTEST_REFERENCE_TO_CONST_(T) x,
305 ::std::ostream* os) const {
306 StreamMatchResultListener listener(os);
307 MatchAndExplain(x, &listener);
308 }
309
310 // Returns the describer for this matcher object; retains ownership
311 // of the describer, which is only guaranteed to be alive when
312 // this matcher object is alive.
313 const MatcherDescriberInterface* GetDescriber() const {
314 return impl_.get();
315 }
316
317 protected:
318 MatcherBase() {}
319
320 // Constructs a matcher from its implementation.
321 explicit MatcherBase(
322 const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)>* impl)
323 : impl_(impl) {}
324
325 template <typename U>
326 explicit MatcherBase(
327 const MatcherInterface<U>* impl,
328 typename internal::EnableIf<
329 !internal::IsSame<U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* =
330 NULL)
331 : impl_(new internal::MatcherInterfaceAdapter<U>(impl)) {}
332
333 virtual ~MatcherBase() {}
334
335 private:
336 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
337 // interfaces. The former dynamically allocates a chunk of memory
338 // to hold the reference count, while the latter tracks all
339 // references using a circular linked list without allocating
340 // memory. It has been observed that linked_ptr performs better in
341 // typical scenarios. However, shared_ptr can out-perform
342 // linked_ptr when there are many more uses of the copy constructor
343 // than the default constructor.
344 //
345 // If performance becomes a problem, we should see if using
346 // shared_ptr helps.
347 ::testing::internal::linked_ptr<
348 const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> >
349 impl_;
350 };
351
352 } // namespace internal
353
354 // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
355 // object that can check whether a value of type T matches. The
356 // implementation of Matcher<T> is just a linked_ptr to const
357 // MatcherInterface<T>, so copying is fairly cheap. Don't inherit
358 // from Matcher!
359 template <typename T>
360 class Matcher : public internal::MatcherBase<T> {
361 public:
362 // Constructs a null matcher. Needed for storing Matcher objects in STL
363 // containers. A default-constructed matcher is not yet initialized. You
364 // cannot use it until a valid value has been assigned to it.
365 explicit Matcher() {} // NOLINT
366
367 // Constructs a matcher from its implementation.
368 explicit Matcher(const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)>* impl)
369 : internal::MatcherBase<T>(impl) {}
370
371 template <typename U>
372 explicit Matcher(const MatcherInterface<U>* impl,
373 typename internal::EnableIf<!internal::IsSame<
374 U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* = NULL)
375 : internal::MatcherBase<T>(impl) {}
376
377 // Implicit constructor here allows people to write
378 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
379 Matcher(T value); // NOLINT
380 };
381
382 // The following two specializations allow the user to write str
383 // instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
384 // matcher is expected.
385 template <>
386 class GTEST_API_ Matcher<const std::string&>
387 : public internal::MatcherBase<const std::string&> {
388 public:
389 Matcher() {}
390
391 explicit Matcher(const MatcherInterface<const std::string&>* impl)
392 : internal::MatcherBase<const std::string&>(impl) {}
393
394 // Allows the user to write str instead of Eq(str) sometimes, where
395 // str is a std::string object.
396 Matcher(const std::string& s); // NOLINT
397
398 #if GTEST_HAS_GLOBAL_STRING
399 // Allows the user to write str instead of Eq(str) sometimes, where
400 // str is a ::string object.
401 Matcher(const ::string& s); // NOLINT
402 #endif // GTEST_HAS_GLOBAL_STRING
403
404 // Allows the user to write "foo" instead of Eq("foo") sometimes.
405 Matcher(const char* s); // NOLINT
406 };
407
408 template <>
409 class GTEST_API_ Matcher<std::string>
410 : public internal::MatcherBase<std::string> {
411 public:
412 Matcher() {}
413
414 explicit Matcher(const MatcherInterface<const std::string&>* impl)
415 : internal::MatcherBase<std::string>(impl) {}
416 explicit Matcher(const MatcherInterface<std::string>* impl)
417 : internal::MatcherBase<std::string>(impl) {}
418
419 // Allows the user to write str instead of Eq(str) sometimes, where
420 // str is a string object.
421 Matcher(const std::string& s); // NOLINT
422
423 #if GTEST_HAS_GLOBAL_STRING
424 // Allows the user to write str instead of Eq(str) sometimes, where
425 // str is a ::string object.
426 Matcher(const ::string& s); // NOLINT
427 #endif // GTEST_HAS_GLOBAL_STRING
428
429 // Allows the user to write "foo" instead of Eq("foo") sometimes.
430 Matcher(const char* s); // NOLINT
431 };
432
433 #if GTEST_HAS_GLOBAL_STRING
434 // The following two specializations allow the user to write str
435 // instead of Eq(str) and "foo" instead of Eq("foo") when a ::string
436 // matcher is expected.
437 template <>
438 class GTEST_API_ Matcher<const ::string&>
439 : public internal::MatcherBase<const ::string&> {
440 public:
441 Matcher() {}
442
443 explicit Matcher(const MatcherInterface<const ::string&>* impl)
444 : internal::MatcherBase<const ::string&>(impl) {}
445
446 // Allows the user to write str instead of Eq(str) sometimes, where
447 // str is a std::string object.
448 Matcher(const std::string& s); // NOLINT
449
450 // Allows the user to write str instead of Eq(str) sometimes, where
451 // str is a ::string object.
452 Matcher(const ::string& s); // NOLINT
453
454 // Allows the user to write "foo" instead of Eq("foo") sometimes.
455 Matcher(const char* s); // NOLINT
456 };
457
458 template <>
459 class GTEST_API_ Matcher< ::string>
460 : public internal::MatcherBase< ::string> {
461 public:
462 Matcher() {}
463
464 explicit Matcher(const MatcherInterface<const ::string&>* impl)
465 : internal::MatcherBase< ::string>(impl) {}
466 explicit Matcher(const MatcherInterface< ::string>* impl)
467 : internal::MatcherBase< ::string>(impl) {}
468
469 // Allows the user to write str instead of Eq(str) sometimes, where
470 // str is a std::string object.
471 Matcher(const std::string& s); // NOLINT
472
473 // Allows the user to write str instead of Eq(str) sometimes, where
474 // str is a ::string object.
475 Matcher(const ::string& s); // NOLINT
476
477 // Allows the user to write "foo" instead of Eq("foo") sometimes.
478 Matcher(const char* s); // NOLINT
479 };
480 #endif // GTEST_HAS_GLOBAL_STRING
481
482 #if GTEST_HAS_ABSL
483 // The following two specializations allow the user to write str
484 // instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
485 // matcher is expected.
486 template <>
487 class GTEST_API_ Matcher<const absl::string_view&>
488 : public internal::MatcherBase<const absl::string_view&> {
489 public:
490 Matcher() {}
491
492 explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
493 : internal::MatcherBase<const absl::string_view&>(impl) {}
494
495 // Allows the user to write str instead of Eq(str) sometimes, where
496 // str is a std::string object.
497 Matcher(const std::string& s); // NOLINT
498
499 #if GTEST_HAS_GLOBAL_STRING
500 // Allows the user to write str instead of Eq(str) sometimes, where
501 // str is a ::string object.
502 Matcher(const ::string& s); // NOLINT
503 #endif // GTEST_HAS_GLOBAL_STRING
504
505 // Allows the user to write "foo" instead of Eq("foo") sometimes.
506 Matcher(const char* s); // NOLINT
507
508 // Allows the user to pass absl::string_views directly.
509 Matcher(absl::string_view s); // NOLINT
510 };
511
512 template <>
513 class GTEST_API_ Matcher<absl::string_view>
514 : public internal::MatcherBase<absl::string_view> {
515 public:
516 Matcher() {}
517
518 explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
519 : internal::MatcherBase<absl::string_view>(impl) {}
520 explicit Matcher(const MatcherInterface<absl::string_view>* impl)
521 : internal::MatcherBase<absl::string_view>(impl) {}
522
523 // Allows the user to write str instead of Eq(str) sometimes, where
524 // str is a std::string object.
525 Matcher(const std::string& s); // NOLINT
526
527 #if GTEST_HAS_GLOBAL_STRING
528 // Allows the user to write str instead of Eq(str) sometimes, where
529 // str is a ::string object.
530 Matcher(const ::string& s); // NOLINT
531 #endif // GTEST_HAS_GLOBAL_STRING
532
533 // Allows the user to write "foo" instead of Eq("foo") sometimes.
534 Matcher(const char* s); // NOLINT
535
536 // Allows the user to pass absl::string_views directly.
537 Matcher(absl::string_view s); // NOLINT
538 };
539 #endif // GTEST_HAS_ABSL
540
541 // Prints a matcher in a human-readable format.
542 template <typename T>
543 std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
544 matcher.DescribeTo(&os);
545 return os;
546 }
547
548 // The PolymorphicMatcher class template makes it easy to implement a
549 // polymorphic matcher (i.e. a matcher that can match values of more
550 // than one type, e.g. Eq(n) and NotNull()).
551 //
552 // To define a polymorphic matcher, a user should provide an Impl
553 // class that has a DescribeTo() method and a DescribeNegationTo()
554 // method, and define a member function (or member function template)
555 //
556 // bool MatchAndExplain(const Value& value,
557 // MatchResultListener* listener) const;
558 //
559 // See the definition of NotNull() for a complete example.
560 template <class Impl>
561 class PolymorphicMatcher {
562 public:
563 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
564
565 // Returns a mutable reference to the underlying matcher
566 // implementation object.
567 Impl& mutable_impl() { return impl_; }
568
569 // Returns an immutable reference to the underlying matcher
570 // implementation object.
571 const Impl& impl() const { return impl_; }
572
573 template <typename T>
574 operator Matcher<T>() const {
575 return Matcher<T>(new MonomorphicImpl<GTEST_REFERENCE_TO_CONST_(T)>(impl_));
576 }
577
578 private:
579 template <typename T>
580 class MonomorphicImpl : public MatcherInterface<T> {
581 public:
582 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
583
584 virtual void DescribeTo(::std::ostream* os) const {
585 impl_.DescribeTo(os);
586 }
587
588 virtual void DescribeNegationTo(::std::ostream* os) const {
589 impl_.DescribeNegationTo(os);
590 }
591
592 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
593 return impl_.MatchAndExplain(x, listener);
594 }
595
596 private:
597 const Impl impl_;
598
599 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
600 };
601
602 Impl impl_;
603
604 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
605 };
606
607 // Creates a matcher from its implementation. This is easier to use
608 // than the Matcher<T> constructor as it doesn't require you to
609 // explicitly write the template argument, e.g.
610 //
611 // MakeMatcher(foo);
612 // vs
613 // Matcher<const string&>(foo);
614 template <typename T>
615 inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
616 return Matcher<T>(impl);
617 }
618
619 // Creates a polymorphic matcher from its implementation. This is
620 // easier to use than the PolymorphicMatcher<Impl> constructor as it
621 // doesn't require you to explicitly write the template argument, e.g.
622 //
623 // MakePolymorphicMatcher(foo);
624 // vs
625 // PolymorphicMatcher<TypeOfFoo>(foo);
626 template <class Impl>
627 inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
628 return PolymorphicMatcher<Impl>(impl);
629 }
630
631 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
632 // and MUST NOT BE USED IN USER CODE!!!
633 namespace internal {
634
635 // The MatcherCastImpl class template is a helper for implementing
636 // MatcherCast(). We need this helper in order to partially
637 // specialize the implementation of MatcherCast() (C++ allows
638 // class/struct templates to be partially specialized, but not
639 // function templates.).
640
641 // This general version is used when MatcherCast()'s argument is a
642 // polymorphic matcher (i.e. something that can be converted to a
643 // Matcher but is not one yet; for example, Eq(value)) or a value (for
644 // example, "hello").
645 template <typename T, typename M>
646 class MatcherCastImpl {
647 public:
648 static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
649 // M can be a polymorphic matcher, in which case we want to use
650 // its conversion operator to create Matcher<T>. Or it can be a value
651 // that should be passed to the Matcher<T>'s constructor.
652 //
653 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
654 // polymorphic matcher because it'll be ambiguous if T has an implicit
655 // constructor from M (this usually happens when T has an implicit
656 // constructor from any type).
657 //
658 // It won't work to unconditionally implict_cast
659 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
660 // a user-defined conversion from M to T if one exists (assuming M is
661 // a value).
662 return CastImpl(
663 polymorphic_matcher_or_value,
664 BooleanConstant<
665 internal::ImplicitlyConvertible<M, Matcher<T> >::value>(),
666 BooleanConstant<
667 internal::ImplicitlyConvertible<M, T>::value>());
668 }
669
670 private:
671 template <bool Ignore>
672 static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
673 BooleanConstant<true> /* convertible_to_matcher */,
674 BooleanConstant<Ignore>) {
675 // M is implicitly convertible to Matcher<T>, which means that either
676 // M is a polymorphic matcher or Matcher<T> has an implicit constructor
677 // from M. In both cases using the implicit conversion will produce a
678 // matcher.
679 //
680 // Even if T has an implicit constructor from M, it won't be called because
681 // creating Matcher<T> would require a chain of two user-defined conversions
682 // (first to create T from M and then to create Matcher<T> from T).
683 return polymorphic_matcher_or_value;
684 }
685
686 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
687 // matcher. It's a value of a type implicitly convertible to T. Use direct
688 // initialization to create a matcher.
689 static Matcher<T> CastImpl(
690 const M& value, BooleanConstant<false> /* convertible_to_matcher */,
691 BooleanConstant<true> /* convertible_to_T */) {
692 return Matcher<T>(ImplicitCast_<T>(value));
693 }
694
695 // M can't be implicitly converted to either Matcher<T> or T. Attempt to use
696 // polymorphic matcher Eq(value) in this case.
697 //
698 // Note that we first attempt to perform an implicit cast on the value and
699 // only fall back to the polymorphic Eq() matcher afterwards because the
700 // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end
701 // which might be undefined even when Rhs is implicitly convertible to Lhs
702 // (e.g. std::pair<const int, int> vs. std::pair<int, int>).
703 //
704 // We don't define this method inline as we need the declaration of Eq().
705 static Matcher<T> CastImpl(
706 const M& value, BooleanConstant<false> /* convertible_to_matcher */,
707 BooleanConstant<false> /* convertible_to_T */);
708 };
709
710 // This more specialized version is used when MatcherCast()'s argument
711 // is already a Matcher. This only compiles when type T can be
712 // statically converted to type U.
713 template <typename T, typename U>
714 class MatcherCastImpl<T, Matcher<U> > {
715 public:
716 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
717 return Matcher<T>(new Impl(source_matcher));
718 }
719
720 private:
721 class Impl : public MatcherInterface<T> {
722 public:
723 explicit Impl(const Matcher<U>& source_matcher)
724 : source_matcher_(source_matcher) {}
725
726 // We delegate the matching logic to the source matcher.
727 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
728 #if GTEST_LANG_CXX11
729 using FromType = typename std::remove_cv<typename std::remove_pointer<
730 typename std::remove_reference<T>::type>::type>::type;
731 using ToType = typename std::remove_cv<typename std::remove_pointer<
732 typename std::remove_reference<U>::type>::type>::type;
733 // Do not allow implicitly converting base*/& to derived*/&.
734 static_assert(
735 // Do not trigger if only one of them is a pointer. That implies a
736 // regular conversion and not a down_cast.
737 (std::is_pointer<typename std::remove_reference<T>::type>::value !=
738 std::is_pointer<typename std::remove_reference<U>::type>::value) ||
739 std::is_same<FromType, ToType>::value ||
740 !std::is_base_of<FromType, ToType>::value,
741 "Can't implicitly convert from <base> to <derived>");
742 #endif // GTEST_LANG_CXX11
743
744 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
745 }
746
747 virtual void DescribeTo(::std::ostream* os) const {
748 source_matcher_.DescribeTo(os);
749 }
750
751 virtual void DescribeNegationTo(::std::ostream* os) const {
752 source_matcher_.DescribeNegationTo(os);
753 }
754
755 private:
756 const Matcher<U> source_matcher_;
757
758 GTEST_DISALLOW_ASSIGN_(Impl);
759 };
760 };
761
762 // This even more specialized version is used for efficiently casting
763 // a matcher to its own type.
764 template <typename T>
765 class MatcherCastImpl<T, Matcher<T> > {
766 public:
767 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
768 };
769
770 } // namespace internal
771
772 // In order to be safe and clear, casting between different matcher
773 // types is done explicitly via MatcherCast<T>(m), which takes a
774 // matcher m and returns a Matcher<T>. It compiles only when T can be
775 // statically converted to the argument type of m.
776 template <typename T, typename M>
777 inline Matcher<T> MatcherCast(const M& matcher) {
778 return internal::MatcherCastImpl<T, M>::Cast(matcher);
779 }
780
781 // Implements SafeMatcherCast().
782 //
783 // We use an intermediate class to do the actual safe casting as Nokia's
784 // Symbian compiler cannot decide between
785 // template <T, M> ... (M) and
786 // template <T, U> ... (const Matcher<U>&)
787 // for function templates but can for member function templates.
788 template <typename T>
789 class SafeMatcherCastImpl {
790 public:
791 // This overload handles polymorphic matchers and values only since
792 // monomorphic matchers are handled by the next one.
793 template <typename M>
794 static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
795 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
796 }
797
798 // This overload handles monomorphic matchers.
799 //
800 // In general, if type T can be implicitly converted to type U, we can
801 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
802 // contravariant): just keep a copy of the original Matcher<U>, convert the
803 // argument from type T to U, and then pass it to the underlying Matcher<U>.
804 // The only exception is when U is a reference and T is not, as the
805 // underlying Matcher<U> may be interested in the argument's address, which
806 // is not preserved in the conversion from T to U.
807 template <typename U>
808 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
809 // Enforce that T can be implicitly converted to U.
810 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
811 T_must_be_implicitly_convertible_to_U);
812 // Enforce that we are not converting a non-reference type T to a reference
813 // type U.
814 GTEST_COMPILE_ASSERT_(
815 internal::is_reference<T>::value || !internal::is_reference<U>::value,
816 cannot_convert_non_reference_arg_to_reference);
817 // In case both T and U are arithmetic types, enforce that the
818 // conversion is not lossy.
819 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
820 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
821 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
822 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
823 GTEST_COMPILE_ASSERT_(
824 kTIsOther || kUIsOther ||
825 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
826 conversion_of_arithmetic_types_must_be_lossless);
827 return MatcherCast<T>(matcher);
828 }
829 };
830
831 template <typename T, typename M>
832 inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
833 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
834 }
835
836 // A<T>() returns a matcher that matches any value of type T.
837 template <typename T>
838 Matcher<T> A();
839
840 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
841 // and MUST NOT BE USED IN USER CODE!!!
842 namespace internal {
843
844 // If the explanation is not empty, prints it to the ostream.
845 inline void PrintIfNotEmpty(const std::string& explanation,
846 ::std::ostream* os) {
847 if (explanation != "" && os != NULL) {
848 *os << ", " << explanation;
849 }
850 }
851
852 // Returns true if the given type name is easy to read by a human.
853 // This is used to decide whether printing the type of a value might
854 // be helpful.
855 inline bool IsReadableTypeName(const std::string& type_name) {
856 // We consider a type name readable if it's short or doesn't contain
857 // a template or function type.
858 return (type_name.length() <= 20 ||
859 type_name.find_first_of("<(") == std::string::npos);
860 }
861
862 // Matches the value against the given matcher, prints the value and explains
863 // the match result to the listener. Returns the match result.
864 // 'listener' must not be NULL.
865 // Value cannot be passed by const reference, because some matchers take a
866 // non-const argument.
867 template <typename Value, typename T>
868 bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
869 MatchResultListener* listener) {
870 if (!listener->IsInterested()) {
871 // If the listener is not interested, we do not need to construct the
872 // inner explanation.
873 return matcher.Matches(value);
874 }
875
876 StringMatchResultListener inner_listener;
877 const bool match = matcher.MatchAndExplain(value, &inner_listener);
878
879 UniversalPrint(value, listener->stream());
880 #if GTEST_HAS_RTTI
881 const std::string& type_name = GetTypeName<Value>();
882 if (IsReadableTypeName(type_name))
883 *listener->stream() << " (of type " << type_name << ")";
884 #endif
885 PrintIfNotEmpty(inner_listener.str(), listener->stream());
886
887 return match;
888 }
889
890 // An internal helper class for doing compile-time loop on a tuple's
891 // fields.
892 template <size_t N>
893 class TuplePrefix {
894 public:
895 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
896 // iff the first N fields of matcher_tuple matches the first N
897 // fields of value_tuple, respectively.
898 template <typename MatcherTuple, typename ValueTuple>
899 static bool Matches(const MatcherTuple& matcher_tuple,
900 const ValueTuple& value_tuple) {
901 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
902 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
903 }
904
905 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
906 // describes failures in matching the first N fields of matchers
907 // against the first N fields of values. If there is no failure,
908 // nothing will be streamed to os.
909 template <typename MatcherTuple, typename ValueTuple>
910 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
911 const ValueTuple& values,
912 ::std::ostream* os) {
913 // First, describes failures in the first N - 1 fields.
914 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
915
916 // Then describes the failure (if any) in the (N - 1)-th (0-based)
917 // field.
918 typename tuple_element<N - 1, MatcherTuple>::type matcher =
919 get<N - 1>(matchers);
920 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
921 GTEST_REFERENCE_TO_CONST_(Value) value = get<N - 1>(values);
922 StringMatchResultListener listener;
923 if (!matcher.MatchAndExplain(value, &listener)) {
924 // TODO(wan): include in the message the name of the parameter
925 // as used in MOCK_METHOD*() when possible.
926 *os << " Expected arg #" << N - 1 << ": ";
927 get<N - 1>(matchers).DescribeTo(os);
928 *os << "\n Actual: ";
929 // We remove the reference in type Value to prevent the
930 // universal printer from printing the address of value, which
931 // isn't interesting to the user most of the time. The
932 // matcher's MatchAndExplain() method handles the case when
933 // the address is interesting.
934 internal::UniversalPrint(value, os);
935 PrintIfNotEmpty(listener.str(), os);
936 *os << "\n";
937 }
938 }
939 };
940
941 // The base case.
942 template <>
943 class TuplePrefix<0> {
944 public:
945 template <typename MatcherTuple, typename ValueTuple>
946 static bool Matches(const MatcherTuple& /* matcher_tuple */,
947 const ValueTuple& /* value_tuple */) {
948 return true;
949 }
950
951 template <typename MatcherTuple, typename ValueTuple>
952 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
953 const ValueTuple& /* values */,
954 ::std::ostream* /* os */) {}
955 };
956
957 // TupleMatches(matcher_tuple, value_tuple) returns true iff all
958 // matchers in matcher_tuple match the corresponding fields in
959 // value_tuple. It is a compiler error if matcher_tuple and
960 // value_tuple have different number of fields or incompatible field
961 // types.
962 template <typename MatcherTuple, typename ValueTuple>
963 bool TupleMatches(const MatcherTuple& matcher_tuple,
964 const ValueTuple& value_tuple) {
965 // Makes sure that matcher_tuple and value_tuple have the same
966 // number of fields.
967 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
968 tuple_size<ValueTuple>::value,
969 matcher_and_value_have_different_numbers_of_fields);
970 return TuplePrefix<tuple_size<ValueTuple>::value>::
971 Matches(matcher_tuple, value_tuple);
972 }
973
974 // Describes failures in matching matchers against values. If there
975 // is no failure, nothing will be streamed to os.
976 template <typename MatcherTuple, typename ValueTuple>
977 void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
978 const ValueTuple& values,
979 ::std::ostream* os) {
980 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
981 matchers, values, os);
982 }
983
984 // TransformTupleValues and its helper.
985 //
986 // TransformTupleValuesHelper hides the internal machinery that
987 // TransformTupleValues uses to implement a tuple traversal.
988 template <typename Tuple, typename Func, typename OutIter>
989 class TransformTupleValuesHelper {
990 private:
991 typedef ::testing::tuple_size<Tuple> TupleSize;
992
993 public:
994 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
995 // Returns the final value of 'out' in case the caller needs it.
996 static OutIter Run(Func f, const Tuple& t, OutIter out) {
997 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
998 }
999
1000 private:
1001 template <typename Tup, size_t kRemainingSize>
1002 struct IterateOverTuple {
1003 OutIter operator() (Func f, const Tup& t, OutIter out) const {
1004 *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
1005 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
1006 }
1007 };
1008 template <typename Tup>
1009 struct IterateOverTuple<Tup, 0> {
1010 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
1011 return out;
1012 }
1013 };
1014 };
1015
1016 // Successively invokes 'f(element)' on each element of the tuple 't',
1017 // appending each result to the 'out' iterator. Returns the final value
1018 // of 'out'.
1019 template <typename Tuple, typename Func, typename OutIter>
1020 OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
1021 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
1022 }
1023
1024 // Implements A<T>().
1025 template <typename T>
1026 class AnyMatcherImpl : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
1027 public:
1028 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) /* x */,
1029 MatchResultListener* /* listener */) const {
1030 return true;
1031 }
1032 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
1033 virtual void DescribeNegationTo(::std::ostream* os) const {
1034 // This is mostly for completeness' safe, as it's not very useful
1035 // to write Not(A<bool>()). However we cannot completely rule out
1036 // such a possibility, and it doesn't hurt to be prepared.
1037 *os << "never matches";
1038 }
1039 };
1040
1041 // Implements _, a matcher that matches any value of any
1042 // type. This is a polymorphic matcher, so we need a template type
1043 // conversion operator to make it appearing as a Matcher<T> for any
1044 // type T.
1045 class AnythingMatcher {
1046 public:
1047 template <typename T>
1048 operator Matcher<T>() const { return A<T>(); }
1049 };
1050
1051 // Implements a matcher that compares a given value with a
1052 // pre-supplied value using one of the ==, <=, <, etc, operators. The
1053 // two values being compared don't have to have the same type.
1054 //
1055 // The matcher defined here is polymorphic (for example, Eq(5) can be
1056 // used to match an int, a short, a double, etc). Therefore we use
1057 // a template type conversion operator in the implementation.
1058 //
1059 // The following template definition assumes that the Rhs parameter is
1060 // a "bare" type (i.e. neither 'const T' nor 'T&').
1061 template <typename D, typename Rhs, typename Op>
1062 class ComparisonBase {
1063 public:
1064 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
1065 template <typename Lhs>
1066 operator Matcher<Lhs>() const {
1067 return MakeMatcher(new Impl<Lhs>(rhs_));
1068 }
1069
1070 private:
1071 template <typename Lhs>
1072 class Impl : public MatcherInterface<Lhs> {
1073 public:
1074 explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
1075 virtual bool MatchAndExplain(
1076 Lhs lhs, MatchResultListener* /* listener */) const {
1077 return Op()(lhs, rhs_);
1078 }
1079 virtual void DescribeTo(::std::ostream* os) const {
1080 *os << D::Desc() << " ";
1081 UniversalPrint(rhs_, os);
1082 }
1083 virtual void DescribeNegationTo(::std::ostream* os) const {
1084 *os << D::NegatedDesc() << " ";
1085 UniversalPrint(rhs_, os);
1086 }
1087 private:
1088 Rhs rhs_;
1089 GTEST_DISALLOW_ASSIGN_(Impl);
1090 };
1091 Rhs rhs_;
1092 GTEST_DISALLOW_ASSIGN_(ComparisonBase);
1093 };
1094
1095 template <typename Rhs>
1096 class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
1097 public:
1098 explicit EqMatcher(const Rhs& rhs)
1099 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
1100 static const char* Desc() { return "is equal to"; }
1101 static const char* NegatedDesc() { return "isn't equal to"; }
1102 };
1103 template <typename Rhs>
1104 class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
1105 public:
1106 explicit NeMatcher(const Rhs& rhs)
1107 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
1108 static const char* Desc() { return "isn't equal to"; }
1109 static const char* NegatedDesc() { return "is equal to"; }
1110 };
1111 template <typename Rhs>
1112 class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
1113 public:
1114 explicit LtMatcher(const Rhs& rhs)
1115 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
1116 static const char* Desc() { return "is <"; }
1117 static const char* NegatedDesc() { return "isn't <"; }
1118 };
1119 template <typename Rhs>
1120 class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
1121 public:
1122 explicit GtMatcher(const Rhs& rhs)
1123 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
1124 static const char* Desc() { return "is >"; }
1125 static const char* NegatedDesc() { return "isn't >"; }
1126 };
1127 template <typename Rhs>
1128 class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
1129 public:
1130 explicit LeMatcher(const Rhs& rhs)
1131 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
1132 static const char* Desc() { return "is <="; }
1133 static const char* NegatedDesc() { return "isn't <="; }
1134 };
1135 template <typename Rhs>
1136 class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
1137 public:
1138 explicit GeMatcher(const Rhs& rhs)
1139 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
1140 static const char* Desc() { return "is >="; }
1141 static const char* NegatedDesc() { return "isn't >="; }
1142 };
1143
1144 // Implements the polymorphic IsNull() matcher, which matches any raw or smart
1145 // pointer that is NULL.
1146 class IsNullMatcher {
1147 public:
1148 template <typename Pointer>
1149 bool MatchAndExplain(const Pointer& p,
1150 MatchResultListener* /* listener */) const {
1151 #if GTEST_LANG_CXX11
1152 return p == nullptr;
1153 #else // GTEST_LANG_CXX11
1154 return GetRawPointer(p) == NULL;
1155 #endif // GTEST_LANG_CXX11
1156 }
1157
1158 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
1159 void DescribeNegationTo(::std::ostream* os) const {
1160 *os << "isn't NULL";
1161 }
1162 };
1163
1164 // Implements the polymorphic NotNull() matcher, which matches any raw or smart
1165 // pointer that is not NULL.
1166 class NotNullMatcher {
1167 public:
1168 template <typename Pointer>
1169 bool MatchAndExplain(const Pointer& p,
1170 MatchResultListener* /* listener */) const {
1171 #if GTEST_LANG_CXX11
1172 return p != nullptr;
1173 #else // GTEST_LANG_CXX11
1174 return GetRawPointer(p) != NULL;
1175 #endif // GTEST_LANG_CXX11
1176 }
1177
1178 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
1179 void DescribeNegationTo(::std::ostream* os) const {
1180 *os << "is NULL";
1181 }
1182 };
1183
1184 // Ref(variable) matches any argument that is a reference to
1185 // 'variable'. This matcher is polymorphic as it can match any
1186 // super type of the type of 'variable'.
1187 //
1188 // The RefMatcher template class implements Ref(variable). It can
1189 // only be instantiated with a reference type. This prevents a user
1190 // from mistakenly using Ref(x) to match a non-reference function
1191 // argument. For example, the following will righteously cause a
1192 // compiler error:
1193 //
1194 // int n;
1195 // Matcher<int> m1 = Ref(n); // This won't compile.
1196 // Matcher<int&> m2 = Ref(n); // This will compile.
1197 template <typename T>
1198 class RefMatcher;
1199
1200 template <typename T>
1201 class RefMatcher<T&> {
1202 // Google Mock is a generic framework and thus needs to support
1203 // mocking any function types, including those that take non-const
1204 // reference arguments. Therefore the template parameter T (and
1205 // Super below) can be instantiated to either a const type or a
1206 // non-const type.
1207 public:
1208 // RefMatcher() takes a T& instead of const T&, as we want the
1209 // compiler to catch using Ref(const_value) as a matcher for a
1210 // non-const reference.
1211 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
1212
1213 template <typename Super>
1214 operator Matcher<Super&>() const {
1215 // By passing object_ (type T&) to Impl(), which expects a Super&,
1216 // we make sure that Super is a super type of T. In particular,
1217 // this catches using Ref(const_value) as a matcher for a
1218 // non-const reference, as you cannot implicitly convert a const
1219 // reference to a non-const reference.
1220 return MakeMatcher(new Impl<Super>(object_));
1221 }
1222
1223 private:
1224 template <typename Super>
1225 class Impl : public MatcherInterface<Super&> {
1226 public:
1227 explicit Impl(Super& x) : object_(x) {} // NOLINT
1228
1229 // MatchAndExplain() takes a Super& (as opposed to const Super&)
1230 // in order to match the interface MatcherInterface<Super&>.
1231 virtual bool MatchAndExplain(
1232 Super& x, MatchResultListener* listener) const {
1233 *listener << "which is located @" << static_cast<const void*>(&x);
1234 return &x == &object_;
1235 }
1236
1237 virtual void DescribeTo(::std::ostream* os) const {
1238 *os << "references the variable ";
1239 UniversalPrinter<Super&>::Print(object_, os);
1240 }
1241
1242 virtual void DescribeNegationTo(::std::ostream* os) const {
1243 *os << "does not reference the variable ";
1244 UniversalPrinter<Super&>::Print(object_, os);
1245 }
1246
1247 private:
1248 const Super& object_;
1249
1250 GTEST_DISALLOW_ASSIGN_(Impl);
1251 };
1252
1253 T& object_;
1254
1255 GTEST_DISALLOW_ASSIGN_(RefMatcher);
1256 };
1257
1258 // Polymorphic helper functions for narrow and wide string matchers.
1259 inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1260 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1261 }
1262
1263 inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1264 const wchar_t* rhs) {
1265 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1266 }
1267
1268 // String comparison for narrow or wide strings that can have embedded NUL
1269 // characters.
1270 template <typename StringType>
1271 bool CaseInsensitiveStringEquals(const StringType& s1,
1272 const StringType& s2) {
1273 // Are the heads equal?
1274 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1275 return false;
1276 }
1277
1278 // Skip the equal heads.
1279 const typename StringType::value_type nul = 0;
1280 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1281
1282 // Are we at the end of either s1 or s2?
1283 if (i1 == StringType::npos || i2 == StringType::npos) {
1284 return i1 == i2;
1285 }
1286
1287 // Are the tails equal?
1288 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1289 }
1290
1291 // String matchers.
1292
1293 // Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1294 template <typename StringType>
1295 class StrEqualityMatcher {
1296 public:
1297 StrEqualityMatcher(const StringType& str, bool expect_eq,
1298 bool case_sensitive)
1299 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1300
1301 #if GTEST_HAS_ABSL
1302 bool MatchAndExplain(const absl::string_view& s,
1303 MatchResultListener* listener) const {
1304 if (s.data() == NULL) {
1305 return !expect_eq_;
1306 }
1307 // This should fail to compile if absl::string_view is used with wide
1308 // strings.
1309 const StringType& str = string(s);
1310 return MatchAndExplain(str, listener);
1311 }
1312 #endif // GTEST_HAS_ABSL
1313
1314 // Accepts pointer types, particularly:
1315 // const char*
1316 // char*
1317 // const wchar_t*
1318 // wchar_t*
1319 template <typename CharType>
1320 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1321 if (s == NULL) {
1322 return !expect_eq_;
1323 }
1324 return MatchAndExplain(StringType(s), listener);
1325 }
1326
1327 // Matches anything that can convert to StringType.
1328 //
1329 // This is a template, not just a plain function with const StringType&,
1330 // because absl::string_view has some interfering non-explicit constructors.
1331 template <typename MatcheeStringType>
1332 bool MatchAndExplain(const MatcheeStringType& s,
1333 MatchResultListener* /* listener */) const {
1334 const StringType& s2(s);
1335 const bool eq = case_sensitive_ ? s2 == string_ :
1336 CaseInsensitiveStringEquals(s2, string_);
1337 return expect_eq_ == eq;
1338 }
1339
1340 void DescribeTo(::std::ostream* os) const {
1341 DescribeToHelper(expect_eq_, os);
1342 }
1343
1344 void DescribeNegationTo(::std::ostream* os) const {
1345 DescribeToHelper(!expect_eq_, os);
1346 }
1347
1348 private:
1349 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
1350 *os << (expect_eq ? "is " : "isn't ");
1351 *os << "equal to ";
1352 if (!case_sensitive_) {
1353 *os << "(ignoring case) ";
1354 }
1355 UniversalPrint(string_, os);
1356 }
1357
1358 const StringType string_;
1359 const bool expect_eq_;
1360 const bool case_sensitive_;
1361
1362 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
1363 };
1364
1365 // Implements the polymorphic HasSubstr(substring) matcher, which
1366 // can be used as a Matcher<T> as long as T can be converted to a
1367 // string.
1368 template <typename StringType>
1369 class HasSubstrMatcher {
1370 public:
1371 explicit HasSubstrMatcher(const StringType& substring)
1372 : substring_(substring) {}
1373
1374 #if GTEST_HAS_ABSL
1375 bool MatchAndExplain(const absl::string_view& s,
1376 MatchResultListener* listener) const {
1377 if (s.data() == NULL) {
1378 return false;
1379 }
1380 // This should fail to compile if absl::string_view is used with wide
1381 // strings.
1382 const StringType& str = string(s);
1383 return MatchAndExplain(str, listener);
1384 }
1385 #endif // GTEST_HAS_ABSL
1386
1387 // Accepts pointer types, particularly:
1388 // const char*
1389 // char*
1390 // const wchar_t*
1391 // wchar_t*
1392 template <typename CharType>
1393 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1394 return s != NULL && MatchAndExplain(StringType(s), listener);
1395 }
1396
1397 // Matches anything that can convert to StringType.
1398 //
1399 // This is a template, not just a plain function with const StringType&,
1400 // because absl::string_view has some interfering non-explicit constructors.
1401 template <typename MatcheeStringType>
1402 bool MatchAndExplain(const MatcheeStringType& s,
1403 MatchResultListener* /* listener */) const {
1404 const StringType& s2(s);
1405 return s2.find(substring_) != StringType::npos;
1406 }
1407
1408 // Describes what this matcher matches.
1409 void DescribeTo(::std::ostream* os) const {
1410 *os << "has substring ";
1411 UniversalPrint(substring_, os);
1412 }
1413
1414 void DescribeNegationTo(::std::ostream* os) const {
1415 *os << "has no substring ";
1416 UniversalPrint(substring_, os);
1417 }
1418
1419 private:
1420 const StringType substring_;
1421
1422 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
1423 };
1424
1425 // Implements the polymorphic StartsWith(substring) matcher, which
1426 // can be used as a Matcher<T> as long as T can be converted to a
1427 // string.
1428 template <typename StringType>
1429 class StartsWithMatcher {
1430 public:
1431 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1432 }
1433
1434 #if GTEST_HAS_ABSL
1435 bool MatchAndExplain(const absl::string_view& s,
1436 MatchResultListener* listener) const {
1437 if (s.data() == NULL) {
1438 return false;
1439 }
1440 // This should fail to compile if absl::string_view is used with wide
1441 // strings.
1442 const StringType& str = string(s);
1443 return MatchAndExplain(str, listener);
1444 }
1445 #endif // GTEST_HAS_ABSL
1446
1447 // Accepts pointer types, particularly:
1448 // const char*
1449 // char*
1450 // const wchar_t*
1451 // wchar_t*
1452 template <typename CharType>
1453 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1454 return s != NULL && MatchAndExplain(StringType(s), listener);
1455 }
1456
1457 // Matches anything that can convert to StringType.
1458 //
1459 // This is a template, not just a plain function with const StringType&,
1460 // because absl::string_view has some interfering non-explicit constructors.
1461 template <typename MatcheeStringType>
1462 bool MatchAndExplain(const MatcheeStringType& s,
1463 MatchResultListener* /* listener */) const {
1464 const StringType& s2(s);
1465 return s2.length() >= prefix_.length() &&
1466 s2.substr(0, prefix_.length()) == prefix_;
1467 }
1468
1469 void DescribeTo(::std::ostream* os) const {
1470 *os << "starts with ";
1471 UniversalPrint(prefix_, os);
1472 }
1473
1474 void DescribeNegationTo(::std::ostream* os) const {
1475 *os << "doesn't start with ";
1476 UniversalPrint(prefix_, os);
1477 }
1478
1479 private:
1480 const StringType prefix_;
1481
1482 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
1483 };
1484
1485 // Implements the polymorphic EndsWith(substring) matcher, which
1486 // can be used as a Matcher<T> as long as T can be converted to a
1487 // string.
1488 template <typename StringType>
1489 class EndsWithMatcher {
1490 public:
1491 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1492
1493 #if GTEST_HAS_ABSL
1494 bool MatchAndExplain(const absl::string_view& s,
1495 MatchResultListener* listener) const {
1496 if (s.data() == NULL) {
1497 return false;
1498 }
1499 // This should fail to compile if absl::string_view is used with wide
1500 // strings.
1501 const StringType& str = string(s);
1502 return MatchAndExplain(str, listener);
1503 }
1504 #endif // GTEST_HAS_ABSL
1505
1506 // Accepts pointer types, particularly:
1507 // const char*
1508 // char*
1509 // const wchar_t*
1510 // wchar_t*
1511 template <typename CharType>
1512 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1513 return s != NULL && MatchAndExplain(StringType(s), listener);
1514 }
1515
1516 // Matches anything that can convert to StringType.
1517 //
1518 // This is a template, not just a plain function with const StringType&,
1519 // because absl::string_view has some interfering non-explicit constructors.
1520 template <typename MatcheeStringType>
1521 bool MatchAndExplain(const MatcheeStringType& s,
1522 MatchResultListener* /* listener */) const {
1523 const StringType& s2(s);
1524 return s2.length() >= suffix_.length() &&
1525 s2.substr(s2.length() - suffix_.length()) == suffix_;
1526 }
1527
1528 void DescribeTo(::std::ostream* os) const {
1529 *os << "ends with ";
1530 UniversalPrint(suffix_, os);
1531 }
1532
1533 void DescribeNegationTo(::std::ostream* os) const {
1534 *os << "doesn't end with ";
1535 UniversalPrint(suffix_, os);
1536 }
1537
1538 private:
1539 const StringType suffix_;
1540
1541 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
1542 };
1543
1544 // Implements polymorphic matchers MatchesRegex(regex) and
1545 // ContainsRegex(regex), which can be used as a Matcher<T> as long as
1546 // T can be converted to a string.
1547 class MatchesRegexMatcher {
1548 public:
1549 MatchesRegexMatcher(const RE* regex, bool full_match)
1550 : regex_(regex), full_match_(full_match) {}
1551
1552 #if GTEST_HAS_ABSL
1553 bool MatchAndExplain(const absl::string_view& s,
1554 MatchResultListener* listener) const {
1555 return s.data() && MatchAndExplain(string(s), listener);
1556 }
1557 #endif // GTEST_HAS_ABSL
1558
1559 // Accepts pointer types, particularly:
1560 // const char*
1561 // char*
1562 // const wchar_t*
1563 // wchar_t*
1564 template <typename CharType>
1565 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1566 return s != NULL && MatchAndExplain(std::string(s), listener);
1567 }
1568
1569 // Matches anything that can convert to std::string.
1570 //
1571 // This is a template, not just a plain function with const std::string&,
1572 // because absl::string_view has some interfering non-explicit constructors.
1573 template <class MatcheeStringType>
1574 bool MatchAndExplain(const MatcheeStringType& s,
1575 MatchResultListener* /* listener */) const {
1576 const std::string& s2(s);
1577 return full_match_ ? RE::FullMatch(s2, *regex_) :
1578 RE::PartialMatch(s2, *regex_);
1579 }
1580
1581 void DescribeTo(::std::ostream* os) const {
1582 *os << (full_match_ ? "matches" : "contains")
1583 << " regular expression ";
1584 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
1585 }
1586
1587 void DescribeNegationTo(::std::ostream* os) const {
1588 *os << "doesn't " << (full_match_ ? "match" : "contain")
1589 << " regular expression ";
1590 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
1591 }
1592
1593 private:
1594 const internal::linked_ptr<const RE> regex_;
1595 const bool full_match_;
1596
1597 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
1598 };
1599
1600 // Implements a matcher that compares the two fields of a 2-tuple
1601 // using one of the ==, <=, <, etc, operators. The two fields being
1602 // compared don't have to have the same type.
1603 //
1604 // The matcher defined here is polymorphic (for example, Eq() can be
1605 // used to match a tuple<int, short>, a tuple<const long&, double>,
1606 // etc). Therefore we use a template type conversion operator in the
1607 // implementation.
1608 template <typename D, typename Op>
1609 class PairMatchBase {
1610 public:
1611 template <typename T1, typename T2>
1612 operator Matcher< ::testing::tuple<T1, T2> >() const {
1613 return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >);
1614 }
1615 template <typename T1, typename T2>
1616 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
1617 return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>);
1618 }
1619
1620 private:
1621 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
1622 return os << D::Desc();
1623 }
1624
1625 template <typename Tuple>
1626 class Impl : public MatcherInterface<Tuple> {
1627 public:
1628 virtual bool MatchAndExplain(
1629 Tuple args,
1630 MatchResultListener* /* listener */) const {
1631 return Op()(::testing::get<0>(args), ::testing::get<1>(args));
1632 }
1633 virtual void DescribeTo(::std::ostream* os) const {
1634 *os << "are " << GetDesc;
1635 }
1636 virtual void DescribeNegationTo(::std::ostream* os) const {
1637 *os << "aren't " << GetDesc;
1638 }
1639 };
1640 };
1641
1642 class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
1643 public:
1644 static const char* Desc() { return "an equal pair"; }
1645 };
1646 class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
1647 public:
1648 static const char* Desc() { return "an unequal pair"; }
1649 };
1650 class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
1651 public:
1652 static const char* Desc() { return "a pair where the first < the second"; }
1653 };
1654 class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
1655 public:
1656 static const char* Desc() { return "a pair where the first > the second"; }
1657 };
1658 class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
1659 public:
1660 static const char* Desc() { return "a pair where the first <= the second"; }
1661 };
1662 class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
1663 public:
1664 static const char* Desc() { return "a pair where the first >= the second"; }
1665 };
1666
1667 // Implements the Not(...) matcher for a particular argument type T.
1668 // We do not nest it inside the NotMatcher class template, as that
1669 // will prevent different instantiations of NotMatcher from sharing
1670 // the same NotMatcherImpl<T> class.
1671 template <typename T>
1672 class NotMatcherImpl : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
1673 public:
1674 explicit NotMatcherImpl(const Matcher<T>& matcher)
1675 : matcher_(matcher) {}
1676
1677 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
1678 MatchResultListener* listener) const {
1679 return !matcher_.MatchAndExplain(x, listener);
1680 }
1681
1682 virtual void DescribeTo(::std::ostream* os) const {
1683 matcher_.DescribeNegationTo(os);
1684 }
1685
1686 virtual void DescribeNegationTo(::std::ostream* os) const {
1687 matcher_.DescribeTo(os);
1688 }
1689
1690 private:
1691 const Matcher<T> matcher_;
1692
1693 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
1694 };
1695
1696 // Implements the Not(m) matcher, which matches a value that doesn't
1697 // match matcher m.
1698 template <typename InnerMatcher>
1699 class NotMatcher {
1700 public:
1701 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1702
1703 // This template type conversion operator allows Not(m) to be used
1704 // to match any type m can match.
1705 template <typename T>
1706 operator Matcher<T>() const {
1707 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
1708 }
1709
1710 private:
1711 InnerMatcher matcher_;
1712
1713 GTEST_DISALLOW_ASSIGN_(NotMatcher);
1714 };
1715
1716 // Implements the AllOf(m1, m2) matcher for a particular argument type
1717 // T. We do not nest it inside the BothOfMatcher class template, as
1718 // that will prevent different instantiations of BothOfMatcher from
1719 // sharing the same BothOfMatcherImpl<T> class.
1720 template <typename T>
1721 class AllOfMatcherImpl
1722 : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
1723 public:
1724 explicit AllOfMatcherImpl(std::vector<Matcher<T> > matchers)
1725 : matchers_(internal::move(matchers)) {}
1726
1727 virtual void DescribeTo(::std::ostream* os) const {
1728 *os << "(";
1729 for (size_t i = 0; i < matchers_.size(); ++i) {
1730 if (i != 0) *os << ") and (";
1731 matchers_[i].DescribeTo(os);
1732 }
1733 *os << ")";
1734 }
1735
1736 virtual void DescribeNegationTo(::std::ostream* os) const {
1737 *os << "(";
1738 for (size_t i = 0; i < matchers_.size(); ++i) {
1739 if (i != 0) *os << ") or (";
1740 matchers_[i].DescribeNegationTo(os);
1741 }
1742 *os << ")";
1743 }
1744
1745 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
1746 MatchResultListener* listener) const {
1747 // If either matcher1_ or matcher2_ doesn't match x, we only need
1748 // to explain why one of them fails.
1749 std::string all_match_result;
1750
1751 for (size_t i = 0; i < matchers_.size(); ++i) {
1752 StringMatchResultListener slistener;
1753 if (matchers_[i].MatchAndExplain(x, &slistener)) {
1754 if (all_match_result.empty()) {
1755 all_match_result = slistener.str();
1756 } else {
1757 std::string result = slistener.str();
1758 if (!result.empty()) {
1759 all_match_result += ", and ";
1760 all_match_result += result;
1761 }
1762 }
1763 } else {
1764 *listener << slistener.str();
1765 return false;
1766 }
1767 }
1768
1769 // Otherwise we need to explain why *both* of them match.
1770 *listener << all_match_result;
1771 return true;
1772 }
1773
1774 private:
1775 const std::vector<Matcher<T> > matchers_;
1776
1777 GTEST_DISALLOW_ASSIGN_(AllOfMatcherImpl);
1778 };
1779
1780 #if GTEST_LANG_CXX11
1781 // VariadicMatcher is used for the variadic implementation of
1782 // AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1783 // CombiningMatcher<T> is used to recursively combine the provided matchers
1784 // (of type Args...).
1785 template <template <typename T> class CombiningMatcher, typename... Args>
1786 class VariadicMatcher {
1787 public:
1788 VariadicMatcher(const Args&... matchers) // NOLINT
1789 : matchers_(matchers...) {
1790 static_assert(sizeof...(Args) > 0, "Must have at least one matcher.");
1791 }
1792
1793 // This template type conversion operator allows an
1794 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1795 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1796 template <typename T>
1797 operator Matcher<T>() const {
1798 std::vector<Matcher<T> > values;
1799 CreateVariadicMatcher<T>(&values, std::integral_constant<size_t, 0>());
1800 return Matcher<T>(new CombiningMatcher<T>(internal::move(values)));
1801 }
1802
1803 private:
1804 template <typename T, size_t I>
1805 void CreateVariadicMatcher(std::vector<Matcher<T> >* values,
1806 std::integral_constant<size_t, I>) const {
1807 values->push_back(SafeMatcherCast<T>(std::get<I>(matchers_)));
1808 CreateVariadicMatcher<T>(values, std::integral_constant<size_t, I + 1>());
1809 }
1810
1811 template <typename T>
1812 void CreateVariadicMatcher(
1813 std::vector<Matcher<T> >*,
1814 std::integral_constant<size_t, sizeof...(Args)>) const {}
1815
1816 tuple<Args...> matchers_;
1817
1818 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1819 };
1820
1821 template <typename... Args>
1822 using AllOfMatcher = VariadicMatcher<AllOfMatcherImpl, Args...>;
1823
1824 #endif // GTEST_LANG_CXX11
1825
1826 // Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1827 // matches a value that matches all of the matchers m_1, ..., and m_n.
1828 template <typename Matcher1, typename Matcher2>
1829 class BothOfMatcher {
1830 public:
1831 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1832 : matcher1_(matcher1), matcher2_(matcher2) {}
1833
1834 // This template type conversion operator allows a
1835 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1836 // both Matcher1 and Matcher2 can match.
1837 template <typename T>
1838 operator Matcher<T>() const {
1839 std::vector<Matcher<T> > values;
1840 values.push_back(SafeMatcherCast<T>(matcher1_));
1841 values.push_back(SafeMatcherCast<T>(matcher2_));
1842 return Matcher<T>(new AllOfMatcherImpl<T>(internal::move(values)));
1843 }
1844
1845 private:
1846 Matcher1 matcher1_;
1847 Matcher2 matcher2_;
1848
1849 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
1850 };
1851
1852 // Implements the AnyOf(m1, m2) matcher for a particular argument type
1853 // T. We do not nest it inside the AnyOfMatcher class template, as
1854 // that will prevent different instantiations of AnyOfMatcher from
1855 // sharing the same EitherOfMatcherImpl<T> class.
1856 template <typename T>
1857 class AnyOfMatcherImpl
1858 : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
1859 public:
1860 explicit AnyOfMatcherImpl(std::vector<Matcher<T> > matchers)
1861 : matchers_(internal::move(matchers)) {}
1862
1863 virtual void DescribeTo(::std::ostream* os) const {
1864 *os << "(";
1865 for (size_t i = 0; i < matchers_.size(); ++i) {
1866 if (i != 0) *os << ") or (";
1867 matchers_[i].DescribeTo(os);
1868 }
1869 *os << ")";
1870 }
1871
1872 virtual void DescribeNegationTo(::std::ostream* os) const {
1873 *os << "(";
1874 for (size_t i = 0; i < matchers_.size(); ++i) {
1875 if (i != 0) *os << ") and (";
1876 matchers_[i].DescribeNegationTo(os);
1877 }
1878 *os << ")";
1879 }
1880
1881 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
1882 MatchResultListener* listener) const {
1883 std::string no_match_result;
1884
1885 // If either matcher1_ or matcher2_ matches x, we just need to
1886 // explain why *one* of them matches.
1887 for (size_t i = 0; i < matchers_.size(); ++i) {
1888 StringMatchResultListener slistener;
1889 if (matchers_[i].MatchAndExplain(x, &slistener)) {
1890 *listener << slistener.str();
1891 return true;
1892 } else {
1893 if (no_match_result.empty()) {
1894 no_match_result = slistener.str();
1895 } else {
1896 std::string result = slistener.str();
1897 if (!result.empty()) {
1898 no_match_result += ", and ";
1899 no_match_result += result;
1900 }
1901 }
1902 }
1903 }
1904
1905 // Otherwise we need to explain why *both* of them fail.
1906 *listener << no_match_result;
1907 return false;
1908 }
1909
1910 private:
1911 const std::vector<Matcher<T> > matchers_;
1912
1913 GTEST_DISALLOW_ASSIGN_(AnyOfMatcherImpl);
1914 };
1915
1916 #if GTEST_LANG_CXX11
1917 // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1918 template <typename... Args>
1919 using AnyOfMatcher = VariadicMatcher<AnyOfMatcherImpl, Args...>;
1920
1921 #endif // GTEST_LANG_CXX11
1922
1923 // Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1924 // matches a value that matches at least one of the matchers m_1, ...,
1925 // and m_n.
1926 template <typename Matcher1, typename Matcher2>
1927 class EitherOfMatcher {
1928 public:
1929 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1930 : matcher1_(matcher1), matcher2_(matcher2) {}
1931
1932 // This template type conversion operator allows a
1933 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1934 // both Matcher1 and Matcher2 can match.
1935 template <typename T>
1936 operator Matcher<T>() const {
1937 std::vector<Matcher<T> > values;
1938 values.push_back(SafeMatcherCast<T>(matcher1_));
1939 values.push_back(SafeMatcherCast<T>(matcher2_));
1940 return Matcher<T>(new AnyOfMatcherImpl<T>(internal::move(values)));
1941 }
1942
1943 private:
1944 Matcher1 matcher1_;
1945 Matcher2 matcher2_;
1946
1947 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
1948 };
1949
1950 // Used for implementing Truly(pred), which turns a predicate into a
1951 // matcher.
1952 template <typename Predicate>
1953 class TrulyMatcher {
1954 public:
1955 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1956
1957 // This method template allows Truly(pred) to be used as a matcher
1958 // for type T where T is the argument type of predicate 'pred'. The
1959 // argument is passed by reference as the predicate may be
1960 // interested in the address of the argument.
1961 template <typename T>
1962 bool MatchAndExplain(T& x, // NOLINT
1963 MatchResultListener* /* listener */) const {
1964 // Without the if-statement, MSVC sometimes warns about converting
1965 // a value to bool (warning 4800).
1966 //
1967 // We cannot write 'return !!predicate_(x);' as that doesn't work
1968 // when predicate_(x) returns a class convertible to bool but
1969 // having no operator!().
1970 if (predicate_(x))
1971 return true;
1972 return false;
1973 }
1974
1975 void DescribeTo(::std::ostream* os) const {
1976 *os << "satisfies the given predicate";
1977 }
1978
1979 void DescribeNegationTo(::std::ostream* os) const {
1980 *os << "doesn't satisfy the given predicate";
1981 }
1982
1983 private:
1984 Predicate predicate_;
1985
1986 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
1987 };
1988
1989 // Used for implementing Matches(matcher), which turns a matcher into
1990 // a predicate.
1991 template <typename M>
1992 class MatcherAsPredicate {
1993 public:
1994 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1995
1996 // This template operator() allows Matches(m) to be used as a
1997 // predicate on type T where m is a matcher on type T.
1998 //
1999 // The argument x is passed by reference instead of by value, as
2000 // some matcher may be interested in its address (e.g. as in
2001 // Matches(Ref(n))(x)).
2002 template <typename T>
2003 bool operator()(const T& x) const {
2004 // We let matcher_ commit to a particular type here instead of
2005 // when the MatcherAsPredicate object was constructed. This
2006 // allows us to write Matches(m) where m is a polymorphic matcher
2007 // (e.g. Eq(5)).
2008 //
2009 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
2010 // compile when matcher_ has type Matcher<const T&>; if we write
2011 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
2012 // when matcher_ has type Matcher<T>; if we just write
2013 // matcher_.Matches(x), it won't compile when matcher_ is
2014 // polymorphic, e.g. Eq(5).
2015 //
2016 // MatcherCast<const T&>() is necessary for making the code work
2017 // in all of the above situations.
2018 return MatcherCast<const T&>(matcher_).Matches(x);
2019 }
2020
2021 private:
2022 M matcher_;
2023
2024 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
2025 };
2026
2027 // For implementing ASSERT_THAT() and EXPECT_THAT(). The template
2028 // argument M must be a type that can be converted to a matcher.
2029 template <typename M>
2030 class PredicateFormatterFromMatcher {
2031 public:
2032 explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {}
2033
2034 // This template () operator allows a PredicateFormatterFromMatcher
2035 // object to act as a predicate-formatter suitable for using with
2036 // Google Test's EXPECT_PRED_FORMAT1() macro.
2037 template <typename T>
2038 AssertionResult operator()(const char* value_text, const T& x) const {
2039 // We convert matcher_ to a Matcher<const T&> *now* instead of
2040 // when the PredicateFormatterFromMatcher object was constructed,
2041 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
2042 // know which type to instantiate it to until we actually see the
2043 // type of x here.
2044 //
2045 // We write SafeMatcherCast<const T&>(matcher_) instead of
2046 // Matcher<const T&>(matcher_), as the latter won't compile when
2047 // matcher_ has type Matcher<T> (e.g. An<int>()).
2048 // We don't write MatcherCast<const T&> either, as that allows
2049 // potentially unsafe downcasting of the matcher argument.
2050 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
2051 StringMatchResultListener listener;
2052 if (MatchPrintAndExplain(x, matcher, &listener))
2053 return AssertionSuccess();
2054
2055 ::std::stringstream ss;
2056 ss << "Value of: " << value_text << "\n"
2057 << "Expected: ";
2058 matcher.DescribeTo(&ss);
2059 ss << "\n Actual: " << listener.str();
2060 return AssertionFailure() << ss.str();
2061 }
2062
2063 private:
2064 const M matcher_;
2065
2066 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
2067 };
2068
2069 // A helper function for converting a matcher to a predicate-formatter
2070 // without the user needing to explicitly write the type. This is
2071 // used for implementing ASSERT_THAT() and EXPECT_THAT().
2072 // Implementation detail: 'matcher' is received by-value to force decaying.
2073 template <typename M>
2074 inline PredicateFormatterFromMatcher<M>
2075 MakePredicateFormatterFromMatcher(M matcher) {
2076 return PredicateFormatterFromMatcher<M>(internal::move(matcher));
2077 }
2078
2079 // Implements the polymorphic floating point equality matcher, which matches
2080 // two float values using ULP-based approximation or, optionally, a
2081 // user-specified epsilon. The template is meant to be instantiated with
2082 // FloatType being either float or double.
2083 template <typename FloatType>
2084 class FloatingEqMatcher {
2085 public:
2086 // Constructor for FloatingEqMatcher.
2087 // The matcher's input will be compared with expected. The matcher treats two
2088 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
2089 // equality comparisons between NANs will always return false. We specify a
2090 // negative max_abs_error_ term to indicate that ULP-based approximation will
2091 // be used for comparison.
2092 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
2093 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
2094 }
2095
2096 // Constructor that supports a user-specified max_abs_error that will be used
2097 // for comparison instead of ULP-based approximation. The max absolute
2098 // should be non-negative.
2099 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
2100 FloatType max_abs_error)
2101 : expected_(expected),
2102 nan_eq_nan_(nan_eq_nan),
2103 max_abs_error_(max_abs_error) {
2104 GTEST_CHECK_(max_abs_error >= 0)
2105 << ", where max_abs_error is" << max_abs_error;
2106 }
2107
2108 // Implements floating point equality matcher as a Matcher<T>.
2109 template <typename T>
2110 class Impl : public MatcherInterface<T> {
2111 public:
2112 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
2113 : expected_(expected),
2114 nan_eq_nan_(nan_eq_nan),
2115 max_abs_error_(max_abs_error) {}
2116
2117 virtual bool MatchAndExplain(T value,
2118 MatchResultListener* listener) const {
2119 const FloatingPoint<FloatType> actual(value), expected(expected_);
2120
2121 // Compares NaNs first, if nan_eq_nan_ is true.
2122 if (actual.is_nan() || expected.is_nan()) {
2123 if (actual.is_nan() && expected.is_nan()) {
2124 return nan_eq_nan_;
2125 }
2126 // One is nan; the other is not nan.
2127 return false;
2128 }
2129 if (HasMaxAbsError()) {
2130 // We perform an equality check so that inf will match inf, regardless
2131 // of error bounds. If the result of value - expected_ would result in
2132 // overflow or if either value is inf, the default result is infinity,
2133 // which should only match if max_abs_error_ is also infinity.
2134 if (value == expected_) {
2135 return true;
2136 }
2137
2138 const FloatType diff = value - expected_;
2139 if (fabs(diff) <= max_abs_error_) {
2140 return true;
2141 }
2142
2143 if (listener->IsInterested()) {
2144 *listener << "which is " << diff << " from " << expected_;
2145 }
2146 return false;
2147 } else {
2148 return actual.AlmostEquals(expected);
2149 }
2150 }
2151
2152 virtual void DescribeTo(::std::ostream* os) const {
2153 // os->precision() returns the previously set precision, which we
2154 // store to restore the ostream to its original configuration
2155 // after outputting.
2156 const ::std::streamsize old_precision = os->precision(
2157 ::std::numeric_limits<FloatType>::digits10 + 2);
2158 if (FloatingPoint<FloatType>(expected_).is_nan()) {
2159 if (nan_eq_nan_) {
2160 *os << "is NaN";
2161 } else {
2162 *os << "never matches";
2163 }
2164 } else {
2165 *os << "is approximately " << expected_;
2166 if (HasMaxAbsError()) {
2167 *os << " (absolute error <= " << max_abs_error_ << ")";
2168 }
2169 }
2170 os->precision(old_precision);
2171 }
2172
2173 virtual void DescribeNegationTo(::std::ostream* os) const {
2174 // As before, get original precision.
2175 const ::std::streamsize old_precision = os->precision(
2176 ::std::numeric_limits<FloatType>::digits10 + 2);
2177 if (FloatingPoint<FloatType>(expected_).is_nan()) {
2178 if (nan_eq_nan_) {
2179 *os << "isn't NaN";
2180 } else {
2181 *os << "is anything";
2182 }
2183 } else {
2184 *os << "isn't approximately " << expected_;
2185 if (HasMaxAbsError()) {
2186 *os << " (absolute error > " << max_abs_error_ << ")";
2187 }
2188 }
2189 // Restore original precision.
2190 os->precision(old_precision);
2191 }
2192
2193 private:
2194 bool HasMaxAbsError() const {
2195 return max_abs_error_ >= 0;
2196 }
2197
2198 const FloatType expected_;
2199 const bool nan_eq_nan_;
2200 // max_abs_error will be used for value comparison when >= 0.
2201 const FloatType max_abs_error_;
2202
2203 GTEST_DISALLOW_ASSIGN_(Impl);
2204 };
2205
2206 // The following 3 type conversion operators allow FloatEq(expected) and
2207 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
2208 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
2209 // (While Google's C++ coding style doesn't allow arguments passed
2210 // by non-const reference, we may see them in code not conforming to
2211 // the style. Therefore Google Mock needs to support them.)
2212 operator Matcher<FloatType>() const {
2213 return MakeMatcher(
2214 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
2215 }
2216
2217 operator Matcher<const FloatType&>() const {
2218 return MakeMatcher(
2219 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
2220 }
2221
2222 operator Matcher<FloatType&>() const {
2223 return MakeMatcher(
2224 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
2225 }
2226
2227 private:
2228 const FloatType expected_;
2229 const bool nan_eq_nan_;
2230 // max_abs_error will be used for value comparison when >= 0.
2231 const FloatType max_abs_error_;
2232
2233 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
2234 };
2235
2236 // A 2-tuple ("binary") wrapper around FloatingEqMatcher:
2237 // FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false)
2238 // against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e)
2239 // against y. The former implements "Eq", the latter "Near". At present, there
2240 // is no version that compares NaNs as equal.
2241 template <typename FloatType>
2242 class FloatingEq2Matcher {
2243 public:
2244 FloatingEq2Matcher() { Init(-1, false); }
2245
2246 explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); }
2247
2248 explicit FloatingEq2Matcher(FloatType max_abs_error) {
2249 Init(max_abs_error, false);
2250 }
2251
2252 FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) {
2253 Init(max_abs_error, nan_eq_nan);
2254 }
2255
2256 template <typename T1, typename T2>
2257 operator Matcher< ::testing::tuple<T1, T2> >() const {
2258 return MakeMatcher(
2259 new Impl< ::testing::tuple<T1, T2> >(max_abs_error_, nan_eq_nan_));
2260 }
2261 template <typename T1, typename T2>
2262 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
2263 return MakeMatcher(
2264 new Impl<const ::testing::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_));
2265 }
2266
2267 private:
2268 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
2269 return os << "an almost-equal pair";
2270 }
2271
2272 template <typename Tuple>
2273 class Impl : public MatcherInterface<Tuple> {
2274 public:
2275 Impl(FloatType max_abs_error, bool nan_eq_nan) :
2276 max_abs_error_(max_abs_error),
2277 nan_eq_nan_(nan_eq_nan) {}
2278
2279 virtual bool MatchAndExplain(Tuple args,
2280 MatchResultListener* listener) const {
2281 if (max_abs_error_ == -1) {
2282 FloatingEqMatcher<FloatType> fm(::testing::get<0>(args), nan_eq_nan_);
2283 return static_cast<Matcher<FloatType> >(fm).MatchAndExplain(
2284 ::testing::get<1>(args), listener);
2285 } else {
2286 FloatingEqMatcher<FloatType> fm(::testing::get<0>(args), nan_eq_nan_,
2287 max_abs_error_);
2288 return static_cast<Matcher<FloatType> >(fm).MatchAndExplain(
2289 ::testing::get<1>(args), listener);
2290 }
2291 }
2292 virtual void DescribeTo(::std::ostream* os) const {
2293 *os << "are " << GetDesc;
2294 }
2295 virtual void DescribeNegationTo(::std::ostream* os) const {
2296 *os << "aren't " << GetDesc;
2297 }
2298
2299 private:
2300 FloatType max_abs_error_;
2301 const bool nan_eq_nan_;
2302 };
2303
2304 void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) {
2305 max_abs_error_ = max_abs_error_val;
2306 nan_eq_nan_ = nan_eq_nan_val;
2307 }
2308 FloatType max_abs_error_;
2309 bool nan_eq_nan_;
2310 };
2311
2312 // Implements the Pointee(m) matcher for matching a pointer whose
2313 // pointee matches matcher m. The pointer can be either raw or smart.
2314 template <typename InnerMatcher>
2315 class PointeeMatcher {
2316 public:
2317 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
2318
2319 // This type conversion operator template allows Pointee(m) to be
2320 // used as a matcher for any pointer type whose pointee type is
2321 // compatible with the inner matcher, where type Pointer can be
2322 // either a raw pointer or a smart pointer.
2323 //
2324 // The reason we do this instead of relying on
2325 // MakePolymorphicMatcher() is that the latter is not flexible
2326 // enough for implementing the DescribeTo() method of Pointee().
2327 template <typename Pointer>
2328 operator Matcher<Pointer>() const {
2329 return Matcher<Pointer>(
2330 new Impl<GTEST_REFERENCE_TO_CONST_(Pointer)>(matcher_));
2331 }
2332
2333 private:
2334 // The monomorphic implementation that works for a particular pointer type.
2335 template <typename Pointer>
2336 class Impl : public MatcherInterface<Pointer> {
2337 public:
2338 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
2339 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
2340
2341 explicit Impl(const InnerMatcher& matcher)
2342 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
2343
2344 virtual void DescribeTo(::std::ostream* os) const {
2345 *os << "points to a value that ";
2346 matcher_.DescribeTo(os);
2347 }
2348
2349 virtual void DescribeNegationTo(::std::ostream* os) const {
2350 *os << "does not point to a value that ";
2351 matcher_.DescribeTo(os);
2352 }
2353
2354 virtual bool MatchAndExplain(Pointer pointer,
2355 MatchResultListener* listener) const {
2356 if (GetRawPointer(pointer) == NULL)
2357 return false;
2358
2359 *listener << "which points to ";
2360 return MatchPrintAndExplain(*pointer, matcher_, listener);
2361 }
2362
2363 private:
2364 const Matcher<const Pointee&> matcher_;
2365
2366 GTEST_DISALLOW_ASSIGN_(Impl);
2367 };
2368
2369 const InnerMatcher matcher_;
2370
2371 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
2372 };
2373
2374 #if GTEST_HAS_RTTI
2375 // Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2376 // reference that matches inner_matcher when dynamic_cast<T> is applied.
2377 // The result of dynamic_cast<To> is forwarded to the inner matcher.
2378 // If To is a pointer and the cast fails, the inner matcher will receive NULL.
2379 // If To is a reference and the cast fails, this matcher returns false
2380 // immediately.
2381 template <typename To>
2382 class WhenDynamicCastToMatcherBase {
2383 public:
2384 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2385 : matcher_(matcher) {}
2386
2387 void DescribeTo(::std::ostream* os) const {
2388 GetCastTypeDescription(os);
2389 matcher_.DescribeTo(os);
2390 }
2391
2392 void DescribeNegationTo(::std::ostream* os) const {
2393 GetCastTypeDescription(os);
2394 matcher_.DescribeNegationTo(os);
2395 }
2396
2397 protected:
2398 const Matcher<To> matcher_;
2399
2400 static std::string GetToName() {
2401 return GetTypeName<To>();
2402 }
2403
2404 private:
2405 static void GetCastTypeDescription(::std::ostream* os) {
2406 *os << "when dynamic_cast to " << GetToName() << ", ";
2407 }
2408
2409 GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2410 };
2411
2412 // Primary template.
2413 // To is a pointer. Cast and forward the result.
2414 template <typename To>
2415 class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2416 public:
2417 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2418 : WhenDynamicCastToMatcherBase<To>(matcher) {}
2419
2420 template <typename From>
2421 bool MatchAndExplain(From from, MatchResultListener* listener) const {
2422 // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail?
2423 To to = dynamic_cast<To>(from);
2424 return MatchPrintAndExplain(to, this->matcher_, listener);
2425 }
2426 };
2427
2428 // Specialize for references.
2429 // In this case we return false if the dynamic_cast fails.
2430 template <typename To>
2431 class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2432 public:
2433 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2434 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2435
2436 template <typename From>
2437 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2438 // We don't want an std::bad_cast here, so do the cast with pointers.
2439 To* to = dynamic_cast<To*>(&from);
2440 if (to == NULL) {
2441 *listener << "which cannot be dynamic_cast to " << this->GetToName();
2442 return false;
2443 }
2444 return MatchPrintAndExplain(*to, this->matcher_, listener);
2445 }
2446 };
2447 #endif // GTEST_HAS_RTTI
2448
2449 // Implements the Field() matcher for matching a field (i.e. member
2450 // variable) of an object.
2451 template <typename Class, typename FieldType>
2452 class FieldMatcher {
2453 public:
2454 FieldMatcher(FieldType Class::*field,
2455 const Matcher<const FieldType&>& matcher)
2456 : field_(field), matcher_(matcher), whose_field_("whose given field ") {}
2457
2458 FieldMatcher(const std::string& field_name, FieldType Class::*field,
2459 const Matcher<const FieldType&>& matcher)
2460 : field_(field),
2461 matcher_(matcher),
2462 whose_field_("whose field `" + field_name + "` ") {}
2463
2464 void DescribeTo(::std::ostream* os) const {
2465 *os << "is an object " << whose_field_;
2466 matcher_.DescribeTo(os);
2467 }
2468
2469 void DescribeNegationTo(::std::ostream* os) const {
2470 *os << "is an object " << whose_field_;
2471 matcher_.DescribeNegationTo(os);
2472 }
2473
2474 template <typename T>
2475 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2476 return MatchAndExplainImpl(
2477 typename ::testing::internal::
2478 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
2479 value, listener);
2480 }
2481
2482 private:
2483 // The first argument of MatchAndExplainImpl() is needed to help
2484 // Symbian's C++ compiler choose which overload to use. Its type is
2485 // true_type iff the Field() matcher is used to match a pointer.
2486 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2487 MatchResultListener* listener) const {
2488 *listener << whose_field_ << "is ";
2489 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
2490 }
2491
2492 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2493 MatchResultListener* listener) const {
2494 if (p == NULL)
2495 return false;
2496
2497 *listener << "which points to an object ";
2498 // Since *p has a field, it must be a class/struct/union type and
2499 // thus cannot be a pointer. Therefore we pass false_type() as
2500 // the first argument.
2501 return MatchAndExplainImpl(false_type(), *p, listener);
2502 }
2503
2504 const FieldType Class::*field_;
2505 const Matcher<const FieldType&> matcher_;
2506
2507 // Contains either "whose given field " if the name of the field is unknown
2508 // or "whose field `name_of_field` " if the name is known.
2509 const std::string whose_field_;
2510
2511 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
2512 };
2513
2514 // Implements the Property() matcher for matching a property
2515 // (i.e. return value of a getter method) of an object.
2516 //
2517 // Property is a const-qualified member function of Class returning
2518 // PropertyType.
2519 template <typename Class, typename PropertyType, typename Property>
2520 class PropertyMatcher {
2521 public:
2522 // The property may have a reference type, so 'const PropertyType&'
2523 // may cause double references and fail to compile. That's why we
2524 // need GTEST_REFERENCE_TO_CONST, which works regardless of
2525 // PropertyType being a reference or not.
2526 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
2527
2528 PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)
2529 : property_(property),
2530 matcher_(matcher),
2531 whose_property_("whose given property ") {}
2532
2533 PropertyMatcher(const std::string& property_name, Property property,
2534 const Matcher<RefToConstProperty>& matcher)
2535 : property_(property),
2536 matcher_(matcher),
2537 whose_property_("whose property `" + property_name + "` ") {}
2538
2539 void DescribeTo(::std::ostream* os) const {
2540 *os << "is an object " << whose_property_;
2541 matcher_.DescribeTo(os);
2542 }
2543
2544 void DescribeNegationTo(::std::ostream* os) const {
2545 *os << "is an object " << whose_property_;
2546 matcher_.DescribeNegationTo(os);
2547 }
2548
2549 template <typename T>
2550 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2551 return MatchAndExplainImpl(
2552 typename ::testing::internal::
2553 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
2554 value, listener);
2555 }
2556
2557 private:
2558 // The first argument of MatchAndExplainImpl() is needed to help
2559 // Symbian's C++ compiler choose which overload to use. Its type is
2560 // true_type iff the Property() matcher is used to match a pointer.
2561 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2562 MatchResultListener* listener) const {
2563 *listener << whose_property_ << "is ";
2564 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2565 // which takes a non-const reference as argument.
2566 #if defined(_PREFAST_ ) && _MSC_VER == 1800
2567 // Workaround bug in VC++ 2013's /analyze parser.
2568 // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move
2569 posix::Abort(); // To make sure it is never run.
2570 return false;
2571 #else
2572 RefToConstProperty result = (obj.*property_)();
2573 return MatchPrintAndExplain(result, matcher_, listener);
2574 #endif
2575 }
2576
2577 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2578 MatchResultListener* listener) const {
2579 if (p == NULL)
2580 return false;
2581
2582 *listener << "which points to an object ";
2583 // Since *p has a property method, it must be a class/struct/union
2584 // type and thus cannot be a pointer. Therefore we pass
2585 // false_type() as the first argument.
2586 return MatchAndExplainImpl(false_type(), *p, listener);
2587 }
2588
2589 Property property_;
2590 const Matcher<RefToConstProperty> matcher_;
2591
2592 // Contains either "whose given property " if the name of the property is
2593 // unknown or "whose property `name_of_property` " if the name is known.
2594 const std::string whose_property_;
2595
2596 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
2597 };
2598
2599 // Type traits specifying various features of different functors for ResultOf.
2600 // The default template specifies features for functor objects.
2601 // Functor classes have to typedef argument_type and result_type
2602 // to be compatible with ResultOf.
2603 template <typename Functor>
2604 struct CallableTraits {
2605 typedef typename Functor::result_type ResultType;
2606 typedef Functor StorageType;
2607
2608 static void CheckIsValid(Functor /* functor */) {}
2609 template <typename T>
2610 static ResultType Invoke(Functor f, T arg) { return f(arg); }
2611 };
2612
2613 // Specialization for function pointers.
2614 template <typename ArgType, typename ResType>
2615 struct CallableTraits<ResType(*)(ArgType)> {
2616 typedef ResType ResultType;
2617 typedef ResType(*StorageType)(ArgType);
2618
2619 static void CheckIsValid(ResType(*f)(ArgType)) {
2620 GTEST_CHECK_(f != NULL)
2621 << "NULL function pointer is passed into ResultOf().";
2622 }
2623 template <typename T>
2624 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2625 return (*f)(arg);
2626 }
2627 };
2628
2629 // Implements the ResultOf() matcher for matching a return value of a
2630 // unary function of an object.
2631 template <typename Callable>
2632 class ResultOfMatcher {
2633 public:
2634 typedef typename CallableTraits<Callable>::ResultType ResultType;
2635
2636 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
2637 : callable_(callable), matcher_(matcher) {
2638 CallableTraits<Callable>::CheckIsValid(callable_);
2639 }
2640
2641 template <typename T>
2642 operator Matcher<T>() const {
2643 return Matcher<T>(new Impl<T>(callable_, matcher_));
2644 }
2645
2646 private:
2647 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2648
2649 template <typename T>
2650 class Impl : public MatcherInterface<T> {
2651 public:
2652 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
2653 : callable_(callable), matcher_(matcher) {}
2654
2655 virtual void DescribeTo(::std::ostream* os) const {
2656 *os << "is mapped by the given callable to a value that ";
2657 matcher_.DescribeTo(os);
2658 }
2659
2660 virtual void DescribeNegationTo(::std::ostream* os) const {
2661 *os << "is mapped by the given callable to a value that ";
2662 matcher_.DescribeNegationTo(os);
2663 }
2664
2665 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
2666 *listener << "which is mapped by the given callable to ";
2667 // Cannot pass the return value (for example, int) to
2668 // MatchPrintAndExplain, which takes a non-const reference as argument.
2669 ResultType result =
2670 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2671 return MatchPrintAndExplain(result, matcher_, listener);
2672 }
2673
2674 private:
2675 // Functors often define operator() as non-const method even though
2676 // they are actually stateless. But we need to use them even when
2677 // 'this' is a const pointer. It's the user's responsibility not to
2678 // use stateful callables with ResultOf(), which does't guarantee
2679 // how many times the callable will be invoked.
2680 mutable CallableStorageType callable_;
2681 const Matcher<ResultType> matcher_;
2682
2683 GTEST_DISALLOW_ASSIGN_(Impl);
2684 }; // class Impl
2685
2686 const CallableStorageType callable_;
2687 const Matcher<ResultType> matcher_;
2688
2689 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
2690 };
2691
2692 // Implements a matcher that checks the size of an STL-style container.
2693 template <typename SizeMatcher>
2694 class SizeIsMatcher {
2695 public:
2696 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2697 : size_matcher_(size_matcher) {
2698 }
2699
2700 template <typename Container>
2701 operator Matcher<Container>() const {
2702 return MakeMatcher(new Impl<Container>(size_matcher_));
2703 }
2704
2705 template <typename Container>
2706 class Impl : public MatcherInterface<Container> {
2707 public:
2708 typedef internal::StlContainerView<
2709 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2710 typedef typename ContainerView::type::size_type SizeType;
2711 explicit Impl(const SizeMatcher& size_matcher)
2712 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2713
2714 virtual void DescribeTo(::std::ostream* os) const {
2715 *os << "size ";
2716 size_matcher_.DescribeTo(os);
2717 }
2718 virtual void DescribeNegationTo(::std::ostream* os) const {
2719 *os << "size ";
2720 size_matcher_.DescribeNegationTo(os);
2721 }
2722
2723 virtual bool MatchAndExplain(Container container,
2724 MatchResultListener* listener) const {
2725 SizeType size = container.size();
2726 StringMatchResultListener size_listener;
2727 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2728 *listener
2729 << "whose size " << size << (result ? " matches" : " doesn't match");
2730 PrintIfNotEmpty(size_listener.str(), listener->stream());
2731 return result;
2732 }
2733
2734 private:
2735 const Matcher<SizeType> size_matcher_;
2736 GTEST_DISALLOW_ASSIGN_(Impl);
2737 };
2738
2739 private:
2740 const SizeMatcher size_matcher_;
2741 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2742 };
2743
2744 // Implements a matcher that checks the begin()..end() distance of an STL-style
2745 // container.
2746 template <typename DistanceMatcher>
2747 class BeginEndDistanceIsMatcher {
2748 public:
2749 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2750 : distance_matcher_(distance_matcher) {}
2751
2752 template <typename Container>
2753 operator Matcher<Container>() const {
2754 return MakeMatcher(new Impl<Container>(distance_matcher_));
2755 }
2756
2757 template <typename Container>
2758 class Impl : public MatcherInterface<Container> {
2759 public:
2760 typedef internal::StlContainerView<
2761 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2762 typedef typename std::iterator_traits<
2763 typename ContainerView::type::const_iterator>::difference_type
2764 DistanceType;
2765 explicit Impl(const DistanceMatcher& distance_matcher)
2766 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2767
2768 virtual void DescribeTo(::std::ostream* os) const {
2769 *os << "distance between begin() and end() ";
2770 distance_matcher_.DescribeTo(os);
2771 }
2772 virtual void DescribeNegationTo(::std::ostream* os) const {
2773 *os << "distance between begin() and end() ";
2774 distance_matcher_.DescribeNegationTo(os);
2775 }
2776
2777 virtual bool MatchAndExplain(Container container,
2778 MatchResultListener* listener) const {
2779 #if GTEST_HAS_STD_BEGIN_AND_END_
2780 using std::begin;
2781 using std::end;
2782 DistanceType distance = std::distance(begin(container), end(container));
2783 #else
2784 DistanceType distance = std::distance(container.begin(), container.end());
2785 #endif
2786 StringMatchResultListener distance_listener;
2787 const bool result =
2788 distance_matcher_.MatchAndExplain(distance, &distance_listener);
2789 *listener << "whose distance between begin() and end() " << distance
2790 << (result ? " matches" : " doesn't match");
2791 PrintIfNotEmpty(distance_listener.str(), listener->stream());
2792 return result;
2793 }
2794
2795 private:
2796 const Matcher<DistanceType> distance_matcher_;
2797 GTEST_DISALLOW_ASSIGN_(Impl);
2798 };
2799
2800 private:
2801 const DistanceMatcher distance_matcher_;
2802 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2803 };
2804
2805 // Implements an equality matcher for any STL-style container whose elements
2806 // support ==. This matcher is like Eq(), but its failure explanations provide
2807 // more detailed information that is useful when the container is used as a set.
2808 // The failure message reports elements that are in one of the operands but not
2809 // the other. The failure messages do not report duplicate or out-of-order
2810 // elements in the containers (which don't properly matter to sets, but can
2811 // occur if the containers are vectors or lists, for example).
2812 //
2813 // Uses the container's const_iterator, value_type, operator ==,
2814 // begin(), and end().
2815 template <typename Container>
2816 class ContainerEqMatcher {
2817 public:
2818 typedef internal::StlContainerView<Container> View;
2819 typedef typename View::type StlContainer;
2820 typedef typename View::const_reference StlContainerReference;
2821
2822 // We make a copy of expected in case the elements in it are modified
2823 // after this matcher is created.
2824 explicit ContainerEqMatcher(const Container& expected)
2825 : expected_(View::Copy(expected)) {
2826 // Makes sure the user doesn't instantiate this class template
2827 // with a const or reference type.
2828 (void)testing::StaticAssertTypeEq<Container,
2829 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
2830 }
2831
2832 void DescribeTo(::std::ostream* os) const {
2833 *os << "equals ";
2834 UniversalPrint(expected_, os);
2835 }
2836 void DescribeNegationTo(::std::ostream* os) const {
2837 *os << "does not equal ";
2838 UniversalPrint(expected_, os);
2839 }
2840
2841 template <typename LhsContainer>
2842 bool MatchAndExplain(const LhsContainer& lhs,
2843 MatchResultListener* listener) const {
2844 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
2845 // that causes LhsContainer to be a const type sometimes.
2846 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
2847 LhsView;
2848 typedef typename LhsView::type LhsStlContainer;
2849 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2850 if (lhs_stl_container == expected_)
2851 return true;
2852
2853 ::std::ostream* const os = listener->stream();
2854 if (os != NULL) {
2855 // Something is different. Check for extra values first.
2856 bool printed_header = false;
2857 for (typename LhsStlContainer::const_iterator it =
2858 lhs_stl_container.begin();
2859 it != lhs_stl_container.end(); ++it) {
2860 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
2861 expected_.end()) {
2862 if (printed_header) {
2863 *os << ", ";
2864 } else {
2865 *os << "which has these unexpected elements: ";
2866 printed_header = true;
2867 }
2868 UniversalPrint(*it, os);
2869 }
2870 }
2871
2872 // Now check for missing values.
2873 bool printed_header2 = false;
2874 for (typename StlContainer::const_iterator it = expected_.begin();
2875 it != expected_.end(); ++it) {
2876 if (internal::ArrayAwareFind(
2877 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2878 lhs_stl_container.end()) {
2879 if (printed_header2) {
2880 *os << ", ";
2881 } else {
2882 *os << (printed_header ? ",\nand" : "which")
2883 << " doesn't have these expected elements: ";
2884 printed_header2 = true;
2885 }
2886 UniversalPrint(*it, os);
2887 }
2888 }
2889 }
2890
2891 return false;
2892 }
2893
2894 private:
2895 const StlContainer expected_;
2896
2897 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
2898 };
2899
2900 // A comparator functor that uses the < operator to compare two values.
2901 struct LessComparator {
2902 template <typename T, typename U>
2903 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2904 };
2905
2906 // Implements WhenSortedBy(comparator, container_matcher).
2907 template <typename Comparator, typename ContainerMatcher>
2908 class WhenSortedByMatcher {
2909 public:
2910 WhenSortedByMatcher(const Comparator& comparator,
2911 const ContainerMatcher& matcher)
2912 : comparator_(comparator), matcher_(matcher) {}
2913
2914 template <typename LhsContainer>
2915 operator Matcher<LhsContainer>() const {
2916 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2917 }
2918
2919 template <typename LhsContainer>
2920 class Impl : public MatcherInterface<LhsContainer> {
2921 public:
2922 typedef internal::StlContainerView<
2923 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2924 typedef typename LhsView::type LhsStlContainer;
2925 typedef typename LhsView::const_reference LhsStlContainerReference;
2926 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2927 // so that we can match associative containers.
2928 typedef typename RemoveConstFromKey<
2929 typename LhsStlContainer::value_type>::type LhsValue;
2930
2931 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2932 : comparator_(comparator), matcher_(matcher) {}
2933
2934 virtual void DescribeTo(::std::ostream* os) const {
2935 *os << "(when sorted) ";
2936 matcher_.DescribeTo(os);
2937 }
2938
2939 virtual void DescribeNegationTo(::std::ostream* os) const {
2940 *os << "(when sorted) ";
2941 matcher_.DescribeNegationTo(os);
2942 }
2943
2944 virtual bool MatchAndExplain(LhsContainer lhs,
2945 MatchResultListener* listener) const {
2946 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2947 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2948 lhs_stl_container.end());
2949 ::std::sort(
2950 sorted_container.begin(), sorted_container.end(), comparator_);
2951
2952 if (!listener->IsInterested()) {
2953 // If the listener is not interested, we do not need to
2954 // construct the inner explanation.
2955 return matcher_.Matches(sorted_container);
2956 }
2957
2958 *listener << "which is ";
2959 UniversalPrint(sorted_container, listener->stream());
2960 *listener << " when sorted";
2961
2962 StringMatchResultListener inner_listener;
2963 const bool match = matcher_.MatchAndExplain(sorted_container,
2964 &inner_listener);
2965 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2966 return match;
2967 }
2968
2969 private:
2970 const Comparator comparator_;
2971 const Matcher<const ::std::vector<LhsValue>&> matcher_;
2972
2973 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2974 };
2975
2976 private:
2977 const Comparator comparator_;
2978 const ContainerMatcher matcher_;
2979
2980 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2981 };
2982
2983 // Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2984 // must be able to be safely cast to Matcher<tuple<const T1&, const
2985 // T2&> >, where T1 and T2 are the types of elements in the LHS
2986 // container and the RHS container respectively.
2987 template <typename TupleMatcher, typename RhsContainer>
2988 class PointwiseMatcher {
2989 GTEST_COMPILE_ASSERT_(
2990 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value,
2991 use_UnorderedPointwise_with_hash_tables);
2992
2993 public:
2994 typedef internal::StlContainerView<RhsContainer> RhsView;
2995 typedef typename RhsView::type RhsStlContainer;
2996 typedef typename RhsStlContainer::value_type RhsValue;
2997
2998 // Like ContainerEq, we make a copy of rhs in case the elements in
2999 // it are modified after this matcher is created.
3000 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
3001 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
3002 // Makes sure the user doesn't instantiate this class template
3003 // with a const or reference type.
3004 (void)testing::StaticAssertTypeEq<RhsContainer,
3005 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
3006 }
3007
3008 template <typename LhsContainer>
3009 operator Matcher<LhsContainer>() const {
3010 GTEST_COMPILE_ASSERT_(
3011 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value,
3012 use_UnorderedPointwise_with_hash_tables);
3013
3014 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
3015 }
3016
3017 template <typename LhsContainer>
3018 class Impl : public MatcherInterface<LhsContainer> {
3019 public:
3020 typedef internal::StlContainerView<
3021 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
3022 typedef typename LhsView::type LhsStlContainer;
3023 typedef typename LhsView::const_reference LhsStlContainerReference;
3024 typedef typename LhsStlContainer::value_type LhsValue;
3025 // We pass the LHS value and the RHS value to the inner matcher by
3026 // reference, as they may be expensive to copy. We must use tuple
3027 // instead of pair here, as a pair cannot hold references (C++ 98,
3028 // 20.2.2 [lib.pairs]).
3029 typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
3030
3031 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
3032 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
3033 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
3034 rhs_(rhs) {}
3035
3036 virtual void DescribeTo(::std::ostream* os) const {
3037 *os << "contains " << rhs_.size()
3038 << " values, where each value and its corresponding value in ";
3039 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
3040 *os << " ";
3041 mono_tuple_matcher_.DescribeTo(os);
3042 }
3043 virtual void DescribeNegationTo(::std::ostream* os) const {
3044 *os << "doesn't contain exactly " << rhs_.size()
3045 << " values, or contains a value x at some index i"
3046 << " where x and the i-th value of ";
3047 UniversalPrint(rhs_, os);
3048 *os << " ";
3049 mono_tuple_matcher_.DescribeNegationTo(os);
3050 }
3051
3052 virtual bool MatchAndExplain(LhsContainer lhs,
3053 MatchResultListener* listener) const {
3054 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
3055 const size_t actual_size = lhs_stl_container.size();
3056 if (actual_size != rhs_.size()) {
3057 *listener << "which contains " << actual_size << " values";
3058 return false;
3059 }
3060
3061 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
3062 typename RhsStlContainer::const_iterator right = rhs_.begin();
3063 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
3064 if (listener->IsInterested()) {
3065 StringMatchResultListener inner_listener;
3066 // Create InnerMatcherArg as a temporarily object to avoid it outlives
3067 // *left and *right. Dereference or the conversion to `const T&` may
3068 // return temp objects, e.g for vector<bool>.
3069 if (!mono_tuple_matcher_.MatchAndExplain(
3070 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
3071 ImplicitCast_<const RhsValue&>(*right)),
3072 &inner_listener)) {
3073 *listener << "where the value pair (";
3074 UniversalPrint(*left, listener->stream());
3075 *listener << ", ";
3076 UniversalPrint(*right, listener->stream());
3077 *listener << ") at index #" << i << " don't match";
3078 PrintIfNotEmpty(inner_listener.str(), listener->stream());
3079 return false;
3080 }
3081 } else {
3082 if (!mono_tuple_matcher_.Matches(
3083 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
3084 ImplicitCast_<const RhsValue&>(*right))))
3085 return false;
3086 }
3087 }
3088
3089 return true;
3090 }
3091
3092 private:
3093 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
3094 const RhsStlContainer rhs_;
3095
3096 GTEST_DISALLOW_ASSIGN_(Impl);
3097 };
3098
3099 private:
3100 const TupleMatcher tuple_matcher_;
3101 const RhsStlContainer rhs_;
3102
3103 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
3104 };
3105
3106 // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
3107 template <typename Container>
3108 class QuantifierMatcherImpl : public MatcherInterface<Container> {
3109 public:
3110 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3111 typedef StlContainerView<RawContainer> View;
3112 typedef typename View::type StlContainer;
3113 typedef typename View::const_reference StlContainerReference;
3114 typedef typename StlContainer::value_type Element;
3115
3116 template <typename InnerMatcher>
3117 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
3118 : inner_matcher_(
3119 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
3120
3121 // Checks whether:
3122 // * All elements in the container match, if all_elements_should_match.
3123 // * Any element in the container matches, if !all_elements_should_match.
3124 bool MatchAndExplainImpl(bool all_elements_should_match,
3125 Container container,
3126 MatchResultListener* listener) const {
3127 StlContainerReference stl_container = View::ConstReference(container);
3128 size_t i = 0;
3129 for (typename StlContainer::const_iterator it = stl_container.begin();
3130 it != stl_container.end(); ++it, ++i) {
3131 StringMatchResultListener inner_listener;
3132 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
3133
3134 if (matches != all_elements_should_match) {
3135 *listener << "whose element #" << i
3136 << (matches ? " matches" : " doesn't match");
3137 PrintIfNotEmpty(inner_listener.str(), listener->stream());
3138 return !all_elements_should_match;
3139 }
3140 }
3141 return all_elements_should_match;
3142 }
3143
3144 protected:
3145 const Matcher<const Element&> inner_matcher_;
3146
3147 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
3148 };
3149
3150 // Implements Contains(element_matcher) for the given argument type Container.
3151 // Symmetric to EachMatcherImpl.
3152 template <typename Container>
3153 class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
3154 public:
3155 template <typename InnerMatcher>
3156 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
3157 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3158
3159 // Describes what this matcher does.
3160 virtual void DescribeTo(::std::ostream* os) const {
3161 *os << "contains at least one element that ";
3162 this->inner_matcher_.DescribeTo(os);
3163 }
3164
3165 virtual void DescribeNegationTo(::std::ostream* os) const {
3166 *os << "doesn't contain any element that ";
3167 this->inner_matcher_.DescribeTo(os);
3168 }
3169
3170 virtual bool MatchAndExplain(Container container,
3171 MatchResultListener* listener) const {
3172 return this->MatchAndExplainImpl(false, container, listener);
3173 }
3174
3175 private:
3176 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
3177 };
3178
3179 // Implements Each(element_matcher) for the given argument type Container.
3180 // Symmetric to ContainsMatcherImpl.
3181 template <typename Container>
3182 class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
3183 public:
3184 template <typename InnerMatcher>
3185 explicit EachMatcherImpl(InnerMatcher inner_matcher)
3186 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3187
3188 // Describes what this matcher does.
3189 virtual void DescribeTo(::std::ostream* os) const {
3190 *os << "only contains elements that ";
3191 this->inner_matcher_.DescribeTo(os);
3192 }
3193
3194 virtual void DescribeNegationTo(::std::ostream* os) const {
3195 *os << "contains some element that ";
3196 this->inner_matcher_.DescribeNegationTo(os);
3197 }
3198
3199 virtual bool MatchAndExplain(Container container,
3200 MatchResultListener* listener) const {
3201 return this->MatchAndExplainImpl(true, container, listener);
3202 }
3203
3204 private:
3205 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
3206 };
3207
3208 // Implements polymorphic Contains(element_matcher).
3209 template <typename M>
3210 class ContainsMatcher {
3211 public:
3212 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
3213
3214 template <typename Container>
3215 operator Matcher<Container>() const {
3216 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
3217 }
3218
3219 private:
3220 const M inner_matcher_;
3221
3222 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
3223 };
3224
3225 // Implements polymorphic Each(element_matcher).
3226 template <typename M>
3227 class EachMatcher {
3228 public:
3229 explicit EachMatcher(M m) : inner_matcher_(m) {}
3230
3231 template <typename Container>
3232 operator Matcher<Container>() const {
3233 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
3234 }
3235
3236 private:
3237 const M inner_matcher_;
3238
3239 GTEST_DISALLOW_ASSIGN_(EachMatcher);
3240 };
3241
3242 struct Rank1 {};
3243 struct Rank0 : Rank1 {};
3244
3245 namespace pair_getters {
3246 #if GTEST_LANG_CXX11
3247 using std::get;
3248 template <typename T>
3249 auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT
3250 return get<0>(x);
3251 }
3252 template <typename T>
3253 auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT
3254 return x.first;
3255 }
3256
3257 template <typename T>
3258 auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT
3259 return get<1>(x);
3260 }
3261 template <typename T>
3262 auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT
3263 return x.second;
3264 }
3265 #else
3266 template <typename T>
3267 typename T::first_type& First(T& x, Rank0) { // NOLINT
3268 return x.first;
3269 }
3270 template <typename T>
3271 const typename T::first_type& First(const T& x, Rank0) {
3272 return x.first;
3273 }
3274
3275 template <typename T>
3276 typename T::second_type& Second(T& x, Rank0) { // NOLINT
3277 return x.second;
3278 }
3279 template <typename T>
3280 const typename T::second_type& Second(const T& x, Rank0) {
3281 return x.second;
3282 }
3283 #endif // GTEST_LANG_CXX11
3284 } // namespace pair_getters
3285
3286 // Implements Key(inner_matcher) for the given argument pair type.
3287 // Key(inner_matcher) matches an std::pair whose 'first' field matches
3288 // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3289 // std::map that contains at least one element whose key is >= 5.
3290 template <typename PairType>
3291 class KeyMatcherImpl : public MatcherInterface<PairType> {
3292 public:
3293 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
3294 typedef typename RawPairType::first_type KeyType;
3295
3296 template <typename InnerMatcher>
3297 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
3298 : inner_matcher_(
3299 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
3300 }
3301
3302 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
3303 virtual bool MatchAndExplain(PairType key_value,
3304 MatchResultListener* listener) const {
3305 StringMatchResultListener inner_listener;
3306 const bool match = inner_matcher_.MatchAndExplain(
3307 pair_getters::First(key_value, Rank0()), &inner_listener);
3308 const std::string explanation = inner_listener.str();
3309 if (explanation != "") {
3310 *listener << "whose first field is a value " << explanation;
3311 }
3312 return match;
3313 }
3314
3315 // Describes what this matcher does.
3316 virtual void DescribeTo(::std::ostream* os) const {
3317 *os << "has a key that ";
3318 inner_matcher_.DescribeTo(os);
3319 }
3320
3321 // Describes what the negation of this matcher does.
3322 virtual void DescribeNegationTo(::std::ostream* os) const {
3323 *os << "doesn't have a key that ";
3324 inner_matcher_.DescribeTo(os);
3325 }
3326
3327 private:
3328 const Matcher<const KeyType&> inner_matcher_;
3329
3330 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
3331 };
3332
3333 // Implements polymorphic Key(matcher_for_key).
3334 template <typename M>
3335 class KeyMatcher {
3336 public:
3337 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
3338
3339 template <typename PairType>
3340 operator Matcher<PairType>() const {
3341 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
3342 }
3343
3344 private:
3345 const M matcher_for_key_;
3346
3347 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
3348 };
3349
3350 // Implements Pair(first_matcher, second_matcher) for the given argument pair
3351 // type with its two matchers. See Pair() function below.
3352 template <typename PairType>
3353 class PairMatcherImpl : public MatcherInterface<PairType> {
3354 public:
3355 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
3356 typedef typename RawPairType::first_type FirstType;
3357 typedef typename RawPairType::second_type SecondType;
3358
3359 template <typename FirstMatcher, typename SecondMatcher>
3360 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
3361 : first_matcher_(
3362 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
3363 second_matcher_(
3364 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
3365 }
3366
3367 // Describes what this matcher does.
3368 virtual void DescribeTo(::std::ostream* os) const {
3369 *os << "has a first field that ";
3370 first_matcher_.DescribeTo(os);
3371 *os << ", and has a second field that ";
3372 second_matcher_.DescribeTo(os);
3373 }
3374
3375 // Describes what the negation of this matcher does.
3376 virtual void DescribeNegationTo(::std::ostream* os) const {
3377 *os << "has a first field that ";
3378 first_matcher_.DescribeNegationTo(os);
3379 *os << ", or has a second field that ";
3380 second_matcher_.DescribeNegationTo(os);
3381 }
3382
3383 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3384 // matches second_matcher.
3385 virtual bool MatchAndExplain(PairType a_pair,
3386 MatchResultListener* listener) const {
3387 if (!listener->IsInterested()) {
3388 // If the listener is not interested, we don't need to construct the
3389 // explanation.
3390 return first_matcher_.Matches(pair_getters::First(a_pair, Rank0())) &&
3391 second_matcher_.Matches(pair_getters::Second(a_pair, Rank0()));
3392 }
3393 StringMatchResultListener first_inner_listener;
3394 if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank0()),
3395 &first_inner_listener)) {
3396 *listener << "whose first field does not match";
3397 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
3398 return false;
3399 }
3400 StringMatchResultListener second_inner_listener;
3401 if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank0()),
3402 &second_inner_listener)) {
3403 *listener << "whose second field does not match";
3404 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
3405 return false;
3406 }
3407 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3408 listener);
3409 return true;
3410 }
3411
3412 private:
3413 void ExplainSuccess(const std::string& first_explanation,
3414 const std::string& second_explanation,
3415 MatchResultListener* listener) const {
3416 *listener << "whose both fields match";
3417 if (first_explanation != "") {
3418 *listener << ", where the first field is a value " << first_explanation;
3419 }
3420 if (second_explanation != "") {
3421 *listener << ", ";
3422 if (first_explanation != "") {
3423 *listener << "and ";
3424 } else {
3425 *listener << "where ";
3426 }
3427 *listener << "the second field is a value " << second_explanation;
3428 }
3429 }
3430
3431 const Matcher<const FirstType&> first_matcher_;
3432 const Matcher<const SecondType&> second_matcher_;
3433
3434 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
3435 };
3436
3437 // Implements polymorphic Pair(first_matcher, second_matcher).
3438 template <typename FirstMatcher, typename SecondMatcher>
3439 class PairMatcher {
3440 public:
3441 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3442 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3443
3444 template <typename PairType>
3445 operator Matcher<PairType> () const {
3446 return MakeMatcher(
3447 new PairMatcherImpl<PairType>(
3448 first_matcher_, second_matcher_));
3449 }
3450
3451 private:
3452 const FirstMatcher first_matcher_;
3453 const SecondMatcher second_matcher_;
3454
3455 GTEST_DISALLOW_ASSIGN_(PairMatcher);
3456 };
3457
3458 // Implements ElementsAre() and ElementsAreArray().
3459 template <typename Container>
3460 class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3461 public:
3462 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3463 typedef internal::StlContainerView<RawContainer> View;
3464 typedef typename View::type StlContainer;
3465 typedef typename View::const_reference StlContainerReference;
3466 typedef typename StlContainer::value_type Element;
3467
3468 // Constructs the matcher from a sequence of element values or
3469 // element matchers.
3470 template <typename InputIter>
3471 ElementsAreMatcherImpl(InputIter first, InputIter last) {
3472 while (first != last) {
3473 matchers_.push_back(MatcherCast<const Element&>(*first++));
3474 }
3475 }
3476
3477 // Describes what this matcher does.
3478 virtual void DescribeTo(::std::ostream* os) const {
3479 if (count() == 0) {
3480 *os << "is empty";
3481 } else if (count() == 1) {
3482 *os << "has 1 element that ";
3483 matchers_[0].DescribeTo(os);
3484 } else {
3485 *os << "has " << Elements(count()) << " where\n";
3486 for (size_t i = 0; i != count(); ++i) {
3487 *os << "element #" << i << " ";
3488 matchers_[i].DescribeTo(os);
3489 if (i + 1 < count()) {
3490 *os << ",\n";
3491 }
3492 }
3493 }
3494 }
3495
3496 // Describes what the negation of this matcher does.
3497 virtual void DescribeNegationTo(::std::ostream* os) const {
3498 if (count() == 0) {
3499 *os << "isn't empty";
3500 return;
3501 }
3502
3503 *os << "doesn't have " << Elements(count()) << ", or\n";
3504 for (size_t i = 0; i != count(); ++i) {
3505 *os << "element #" << i << " ";
3506 matchers_[i].DescribeNegationTo(os);
3507 if (i + 1 < count()) {
3508 *os << ", or\n";
3509 }
3510 }
3511 }
3512
3513 virtual bool MatchAndExplain(Container container,
3514 MatchResultListener* listener) const {
3515 // To work with stream-like "containers", we must only walk
3516 // through the elements in one pass.
3517
3518 const bool listener_interested = listener->IsInterested();
3519
3520 // explanations[i] is the explanation of the element at index i.
3521 ::std::vector<std::string> explanations(count());
3522 StlContainerReference stl_container = View::ConstReference(container);
3523 typename StlContainer::const_iterator it = stl_container.begin();
3524 size_t exam_pos = 0;
3525 bool mismatch_found = false; // Have we found a mismatched element yet?
3526
3527 // Go through the elements and matchers in pairs, until we reach
3528 // the end of either the elements or the matchers, or until we find a
3529 // mismatch.
3530 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3531 bool match; // Does the current element match the current matcher?
3532 if (listener_interested) {
3533 StringMatchResultListener s;
3534 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3535 explanations[exam_pos] = s.str();
3536 } else {
3537 match = matchers_[exam_pos].Matches(*it);
3538 }
3539
3540 if (!match) {
3541 mismatch_found = true;
3542 break;
3543 }
3544 }
3545 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3546
3547 // Find how many elements the actual container has. We avoid
3548 // calling size() s.t. this code works for stream-like "containers"
3549 // that don't define size().
3550 size_t actual_count = exam_pos;
3551 for (; it != stl_container.end(); ++it) {
3552 ++actual_count;
3553 }
3554
3555 if (actual_count != count()) {
3556 // The element count doesn't match. If the container is empty,
3557 // there's no need to explain anything as Google Mock already
3558 // prints the empty container. Otherwise we just need to show
3559 // how many elements there actually are.
3560 if (listener_interested && (actual_count != 0)) {
3561 *listener << "which has " << Elements(actual_count);
3562 }
3563 return false;
3564 }
3565
3566 if (mismatch_found) {
3567 // The element count matches, but the exam_pos-th element doesn't match.
3568 if (listener_interested) {
3569 *listener << "whose element #" << exam_pos << " doesn't match";
3570 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
3571 }
3572 return false;
3573 }
3574
3575 // Every element matches its expectation. We need to explain why
3576 // (the obvious ones can be skipped).
3577 if (listener_interested) {
3578 bool reason_printed = false;
3579 for (size_t i = 0; i != count(); ++i) {
3580 const std::string& s = explanations[i];
3581 if (!s.empty()) {
3582 if (reason_printed) {
3583 *listener << ",\nand ";
3584 }
3585 *listener << "whose element #" << i << " matches, " << s;
3586 reason_printed = true;
3587 }
3588 }
3589 }
3590 return true;
3591 }
3592
3593 private:
3594 static Message Elements(size_t count) {
3595 return Message() << count << (count == 1 ? " element" : " elements");
3596 }
3597
3598 size_t count() const { return matchers_.size(); }
3599
3600 ::std::vector<Matcher<const Element&> > matchers_;
3601
3602 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
3603 };
3604
3605 // Connectivity matrix of (elements X matchers), in element-major order.
3606 // Initially, there are no edges.
3607 // Use NextGraph() to iterate over all possible edge configurations.
3608 // Use Randomize() to generate a random edge configuration.
3609 class GTEST_API_ MatchMatrix {
3610 public:
3611 MatchMatrix(size_t num_elements, size_t num_matchers)
3612 : num_elements_(num_elements),
3613 num_matchers_(num_matchers),
3614 matched_(num_elements_* num_matchers_, 0) {
3615 }
3616
3617 size_t LhsSize() const { return num_elements_; }
3618 size_t RhsSize() const { return num_matchers_; }
3619 bool HasEdge(size_t ilhs, size_t irhs) const {
3620 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3621 }
3622 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3623 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3624 }
3625
3626 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3627 // adds 1 to that number; returns false if incrementing the graph left it
3628 // empty.
3629 bool NextGraph();
3630
3631 void Randomize();
3632
3633 std::string DebugString() const;
3634
3635 private:
3636 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3637 return ilhs * num_matchers_ + irhs;
3638 }
3639
3640 size_t num_elements_;
3641 size_t num_matchers_;
3642
3643 // Each element is a char interpreted as bool. They are stored as a
3644 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3645 // a (ilhs, irhs) matrix coordinate into an offset.
3646 ::std::vector<char> matched_;
3647 };
3648
3649 typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3650 typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3651
3652 // Returns a maximum bipartite matching for the specified graph 'g'.
3653 // The matching is represented as a vector of {element, matcher} pairs.
3654 GTEST_API_ ElementMatcherPairs
3655 FindMaxBipartiteMatching(const MatchMatrix& g);
3656
3657 struct UnorderedMatcherRequire {
3658 enum Flags {
3659 Superset = 1 << 0,
3660 Subset = 1 << 1,
3661 ExactMatch = Superset | Subset,
3662 };
3663 };
3664
3665 // Untyped base class for implementing UnorderedElementsAre. By
3666 // putting logic that's not specific to the element type here, we
3667 // reduce binary bloat and increase compilation speed.
3668 class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3669 protected:
3670 explicit UnorderedElementsAreMatcherImplBase(
3671 UnorderedMatcherRequire::Flags matcher_flags)
3672 : match_flags_(matcher_flags) {}
3673
3674 // A vector of matcher describers, one for each element matcher.
3675 // Does not own the describers (and thus can be used only when the
3676 // element matchers are alive).
3677 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3678
3679 // Describes this UnorderedElementsAre matcher.
3680 void DescribeToImpl(::std::ostream* os) const;
3681
3682 // Describes the negation of this UnorderedElementsAre matcher.
3683 void DescribeNegationToImpl(::std::ostream* os) const;
3684
3685 bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,
3686 const MatchMatrix& matrix,
3687 MatchResultListener* listener) const;
3688
3689 bool FindPairing(const MatchMatrix& matrix,
3690 MatchResultListener* listener) const;
3691
3692 MatcherDescriberVec& matcher_describers() {
3693 return matcher_describers_;
3694 }
3695
3696 static Message Elements(size_t n) {
3697 return Message() << n << " element" << (n == 1 ? "" : "s");
3698 }
3699
3700 UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }
3701
3702 private:
3703 UnorderedMatcherRequire::Flags match_flags_;
3704 MatcherDescriberVec matcher_describers_;
3705
3706 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3707 };
3708
3709 // Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
3710 // IsSupersetOf.
3711 template <typename Container>
3712 class UnorderedElementsAreMatcherImpl
3713 : public MatcherInterface<Container>,
3714 public UnorderedElementsAreMatcherImplBase {
3715 public:
3716 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3717 typedef internal::StlContainerView<RawContainer> View;
3718 typedef typename View::type StlContainer;
3719 typedef typename View::const_reference StlContainerReference;
3720 typedef typename StlContainer::const_iterator StlContainerConstIterator;
3721 typedef typename StlContainer::value_type Element;
3722
3723 template <typename InputIter>
3724 UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,
3725 InputIter first, InputIter last)
3726 : UnorderedElementsAreMatcherImplBase(matcher_flags) {
3727 for (; first != last; ++first) {
3728 matchers_.push_back(MatcherCast<const Element&>(*first));
3729 matcher_describers().push_back(matchers_.back().GetDescriber());
3730 }
3731 }
3732
3733 // Describes what this matcher does.
3734 virtual void DescribeTo(::std::ostream* os) const {
3735 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3736 }
3737
3738 // Describes what the negation of this matcher does.
3739 virtual void DescribeNegationTo(::std::ostream* os) const {
3740 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3741 }
3742
3743 virtual bool MatchAndExplain(Container container,
3744 MatchResultListener* listener) const {
3745 StlContainerReference stl_container = View::ConstReference(container);
3746 ::std::vector<std::string> element_printouts;
3747 MatchMatrix matrix =
3748 AnalyzeElements(stl_container.begin(), stl_container.end(),
3749 &element_printouts, listener);
3750
3751 if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
3752 return true;
3753 }
3754
3755 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
3756 if (matrix.LhsSize() != matrix.RhsSize()) {
3757 // The element count doesn't match. If the container is empty,
3758 // there's no need to explain anything as Google Mock already
3759 // prints the empty container. Otherwise we just need to show
3760 // how many elements there actually are.
3761 if (matrix.LhsSize() != 0 && listener->IsInterested()) {
3762 *listener << "which has " << Elements(matrix.LhsSize());
3763 }
3764 return false;
3765 }
3766 }
3767
3768 return VerifyMatchMatrix(element_printouts, matrix, listener) &&
3769 FindPairing(matrix, listener);
3770 }
3771
3772 private:
3773 template <typename ElementIter>
3774 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
3775 ::std::vector<std::string>* element_printouts,
3776 MatchResultListener* listener) const {
3777 element_printouts->clear();
3778 ::std::vector<char> did_match;
3779 size_t num_elements = 0;
3780 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3781 if (listener->IsInterested()) {
3782 element_printouts->push_back(PrintToString(*elem_first));
3783 }
3784 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3785 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3786 }
3787 }
3788
3789 MatchMatrix matrix(num_elements, matchers_.size());
3790 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3791 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3792 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3793 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3794 }
3795 }
3796 return matrix;
3797 }
3798
3799 ::std::vector<Matcher<const Element&> > matchers_;
3800
3801 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3802 };
3803
3804 // Functor for use in TransformTuple.
3805 // Performs MatcherCast<Target> on an input argument of any type.
3806 template <typename Target>
3807 struct CastAndAppendTransform {
3808 template <typename Arg>
3809 Matcher<Target> operator()(const Arg& a) const {
3810 return MatcherCast<Target>(a);
3811 }
3812 };
3813
3814 // Implements UnorderedElementsAre.
3815 template <typename MatcherTuple>
3816 class UnorderedElementsAreMatcher {
3817 public:
3818 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3819 : matchers_(args) {}
3820
3821 template <typename Container>
3822 operator Matcher<Container>() const {
3823 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3824 typedef typename internal::StlContainerView<RawContainer>::type View;
3825 typedef typename View::value_type Element;
3826 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3827 MatcherVec matchers;
3828 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
3829 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3830 ::std::back_inserter(matchers));
3831 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3832 UnorderedMatcherRequire::ExactMatch, matchers.begin(), matchers.end()));
3833 }
3834
3835 private:
3836 const MatcherTuple matchers_;
3837 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3838 };
3839
3840 // Implements ElementsAre.
3841 template <typename MatcherTuple>
3842 class ElementsAreMatcher {
3843 public:
3844 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3845
3846 template <typename Container>
3847 operator Matcher<Container>() const {
3848 GTEST_COMPILE_ASSERT_(
3849 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value ||
3850 ::testing::tuple_size<MatcherTuple>::value < 2,
3851 use_UnorderedElementsAre_with_hash_tables);
3852
3853 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3854 typedef typename internal::StlContainerView<RawContainer>::type View;
3855 typedef typename View::value_type Element;
3856 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3857 MatcherVec matchers;
3858 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
3859 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3860 ::std::back_inserter(matchers));
3861 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3862 matchers.begin(), matchers.end()));
3863 }
3864
3865 private:
3866 const MatcherTuple matchers_;
3867 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3868 };
3869
3870 // Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
3871 template <typename T>
3872 class UnorderedElementsAreArrayMatcher {
3873 public:
3874 template <typename Iter>
3875 UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,
3876 Iter first, Iter last)
3877 : match_flags_(match_flags), matchers_(first, last) {}
3878
3879 template <typename Container>
3880 operator Matcher<Container>() const {
3881 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3882 match_flags_, matchers_.begin(), matchers_.end()));
3883 }
3884
3885 private:
3886 UnorderedMatcherRequire::Flags match_flags_;
3887 ::std::vector<T> matchers_;
3888
3889 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
3890 };
3891
3892 // Implements ElementsAreArray().
3893 template <typename T>
3894 class ElementsAreArrayMatcher {
3895 public:
3896 template <typename Iter>
3897 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
3898
3899 template <typename Container>
3900 operator Matcher<Container>() const {
3901 GTEST_COMPILE_ASSERT_(
3902 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value,
3903 use_UnorderedElementsAreArray_with_hash_tables);
3904
3905 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3906 matchers_.begin(), matchers_.end()));
3907 }
3908
3909 private:
3910 const ::std::vector<T> matchers_;
3911
3912 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
3913 };
3914
3915 // Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3916 // of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3917 // second) is a polymorphic matcher that matches a value x iff tm
3918 // matches tuple (x, second). Useful for implementing
3919 // UnorderedPointwise() in terms of UnorderedElementsAreArray().
3920 //
3921 // BoundSecondMatcher is copyable and assignable, as we need to put
3922 // instances of this class in a vector when implementing
3923 // UnorderedPointwise().
3924 template <typename Tuple2Matcher, typename Second>
3925 class BoundSecondMatcher {
3926 public:
3927 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3928 : tuple2_matcher_(tm), second_value_(second) {}
3929
3930 template <typename T>
3931 operator Matcher<T>() const {
3932 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3933 }
3934
3935 // We have to define this for UnorderedPointwise() to compile in
3936 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3937 // which requires the elements to be assignable in C++98. The
3938 // compiler cannot generate the operator= for us, as Tuple2Matcher
3939 // and Second may not be assignable.
3940 //
3941 // However, this should never be called, so the implementation just
3942 // need to assert.
3943 void operator=(const BoundSecondMatcher& /*rhs*/) {
3944 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3945 }
3946
3947 private:
3948 template <typename T>
3949 class Impl : public MatcherInterface<T> {
3950 public:
3951 typedef ::testing::tuple<T, Second> ArgTuple;
3952
3953 Impl(const Tuple2Matcher& tm, const Second& second)
3954 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3955 second_value_(second) {}
3956
3957 virtual void DescribeTo(::std::ostream* os) const {
3958 *os << "and ";
3959 UniversalPrint(second_value_, os);
3960 *os << " ";
3961 mono_tuple2_matcher_.DescribeTo(os);
3962 }
3963
3964 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3965 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3966 listener);
3967 }
3968
3969 private:
3970 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3971 const Second second_value_;
3972
3973 GTEST_DISALLOW_ASSIGN_(Impl);
3974 };
3975
3976 const Tuple2Matcher tuple2_matcher_;
3977 const Second second_value_;
3978 };
3979
3980 // Given a 2-tuple matcher tm and a value second,
3981 // MatcherBindSecond(tm, second) returns a matcher that matches a
3982 // value x iff tm matches tuple (x, second). Useful for implementing
3983 // UnorderedPointwise() in terms of UnorderedElementsAreArray().
3984 template <typename Tuple2Matcher, typename Second>
3985 BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
3986 const Tuple2Matcher& tm, const Second& second) {
3987 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
3988 }
3989
3990 // Returns the description for a matcher defined using the MATCHER*()
3991 // macro where the user-supplied description string is "", if
3992 // 'negation' is false; otherwise returns the description of the
3993 // negation of the matcher. 'param_values' contains a list of strings
3994 // that are the print-out of the matcher's parameters.
3995 GTEST_API_ std::string FormatMatcherDescription(bool negation,
3996 const char* matcher_name,
3997 const Strings& param_values);
3998
3999 // Implements a matcher that checks the value of a optional<> type variable.
4000 template <typename ValueMatcher>
4001 class OptionalMatcher {
4002 public:
4003 explicit OptionalMatcher(const ValueMatcher& value_matcher)
4004 : value_matcher_(value_matcher) {}
4005
4006 template <typename Optional>
4007 operator Matcher<Optional>() const {
4008 return MakeMatcher(new Impl<Optional>(value_matcher_));
4009 }
4010
4011 template <typename Optional>
4012 class Impl : public MatcherInterface<Optional> {
4013 public:
4014 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView;
4015 typedef typename OptionalView::value_type ValueType;
4016 explicit Impl(const ValueMatcher& value_matcher)
4017 : value_matcher_(MatcherCast<ValueType>(value_matcher)) {}
4018
4019 virtual void DescribeTo(::std::ostream* os) const {
4020 *os << "value ";
4021 value_matcher_.DescribeTo(os);
4022 }
4023
4024 virtual void DescribeNegationTo(::std::ostream* os) const {
4025 *os << "value ";
4026 value_matcher_.DescribeNegationTo(os);
4027 }
4028
4029 virtual bool MatchAndExplain(Optional optional,
4030 MatchResultListener* listener) const {
4031 if (!optional) {
4032 *listener << "which is not engaged";
4033 return false;
4034 }
4035 const ValueType& value = *optional;
4036 StringMatchResultListener value_listener;
4037 const bool match = value_matcher_.MatchAndExplain(value, &value_listener);
4038 *listener << "whose value " << PrintToString(value)
4039 << (match ? " matches" : " doesn't match");
4040 PrintIfNotEmpty(value_listener.str(), listener->stream());
4041 return match;
4042 }
4043
4044 private:
4045 const Matcher<ValueType> value_matcher_;
4046 GTEST_DISALLOW_ASSIGN_(Impl);
4047 };
4048
4049 private:
4050 const ValueMatcher value_matcher_;
4051 GTEST_DISALLOW_ASSIGN_(OptionalMatcher);
4052 };
4053
4054 namespace variant_matcher {
4055 // Overloads to allow VariantMatcher to do proper ADL lookup.
4056 template <typename T>
4057 void holds_alternative() {}
4058 template <typename T>
4059 void get() {}
4060
4061 // Implements a matcher that checks the value of a variant<> type variable.
4062 template <typename T>
4063 class VariantMatcher {
4064 public:
4065 explicit VariantMatcher(::testing::Matcher<const T&> matcher)
4066 : matcher_(internal::move(matcher)) {}
4067
4068 template <typename Variant>
4069 bool MatchAndExplain(const Variant& value,
4070 ::testing::MatchResultListener* listener) const {
4071 if (!listener->IsInterested()) {
4072 return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));
4073 }
4074
4075 if (!holds_alternative<T>(value)) {
4076 *listener << "whose value is not of type '" << GetTypeName() << "'";
4077 return false;
4078 }
4079
4080 const T& elem = get<T>(value);
4081 StringMatchResultListener elem_listener;
4082 const bool match = matcher_.MatchAndExplain(elem, &elem_listener);
4083 *listener << "whose value " << PrintToString(elem)
4084 << (match ? " matches" : " doesn't match");
4085 PrintIfNotEmpty(elem_listener.str(), listener->stream());
4086 return match;
4087 }
4088
4089 void DescribeTo(std::ostream* os) const {
4090 *os << "is a variant<> with value of type '" << GetTypeName()
4091 << "' and the value ";
4092 matcher_.DescribeTo(os);
4093 }
4094
4095 void DescribeNegationTo(std::ostream* os) const {
4096 *os << "is a variant<> with value of type other than '" << GetTypeName()
4097 << "' or the value ";
4098 matcher_.DescribeNegationTo(os);
4099 }
4100
4101 private:
4102 static std::string GetTypeName() {
4103 #if GTEST_HAS_RTTI
4104 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
4105 return internal::GetTypeName<T>());
4106 #endif
4107 return "the element type";
4108 }
4109
4110 const ::testing::Matcher<const T&> matcher_;
4111 };
4112
4113 } // namespace variant_matcher
4114
4115 namespace any_cast_matcher {
4116
4117 // Overloads to allow AnyCastMatcher to do proper ADL lookup.
4118 template <typename T>
4119 void any_cast() {}
4120
4121 // Implements a matcher that any_casts the value.
4122 template <typename T>
4123 class AnyCastMatcher {
4124 public:
4125 explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher)
4126 : matcher_(matcher) {}
4127
4128 template <typename AnyType>
4129 bool MatchAndExplain(const AnyType& value,
4130 ::testing::MatchResultListener* listener) const {
4131 if (!listener->IsInterested()) {
4132 const T* ptr = any_cast<T>(&value);
4133 return ptr != NULL && matcher_.Matches(*ptr);
4134 }
4135
4136 const T* elem = any_cast<T>(&value);
4137 if (elem == NULL) {
4138 *listener << "whose value is not of type '" << GetTypeName() << "'";
4139 return false;
4140 }
4141
4142 StringMatchResultListener elem_listener;
4143 const bool match = matcher_.MatchAndExplain(*elem, &elem_listener);
4144 *listener << "whose value " << PrintToString(*elem)
4145 << (match ? " matches" : " doesn't match");
4146 PrintIfNotEmpty(elem_listener.str(), listener->stream());
4147 return match;
4148 }
4149
4150 void DescribeTo(std::ostream* os) const {
4151 *os << "is an 'any' type with value of type '" << GetTypeName()
4152 << "' and the value ";
4153 matcher_.DescribeTo(os);
4154 }
4155
4156 void DescribeNegationTo(std::ostream* os) const {
4157 *os << "is an 'any' type with value of type other than '" << GetTypeName()
4158 << "' or the value ";
4159 matcher_.DescribeNegationTo(os);
4160 }
4161
4162 private:
4163 static std::string GetTypeName() {
4164 #if GTEST_HAS_RTTI
4165 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
4166 return internal::GetTypeName<T>());
4167 #endif
4168 return "the element type";
4169 }
4170
4171 const ::testing::Matcher<const T&> matcher_;
4172 };
4173
4174 } // namespace any_cast_matcher
4175 } // namespace internal
4176
4177 // ElementsAreArray(iterator_first, iterator_last)
4178 // ElementsAreArray(pointer, count)
4179 // ElementsAreArray(array)
4180 // ElementsAreArray(container)
4181 // ElementsAreArray({ e1, e2, ..., en })
4182 //
4183 // The ElementsAreArray() functions are like ElementsAre(...), except
4184 // that they are given a homogeneous sequence rather than taking each
4185 // element as a function argument. The sequence can be specified as an
4186 // array, a pointer and count, a vector, an initializer list, or an
4187 // STL iterator range. In each of these cases, the underlying sequence
4188 // can be either a sequence of values or a sequence of matchers.
4189 //
4190 // All forms of ElementsAreArray() make a copy of the input matcher sequence.
4191
4192 template <typename Iter>
4193 inline internal::ElementsAreArrayMatcher<
4194 typename ::std::iterator_traits<Iter>::value_type>
4195 ElementsAreArray(Iter first, Iter last) {
4196 typedef typename ::std::iterator_traits<Iter>::value_type T;
4197 return internal::ElementsAreArrayMatcher<T>(first, last);
4198 }
4199
4200 template <typename T>
4201 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
4202 const T* pointer, size_t count) {
4203 return ElementsAreArray(pointer, pointer + count);
4204 }
4205
4206 template <typename T, size_t N>
4207 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
4208 const T (&array)[N]) {
4209 return ElementsAreArray(array, N);
4210 }
4211
4212 template <typename Container>
4213 inline internal::ElementsAreArrayMatcher<typename Container::value_type>
4214 ElementsAreArray(const Container& container) {
4215 return ElementsAreArray(container.begin(), container.end());
4216 }
4217
4218 #if GTEST_HAS_STD_INITIALIZER_LIST_
4219 template <typename T>
4220 inline internal::ElementsAreArrayMatcher<T>
4221 ElementsAreArray(::std::initializer_list<T> xs) {
4222 return ElementsAreArray(xs.begin(), xs.end());
4223 }
4224 #endif
4225
4226 // UnorderedElementsAreArray(iterator_first, iterator_last)
4227 // UnorderedElementsAreArray(pointer, count)
4228 // UnorderedElementsAreArray(array)
4229 // UnorderedElementsAreArray(container)
4230 // UnorderedElementsAreArray({ e1, e2, ..., en })
4231 //
4232 // UnorderedElementsAreArray() verifies that a bijective mapping onto a
4233 // collection of matchers exists.
4234 //
4235 // The matchers can be specified as an array, a pointer and count, a container,
4236 // an initializer list, or an STL iterator range. In each of these cases, the
4237 // underlying matchers can be either values or matchers.
4238
4239 template <typename Iter>
4240 inline internal::UnorderedElementsAreArrayMatcher<
4241 typename ::std::iterator_traits<Iter>::value_type>
4242 UnorderedElementsAreArray(Iter first, Iter last) {
4243 typedef typename ::std::iterator_traits<Iter>::value_type T;
4244 return internal::UnorderedElementsAreArrayMatcher<T>(
4245 internal::UnorderedMatcherRequire::ExactMatch, first, last);
4246 }
4247
4248 template <typename T>
4249 inline internal::UnorderedElementsAreArrayMatcher<T>
4250 UnorderedElementsAreArray(const T* pointer, size_t count) {
4251 return UnorderedElementsAreArray(pointer, pointer + count);
4252 }
4253
4254 template <typename T, size_t N>
4255 inline internal::UnorderedElementsAreArrayMatcher<T>
4256 UnorderedElementsAreArray(const T (&array)[N]) {
4257 return UnorderedElementsAreArray(array, N);
4258 }
4259
4260 template <typename Container>
4261 inline internal::UnorderedElementsAreArrayMatcher<
4262 typename Container::value_type>
4263 UnorderedElementsAreArray(const Container& container) {
4264 return UnorderedElementsAreArray(container.begin(), container.end());
4265 }
4266
4267 #if GTEST_HAS_STD_INITIALIZER_LIST_
4268 template <typename T>
4269 inline internal::UnorderedElementsAreArrayMatcher<T>
4270 UnorderedElementsAreArray(::std::initializer_list<T> xs) {
4271 return UnorderedElementsAreArray(xs.begin(), xs.end());
4272 }
4273 #endif
4274
4275 // _ is a matcher that matches anything of any type.
4276 //
4277 // This definition is fine as:
4278 //
4279 // 1. The C++ standard permits using the name _ in a namespace that
4280 // is not the global namespace or ::std.
4281 // 2. The AnythingMatcher class has no data member or constructor,
4282 // so it's OK to create global variables of this type.
4283 // 3. c-style has approved of using _ in this case.
4284 const internal::AnythingMatcher _ = {};
4285 // Creates a matcher that matches any value of the given type T.
4286 template <typename T>
4287 inline Matcher<T> A() {
4288 return Matcher<T>(new internal::AnyMatcherImpl<T>());
4289 }
4290
4291 // Creates a matcher that matches any value of the given type T.
4292 template <typename T>
4293 inline Matcher<T> An() { return A<T>(); }
4294
4295 // Creates a polymorphic matcher that matches anything equal to x.
4296 // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
4297 // wouldn't compile.
4298 template <typename T>
4299 inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
4300
4301 // Constructs a Matcher<T> from a 'value' of type T. The constructed
4302 // matcher matches any value that's equal to 'value'.
4303 template <typename T>
4304 Matcher<T>::Matcher(T value) { *this = Eq(value); }
4305
4306 template <typename T, typename M>
4307 Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(
4308 const M& value,
4309 internal::BooleanConstant<false> /* convertible_to_matcher */,
4310 internal::BooleanConstant<false> /* convertible_to_T */) {
4311 return Eq(value);
4312 }
4313
4314 // Creates a monomorphic matcher that matches anything with type Lhs
4315 // and equal to rhs. A user may need to use this instead of Eq(...)
4316 // in order to resolve an overloading ambiguity.
4317 //
4318 // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
4319 // or Matcher<T>(x), but more readable than the latter.
4320 //
4321 // We could define similar monomorphic matchers for other comparison
4322 // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
4323 // it yet as those are used much less than Eq() in practice. A user
4324 // can always write Matcher<T>(Lt(5)) to be explicit about the type,
4325 // for example.
4326 template <typename Lhs, typename Rhs>
4327 inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
4328
4329 // Creates a polymorphic matcher that matches anything >= x.
4330 template <typename Rhs>
4331 inline internal::GeMatcher<Rhs> Ge(Rhs x) {
4332 return internal::GeMatcher<Rhs>(x);
4333 }
4334
4335 // Creates a polymorphic matcher that matches anything > x.
4336 template <typename Rhs>
4337 inline internal::GtMatcher<Rhs> Gt(Rhs x) {
4338 return internal::GtMatcher<Rhs>(x);
4339 }
4340
4341 // Creates a polymorphic matcher that matches anything <= x.
4342 template <typename Rhs>
4343 inline internal::LeMatcher<Rhs> Le(Rhs x) {
4344 return internal::LeMatcher<Rhs>(x);
4345 }
4346
4347 // Creates a polymorphic matcher that matches anything < x.
4348 template <typename Rhs>
4349 inline internal::LtMatcher<Rhs> Lt(Rhs x) {
4350 return internal::LtMatcher<Rhs>(x);
4351 }
4352
4353 // Creates a polymorphic matcher that matches anything != x.
4354 template <typename Rhs>
4355 inline internal::NeMatcher<Rhs> Ne(Rhs x) {
4356 return internal::NeMatcher<Rhs>(x);
4357 }
4358
4359 // Creates a polymorphic matcher that matches any NULL pointer.
4360 inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
4361 return MakePolymorphicMatcher(internal::IsNullMatcher());
4362 }
4363
4364 // Creates a polymorphic matcher that matches any non-NULL pointer.
4365 // This is convenient as Not(NULL) doesn't compile (the compiler
4366 // thinks that that expression is comparing a pointer with an integer).
4367 inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
4368 return MakePolymorphicMatcher(internal::NotNullMatcher());
4369 }
4370
4371 // Creates a polymorphic matcher that matches any argument that
4372 // references variable x.
4373 template <typename T>
4374 inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
4375 return internal::RefMatcher<T&>(x);
4376 }
4377
4378 // Creates a matcher that matches any double argument approximately
4379 // equal to rhs, where two NANs are considered unequal.
4380 inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
4381 return internal::FloatingEqMatcher<double>(rhs, false);
4382 }
4383
4384 // Creates a matcher that matches any double argument approximately
4385 // equal to rhs, including NaN values when rhs is NaN.
4386 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
4387 return internal::FloatingEqMatcher<double>(rhs, true);
4388 }
4389
4390 // Creates a matcher that matches any double argument approximately equal to
4391 // rhs, up to the specified max absolute error bound, where two NANs are
4392 // considered unequal. The max absolute error bound must be non-negative.
4393 inline internal::FloatingEqMatcher<double> DoubleNear(
4394 double rhs, double max_abs_error) {
4395 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
4396 }
4397
4398 // Creates a matcher that matches any double argument approximately equal to
4399 // rhs, up to the specified max absolute error bound, including NaN values when
4400 // rhs is NaN. The max absolute error bound must be non-negative.
4401 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
4402 double rhs, double max_abs_error) {
4403 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
4404 }
4405
4406 // Creates a matcher that matches any float argument approximately
4407 // equal to rhs, where two NANs are considered unequal.
4408 inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
4409 return internal::FloatingEqMatcher<float>(rhs, false);
4410 }
4411
4412 // Creates a matcher that matches any float argument approximately
4413 // equal to rhs, including NaN values when rhs is NaN.
4414 inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
4415 return internal::FloatingEqMatcher<float>(rhs, true);
4416 }
4417
4418 // Creates a matcher that matches any float argument approximately equal to
4419 // rhs, up to the specified max absolute error bound, where two NANs are
4420 // considered unequal. The max absolute error bound must be non-negative.
4421 inline internal::FloatingEqMatcher<float> FloatNear(
4422 float rhs, float max_abs_error) {
4423 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
4424 }
4425
4426 // Creates a matcher that matches any float argument approximately equal to
4427 // rhs, up to the specified max absolute error bound, including NaN values when
4428 // rhs is NaN. The max absolute error bound must be non-negative.
4429 inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
4430 float rhs, float max_abs_error) {
4431 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
4432 }
4433
4434 // Creates a matcher that matches a pointer (raw or smart) that points
4435 // to a value that matches inner_matcher.
4436 template <typename InnerMatcher>
4437 inline internal::PointeeMatcher<InnerMatcher> Pointee(
4438 const InnerMatcher& inner_matcher) {
4439 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
4440 }
4441
4442 #if GTEST_HAS_RTTI
4443 // Creates a matcher that matches a pointer or reference that matches
4444 // inner_matcher when dynamic_cast<To> is applied.
4445 // The result of dynamic_cast<To> is forwarded to the inner matcher.
4446 // If To is a pointer and the cast fails, the inner matcher will receive NULL.
4447 // If To is a reference and the cast fails, this matcher returns false
4448 // immediately.
4449 template <typename To>
4450 inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
4451 WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
4452 return MakePolymorphicMatcher(
4453 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
4454 }
4455 #endif // GTEST_HAS_RTTI
4456
4457 // Creates a matcher that matches an object whose given field matches
4458 // 'matcher'. For example,
4459 // Field(&Foo::number, Ge(5))
4460 // matches a Foo object x iff x.number >= 5.
4461 template <typename Class, typename FieldType, typename FieldMatcher>
4462 inline PolymorphicMatcher<
4463 internal::FieldMatcher<Class, FieldType> > Field(
4464 FieldType Class::*field, const FieldMatcher& matcher) {
4465 return MakePolymorphicMatcher(
4466 internal::FieldMatcher<Class, FieldType>(
4467 field, MatcherCast<const FieldType&>(matcher)));
4468 // The call to MatcherCast() is required for supporting inner
4469 // matchers of compatible types. For example, it allows
4470 // Field(&Foo::bar, m)
4471 // to compile where bar is an int32 and m is a matcher for int64.
4472 }
4473
4474 // Same as Field() but also takes the name of the field to provide better error
4475 // messages.
4476 template <typename Class, typename FieldType, typename FieldMatcher>
4477 inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType> > Field(
4478 const std::string& field_name, FieldType Class::*field,
4479 const FieldMatcher& matcher) {
4480 return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(
4481 field_name, field, MatcherCast<const FieldType&>(matcher)));
4482 }
4483
4484 // Creates a matcher that matches an object whose given property
4485 // matches 'matcher'. For example,
4486 // Property(&Foo::str, StartsWith("hi"))
4487 // matches a Foo object x iff x.str() starts with "hi".
4488 template <typename Class, typename PropertyType, typename PropertyMatcher>
4489 inline PolymorphicMatcher<internal::PropertyMatcher<
4490 Class, PropertyType, PropertyType (Class::*)() const> >
4491 Property(PropertyType (Class::*property)() const,
4492 const PropertyMatcher& matcher) {
4493 return MakePolymorphicMatcher(
4494 internal::PropertyMatcher<Class, PropertyType,
4495 PropertyType (Class::*)() const>(
4496 property,
4497 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4498 // The call to MatcherCast() is required for supporting inner
4499 // matchers of compatible types. For example, it allows
4500 // Property(&Foo::bar, m)
4501 // to compile where bar() returns an int32 and m is a matcher for int64.
4502 }
4503
4504 // Same as Property() above, but also takes the name of the property to provide
4505 // better error messages.
4506 template <typename Class, typename PropertyType, typename PropertyMatcher>
4507 inline PolymorphicMatcher<internal::PropertyMatcher<
4508 Class, PropertyType, PropertyType (Class::*)() const> >
4509 Property(const std::string& property_name,
4510 PropertyType (Class::*property)() const,
4511 const PropertyMatcher& matcher) {
4512 return MakePolymorphicMatcher(
4513 internal::PropertyMatcher<Class, PropertyType,
4514 PropertyType (Class::*)() const>(
4515 property_name, property,
4516 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4517 }
4518
4519 #if GTEST_LANG_CXX11
4520 // The same as above but for reference-qualified member functions.
4521 template <typename Class, typename PropertyType, typename PropertyMatcher>
4522 inline PolymorphicMatcher<internal::PropertyMatcher<
4523 Class, PropertyType, PropertyType (Class::*)() const &> >
4524 Property(PropertyType (Class::*property)() const &,
4525 const PropertyMatcher& matcher) {
4526 return MakePolymorphicMatcher(
4527 internal::PropertyMatcher<Class, PropertyType,
4528 PropertyType (Class::*)() const &>(
4529 property,
4530 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4531 }
4532 #endif
4533
4534 // Creates a matcher that matches an object iff the result of applying
4535 // a callable to x matches 'matcher'.
4536 // For example,
4537 // ResultOf(f, StartsWith("hi"))
4538 // matches a Foo object x iff f(x) starts with "hi".
4539 // callable parameter can be a function, function pointer, or a functor.
4540 // Callable has to satisfy the following conditions:
4541 // * It is required to keep no state affecting the results of
4542 // the calls on it and make no assumptions about how many calls
4543 // will be made. Any state it keeps must be protected from the
4544 // concurrent access.
4545 // * If it is a function object, it has to define type result_type.
4546 // We recommend deriving your functor classes from std::unary_function.
4547 //
4548 template <typename Callable, typename ResultOfMatcher>
4549 internal::ResultOfMatcher<Callable> ResultOf(
4550 Callable callable, const ResultOfMatcher& matcher) {
4551 return internal::ResultOfMatcher<Callable>(
4552 callable,
4553 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
4554 matcher));
4555 // The call to MatcherCast() is required for supporting inner
4556 // matchers of compatible types. For example, it allows
4557 // ResultOf(Function, m)
4558 // to compile where Function() returns an int32 and m is a matcher for int64.
4559 }
4560
4561 // String matchers.
4562
4563 // Matches a string equal to str.
4564 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
4565 const std::string& str) {
4566 return MakePolymorphicMatcher(
4567 internal::StrEqualityMatcher<std::string>(str, true, true));
4568 }
4569
4570 // Matches a string not equal to str.
4571 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
4572 const std::string& str) {
4573 return MakePolymorphicMatcher(
4574 internal::StrEqualityMatcher<std::string>(str, false, true));
4575 }
4576
4577 // Matches a string equal to str, ignoring case.
4578 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
4579 const std::string& str) {
4580 return MakePolymorphicMatcher(
4581 internal::StrEqualityMatcher<std::string>(str, true, false));
4582 }
4583
4584 // Matches a string not equal to str, ignoring case.
4585 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
4586 const std::string& str) {
4587 return MakePolymorphicMatcher(
4588 internal::StrEqualityMatcher<std::string>(str, false, false));
4589 }
4590
4591 // Creates a matcher that matches any string, std::string, or C string
4592 // that contains the given substring.
4593 inline PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
4594 const std::string& substring) {
4595 return MakePolymorphicMatcher(
4596 internal::HasSubstrMatcher<std::string>(substring));
4597 }
4598
4599 // Matches a string that starts with 'prefix' (case-sensitive).
4600 inline PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
4601 const std::string& prefix) {
4602 return MakePolymorphicMatcher(
4603 internal::StartsWithMatcher<std::string>(prefix));
4604 }
4605
4606 // Matches a string that ends with 'suffix' (case-sensitive).
4607 inline PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
4608 const std::string& suffix) {
4609 return MakePolymorphicMatcher(internal::EndsWithMatcher<std::string>(suffix));
4610 }
4611
4612 // Matches a string that fully matches regular expression 'regex'.
4613 // The matcher takes ownership of 'regex'.
4614 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4615 const internal::RE* regex) {
4616 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
4617 }
4618 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4619 const std::string& regex) {
4620 return MatchesRegex(new internal::RE(regex));
4621 }
4622
4623 // Matches a string that contains regular expression 'regex'.
4624 // The matcher takes ownership of 'regex'.
4625 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4626 const internal::RE* regex) {
4627 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4628 }
4629 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4630 const std::string& regex) {
4631 return ContainsRegex(new internal::RE(regex));
4632 }
4633
4634 #if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4635 // Wide string matchers.
4636
4637 // Matches a string equal to str.
4638 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrEq(
4639 const std::wstring& str) {
4640 return MakePolymorphicMatcher(
4641 internal::StrEqualityMatcher<std::wstring>(str, true, true));
4642 }
4643
4644 // Matches a string not equal to str.
4645 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrNe(
4646 const std::wstring& str) {
4647 return MakePolymorphicMatcher(
4648 internal::StrEqualityMatcher<std::wstring>(str, false, true));
4649 }
4650
4651 // Matches a string equal to str, ignoring case.
4652 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
4653 StrCaseEq(const std::wstring& str) {
4654 return MakePolymorphicMatcher(
4655 internal::StrEqualityMatcher<std::wstring>(str, true, false));
4656 }
4657
4658 // Matches a string not equal to str, ignoring case.
4659 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
4660 StrCaseNe(const std::wstring& str) {
4661 return MakePolymorphicMatcher(
4662 internal::StrEqualityMatcher<std::wstring>(str, false, false));
4663 }
4664
4665 // Creates a matcher that matches any ::wstring, std::wstring, or C wide string
4666 // that contains the given substring.
4667 inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring> > HasSubstr(
4668 const std::wstring& substring) {
4669 return MakePolymorphicMatcher(
4670 internal::HasSubstrMatcher<std::wstring>(substring));
4671 }
4672
4673 // Matches a string that starts with 'prefix' (case-sensitive).
4674 inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring> >
4675 StartsWith(const std::wstring& prefix) {
4676 return MakePolymorphicMatcher(
4677 internal::StartsWithMatcher<std::wstring>(prefix));
4678 }
4679
4680 // Matches a string that ends with 'suffix' (case-sensitive).
4681 inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring> > EndsWith(
4682 const std::wstring& suffix) {
4683 return MakePolymorphicMatcher(
4684 internal::EndsWithMatcher<std::wstring>(suffix));
4685 }
4686
4687 #endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4688
4689 // Creates a polymorphic matcher that matches a 2-tuple where the
4690 // first field == the second field.
4691 inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4692
4693 // Creates a polymorphic matcher that matches a 2-tuple where the
4694 // first field >= the second field.
4695 inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4696
4697 // Creates a polymorphic matcher that matches a 2-tuple where the
4698 // first field > the second field.
4699 inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4700
4701 // Creates a polymorphic matcher that matches a 2-tuple where the
4702 // first field <= the second field.
4703 inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4704
4705 // Creates a polymorphic matcher that matches a 2-tuple where the
4706 // first field < the second field.
4707 inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4708
4709 // Creates a polymorphic matcher that matches a 2-tuple where the
4710 // first field != the second field.
4711 inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4712
4713 // Creates a polymorphic matcher that matches a 2-tuple where
4714 // FloatEq(first field) matches the second field.
4715 inline internal::FloatingEq2Matcher<float> FloatEq() {
4716 return internal::FloatingEq2Matcher<float>();
4717 }
4718
4719 // Creates a polymorphic matcher that matches a 2-tuple where
4720 // DoubleEq(first field) matches the second field.
4721 inline internal::FloatingEq2Matcher<double> DoubleEq() {
4722 return internal::FloatingEq2Matcher<double>();
4723 }
4724
4725 // Creates a polymorphic matcher that matches a 2-tuple where
4726 // FloatEq(first field) matches the second field with NaN equality.
4727 inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() {
4728 return internal::FloatingEq2Matcher<float>(true);
4729 }
4730
4731 // Creates a polymorphic matcher that matches a 2-tuple where
4732 // DoubleEq(first field) matches the second field with NaN equality.
4733 inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() {
4734 return internal::FloatingEq2Matcher<double>(true);
4735 }
4736
4737 // Creates a polymorphic matcher that matches a 2-tuple where
4738 // FloatNear(first field, max_abs_error) matches the second field.
4739 inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) {
4740 return internal::FloatingEq2Matcher<float>(max_abs_error);
4741 }
4742
4743 // Creates a polymorphic matcher that matches a 2-tuple where
4744 // DoubleNear(first field, max_abs_error) matches the second field.
4745 inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) {
4746 return internal::FloatingEq2Matcher<double>(max_abs_error);
4747 }
4748
4749 // Creates a polymorphic matcher that matches a 2-tuple where
4750 // FloatNear(first field, max_abs_error) matches the second field with NaN
4751 // equality.
4752 inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear(
4753 float max_abs_error) {
4754 return internal::FloatingEq2Matcher<float>(max_abs_error, true);
4755 }
4756
4757 // Creates a polymorphic matcher that matches a 2-tuple where
4758 // DoubleNear(first field, max_abs_error) matches the second field with NaN
4759 // equality.
4760 inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear(
4761 double max_abs_error) {
4762 return internal::FloatingEq2Matcher<double>(max_abs_error, true);
4763 }
4764
4765 // Creates a matcher that matches any value of type T that m doesn't
4766 // match.
4767 template <typename InnerMatcher>
4768 inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4769 return internal::NotMatcher<InnerMatcher>(m);
4770 }
4771
4772 // Returns a matcher that matches anything that satisfies the given
4773 // predicate. The predicate can be any unary function or functor
4774 // whose return type can be implicitly converted to bool.
4775 template <typename Predicate>
4776 inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4777 Truly(Predicate pred) {
4778 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4779 }
4780
4781 // Returns a matcher that matches the container size. The container must
4782 // support both size() and size_type which all STL-like containers provide.
4783 // Note that the parameter 'size' can be a value of type size_type as well as
4784 // matcher. For instance:
4785 // EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
4786 // EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
4787 template <typename SizeMatcher>
4788 inline internal::SizeIsMatcher<SizeMatcher>
4789 SizeIs(const SizeMatcher& size_matcher) {
4790 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4791 }
4792
4793 // Returns a matcher that matches the distance between the container's begin()
4794 // iterator and its end() iterator, i.e. the size of the container. This matcher
4795 // can be used instead of SizeIs with containers such as std::forward_list which
4796 // do not implement size(). The container must provide const_iterator (with
4797 // valid iterator_traits), begin() and end().
4798 template <typename DistanceMatcher>
4799 inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4800 BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4801 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4802 }
4803
4804 // Returns a matcher that matches an equal container.
4805 // This matcher behaves like Eq(), but in the event of mismatch lists the
4806 // values that are included in one container but not the other. (Duplicate
4807 // values and order differences are not explained.)
4808 template <typename Container>
4809 inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
4810 GTEST_REMOVE_CONST_(Container)> >
4811 ContainerEq(const Container& rhs) {
4812 // This following line is for working around a bug in MSVC 8.0,
4813 // which causes Container to be a const type sometimes.
4814 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4815 return MakePolymorphicMatcher(
4816 internal::ContainerEqMatcher<RawContainer>(rhs));
4817 }
4818
4819 // Returns a matcher that matches a container that, when sorted using
4820 // the given comparator, matches container_matcher.
4821 template <typename Comparator, typename ContainerMatcher>
4822 inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4823 WhenSortedBy(const Comparator& comparator,
4824 const ContainerMatcher& container_matcher) {
4825 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4826 comparator, container_matcher);
4827 }
4828
4829 // Returns a matcher that matches a container that, when sorted using
4830 // the < operator, matches container_matcher.
4831 template <typename ContainerMatcher>
4832 inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4833 WhenSorted(const ContainerMatcher& container_matcher) {
4834 return
4835 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4836 internal::LessComparator(), container_matcher);
4837 }
4838
4839 // Matches an STL-style container or a native array that contains the
4840 // same number of elements as in rhs, where its i-th element and rhs's
4841 // i-th element (as a pair) satisfy the given pair matcher, for all i.
4842 // TupleMatcher must be able to be safely cast to Matcher<tuple<const
4843 // T1&, const T2&> >, where T1 and T2 are the types of elements in the
4844 // LHS container and the RHS container respectively.
4845 template <typename TupleMatcher, typename Container>
4846 inline internal::PointwiseMatcher<TupleMatcher,
4847 GTEST_REMOVE_CONST_(Container)>
4848 Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4849 // This following line is for working around a bug in MSVC 8.0,
4850 // which causes Container to be a const type sometimes (e.g. when
4851 // rhs is a const int[])..
4852 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4853 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4854 tuple_matcher, rhs);
4855 }
4856
4857 #if GTEST_HAS_STD_INITIALIZER_LIST_
4858
4859 // Supports the Pointwise(m, {a, b, c}) syntax.
4860 template <typename TupleMatcher, typename T>
4861 inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4862 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4863 return Pointwise(tuple_matcher, std::vector<T>(rhs));
4864 }
4865
4866 #endif // GTEST_HAS_STD_INITIALIZER_LIST_
4867
4868 // UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4869 // container or a native array that contains the same number of
4870 // elements as in rhs, where in some permutation of the container, its
4871 // i-th element and rhs's i-th element (as a pair) satisfy the given
4872 // pair matcher, for all i. Tuple2Matcher must be able to be safely
4873 // cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4874 // the types of elements in the LHS container and the RHS container
4875 // respectively.
4876 //
4877 // This is like Pointwise(pair_matcher, rhs), except that the element
4878 // order doesn't matter.
4879 template <typename Tuple2Matcher, typename RhsContainer>
4880 inline internal::UnorderedElementsAreArrayMatcher<
4881 typename internal::BoundSecondMatcher<
4882 Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4883 RhsContainer)>::type::value_type> >
4884 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4885 const RhsContainer& rhs_container) {
4886 // This following line is for working around a bug in MSVC 8.0,
4887 // which causes RhsContainer to be a const type sometimes (e.g. when
4888 // rhs_container is a const int[]).
4889 typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4890
4891 // RhsView allows the same code to handle RhsContainer being a
4892 // STL-style container and it being a native C-style array.
4893 typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4894 typedef typename RhsView::type RhsStlContainer;
4895 typedef typename RhsStlContainer::value_type Second;
4896 const RhsStlContainer& rhs_stl_container =
4897 RhsView::ConstReference(rhs_container);
4898
4899 // Create a matcher for each element in rhs_container.
4900 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4901 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4902 it != rhs_stl_container.end(); ++it) {
4903 matchers.push_back(
4904 internal::MatcherBindSecond(tuple2_matcher, *it));
4905 }
4906
4907 // Delegate the work to UnorderedElementsAreArray().
4908 return UnorderedElementsAreArray(matchers);
4909 }
4910
4911 #if GTEST_HAS_STD_INITIALIZER_LIST_
4912
4913 // Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4914 template <typename Tuple2Matcher, typename T>
4915 inline internal::UnorderedElementsAreArrayMatcher<
4916 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4917 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4918 std::initializer_list<T> rhs) {
4919 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4920 }
4921
4922 #endif // GTEST_HAS_STD_INITIALIZER_LIST_
4923
4924 // Matches an STL-style container or a native array that contains at
4925 // least one element matching the given value or matcher.
4926 //
4927 // Examples:
4928 // ::std::set<int> page_ids;
4929 // page_ids.insert(3);
4930 // page_ids.insert(1);
4931 // EXPECT_THAT(page_ids, Contains(1));
4932 // EXPECT_THAT(page_ids, Contains(Gt(2)));
4933 // EXPECT_THAT(page_ids, Not(Contains(4)));
4934 //
4935 // ::std::map<int, size_t> page_lengths;
4936 // page_lengths[1] = 100;
4937 // EXPECT_THAT(page_lengths,
4938 // Contains(::std::pair<const int, size_t>(1, 100)));
4939 //
4940 // const char* user_ids[] = { "joe", "mike", "tom" };
4941 // EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4942 template <typename M>
4943 inline internal::ContainsMatcher<M> Contains(M matcher) {
4944 return internal::ContainsMatcher<M>(matcher);
4945 }
4946
4947 // IsSupersetOf(iterator_first, iterator_last)
4948 // IsSupersetOf(pointer, count)
4949 // IsSupersetOf(array)
4950 // IsSupersetOf(container)
4951 // IsSupersetOf({e1, e2, ..., en})
4952 //
4953 // IsSupersetOf() verifies that a surjective partial mapping onto a collection
4954 // of matchers exists. In other words, a container matches
4955 // IsSupersetOf({e1, ..., en}) if and only if there is a permutation
4956 // {y1, ..., yn} of some of the container's elements where y1 matches e1,
4957 // ..., and yn matches en. Obviously, the size of the container must be >= n
4958 // in order to have a match. Examples:
4959 //
4960 // - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and
4961 // 1 matches Ne(0).
4962 // - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches
4963 // both Eq(1) and Lt(2). The reason is that different matchers must be used
4964 // for elements in different slots of the container.
4965 // - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches
4966 // Eq(1) and (the second) 1 matches Lt(2).
4967 // - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)
4968 // Gt(1) and 3 matches (the second) Gt(1).
4969 //
4970 // The matchers can be specified as an array, a pointer and count, a container,
4971 // an initializer list, or an STL iterator range. In each of these cases, the
4972 // underlying matchers can be either values or matchers.
4973
4974 template <typename Iter>
4975 inline internal::UnorderedElementsAreArrayMatcher<
4976 typename ::std::iterator_traits<Iter>::value_type>
4977 IsSupersetOf(Iter first, Iter last) {
4978 typedef typename ::std::iterator_traits<Iter>::value_type T;
4979 return internal::UnorderedElementsAreArrayMatcher<T>(
4980 internal::UnorderedMatcherRequire::Superset, first, last);
4981 }
4982
4983 template <typename T>
4984 inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
4985 const T* pointer, size_t count) {
4986 return IsSupersetOf(pointer, pointer + count);
4987 }
4988
4989 template <typename T, size_t N>
4990 inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
4991 const T (&array)[N]) {
4992 return IsSupersetOf(array, N);
4993 }
4994
4995 template <typename Container>
4996 inline internal::UnorderedElementsAreArrayMatcher<
4997 typename Container::value_type>
4998 IsSupersetOf(const Container& container) {
4999 return IsSupersetOf(container.begin(), container.end());
5000 }
5001
5002 #if GTEST_HAS_STD_INITIALIZER_LIST_
5003 template <typename T>
5004 inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
5005 ::std::initializer_list<T> xs) {
5006 return IsSupersetOf(xs.begin(), xs.end());
5007 }
5008 #endif
5009
5010 // IsSubsetOf(iterator_first, iterator_last)
5011 // IsSubsetOf(pointer, count)
5012 // IsSubsetOf(array)
5013 // IsSubsetOf(container)
5014 // IsSubsetOf({e1, e2, ..., en})
5015 //
5016 // IsSubsetOf() verifies that an injective mapping onto a collection of matchers
5017 // exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and
5018 // only if there is a subset of matchers {m1, ..., mk} which would match the
5019 // container using UnorderedElementsAre. Obviously, the size of the container
5020 // must be <= n in order to have a match. Examples:
5021 //
5022 // - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).
5023 // - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1
5024 // matches Lt(0).
5025 // - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both
5026 // match Gt(0). The reason is that different matchers must be used for
5027 // elements in different slots of the container.
5028 //
5029 // The matchers can be specified as an array, a pointer and count, a container,
5030 // an initializer list, or an STL iterator range. In each of these cases, the
5031 // underlying matchers can be either values or matchers.
5032
5033 template <typename Iter>
5034 inline internal::UnorderedElementsAreArrayMatcher<
5035 typename ::std::iterator_traits<Iter>::value_type>
5036 IsSubsetOf(Iter first, Iter last) {
5037 typedef typename ::std::iterator_traits<Iter>::value_type T;
5038 return internal::UnorderedElementsAreArrayMatcher<T>(
5039 internal::UnorderedMatcherRequire::Subset, first, last);
5040 }
5041
5042 template <typename T>
5043 inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
5044 const T* pointer, size_t count) {
5045 return IsSubsetOf(pointer, pointer + count);
5046 }
5047
5048 template <typename T, size_t N>
5049 inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
5050 const T (&array)[N]) {
5051 return IsSubsetOf(array, N);
5052 }
5053
5054 template <typename Container>
5055 inline internal::UnorderedElementsAreArrayMatcher<
5056 typename Container::value_type>
5057 IsSubsetOf(const Container& container) {
5058 return IsSubsetOf(container.begin(), container.end());
5059 }
5060
5061 #if GTEST_HAS_STD_INITIALIZER_LIST_
5062 template <typename T>
5063 inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
5064 ::std::initializer_list<T> xs) {
5065 return IsSubsetOf(xs.begin(), xs.end());
5066 }
5067 #endif
5068
5069 // Matches an STL-style container or a native array that contains only
5070 // elements matching the given value or matcher.
5071 //
5072 // Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
5073 // the messages are different.
5074 //
5075 // Examples:
5076 // ::std::set<int> page_ids;
5077 // // Each(m) matches an empty container, regardless of what m is.
5078 // EXPECT_THAT(page_ids, Each(Eq(1)));
5079 // EXPECT_THAT(page_ids, Each(Eq(77)));
5080 //
5081 // page_ids.insert(3);
5082 // EXPECT_THAT(page_ids, Each(Gt(0)));
5083 // EXPECT_THAT(page_ids, Not(Each(Gt(4))));
5084 // page_ids.insert(1);
5085 // EXPECT_THAT(page_ids, Not(Each(Lt(2))));
5086 //
5087 // ::std::map<int, size_t> page_lengths;
5088 // page_lengths[1] = 100;
5089 // page_lengths[2] = 200;
5090 // page_lengths[3] = 300;
5091 // EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
5092 // EXPECT_THAT(page_lengths, Each(Key(Le(3))));
5093 //
5094 // const char* user_ids[] = { "joe", "mike", "tom" };
5095 // EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
5096 template <typename M>
5097 inline internal::EachMatcher<M> Each(M matcher) {
5098 return internal::EachMatcher<M>(matcher);
5099 }
5100
5101 // Key(inner_matcher) matches an std::pair whose 'first' field matches
5102 // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
5103 // std::map that contains at least one element whose key is >= 5.
5104 template <typename M>
5105 inline internal::KeyMatcher<M> Key(M inner_matcher) {
5106 return internal::KeyMatcher<M>(inner_matcher);
5107 }
5108
5109 // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
5110 // matches first_matcher and whose 'second' field matches second_matcher. For
5111 // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
5112 // to match a std::map<int, string> that contains exactly one element whose key
5113 // is >= 5 and whose value equals "foo".
5114 template <typename FirstMatcher, typename SecondMatcher>
5115 inline internal::PairMatcher<FirstMatcher, SecondMatcher>
5116 Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
5117 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
5118 first_matcher, second_matcher);
5119 }
5120
5121 // Returns a predicate that is satisfied by anything that matches the
5122 // given matcher.
5123 template <typename M>
5124 inline internal::MatcherAsPredicate<M> Matches(M matcher) {
5125 return internal::MatcherAsPredicate<M>(matcher);
5126 }
5127
5128 // Returns true iff the value matches the matcher.
5129 template <typename T, typename M>
5130 inline bool Value(const T& value, M matcher) {
5131 return testing::Matches(matcher)(value);
5132 }
5133
5134 // Matches the value against the given matcher and explains the match
5135 // result to listener.
5136 template <typename T, typename M>
5137 inline bool ExplainMatchResult(
5138 M matcher, const T& value, MatchResultListener* listener) {
5139 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
5140 }
5141
5142 // Returns a string representation of the given matcher. Useful for description
5143 // strings of matchers defined using MATCHER_P* macros that accept matchers as
5144 // their arguments. For example:
5145 //
5146 // MATCHER_P(XAndYThat, matcher,
5147 // "X that " + DescribeMatcher<int>(matcher, negation) +
5148 // " and Y that " + DescribeMatcher<double>(matcher, negation)) {
5149 // return ExplainMatchResult(matcher, arg.x(), result_listener) &&
5150 // ExplainMatchResult(matcher, arg.y(), result_listener);
5151 // }
5152 template <typename T, typename M>
5153 std::string DescribeMatcher(const M& matcher, bool negation = false) {
5154 ::std::stringstream ss;
5155 Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher);
5156 if (negation) {
5157 monomorphic_matcher.DescribeNegationTo(&ss);
5158 } else {
5159 monomorphic_matcher.DescribeTo(&ss);
5160 }
5161 return ss.str();
5162 }
5163
5164 #if GTEST_LANG_CXX11
5165 // Define variadic matcher versions. They are overloaded in
5166 // gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
5167 template <typename... Args>
5168 internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
5169 return internal::AllOfMatcher<Args...>(matchers...);
5170 }
5171
5172 template <typename... Args>
5173 internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
5174 return internal::AnyOfMatcher<Args...>(matchers...);
5175 }
5176
5177 template <typename... Args>
5178 internal::ElementsAreMatcher<tuple<typename std::decay<const Args&>::type...>>
5179 ElementsAre(const Args&... matchers) {
5180 return internal::ElementsAreMatcher<
5181 tuple<typename std::decay<const Args&>::type...>>(
5182 make_tuple(matchers...));
5183 }
5184
5185 template <typename... Args>
5186 internal::UnorderedElementsAreMatcher<
5187 tuple<typename std::decay<const Args&>::type...>>
5188 UnorderedElementsAre(const Args&... matchers) {
5189 return internal::UnorderedElementsAreMatcher<
5190 tuple<typename std::decay<const Args&>::type...>>(
5191 make_tuple(matchers...));
5192 }
5193
5194 #endif // GTEST_LANG_CXX11
5195
5196 // AllArgs(m) is a synonym of m. This is useful in
5197 //
5198 // EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
5199 //
5200 // which is easier to read than
5201 //
5202 // EXPECT_CALL(foo, Bar(_, _)).With(Eq());
5203 template <typename InnerMatcher>
5204 inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
5205
5206 // Returns a matcher that matches the value of an optional<> type variable.
5207 // The matcher implementation only uses '!arg' and requires that the optional<>
5208 // type has a 'value_type' member type and that '*arg' is of type 'value_type'
5209 // and is printable using 'PrintToString'. It is compatible with
5210 // std::optional/std::experimental::optional.
5211 // Note that to compare an optional type variable against nullopt you should
5212 // use Eq(nullopt) and not Optional(Eq(nullopt)). The latter implies that the
5213 // optional value contains an optional itself.
5214 template <typename ValueMatcher>
5215 inline internal::OptionalMatcher<ValueMatcher> Optional(
5216 const ValueMatcher& value_matcher) {
5217 return internal::OptionalMatcher<ValueMatcher>(value_matcher);
5218 }
5219
5220 // Returns a matcher that matches the value of a absl::any type variable.
5221 template <typename T>
5222 PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T> > AnyWith(
5223 const Matcher<const T&>& matcher) {
5224 return MakePolymorphicMatcher(
5225 internal::any_cast_matcher::AnyCastMatcher<T>(matcher));
5226 }
5227
5228 // Returns a matcher that matches the value of a variant<> type variable.
5229 // The matcher implementation uses ADL to find the holds_alternative and get
5230 // functions.
5231 // It is compatible with std::variant.
5232 template <typename T>
5233 PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
5234 const Matcher<const T&>& matcher) {
5235 return MakePolymorphicMatcher(
5236 internal::variant_matcher::VariantMatcher<T>(matcher));
5237 }
5238
5239 // These macros allow using matchers to check values in Google Test
5240 // tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
5241 // succeed iff the value matches the matcher. If the assertion fails,
5242 // the value and the description of the matcher will be printed.
5243 #define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
5244 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
5245 #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
5246 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
5247
5248 } // namespace testing
5249
5250 // Include any custom callback matchers added by the local installation.
5251 // We must include this header at the end to make sure it can use the
5252 // declarations from this file.
5253 #include "gmock/internal/custom/gmock-matchers.h"
5254
5255 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_