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