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