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