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