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