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