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