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