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