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