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