blob: 9cd1a0650a11e767b58fad427653fca40af11100 [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// 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.
Gennadiy Civila3c0dd02018-08-14 14:04:07 -040029
shiqiane35fdd92008-12-10 05:08:54 +000030
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
Gennadiy Civil984cba32018-07-27 11:15:08 -040037// GOOGLETEST_CM0002 DO NOT DELETE
38
shiqiane35fdd92008-12-10 05:08:54 +000039#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
40#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
41
zhanyong.wan616180e2013-06-18 18:49:51 +000042#include <math.h>
zhanyong.wan6a896b52009-01-16 01:13:50 +000043#include <algorithm>
zhanyong.wanfb25d532013-07-28 08:24:00 +000044#include <iterator>
zhanyong.wan16cf4732009-05-14 20:55:30 +000045#include <limits>
shiqiane35fdd92008-12-10 05:08:54 +000046#include <ostream> // NOLINT
47#include <sstream>
48#include <string>
zhanyong.wanab5b77c2010-05-17 19:32:48 +000049#include <utility>
shiqiane35fdd92008-12-10 05:08:54 +000050#include <vector>
Gennadiy Civilfbb48a72018-01-26 11:57:58 -050051#include "gtest/gtest.h"
zhanyong.wan53e08c42010-09-14 05:38:21 +000052#include "gmock/internal/gmock-internal-utils.h"
53#include "gmock/internal/gmock-port.h"
shiqiane35fdd92008-12-10 05:08:54 +000054
kosak18489fa2013-12-04 23:49:07 +000055#if GTEST_HAS_STD_INITIALIZER_LIST_
56# include <initializer_list> // NOLINT -- must be after gtest.h
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +000057#endif
58
Gennadiy Civil9ad73982018-08-29 22:32:08 -040059GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 5046 \
60/* class A needs to have dll-interface to be used by clients of class B */ \
61/* Symbol involving type with internal linkage not defined */)
mistergdf428ec2018-08-20 14:48:45 -040062
shiqiane35fdd92008-12-10 05:08:54 +000063namespace testing {
64
65// To implement a matcher Foo for type T, define:
66// 1. a class FooMatcherImpl that implements the
67// MatcherInterface<T> interface, and
68// 2. a factory function that creates a Matcher<T> object from a
69// FooMatcherImpl*.
70//
71// The two-level delegation design makes it possible to allow a user
72// to write "v" instead of "Eq(v)" where a Matcher is expected, which
73// is impossible if we pass matchers by pointers. It also eases
74// ownership management as Matcher objects can now be copied like
75// plain values.
76
zhanyong.wan82113312010-01-08 21:55:40 +000077// MatchResultListener is an abstract class. Its << operator can be
78// used by a matcher to explain why a value matches or doesn't match.
79//
Gennadiy Civil265efde2018-08-14 15:04:11 -040080// FIXME: add method
zhanyong.wan82113312010-01-08 21:55:40 +000081// bool InterestedInWhy(bool result) const;
82// to indicate whether the listener is interested in why the match
83// result is 'result'.
84class MatchResultListener {
85 public:
86 // Creates a listener object with the given underlying ostream. The
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +000087 // listener does not own the ostream, and does not dereference it
88 // in the constructor or destructor.
zhanyong.wan82113312010-01-08 21:55:40 +000089 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
90 virtual ~MatchResultListener() = 0; // Makes this class abstract.
91
92 // Streams x to the underlying ostream; does nothing if the ostream
93 // is NULL.
94 template <typename T>
95 MatchResultListener& operator<<(const T& x) {
96 if (stream_ != NULL)
97 *stream_ << x;
98 return *this;
99 }
100
101 // Returns the underlying ostream.
102 ::std::ostream* stream() { return stream_; }
103
zhanyong.wana862f1d2010-03-15 21:23:04 +0000104 // Returns true iff the listener is interested in an explanation of
105 // the match result. A matcher's MatchAndExplain() method can use
106 // this information to avoid generating the explanation when no one
107 // intends to hear it.
108 bool IsInterested() const { return stream_ != NULL; }
109
zhanyong.wan82113312010-01-08 21:55:40 +0000110 private:
111 ::std::ostream* const stream_;
112
113 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
114};
115
116inline MatchResultListener::~MatchResultListener() {
117}
118
zhanyong.wanfb25d532013-07-28 08:24:00 +0000119// An instance of a subclass of this knows how to describe itself as a
120// matcher.
121class MatcherDescriberInterface {
122 public:
123 virtual ~MatcherDescriberInterface() {}
124
125 // Describes this matcher to an ostream. The function should print
126 // a verb phrase that describes the property a value matching this
127 // matcher should have. The subject of the verb phrase is the value
128 // being matched. For example, the DescribeTo() method of the Gt(7)
129 // matcher prints "is greater than 7".
130 virtual void DescribeTo(::std::ostream* os) const = 0;
131
132 // Describes the negation of this matcher to an ostream. For
133 // example, if the description of this matcher is "is greater than
134 // 7", the negated description could be "is not greater than 7".
135 // You are not required to override this when implementing
136 // MatcherInterface, but it is highly advised so that your matcher
137 // can produce good error messages.
138 virtual void DescribeNegationTo(::std::ostream* os) const {
139 *os << "not (";
140 DescribeTo(os);
141 *os << ")";
142 }
143};
144
shiqiane35fdd92008-12-10 05:08:54 +0000145// The implementation of a matcher.
146template <typename T>
zhanyong.wanfb25d532013-07-28 08:24:00 +0000147class MatcherInterface : public MatcherDescriberInterface {
shiqiane35fdd92008-12-10 05:08:54 +0000148 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000149 // Returns true iff the matcher matches x; also explains the match
zhanyong.wan83f6b082013-03-01 01:47:35 +0000150 // result to 'listener' if necessary (see the next paragraph), in
151 // the form of a non-restrictive relative clause ("which ...",
152 // "whose ...", etc) that describes x. For example, the
153 // MatchAndExplain() method of the Pointee(...) matcher should
154 // generate an explanation like "which points to ...".
155 //
156 // Implementations of MatchAndExplain() should add an explanation of
157 // the match result *if and only if* they can provide additional
158 // information that's not already present (or not obvious) in the
159 // print-out of x and the matcher's description. Whether the match
160 // succeeds is not a factor in deciding whether an explanation is
161 // needed, as sometimes the caller needs to print a failure message
162 // when the match succeeds (e.g. when the matcher is used inside
163 // Not()).
164 //
165 // For example, a "has at least 10 elements" matcher should explain
166 // what the actual element count is, regardless of the match result,
167 // as it is useful information to the reader; on the other hand, an
168 // "is empty" matcher probably only needs to explain what the actual
169 // size is when the match fails, as it's redundant to say that the
170 // size is 0 when the value is already known to be empty.
zhanyong.wan82113312010-01-08 21:55:40 +0000171 //
zhanyong.wandb22c222010-01-28 21:52:29 +0000172 // You should override this method when defining a new matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000173 //
174 // It's the responsibility of the caller (Google Mock) to guarantee
175 // that 'listener' is not NULL. This helps to simplify a matcher's
176 // implementation when it doesn't care about the performance, as it
177 // can talk to 'listener' without checking its validity first.
178 // However, in order to implement dummy listeners efficiently,
179 // listener->stream() may be NULL.
zhanyong.wandb22c222010-01-28 21:52:29 +0000180 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
shiqiane35fdd92008-12-10 05:08:54 +0000181
zhanyong.wanfb25d532013-07-28 08:24:00 +0000182 // Inherits these methods from MatcherDescriberInterface:
183 // virtual void DescribeTo(::std::ostream* os) const = 0;
184 // virtual void DescribeNegationTo(::std::ostream* os) const;
shiqiane35fdd92008-12-10 05:08:54 +0000185};
186
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400187namespace internal {
188
189// Converts a MatcherInterface<T> to a MatcherInterface<const T&>.
190template <typename T>
191class MatcherInterfaceAdapter : public MatcherInterface<const T&> {
192 public:
193 explicit MatcherInterfaceAdapter(const MatcherInterface<T>* impl)
194 : impl_(impl) {}
195 virtual ~MatcherInterfaceAdapter() { delete impl_; }
196
197 virtual void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
198
199 virtual void DescribeNegationTo(::std::ostream* os) const {
200 impl_->DescribeNegationTo(os);
201 }
202
203 virtual bool MatchAndExplain(const T& x,
204 MatchResultListener* listener) const {
205 return impl_->MatchAndExplain(x, listener);
206 }
207
208 private:
209 const MatcherInterface<T>* const impl_;
210
211 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatcherInterfaceAdapter);
212};
213
214} // namespace internal
215
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000216// A match result listener that stores the explanation in a string.
217class StringMatchResultListener : public MatchResultListener {
218 public:
219 StringMatchResultListener() : MatchResultListener(&ss_) {}
220
221 // Returns the explanation accumulated so far.
Nico Weber09fd5b32017-05-15 17:07:03 -0400222 std::string str() const { return ss_.str(); }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000223
224 // Clears the explanation accumulated so far.
225 void Clear() { ss_.str(""); }
226
227 private:
228 ::std::stringstream ss_;
229
230 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
231};
232
shiqiane35fdd92008-12-10 05:08:54 +0000233namespace internal {
234
kosak506340a2014-11-17 01:47:54 +0000235struct AnyEq {
236 template <typename A, typename B>
237 bool operator()(const A& a, const B& b) const { return a == b; }
238};
239struct AnyNe {
240 template <typename A, typename B>
241 bool operator()(const A& a, const B& b) const { return a != b; }
242};
243struct AnyLt {
244 template <typename A, typename B>
245 bool operator()(const A& a, const B& b) const { return a < b; }
246};
247struct AnyGt {
248 template <typename A, typename B>
249 bool operator()(const A& a, const B& b) const { return a > b; }
250};
251struct AnyLe {
252 template <typename A, typename B>
253 bool operator()(const A& a, const B& b) const { return a <= b; }
254};
255struct AnyGe {
256 template <typename A, typename B>
257 bool operator()(const A& a, const B& b) const { return a >= b; }
258};
259
zhanyong.wan82113312010-01-08 21:55:40 +0000260// A match result listener that ignores the explanation.
261class DummyMatchResultListener : public MatchResultListener {
262 public:
263 DummyMatchResultListener() : MatchResultListener(NULL) {}
264
265 private:
266 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
267};
268
269// A match result listener that forwards the explanation to a given
270// ostream. The difference between this and MatchResultListener is
271// that the former is concrete.
272class StreamMatchResultListener : public MatchResultListener {
273 public:
274 explicit StreamMatchResultListener(::std::ostream* os)
275 : MatchResultListener(os) {}
276
277 private:
278 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
279};
280
shiqiane35fdd92008-12-10 05:08:54 +0000281// An internal class for implementing Matcher<T>, which will derive
282// from it. We put functionalities common to all Matcher<T>
283// specializations here to avoid code duplication.
284template <typename T>
285class MatcherBase {
286 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000287 // Returns true iff the matcher matches x; also explains the match
288 // result to 'listener'.
Gennadiy Civil6aae2062018-03-26 10:36:26 -0400289 bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
290 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000291 return impl_->MatchAndExplain(x, listener);
292 }
293
shiqiane35fdd92008-12-10 05:08:54 +0000294 // Returns true iff this matcher matches x.
Gennadiy Civile55089e2018-04-04 14:05:00 -0400295 bool Matches(GTEST_REFERENCE_TO_CONST_(T) x) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000296 DummyMatchResultListener dummy;
297 return MatchAndExplain(x, &dummy);
298 }
shiqiane35fdd92008-12-10 05:08:54 +0000299
300 // Describes this matcher to an ostream.
301 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
302
303 // Describes the negation of this matcher to an ostream.
304 void DescribeNegationTo(::std::ostream* os) const {
305 impl_->DescribeNegationTo(os);
306 }
307
308 // Explains why x matches, or doesn't match, the matcher.
Gennadiy Civile55089e2018-04-04 14:05:00 -0400309 void ExplainMatchResultTo(GTEST_REFERENCE_TO_CONST_(T) x,
310 ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000311 StreamMatchResultListener listener(os);
312 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000313 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000314
zhanyong.wanfb25d532013-07-28 08:24:00 +0000315 // Returns the describer for this matcher object; retains ownership
316 // of the describer, which is only guaranteed to be alive when
317 // this matcher object is alive.
318 const MatcherDescriberInterface* GetDescriber() const {
319 return impl_.get();
320 }
321
shiqiane35fdd92008-12-10 05:08:54 +0000322 protected:
323 MatcherBase() {}
324
325 // Constructs a matcher from its implementation.
Gennadiy Civile55089e2018-04-04 14:05:00 -0400326 explicit MatcherBase(
327 const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)>* impl)
shiqiane35fdd92008-12-10 05:08:54 +0000328 : impl_(impl) {}
329
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400330 template <typename U>
331 explicit MatcherBase(
332 const MatcherInterface<U>* impl,
333 typename internal::EnableIf<
334 !internal::IsSame<U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* =
335 NULL)
336 : impl_(new internal::MatcherInterfaceAdapter<U>(impl)) {}
337
shiqiane35fdd92008-12-10 05:08:54 +0000338 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000339
shiqiane35fdd92008-12-10 05:08:54 +0000340 private:
341 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
342 // interfaces. The former dynamically allocates a chunk of memory
343 // to hold the reference count, while the latter tracks all
344 // references using a circular linked list without allocating
345 // memory. It has been observed that linked_ptr performs better in
346 // typical scenarios. However, shared_ptr can out-perform
347 // linked_ptr when there are many more uses of the copy constructor
348 // than the default constructor.
349 //
350 // If performance becomes a problem, we should see if using
351 // shared_ptr helps.
Gennadiy Civile55089e2018-04-04 14:05:00 -0400352 ::testing::internal::linked_ptr<
353 const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> >
354 impl_;
shiqiane35fdd92008-12-10 05:08:54 +0000355};
356
shiqiane35fdd92008-12-10 05:08:54 +0000357} // namespace internal
358
359// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
360// object that can check whether a value of type T matches. The
361// implementation of Matcher<T> is just a linked_ptr to const
362// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
363// from Matcher!
364template <typename T>
365class Matcher : public internal::MatcherBase<T> {
366 public:
vladlosev88032d82010-11-17 23:29:21 +0000367 // Constructs a null matcher. Needed for storing Matcher objects in STL
368 // containers. A default-constructed matcher is not yet initialized. You
369 // cannot use it until a valid value has been assigned to it.
kosakd86a7232015-07-13 21:19:43 +0000370 explicit Matcher() {} // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000371
372 // Constructs a matcher from its implementation.
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400373 explicit Matcher(const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)>* impl)
374 : internal::MatcherBase<T>(impl) {}
375
376 template <typename U>
377 explicit Matcher(const MatcherInterface<U>* impl,
378 typename internal::EnableIf<!internal::IsSame<
379 U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* = NULL)
shiqiane35fdd92008-12-10 05:08:54 +0000380 : internal::MatcherBase<T>(impl) {}
381
zhanyong.wan18490652009-05-11 18:54:08 +0000382 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000383 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
384 Matcher(T value); // NOLINT
385};
386
387// The following two specializations allow the user to write str
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400388// instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
shiqiane35fdd92008-12-10 05:08:54 +0000389// matcher is expected.
390template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400391class GTEST_API_ Matcher<const std::string&>
392 : public internal::MatcherBase<const std::string&> {
shiqiane35fdd92008-12-10 05:08:54 +0000393 public:
394 Matcher() {}
395
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400396 explicit Matcher(const MatcherInterface<const std::string&>* impl)
397 : internal::MatcherBase<const std::string&>(impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000398
399 // Allows the user to write str instead of Eq(str) sometimes, where
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400400 // str is a std::string object.
401 Matcher(const std::string& s); // NOLINT
402
403#if GTEST_HAS_GLOBAL_STRING
404 // Allows the user to write str instead of Eq(str) sometimes, where
405 // str is a ::string object.
406 Matcher(const ::string& s); // NOLINT
407#endif // GTEST_HAS_GLOBAL_STRING
shiqiane35fdd92008-12-10 05:08:54 +0000408
409 // Allows the user to write "foo" instead of Eq("foo") sometimes.
410 Matcher(const char* s); // NOLINT
411};
412
413template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400414class GTEST_API_ Matcher<std::string>
415 : public internal::MatcherBase<std::string> {
shiqiane35fdd92008-12-10 05:08:54 +0000416 public:
417 Matcher() {}
418
Gennadiy Civile55089e2018-04-04 14:05:00 -0400419 explicit Matcher(const MatcherInterface<const std::string&>* impl)
420 : internal::MatcherBase<std::string>(impl) {}
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400421 explicit Matcher(const MatcherInterface<std::string>* impl)
422 : internal::MatcherBase<std::string>(impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000423
424 // Allows the user to write str instead of Eq(str) sometimes, where
425 // str is a string object.
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400426 Matcher(const std::string& s); // NOLINT
427
428#if GTEST_HAS_GLOBAL_STRING
429 // Allows the user to write str instead of Eq(str) sometimes, where
430 // str is a ::string object.
431 Matcher(const ::string& s); // NOLINT
432#endif // GTEST_HAS_GLOBAL_STRING
shiqiane35fdd92008-12-10 05:08:54 +0000433
434 // Allows the user to write "foo" instead of Eq("foo") sometimes.
435 Matcher(const char* s); // NOLINT
436};
437
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400438#if GTEST_HAS_GLOBAL_STRING
zhanyong.wan1f122a02013-03-25 16:27:03 +0000439// The following two specializations allow the user to write str
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400440// instead of Eq(str) and "foo" instead of Eq("foo") when a ::string
zhanyong.wan1f122a02013-03-25 16:27:03 +0000441// matcher is expected.
442template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400443class GTEST_API_ Matcher<const ::string&>
444 : public internal::MatcherBase<const ::string&> {
zhanyong.wan1f122a02013-03-25 16:27:03 +0000445 public:
446 Matcher() {}
447
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400448 explicit Matcher(const MatcherInterface<const ::string&>* impl)
449 : internal::MatcherBase<const ::string&>(impl) {}
zhanyong.wan1f122a02013-03-25 16:27:03 +0000450
451 // Allows the user to write str instead of Eq(str) sometimes, where
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400452 // str is a std::string object.
453 Matcher(const std::string& s); // NOLINT
454
455 // Allows the user to write str instead of Eq(str) sometimes, where
456 // str is a ::string object.
457 Matcher(const ::string& s); // NOLINT
zhanyong.wan1f122a02013-03-25 16:27:03 +0000458
459 // Allows the user to write "foo" instead of Eq("foo") sometimes.
460 Matcher(const char* s); // NOLINT
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400461};
zhanyong.wan1f122a02013-03-25 16:27:03 +0000462
zhanyong.wan1f122a02013-03-25 16:27:03 +0000463template <>
Gennadiy Civile55089e2018-04-04 14:05:00 -0400464class GTEST_API_ Matcher< ::string>
465 : public internal::MatcherBase< ::string> {
zhanyong.wan1f122a02013-03-25 16:27:03 +0000466 public:
467 Matcher() {}
468
Gennadiy Civile55089e2018-04-04 14:05:00 -0400469 explicit Matcher(const MatcherInterface<const ::string&>* impl)
470 : internal::MatcherBase< ::string>(impl) {}
471 explicit Matcher(const MatcherInterface< ::string>* impl)
472 : internal::MatcherBase< ::string>(impl) {}
zhanyong.wan1f122a02013-03-25 16:27:03 +0000473
474 // Allows the user to write str instead of Eq(str) sometimes, where
Gennadiy Civile55089e2018-04-04 14:05:00 -0400475 // str is a std::string object.
476 Matcher(const std::string& s); // NOLINT
477
478 // Allows the user to write str instead of Eq(str) sometimes, where
479 // str is a ::string object.
480 Matcher(const ::string& s); // NOLINT
481
482 // Allows the user to write "foo" instead of Eq("foo") sometimes.
483 Matcher(const char* s); // NOLINT
484};
485#endif // GTEST_HAS_GLOBAL_STRING
486
487#if GTEST_HAS_ABSL
488// The following two specializations allow the user to write str
489// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
490// matcher is expected.
491template <>
492class GTEST_API_ Matcher<const absl::string_view&>
493 : public internal::MatcherBase<const absl::string_view&> {
494 public:
495 Matcher() {}
496
497 explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
498 : internal::MatcherBase<const absl::string_view&>(impl) {}
499
500 // Allows the user to write str instead of Eq(str) sometimes, where
501 // str is a std::string object.
502 Matcher(const std::string& s); // NOLINT
503
504#if GTEST_HAS_GLOBAL_STRING
505 // Allows the user to write str instead of Eq(str) sometimes, where
506 // str is a ::string object.
507 Matcher(const ::string& s); // NOLINT
508#endif // GTEST_HAS_GLOBAL_STRING
zhanyong.wan1f122a02013-03-25 16:27:03 +0000509
510 // Allows the user to write "foo" instead of Eq("foo") sometimes.
511 Matcher(const char* s); // NOLINT
512
Gennadiy Civile55089e2018-04-04 14:05:00 -0400513 // Allows the user to pass absl::string_views directly.
514 Matcher(absl::string_view s); // NOLINT
zhanyong.wan1f122a02013-03-25 16:27:03 +0000515};
Gennadiy Civile55089e2018-04-04 14:05:00 -0400516
517template <>
518class GTEST_API_ Matcher<absl::string_view>
519 : public internal::MatcherBase<absl::string_view> {
520 public:
521 Matcher() {}
522
523 explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
524 : internal::MatcherBase<absl::string_view>(impl) {}
525 explicit Matcher(const MatcherInterface<absl::string_view>* impl)
526 : internal::MatcherBase<absl::string_view>(impl) {}
527
528 // Allows the user to write str instead of Eq(str) sometimes, where
529 // str is a std::string object.
530 Matcher(const std::string& s); // NOLINT
531
532#if GTEST_HAS_GLOBAL_STRING
533 // Allows the user to write str instead of Eq(str) sometimes, where
534 // str is a ::string object.
535 Matcher(const ::string& s); // NOLINT
536#endif // GTEST_HAS_GLOBAL_STRING
537
538 // Allows the user to write "foo" instead of Eq("foo") sometimes.
539 Matcher(const char* s); // NOLINT
540
541 // Allows the user to pass absl::string_views directly.
542 Matcher(absl::string_view s); // NOLINT
543};
544#endif // GTEST_HAS_ABSL
545
546// Prints a matcher in a human-readable format.
547template <typename T>
548std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
549 matcher.DescribeTo(&os);
550 return os;
551}
zhanyong.wan1f122a02013-03-25 16:27:03 +0000552
shiqiane35fdd92008-12-10 05:08:54 +0000553// The PolymorphicMatcher class template makes it easy to implement a
554// polymorphic matcher (i.e. a matcher that can match values of more
555// than one type, e.g. Eq(n) and NotNull()).
556//
zhanyong.wandb22c222010-01-28 21:52:29 +0000557// To define a polymorphic matcher, a user should provide an Impl
558// class that has a DescribeTo() method and a DescribeNegationTo()
559// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000560//
zhanyong.wandb22c222010-01-28 21:52:29 +0000561// bool MatchAndExplain(const Value& value,
562// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000563//
564// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000565template <class Impl>
566class PolymorphicMatcher {
567 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000568 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000569
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000570 // Returns a mutable reference to the underlying matcher
571 // implementation object.
572 Impl& mutable_impl() { return impl_; }
573
574 // Returns an immutable reference to the underlying matcher
575 // implementation object.
576 const Impl& impl() const { return impl_; }
577
shiqiane35fdd92008-12-10 05:08:54 +0000578 template <typename T>
579 operator Matcher<T>() const {
Gennadiy Civile55089e2018-04-04 14:05:00 -0400580 return Matcher<T>(new MonomorphicImpl<GTEST_REFERENCE_TO_CONST_(T)>(impl_));
shiqiane35fdd92008-12-10 05:08:54 +0000581 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000582
shiqiane35fdd92008-12-10 05:08:54 +0000583 private:
584 template <typename T>
585 class MonomorphicImpl : public MatcherInterface<T> {
586 public:
587 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
588
shiqiane35fdd92008-12-10 05:08:54 +0000589 virtual void DescribeTo(::std::ostream* os) const {
590 impl_.DescribeTo(os);
591 }
592
593 virtual void DescribeNegationTo(::std::ostream* os) const {
594 impl_.DescribeNegationTo(os);
595 }
596
zhanyong.wan82113312010-01-08 21:55:40 +0000597 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000598 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000599 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000600
shiqiane35fdd92008-12-10 05:08:54 +0000601 private:
602 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000603
604 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000605 };
606
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000607 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000608
609 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000610};
611
612// Creates a matcher from its implementation. This is easier to use
613// than the Matcher<T> constructor as it doesn't require you to
614// explicitly write the template argument, e.g.
615//
616// MakeMatcher(foo);
617// vs
618// Matcher<const string&>(foo);
619template <typename T>
620inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
621 return Matcher<T>(impl);
zhanyong.wan2eab17b2013-03-08 17:53:24 +0000622}
shiqiane35fdd92008-12-10 05:08:54 +0000623
624// Creates a polymorphic matcher from its implementation. This is
625// easier to use than the PolymorphicMatcher<Impl> constructor as it
626// doesn't require you to explicitly write the template argument, e.g.
627//
628// MakePolymorphicMatcher(foo);
629// vs
630// PolymorphicMatcher<TypeOfFoo>(foo);
631template <class Impl>
632inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
633 return PolymorphicMatcher<Impl>(impl);
634}
635
jgm79a367e2012-04-10 16:02:11 +0000636// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
637// and MUST NOT BE USED IN USER CODE!!!
638namespace internal {
639
640// The MatcherCastImpl class template is a helper for implementing
641// MatcherCast(). We need this helper in order to partially
642// specialize the implementation of MatcherCast() (C++ allows
643// class/struct templates to be partially specialized, but not
644// function templates.).
645
646// This general version is used when MatcherCast()'s argument is a
647// polymorphic matcher (i.e. something that can be converted to a
648// Matcher but is not one yet; for example, Eq(value)) or a value (for
649// example, "hello").
650template <typename T, typename M>
651class MatcherCastImpl {
652 public:
kosak5f2a6ca2013-12-03 01:43:07 +0000653 static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
Gennadiy Civil2bd17502018-02-27 13:51:09 -0500654 // M can be a polymorphic matcher, in which case we want to use
jgm79a367e2012-04-10 16:02:11 +0000655 // its conversion operator to create Matcher<T>. Or it can be a value
656 // that should be passed to the Matcher<T>'s constructor.
657 //
658 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
659 // polymorphic matcher because it'll be ambiguous if T has an implicit
660 // constructor from M (this usually happens when T has an implicit
661 // constructor from any type).
662 //
663 // It won't work to unconditionally implict_cast
664 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
665 // a user-defined conversion from M to T if one exists (assuming M is
666 // a value).
667 return CastImpl(
668 polymorphic_matcher_or_value,
669 BooleanConstant<
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400670 internal::ImplicitlyConvertible<M, Matcher<T> >::value>(),
671 BooleanConstant<
672 internal::ImplicitlyConvertible<M, T>::value>());
jgm79a367e2012-04-10 16:02:11 +0000673 }
674
675 private:
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400676 template <bool Ignore>
kosak5f2a6ca2013-12-03 01:43:07 +0000677 static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400678 BooleanConstant<true> /* convertible_to_matcher */,
679 BooleanConstant<Ignore>) {
jgm79a367e2012-04-10 16:02:11 +0000680 // M is implicitly convertible to Matcher<T>, which means that either
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400681 // M is a polymorphic matcher or Matcher<T> has an implicit constructor
jgm79a367e2012-04-10 16:02:11 +0000682 // from M. In both cases using the implicit conversion will produce a
683 // matcher.
684 //
685 // Even if T has an implicit constructor from M, it won't be called because
686 // creating Matcher<T> would require a chain of two user-defined conversions
687 // (first to create T from M and then to create Matcher<T> from T).
688 return polymorphic_matcher_or_value;
689 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400690
691 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
692 // matcher. It's a value of a type implicitly convertible to T. Use direct
693 // initialization to create a matcher.
694 static Matcher<T> CastImpl(
695 const M& value, BooleanConstant<false> /* convertible_to_matcher */,
696 BooleanConstant<true> /* convertible_to_T */) {
697 return Matcher<T>(ImplicitCast_<T>(value));
698 }
699
700 // M can't be implicitly converted to either Matcher<T> or T. Attempt to use
701 // polymorphic matcher Eq(value) in this case.
702 //
703 // Note that we first attempt to perform an implicit cast on the value and
704 // only fall back to the polymorphic Eq() matcher afterwards because the
705 // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end
706 // which might be undefined even when Rhs is implicitly convertible to Lhs
707 // (e.g. std::pair<const int, int> vs. std::pair<int, int>).
708 //
709 // We don't define this method inline as we need the declaration of Eq().
710 static Matcher<T> CastImpl(
711 const M& value, BooleanConstant<false> /* convertible_to_matcher */,
712 BooleanConstant<false> /* convertible_to_T */);
jgm79a367e2012-04-10 16:02:11 +0000713};
714
715// This more specialized version is used when MatcherCast()'s argument
716// is already a Matcher. This only compiles when type T can be
717// statically converted to type U.
718template <typename T, typename U>
719class MatcherCastImpl<T, Matcher<U> > {
720 public:
721 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
722 return Matcher<T>(new Impl(source_matcher));
723 }
724
725 private:
726 class Impl : public MatcherInterface<T> {
727 public:
728 explicit Impl(const Matcher<U>& source_matcher)
729 : source_matcher_(source_matcher) {}
730
731 // We delegate the matching logic to the source matcher.
732 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
Gennadiy Civilb907c262018-03-23 11:42:41 -0400733#if GTEST_LANG_CXX11
734 using FromType = typename std::remove_cv<typename std::remove_pointer<
735 typename std::remove_reference<T>::type>::type>::type;
736 using ToType = typename std::remove_cv<typename std::remove_pointer<
737 typename std::remove_reference<U>::type>::type>::type;
738 // Do not allow implicitly converting base*/& to derived*/&.
739 static_assert(
740 // Do not trigger if only one of them is a pointer. That implies a
741 // regular conversion and not a down_cast.
742 (std::is_pointer<typename std::remove_reference<T>::type>::value !=
743 std::is_pointer<typename std::remove_reference<U>::type>::value) ||
744 std::is_same<FromType, ToType>::value ||
745 !std::is_base_of<FromType, ToType>::value,
746 "Can't implicitly convert from <base> to <derived>");
747#endif // GTEST_LANG_CXX11
748
jgm79a367e2012-04-10 16:02:11 +0000749 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
750 }
751
752 virtual void DescribeTo(::std::ostream* os) const {
753 source_matcher_.DescribeTo(os);
754 }
755
756 virtual void DescribeNegationTo(::std::ostream* os) const {
757 source_matcher_.DescribeNegationTo(os);
758 }
759
760 private:
761 const Matcher<U> source_matcher_;
762
763 GTEST_DISALLOW_ASSIGN_(Impl);
764 };
765};
766
767// This even more specialized version is used for efficiently casting
768// a matcher to its own type.
769template <typename T>
770class MatcherCastImpl<T, Matcher<T> > {
771 public:
772 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
773};
774
775} // namespace internal
776
shiqiane35fdd92008-12-10 05:08:54 +0000777// In order to be safe and clear, casting between different matcher
778// types is done explicitly via MatcherCast<T>(m), which takes a
779// matcher m and returns a Matcher<T>. It compiles only when T can be
780// statically converted to the argument type of m.
781template <typename T, typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000782inline Matcher<T> MatcherCast(const M& matcher) {
jgm79a367e2012-04-10 16:02:11 +0000783 return internal::MatcherCastImpl<T, M>::Cast(matcher);
784}
shiqiane35fdd92008-12-10 05:08:54 +0000785
zhanyong.wan18490652009-05-11 18:54:08 +0000786// Implements SafeMatcherCast().
787//
zhanyong.wan95b12332009-09-25 18:55:50 +0000788// We use an intermediate class to do the actual safe casting as Nokia's
789// Symbian compiler cannot decide between
790// template <T, M> ... (M) and
791// template <T, U> ... (const Matcher<U>&)
792// for function templates but can for member function templates.
793template <typename T>
794class SafeMatcherCastImpl {
795 public:
jgm79a367e2012-04-10 16:02:11 +0000796 // This overload handles polymorphic matchers and values only since
797 // monomorphic matchers are handled by the next one.
zhanyong.wan95b12332009-09-25 18:55:50 +0000798 template <typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000799 static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
jgm79a367e2012-04-10 16:02:11 +0000800 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
zhanyong.wan95b12332009-09-25 18:55:50 +0000801 }
zhanyong.wan18490652009-05-11 18:54:08 +0000802
zhanyong.wan95b12332009-09-25 18:55:50 +0000803 // This overload handles monomorphic matchers.
804 //
805 // In general, if type T can be implicitly converted to type U, we can
806 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
807 // contravariant): just keep a copy of the original Matcher<U>, convert the
808 // argument from type T to U, and then pass it to the underlying Matcher<U>.
809 // The only exception is when U is a reference and T is not, as the
810 // underlying Matcher<U> may be interested in the argument's address, which
811 // is not preserved in the conversion from T to U.
812 template <typename U>
813 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
814 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000815 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000816 T_must_be_implicitly_convertible_to_U);
817 // Enforce that we are not converting a non-reference type T to a reference
818 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000819 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000820 internal::is_reference<T>::value || !internal::is_reference<U>::value,
Hector Dearman24054ff2017-06-19 18:27:33 +0100821 cannot_convert_non_reference_arg_to_reference);
zhanyong.wan95b12332009-09-25 18:55:50 +0000822 // In case both T and U are arithmetic types, enforce that the
823 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000824 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
825 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000826 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
827 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000828 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000829 kTIsOther || kUIsOther ||
830 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
831 conversion_of_arithmetic_types_must_be_lossless);
832 return MatcherCast<T>(matcher);
833 }
834};
835
836template <typename T, typename M>
837inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
838 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000839}
840
shiqiane35fdd92008-12-10 05:08:54 +0000841// A<T>() returns a matcher that matches any value of type T.
842template <typename T>
843Matcher<T> A();
844
845// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
846// and MUST NOT BE USED IN USER CODE!!!
847namespace internal {
848
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000849// If the explanation is not empty, prints it to the ostream.
Nico Weber09fd5b32017-05-15 17:07:03 -0400850inline void PrintIfNotEmpty(const std::string& explanation,
zhanyong.wanfb25d532013-07-28 08:24:00 +0000851 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000852 if (explanation != "" && os != NULL) {
853 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000854 }
855}
856
zhanyong.wan736baa82010-09-27 17:44:16 +0000857// Returns true if the given type name is easy to read by a human.
858// This is used to decide whether printing the type of a value might
859// be helpful.
Nico Weber09fd5b32017-05-15 17:07:03 -0400860inline bool IsReadableTypeName(const std::string& type_name) {
zhanyong.wan736baa82010-09-27 17:44:16 +0000861 // We consider a type name readable if it's short or doesn't contain
862 // a template or function type.
863 return (type_name.length() <= 20 ||
Nico Weber09fd5b32017-05-15 17:07:03 -0400864 type_name.find_first_of("<(") == std::string::npos);
zhanyong.wan736baa82010-09-27 17:44:16 +0000865}
866
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000867// Matches the value against the given matcher, prints the value and explains
868// the match result to the listener. Returns the match result.
869// 'listener' must not be NULL.
870// Value cannot be passed by const reference, because some matchers take a
871// non-const argument.
872template <typename Value, typename T>
873bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
874 MatchResultListener* listener) {
875 if (!listener->IsInterested()) {
876 // If the listener is not interested, we do not need to construct the
877 // inner explanation.
878 return matcher.Matches(value);
879 }
880
881 StringMatchResultListener inner_listener;
882 const bool match = matcher.MatchAndExplain(value, &inner_listener);
883
884 UniversalPrint(value, listener->stream());
zhanyong.wan736baa82010-09-27 17:44:16 +0000885#if GTEST_HAS_RTTI
Nico Weber09fd5b32017-05-15 17:07:03 -0400886 const std::string& type_name = GetTypeName<Value>();
zhanyong.wan736baa82010-09-27 17:44:16 +0000887 if (IsReadableTypeName(type_name))
888 *listener->stream() << " (of type " << type_name << ")";
889#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000890 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000891
892 return match;
893}
894
shiqiane35fdd92008-12-10 05:08:54 +0000895// An internal helper class for doing compile-time loop on a tuple's
896// fields.
897template <size_t N>
898class TuplePrefix {
899 public:
900 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
901 // iff the first N fields of matcher_tuple matches the first N
902 // fields of value_tuple, respectively.
903 template <typename MatcherTuple, typename ValueTuple>
904 static bool Matches(const MatcherTuple& matcher_tuple,
905 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000906 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
907 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
908 }
909
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000910 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000911 // describes failures in matching the first N fields of matchers
912 // against the first N fields of values. If there is no failure,
913 // nothing will be streamed to os.
914 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000915 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
916 const ValueTuple& values,
917 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000918 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000919 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000920
921 // Then describes the failure (if any) in the (N - 1)-th (0-based)
922 // field.
923 typename tuple_element<N - 1, MatcherTuple>::type matcher =
924 get<N - 1>(matchers);
925 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
Gennadiy Civile55089e2018-04-04 14:05:00 -0400926 GTEST_REFERENCE_TO_CONST_(Value) value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000927 StringMatchResultListener listener;
928 if (!matcher.MatchAndExplain(value, &listener)) {
Gennadiy Civil265efde2018-08-14 15:04:11 -0400929 // FIXME: include in the message the name of the parameter
shiqiane35fdd92008-12-10 05:08:54 +0000930 // as used in MOCK_METHOD*() when possible.
931 *os << " Expected arg #" << N - 1 << ": ";
932 get<N - 1>(matchers).DescribeTo(os);
933 *os << "\n Actual: ";
934 // We remove the reference in type Value to prevent the
935 // universal printer from printing the address of value, which
936 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000937 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000938 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000939 internal::UniversalPrint(value, os);
940 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000941 *os << "\n";
942 }
943 }
944};
945
946// The base case.
947template <>
948class TuplePrefix<0> {
949 public:
950 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000951 static bool Matches(const MatcherTuple& /* matcher_tuple */,
952 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000953 return true;
954 }
955
956 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000957 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
958 const ValueTuple& /* values */,
959 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000960};
961
962// TupleMatches(matcher_tuple, value_tuple) returns true iff all
963// matchers in matcher_tuple match the corresponding fields in
964// value_tuple. It is a compiler error if matcher_tuple and
965// value_tuple have different number of fields or incompatible field
966// types.
967template <typename MatcherTuple, typename ValueTuple>
968bool TupleMatches(const MatcherTuple& matcher_tuple,
969 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000970 // Makes sure that matcher_tuple and value_tuple have the same
971 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000972 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000973 tuple_size<ValueTuple>::value,
974 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000975 return TuplePrefix<tuple_size<ValueTuple>::value>::
976 Matches(matcher_tuple, value_tuple);
977}
978
979// Describes failures in matching matchers against values. If there
980// is no failure, nothing will be streamed to os.
981template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000982void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
983 const ValueTuple& values,
984 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000985 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000986 matchers, values, os);
987}
988
zhanyong.wanfb25d532013-07-28 08:24:00 +0000989// TransformTupleValues and its helper.
990//
991// TransformTupleValuesHelper hides the internal machinery that
992// TransformTupleValues uses to implement a tuple traversal.
993template <typename Tuple, typename Func, typename OutIter>
994class TransformTupleValuesHelper {
995 private:
kosakbd018832014-04-02 20:30:00 +0000996 typedef ::testing::tuple_size<Tuple> TupleSize;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000997
998 public:
999 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
1000 // Returns the final value of 'out' in case the caller needs it.
1001 static OutIter Run(Func f, const Tuple& t, OutIter out) {
1002 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
1003 }
1004
1005 private:
1006 template <typename Tup, size_t kRemainingSize>
1007 struct IterateOverTuple {
1008 OutIter operator() (Func f, const Tup& t, OutIter out) const {
kosakbd018832014-04-02 20:30:00 +00001009 *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
zhanyong.wanfb25d532013-07-28 08:24:00 +00001010 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
1011 }
1012 };
1013 template <typename Tup>
1014 struct IterateOverTuple<Tup, 0> {
1015 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
1016 return out;
1017 }
1018 };
1019};
1020
1021// Successively invokes 'f(element)' on each element of the tuple 't',
1022// appending each result to the 'out' iterator. Returns the final value
1023// of 'out'.
1024template <typename Tuple, typename Func, typename OutIter>
1025OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
1026 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
1027}
1028
shiqiane35fdd92008-12-10 05:08:54 +00001029// Implements A<T>().
1030template <typename T>
Gennadiy Civile55089e2018-04-04 14:05:00 -04001031class AnyMatcherImpl : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
shiqiane35fdd92008-12-10 05:08:54 +00001032 public:
Gennadiy Civile55089e2018-04-04 14:05:00 -04001033 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) /* x */,
1034 MatchResultListener* /* listener */) const {
1035 return true;
1036 }
shiqiane35fdd92008-12-10 05:08:54 +00001037 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
1038 virtual void DescribeNegationTo(::std::ostream* os) const {
1039 // This is mostly for completeness' safe, as it's not very useful
1040 // to write Not(A<bool>()). However we cannot completely rule out
1041 // such a possibility, and it doesn't hurt to be prepared.
1042 *os << "never matches";
1043 }
1044};
1045
1046// Implements _, a matcher that matches any value of any
1047// type. This is a polymorphic matcher, so we need a template type
1048// conversion operator to make it appearing as a Matcher<T> for any
1049// type T.
1050class AnythingMatcher {
1051 public:
1052 template <typename T>
1053 operator Matcher<T>() const { return A<T>(); }
1054};
1055
1056// Implements a matcher that compares a given value with a
1057// pre-supplied value using one of the ==, <=, <, etc, operators. The
1058// two values being compared don't have to have the same type.
1059//
1060// The matcher defined here is polymorphic (for example, Eq(5) can be
1061// used to match an int, a short, a double, etc). Therefore we use
1062// a template type conversion operator in the implementation.
1063//
shiqiane35fdd92008-12-10 05:08:54 +00001064// The following template definition assumes that the Rhs parameter is
1065// a "bare" type (i.e. neither 'const T' nor 'T&').
kosak506340a2014-11-17 01:47:54 +00001066template <typename D, typename Rhs, typename Op>
1067class ComparisonBase {
1068 public:
1069 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
1070 template <typename Lhs>
1071 operator Matcher<Lhs>() const {
1072 return MakeMatcher(new Impl<Lhs>(rhs_));
shiqiane35fdd92008-12-10 05:08:54 +00001073 }
1074
kosak506340a2014-11-17 01:47:54 +00001075 private:
1076 template <typename Lhs>
1077 class Impl : public MatcherInterface<Lhs> {
1078 public:
1079 explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
1080 virtual bool MatchAndExplain(
1081 Lhs lhs, MatchResultListener* /* listener */) const {
1082 return Op()(lhs, rhs_);
1083 }
1084 virtual void DescribeTo(::std::ostream* os) const {
1085 *os << D::Desc() << " ";
1086 UniversalPrint(rhs_, os);
1087 }
1088 virtual void DescribeNegationTo(::std::ostream* os) const {
1089 *os << D::NegatedDesc() << " ";
1090 UniversalPrint(rhs_, os);
1091 }
1092 private:
1093 Rhs rhs_;
1094 GTEST_DISALLOW_ASSIGN_(Impl);
1095 };
1096 Rhs rhs_;
1097 GTEST_DISALLOW_ASSIGN_(ComparisonBase);
1098};
shiqiane35fdd92008-12-10 05:08:54 +00001099
kosak506340a2014-11-17 01:47:54 +00001100template <typename Rhs>
1101class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
1102 public:
1103 explicit EqMatcher(const Rhs& rhs)
1104 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
1105 static const char* Desc() { return "is equal to"; }
1106 static const char* NegatedDesc() { return "isn't equal to"; }
1107};
1108template <typename Rhs>
1109class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
1110 public:
1111 explicit NeMatcher(const Rhs& rhs)
1112 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
1113 static const char* Desc() { return "isn't equal to"; }
1114 static const char* NegatedDesc() { return "is equal to"; }
1115};
1116template <typename Rhs>
1117class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
1118 public:
1119 explicit LtMatcher(const Rhs& rhs)
1120 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
1121 static const char* Desc() { return "is <"; }
1122 static const char* NegatedDesc() { return "isn't <"; }
1123};
1124template <typename Rhs>
1125class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
1126 public:
1127 explicit GtMatcher(const Rhs& rhs)
1128 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
1129 static const char* Desc() { return "is >"; }
1130 static const char* NegatedDesc() { return "isn't >"; }
1131};
1132template <typename Rhs>
1133class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
1134 public:
1135 explicit LeMatcher(const Rhs& rhs)
1136 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
1137 static const char* Desc() { return "is <="; }
1138 static const char* NegatedDesc() { return "isn't <="; }
1139};
1140template <typename Rhs>
1141class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
1142 public:
1143 explicit GeMatcher(const Rhs& rhs)
1144 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
1145 static const char* Desc() { return "is >="; }
1146 static const char* NegatedDesc() { return "isn't >="; }
1147};
shiqiane35fdd92008-12-10 05:08:54 +00001148
vladlosev79b83502009-11-18 00:43:37 +00001149// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001150// pointer that is NULL.
1151class IsNullMatcher {
1152 public:
vladlosev79b83502009-11-18 00:43:37 +00001153 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +00001154 bool MatchAndExplain(const Pointer& p,
1155 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001156#if GTEST_LANG_CXX11
1157 return p == nullptr;
1158#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001159 return GetRawPointer(p) == NULL;
kosak6305ff52015-04-28 22:36:31 +00001160#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001161 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001162
1163 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
1164 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001165 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001166 }
1167};
1168
vladlosev79b83502009-11-18 00:43:37 +00001169// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +00001170// pointer that is not NULL.
1171class NotNullMatcher {
1172 public:
vladlosev79b83502009-11-18 00:43:37 +00001173 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +00001174 bool MatchAndExplain(const Pointer& p,
1175 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001176#if GTEST_LANG_CXX11
1177 return p != nullptr;
1178#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001179 return GetRawPointer(p) != NULL;
kosak6305ff52015-04-28 22:36:31 +00001180#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001181 }
shiqiane35fdd92008-12-10 05:08:54 +00001182
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001183 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +00001184 void DescribeNegationTo(::std::ostream* os) const {
1185 *os << "is NULL";
1186 }
1187};
1188
1189// Ref(variable) matches any argument that is a reference to
1190// 'variable'. This matcher is polymorphic as it can match any
1191// super type of the type of 'variable'.
1192//
1193// The RefMatcher template class implements Ref(variable). It can
1194// only be instantiated with a reference type. This prevents a user
1195// from mistakenly using Ref(x) to match a non-reference function
1196// argument. For example, the following will righteously cause a
1197// compiler error:
1198//
1199// int n;
1200// Matcher<int> m1 = Ref(n); // This won't compile.
1201// Matcher<int&> m2 = Ref(n); // This will compile.
1202template <typename T>
1203class RefMatcher;
1204
1205template <typename T>
1206class RefMatcher<T&> {
1207 // Google Mock is a generic framework and thus needs to support
1208 // mocking any function types, including those that take non-const
1209 // reference arguments. Therefore the template parameter T (and
1210 // Super below) can be instantiated to either a const type or a
1211 // non-const type.
1212 public:
1213 // RefMatcher() takes a T& instead of const T&, as we want the
1214 // compiler to catch using Ref(const_value) as a matcher for a
1215 // non-const reference.
1216 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
1217
1218 template <typename Super>
1219 operator Matcher<Super&>() const {
1220 // By passing object_ (type T&) to Impl(), which expects a Super&,
1221 // we make sure that Super is a super type of T. In particular,
1222 // this catches using Ref(const_value) as a matcher for a
1223 // non-const reference, as you cannot implicitly convert a const
1224 // reference to a non-const reference.
1225 return MakeMatcher(new Impl<Super>(object_));
1226 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001227
shiqiane35fdd92008-12-10 05:08:54 +00001228 private:
1229 template <typename Super>
1230 class Impl : public MatcherInterface<Super&> {
1231 public:
1232 explicit Impl(Super& x) : object_(x) {} // NOLINT
1233
zhanyong.wandb22c222010-01-28 21:52:29 +00001234 // MatchAndExplain() takes a Super& (as opposed to const Super&)
1235 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +00001236 virtual bool MatchAndExplain(
1237 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001238 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +00001239 return &x == &object_;
1240 }
shiqiane35fdd92008-12-10 05:08:54 +00001241
1242 virtual void DescribeTo(::std::ostream* os) const {
1243 *os << "references the variable ";
1244 UniversalPrinter<Super&>::Print(object_, os);
1245 }
1246
1247 virtual void DescribeNegationTo(::std::ostream* os) const {
1248 *os << "does not reference the variable ";
1249 UniversalPrinter<Super&>::Print(object_, os);
1250 }
1251
shiqiane35fdd92008-12-10 05:08:54 +00001252 private:
1253 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001254
1255 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001256 };
1257
1258 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001259
1260 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001261};
1262
1263// Polymorphic helper functions for narrow and wide string matchers.
1264inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1265 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1266}
1267
1268inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1269 const wchar_t* rhs) {
1270 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1271}
1272
1273// String comparison for narrow or wide strings that can have embedded NUL
1274// characters.
1275template <typename StringType>
1276bool CaseInsensitiveStringEquals(const StringType& s1,
1277 const StringType& s2) {
1278 // Are the heads equal?
1279 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1280 return false;
1281 }
1282
1283 // Skip the equal heads.
1284 const typename StringType::value_type nul = 0;
1285 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1286
1287 // Are we at the end of either s1 or s2?
1288 if (i1 == StringType::npos || i2 == StringType::npos) {
1289 return i1 == i2;
1290 }
1291
1292 // Are the tails equal?
1293 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1294}
1295
1296// String matchers.
1297
1298// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1299template <typename StringType>
1300class StrEqualityMatcher {
1301 public:
shiqiane35fdd92008-12-10 05:08:54 +00001302 StrEqualityMatcher(const StringType& str, bool expect_eq,
1303 bool case_sensitive)
1304 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1305
Gennadiy Civile55089e2018-04-04 14:05:00 -04001306#if GTEST_HAS_ABSL
1307 bool MatchAndExplain(const absl::string_view& s,
1308 MatchResultListener* listener) const {
1309 if (s.data() == NULL) {
1310 return !expect_eq_;
1311 }
1312 // This should fail to compile if absl::string_view is used with wide
1313 // strings.
1314 const StringType& str = string(s);
1315 return MatchAndExplain(str, listener);
1316 }
1317#endif // GTEST_HAS_ABSL
1318
jgm38513a82012-11-15 15:50:36 +00001319 // Accepts pointer types, particularly:
1320 // const char*
1321 // char*
1322 // const wchar_t*
1323 // wchar_t*
1324 template <typename CharType>
1325 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001326 if (s == NULL) {
1327 return !expect_eq_;
1328 }
zhanyong.wandb22c222010-01-28 21:52:29 +00001329 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001330 }
1331
jgm38513a82012-11-15 15:50:36 +00001332 // Matches anything that can convert to StringType.
1333 //
1334 // This is a template, not just a plain function with const StringType&,
Gennadiy Civile55089e2018-04-04 14:05:00 -04001335 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001336 template <typename MatcheeStringType>
1337 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001338 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001339 const StringType& s2(s);
1340 const bool eq = case_sensitive_ ? s2 == string_ :
1341 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +00001342 return expect_eq_ == eq;
1343 }
1344
1345 void DescribeTo(::std::ostream* os) const {
1346 DescribeToHelper(expect_eq_, os);
1347 }
1348
1349 void DescribeNegationTo(::std::ostream* os) const {
1350 DescribeToHelper(!expect_eq_, os);
1351 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001352
shiqiane35fdd92008-12-10 05:08:54 +00001353 private:
1354 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001355 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +00001356 *os << "equal to ";
1357 if (!case_sensitive_) {
1358 *os << "(ignoring case) ";
1359 }
vladloseve2e8ba42010-05-13 18:16:03 +00001360 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001361 }
1362
1363 const StringType string_;
1364 const bool expect_eq_;
1365 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001366
1367 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001368};
1369
1370// Implements the polymorphic HasSubstr(substring) matcher, which
1371// can be used as a Matcher<T> as long as T can be converted to a
1372// string.
1373template <typename StringType>
1374class HasSubstrMatcher {
1375 public:
shiqiane35fdd92008-12-10 05:08:54 +00001376 explicit HasSubstrMatcher(const StringType& substring)
1377 : substring_(substring) {}
1378
Gennadiy Civile55089e2018-04-04 14:05:00 -04001379#if GTEST_HAS_ABSL
1380 bool MatchAndExplain(const absl::string_view& s,
1381 MatchResultListener* listener) const {
1382 if (s.data() == NULL) {
1383 return false;
1384 }
1385 // This should fail to compile if absl::string_view is used with wide
1386 // strings.
1387 const StringType& str = string(s);
1388 return MatchAndExplain(str, listener);
1389 }
1390#endif // GTEST_HAS_ABSL
1391
jgm38513a82012-11-15 15:50:36 +00001392 // Accepts pointer types, particularly:
1393 // const char*
1394 // char*
1395 // const wchar_t*
1396 // wchar_t*
1397 template <typename CharType>
1398 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001399 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001400 }
1401
jgm38513a82012-11-15 15:50:36 +00001402 // Matches anything that can convert to StringType.
1403 //
1404 // This is a template, not just a plain function with const StringType&,
Gennadiy Civile55089e2018-04-04 14:05:00 -04001405 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001406 template <typename MatcheeStringType>
1407 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001408 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001409 const StringType& s2(s);
1410 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001411 }
1412
1413 // Describes what this matcher matches.
1414 void DescribeTo(::std::ostream* os) const {
1415 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001416 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001417 }
1418
1419 void DescribeNegationTo(::std::ostream* os) const {
1420 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001421 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001422 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001423
shiqiane35fdd92008-12-10 05:08:54 +00001424 private:
1425 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001426
1427 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001428};
1429
1430// Implements the polymorphic StartsWith(substring) matcher, which
1431// can be used as a Matcher<T> as long as T can be converted to a
1432// string.
1433template <typename StringType>
1434class StartsWithMatcher {
1435 public:
shiqiane35fdd92008-12-10 05:08:54 +00001436 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1437 }
1438
Gennadiy Civile55089e2018-04-04 14:05:00 -04001439#if GTEST_HAS_ABSL
1440 bool MatchAndExplain(const absl::string_view& s,
1441 MatchResultListener* listener) const {
1442 if (s.data() == NULL) {
1443 return false;
1444 }
1445 // This should fail to compile if absl::string_view is used with wide
1446 // strings.
1447 const StringType& str = string(s);
1448 return MatchAndExplain(str, listener);
1449 }
1450#endif // GTEST_HAS_ABSL
1451
jgm38513a82012-11-15 15:50:36 +00001452 // Accepts pointer types, particularly:
1453 // const char*
1454 // char*
1455 // const wchar_t*
1456 // wchar_t*
1457 template <typename CharType>
1458 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001459 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001460 }
1461
jgm38513a82012-11-15 15:50:36 +00001462 // Matches anything that can convert to StringType.
1463 //
1464 // This is a template, not just a plain function with const StringType&,
Gennadiy Civile55089e2018-04-04 14:05:00 -04001465 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001466 template <typename MatcheeStringType>
1467 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001468 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001469 const StringType& s2(s);
1470 return s2.length() >= prefix_.length() &&
1471 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001472 }
1473
1474 void DescribeTo(::std::ostream* os) const {
1475 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001476 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001477 }
1478
1479 void DescribeNegationTo(::std::ostream* os) const {
1480 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001481 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001482 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001483
shiqiane35fdd92008-12-10 05:08:54 +00001484 private:
1485 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001486
1487 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001488};
1489
1490// Implements the polymorphic EndsWith(substring) matcher, which
1491// can be used as a Matcher<T> as long as T can be converted to a
1492// string.
1493template <typename StringType>
1494class EndsWithMatcher {
1495 public:
shiqiane35fdd92008-12-10 05:08:54 +00001496 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1497
Gennadiy Civile55089e2018-04-04 14:05:00 -04001498#if GTEST_HAS_ABSL
1499 bool MatchAndExplain(const absl::string_view& s,
1500 MatchResultListener* listener) const {
1501 if (s.data() == NULL) {
1502 return false;
1503 }
1504 // This should fail to compile if absl::string_view is used with wide
1505 // strings.
1506 const StringType& str = string(s);
1507 return MatchAndExplain(str, listener);
1508 }
1509#endif // GTEST_HAS_ABSL
1510
jgm38513a82012-11-15 15:50:36 +00001511 // Accepts pointer types, particularly:
1512 // const char*
1513 // char*
1514 // const wchar_t*
1515 // wchar_t*
1516 template <typename CharType>
1517 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001518 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001519 }
1520
jgm38513a82012-11-15 15:50:36 +00001521 // Matches anything that can convert to StringType.
1522 //
1523 // This is a template, not just a plain function with const StringType&,
Gennadiy Civile55089e2018-04-04 14:05:00 -04001524 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001525 template <typename MatcheeStringType>
1526 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001527 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001528 const StringType& s2(s);
1529 return s2.length() >= suffix_.length() &&
1530 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001531 }
1532
1533 void DescribeTo(::std::ostream* os) const {
1534 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001535 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001536 }
1537
1538 void DescribeNegationTo(::std::ostream* os) const {
1539 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001540 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001541 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001542
shiqiane35fdd92008-12-10 05:08:54 +00001543 private:
1544 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001545
1546 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001547};
1548
shiqiane35fdd92008-12-10 05:08:54 +00001549// Implements polymorphic matchers MatchesRegex(regex) and
1550// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1551// T can be converted to a string.
1552class MatchesRegexMatcher {
1553 public:
1554 MatchesRegexMatcher(const RE* regex, bool full_match)
1555 : regex_(regex), full_match_(full_match) {}
1556
Gennadiy Civile55089e2018-04-04 14:05:00 -04001557#if GTEST_HAS_ABSL
1558 bool MatchAndExplain(const absl::string_view& s,
1559 MatchResultListener* listener) const {
1560 return s.data() && MatchAndExplain(string(s), listener);
1561 }
1562#endif // GTEST_HAS_ABSL
1563
jgm38513a82012-11-15 15:50:36 +00001564 // Accepts pointer types, particularly:
1565 // const char*
1566 // char*
1567 // const wchar_t*
1568 // wchar_t*
1569 template <typename CharType>
1570 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001571 return s != NULL && MatchAndExplain(std::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001572 }
1573
Nico Weber09fd5b32017-05-15 17:07:03 -04001574 // Matches anything that can convert to std::string.
jgm38513a82012-11-15 15:50:36 +00001575 //
Nico Weber09fd5b32017-05-15 17:07:03 -04001576 // This is a template, not just a plain function with const std::string&,
Gennadiy Civilb7c56832018-03-22 15:35:37 -04001577 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001578 template <class MatcheeStringType>
1579 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001580 MatchResultListener* /* listener */) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001581 const std::string& s2(s);
jgm38513a82012-11-15 15:50:36 +00001582 return full_match_ ? RE::FullMatch(s2, *regex_) :
1583 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001584 }
1585
1586 void DescribeTo(::std::ostream* os) const {
1587 *os << (full_match_ ? "matches" : "contains")
1588 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001589 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001590 }
1591
1592 void DescribeNegationTo(::std::ostream* os) const {
1593 *os << "doesn't " << (full_match_ ? "match" : "contain")
1594 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001595 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001596 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001597
shiqiane35fdd92008-12-10 05:08:54 +00001598 private:
1599 const internal::linked_ptr<const RE> regex_;
1600 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001601
1602 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001603};
1604
shiqiane35fdd92008-12-10 05:08:54 +00001605// Implements a matcher that compares the two fields of a 2-tuple
1606// using one of the ==, <=, <, etc, operators. The two fields being
1607// compared don't have to have the same type.
1608//
1609// The matcher defined here is polymorphic (for example, Eq() can be
1610// used to match a tuple<int, short>, a tuple<const long&, double>,
1611// etc). Therefore we use a template type conversion operator in the
1612// implementation.
kosak506340a2014-11-17 01:47:54 +00001613template <typename D, typename Op>
1614class PairMatchBase {
1615 public:
1616 template <typename T1, typename T2>
1617 operator Matcher< ::testing::tuple<T1, T2> >() const {
1618 return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >);
1619 }
1620 template <typename T1, typename T2>
1621 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
1622 return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>);
shiqiane35fdd92008-12-10 05:08:54 +00001623 }
1624
kosak506340a2014-11-17 01:47:54 +00001625 private:
1626 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
1627 return os << D::Desc();
1628 }
shiqiane35fdd92008-12-10 05:08:54 +00001629
kosak506340a2014-11-17 01:47:54 +00001630 template <typename Tuple>
1631 class Impl : public MatcherInterface<Tuple> {
1632 public:
1633 virtual bool MatchAndExplain(
1634 Tuple args,
1635 MatchResultListener* /* listener */) const {
1636 return Op()(::testing::get<0>(args), ::testing::get<1>(args));
1637 }
1638 virtual void DescribeTo(::std::ostream* os) const {
1639 *os << "are " << GetDesc;
1640 }
1641 virtual void DescribeNegationTo(::std::ostream* os) const {
1642 *os << "aren't " << GetDesc;
1643 }
1644 };
1645};
1646
1647class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
1648 public:
1649 static const char* Desc() { return "an equal pair"; }
1650};
1651class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
1652 public:
1653 static const char* Desc() { return "an unequal pair"; }
1654};
1655class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
1656 public:
1657 static const char* Desc() { return "a pair where the first < the second"; }
1658};
1659class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
1660 public:
1661 static const char* Desc() { return "a pair where the first > the second"; }
1662};
1663class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
1664 public:
1665 static const char* Desc() { return "a pair where the first <= the second"; }
1666};
1667class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
1668 public:
1669 static const char* Desc() { return "a pair where the first >= the second"; }
1670};
shiqiane35fdd92008-12-10 05:08:54 +00001671
zhanyong.wanc6a41232009-05-13 23:38:40 +00001672// Implements the Not(...) matcher for a particular argument type T.
1673// We do not nest it inside the NotMatcher class template, as that
1674// will prevent different instantiations of NotMatcher from sharing
1675// the same NotMatcherImpl<T> class.
1676template <typename T>
Gennadiy Civile55089e2018-04-04 14:05:00 -04001677class NotMatcherImpl : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001678 public:
1679 explicit NotMatcherImpl(const Matcher<T>& matcher)
1680 : matcher_(matcher) {}
1681
Gennadiy Civile55089e2018-04-04 14:05:00 -04001682 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
1683 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001684 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001685 }
1686
1687 virtual void DescribeTo(::std::ostream* os) const {
1688 matcher_.DescribeNegationTo(os);
1689 }
1690
1691 virtual void DescribeNegationTo(::std::ostream* os) const {
1692 matcher_.DescribeTo(os);
1693 }
1694
zhanyong.wanc6a41232009-05-13 23:38:40 +00001695 private:
1696 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001697
1698 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001699};
1700
shiqiane35fdd92008-12-10 05:08:54 +00001701// Implements the Not(m) matcher, which matches a value that doesn't
1702// match matcher m.
1703template <typename InnerMatcher>
1704class NotMatcher {
1705 public:
1706 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1707
1708 // This template type conversion operator allows Not(m) to be used
1709 // to match any type m can match.
1710 template <typename T>
1711 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001712 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001713 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001714
shiqiane35fdd92008-12-10 05:08:54 +00001715 private:
shiqiane35fdd92008-12-10 05:08:54 +00001716 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001717
1718 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001719};
1720
zhanyong.wanc6a41232009-05-13 23:38:40 +00001721// Implements the AllOf(m1, m2) matcher for a particular argument type
1722// T. We do not nest it inside the BothOfMatcher class template, as
1723// that will prevent different instantiations of BothOfMatcher from
1724// sharing the same BothOfMatcherImpl<T> class.
1725template <typename T>
Gennadiy Civilb5391672018-04-25 13:10:41 -04001726class AllOfMatcherImpl
Gennadiy Civile55089e2018-04-04 14:05:00 -04001727 : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001728 public:
Gennadiy Civilb5391672018-04-25 13:10:41 -04001729 explicit AllOfMatcherImpl(std::vector<Matcher<T> > matchers)
1730 : matchers_(internal::move(matchers)) {}
zhanyong.wanc6a41232009-05-13 23:38:40 +00001731
zhanyong.wanc6a41232009-05-13 23:38:40 +00001732 virtual void DescribeTo(::std::ostream* os) const {
1733 *os << "(";
Gennadiy Civilb5391672018-04-25 13:10:41 -04001734 for (size_t i = 0; i < matchers_.size(); ++i) {
1735 if (i != 0) *os << ") and (";
1736 matchers_[i].DescribeTo(os);
1737 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001738 *os << ")";
1739 }
1740
1741 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001742 *os << "(";
Gennadiy Civilb5391672018-04-25 13:10:41 -04001743 for (size_t i = 0; i < matchers_.size(); ++i) {
1744 if (i != 0) *os << ") or (";
1745 matchers_[i].DescribeNegationTo(os);
1746 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001747 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001748 }
1749
Gennadiy Civile55089e2018-04-04 14:05:00 -04001750 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
1751 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001752 // If either matcher1_ or matcher2_ doesn't match x, we only need
1753 // to explain why one of them fails.
Gennadiy Civilb5391672018-04-25 13:10:41 -04001754 std::string all_match_result;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001755
Gennadiy Civilb5391672018-04-25 13:10:41 -04001756 for (size_t i = 0; i < matchers_.size(); ++i) {
1757 StringMatchResultListener slistener;
1758 if (matchers_[i].MatchAndExplain(x, &slistener)) {
1759 if (all_match_result.empty()) {
1760 all_match_result = slistener.str();
1761 } else {
1762 std::string result = slistener.str();
1763 if (!result.empty()) {
1764 all_match_result += ", and ";
1765 all_match_result += result;
1766 }
1767 }
1768 } else {
1769 *listener << slistener.str();
1770 return false;
1771 }
zhanyong.wan82113312010-01-08 21:55:40 +00001772 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001773
zhanyong.wan82113312010-01-08 21:55:40 +00001774 // Otherwise we need to explain why *both* of them match.
Gennadiy Civilb5391672018-04-25 13:10:41 -04001775 *listener << all_match_result;
zhanyong.wan82113312010-01-08 21:55:40 +00001776 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001777 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001778
zhanyong.wanc6a41232009-05-13 23:38:40 +00001779 private:
Gennadiy Civilb5391672018-04-25 13:10:41 -04001780 const std::vector<Matcher<T> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001781
Gennadiy Civilb5391672018-04-25 13:10:41 -04001782 GTEST_DISALLOW_ASSIGN_(AllOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001783};
1784
zhanyong.wan616180e2013-06-18 18:49:51 +00001785#if GTEST_LANG_CXX11
zhanyong.wan616180e2013-06-18 18:49:51 +00001786// VariadicMatcher is used for the variadic implementation of
1787// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1788// CombiningMatcher<T> is used to recursively combine the provided matchers
1789// (of type Args...).
1790template <template <typename T> class CombiningMatcher, typename... Args>
1791class VariadicMatcher {
1792 public:
1793 VariadicMatcher(const Args&... matchers) // NOLINT
Gennadiy Civilb5391672018-04-25 13:10:41 -04001794 : matchers_(matchers...) {
1795 static_assert(sizeof...(Args) > 0, "Must have at least one matcher.");
1796 }
zhanyong.wan616180e2013-06-18 18:49:51 +00001797
1798 // This template type conversion operator allows an
1799 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1800 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1801 template <typename T>
1802 operator Matcher<T>() const {
Gennadiy Civilb5391672018-04-25 13:10:41 -04001803 std::vector<Matcher<T> > values;
1804 CreateVariadicMatcher<T>(&values, std::integral_constant<size_t, 0>());
1805 return Matcher<T>(new CombiningMatcher<T>(internal::move(values)));
zhanyong.wan616180e2013-06-18 18:49:51 +00001806 }
1807
1808 private:
Gennadiy Civilb5391672018-04-25 13:10:41 -04001809 template <typename T, size_t I>
1810 void CreateVariadicMatcher(std::vector<Matcher<T> >* values,
1811 std::integral_constant<size_t, I>) const {
1812 values->push_back(SafeMatcherCast<T>(std::get<I>(matchers_)));
1813 CreateVariadicMatcher<T>(values, std::integral_constant<size_t, I + 1>());
1814 }
zhanyong.wan616180e2013-06-18 18:49:51 +00001815
Gennadiy Civilb5391672018-04-25 13:10:41 -04001816 template <typename T>
1817 void CreateVariadicMatcher(
1818 std::vector<Matcher<T> >*,
1819 std::integral_constant<size_t, sizeof...(Args)>) const {}
1820
1821 tuple<Args...> matchers_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001822
1823 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1824};
1825
1826template <typename... Args>
Gennadiy Civilb5391672018-04-25 13:10:41 -04001827using AllOfMatcher = VariadicMatcher<AllOfMatcherImpl, Args...>;
zhanyong.wan616180e2013-06-18 18:49:51 +00001828
1829#endif // GTEST_LANG_CXX11
1830
shiqiane35fdd92008-12-10 05:08:54 +00001831// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1832// matches a value that matches all of the matchers m_1, ..., and m_n.
1833template <typename Matcher1, typename Matcher2>
1834class BothOfMatcher {
1835 public:
1836 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1837 : matcher1_(matcher1), matcher2_(matcher2) {}
1838
1839 // This template type conversion operator allows a
1840 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1841 // both Matcher1 and Matcher2 can match.
1842 template <typename T>
1843 operator Matcher<T>() const {
Gennadiy Civilb5391672018-04-25 13:10:41 -04001844 std::vector<Matcher<T> > values;
1845 values.push_back(SafeMatcherCast<T>(matcher1_));
1846 values.push_back(SafeMatcherCast<T>(matcher2_));
1847 return Matcher<T>(new AllOfMatcherImpl<T>(internal::move(values)));
shiqiane35fdd92008-12-10 05:08:54 +00001848 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001849
shiqiane35fdd92008-12-10 05:08:54 +00001850 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001851 Matcher1 matcher1_;
1852 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001853
1854 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001855};
shiqiane35fdd92008-12-10 05:08:54 +00001856
zhanyong.wanc6a41232009-05-13 23:38:40 +00001857// Implements the AnyOf(m1, m2) matcher for a particular argument type
1858// T. We do not nest it inside the AnyOfMatcher class template, as
1859// that will prevent different instantiations of AnyOfMatcher from
1860// sharing the same EitherOfMatcherImpl<T> class.
1861template <typename T>
Gennadiy Civilb5391672018-04-25 13:10:41 -04001862class AnyOfMatcherImpl
Gennadiy Civile55089e2018-04-04 14:05:00 -04001863 : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001864 public:
Gennadiy Civilb5391672018-04-25 13:10:41 -04001865 explicit AnyOfMatcherImpl(std::vector<Matcher<T> > matchers)
1866 : matchers_(internal::move(matchers)) {}
shiqiane35fdd92008-12-10 05:08:54 +00001867
zhanyong.wanc6a41232009-05-13 23:38:40 +00001868 virtual void DescribeTo(::std::ostream* os) const {
1869 *os << "(";
Gennadiy Civilb5391672018-04-25 13:10:41 -04001870 for (size_t i = 0; i < matchers_.size(); ++i) {
1871 if (i != 0) *os << ") or (";
1872 matchers_[i].DescribeTo(os);
1873 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001874 *os << ")";
1875 }
shiqiane35fdd92008-12-10 05:08:54 +00001876
zhanyong.wanc6a41232009-05-13 23:38:40 +00001877 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001878 *os << "(";
Gennadiy Civilb5391672018-04-25 13:10:41 -04001879 for (size_t i = 0; i < matchers_.size(); ++i) {
1880 if (i != 0) *os << ") and (";
1881 matchers_[i].DescribeNegationTo(os);
1882 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001883 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001884 }
shiqiane35fdd92008-12-10 05:08:54 +00001885
Gennadiy Civile55089e2018-04-04 14:05:00 -04001886 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
1887 MatchResultListener* listener) const {
Gennadiy Civilb5391672018-04-25 13:10:41 -04001888 std::string no_match_result;
1889
zhanyong.wan82113312010-01-08 21:55:40 +00001890 // If either matcher1_ or matcher2_ matches x, we just need to
1891 // explain why *one* of them matches.
Gennadiy Civilb5391672018-04-25 13:10:41 -04001892 for (size_t i = 0; i < matchers_.size(); ++i) {
1893 StringMatchResultListener slistener;
1894 if (matchers_[i].MatchAndExplain(x, &slistener)) {
1895 *listener << slistener.str();
1896 return true;
1897 } else {
1898 if (no_match_result.empty()) {
1899 no_match_result = slistener.str();
1900 } else {
1901 std::string result = slistener.str();
1902 if (!result.empty()) {
1903 no_match_result += ", and ";
1904 no_match_result += result;
1905 }
1906 }
1907 }
zhanyong.wan82113312010-01-08 21:55:40 +00001908 }
1909
1910 // Otherwise we need to explain why *both* of them fail.
Gennadiy Civilb5391672018-04-25 13:10:41 -04001911 *listener << no_match_result;
zhanyong.wan82113312010-01-08 21:55:40 +00001912 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001913 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001914
zhanyong.wanc6a41232009-05-13 23:38:40 +00001915 private:
Gennadiy Civilb5391672018-04-25 13:10:41 -04001916 const std::vector<Matcher<T> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001917
Gennadiy Civilb5391672018-04-25 13:10:41 -04001918 GTEST_DISALLOW_ASSIGN_(AnyOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001919};
1920
zhanyong.wan616180e2013-06-18 18:49:51 +00001921#if GTEST_LANG_CXX11
1922// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1923template <typename... Args>
Gennadiy Civilb5391672018-04-25 13:10:41 -04001924using AnyOfMatcher = VariadicMatcher<AnyOfMatcherImpl, Args...>;
zhanyong.wan616180e2013-06-18 18:49:51 +00001925
1926#endif // GTEST_LANG_CXX11
1927
shiqiane35fdd92008-12-10 05:08:54 +00001928// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1929// matches a value that matches at least one of the matchers m_1, ...,
1930// and m_n.
1931template <typename Matcher1, typename Matcher2>
1932class EitherOfMatcher {
1933 public:
1934 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1935 : matcher1_(matcher1), matcher2_(matcher2) {}
1936
1937 // This template type conversion operator allows a
1938 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1939 // both Matcher1 and Matcher2 can match.
1940 template <typename T>
1941 operator Matcher<T>() const {
Gennadiy Civilb5391672018-04-25 13:10:41 -04001942 std::vector<Matcher<T> > values;
1943 values.push_back(SafeMatcherCast<T>(matcher1_));
1944 values.push_back(SafeMatcherCast<T>(matcher2_));
1945 return Matcher<T>(new AnyOfMatcherImpl<T>(internal::move(values)));
shiqiane35fdd92008-12-10 05:08:54 +00001946 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001947
shiqiane35fdd92008-12-10 05:08:54 +00001948 private:
shiqiane35fdd92008-12-10 05:08:54 +00001949 Matcher1 matcher1_;
1950 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001951
1952 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001953};
1954
1955// Used for implementing Truly(pred), which turns a predicate into a
1956// matcher.
1957template <typename Predicate>
1958class TrulyMatcher {
1959 public:
1960 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1961
1962 // This method template allows Truly(pred) to be used as a matcher
1963 // for type T where T is the argument type of predicate 'pred'. The
1964 // argument is passed by reference as the predicate may be
1965 // interested in the address of the argument.
1966 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001967 bool MatchAndExplain(T& x, // NOLINT
1968 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001969 // Without the if-statement, MSVC sometimes warns about converting
1970 // a value to bool (warning 4800).
1971 //
1972 // We cannot write 'return !!predicate_(x);' as that doesn't work
1973 // when predicate_(x) returns a class convertible to bool but
1974 // having no operator!().
1975 if (predicate_(x))
1976 return true;
1977 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001978 }
1979
1980 void DescribeTo(::std::ostream* os) const {
1981 *os << "satisfies the given predicate";
1982 }
1983
1984 void DescribeNegationTo(::std::ostream* os) const {
1985 *os << "doesn't satisfy the given predicate";
1986 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001987
shiqiane35fdd92008-12-10 05:08:54 +00001988 private:
1989 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001990
1991 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001992};
1993
1994// Used for implementing Matches(matcher), which turns a matcher into
1995// a predicate.
1996template <typename M>
1997class MatcherAsPredicate {
1998 public:
1999 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
2000
2001 // This template operator() allows Matches(m) to be used as a
2002 // predicate on type T where m is a matcher on type T.
2003 //
2004 // The argument x is passed by reference instead of by value, as
2005 // some matcher may be interested in its address (e.g. as in
2006 // Matches(Ref(n))(x)).
2007 template <typename T>
2008 bool operator()(const T& x) const {
2009 // We let matcher_ commit to a particular type here instead of
2010 // when the MatcherAsPredicate object was constructed. This
2011 // allows us to write Matches(m) where m is a polymorphic matcher
2012 // (e.g. Eq(5)).
2013 //
2014 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
2015 // compile when matcher_ has type Matcher<const T&>; if we write
2016 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
2017 // when matcher_ has type Matcher<T>; if we just write
2018 // matcher_.Matches(x), it won't compile when matcher_ is
2019 // polymorphic, e.g. Eq(5).
2020 //
2021 // MatcherCast<const T&>() is necessary for making the code work
2022 // in all of the above situations.
2023 return MatcherCast<const T&>(matcher_).Matches(x);
2024 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002025
shiqiane35fdd92008-12-10 05:08:54 +00002026 private:
2027 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002028
2029 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00002030};
2031
2032// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
2033// argument M must be a type that can be converted to a matcher.
2034template <typename M>
2035class PredicateFormatterFromMatcher {
2036 public:
kosak9b1a9442015-04-28 23:06:58 +00002037 explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {}
shiqiane35fdd92008-12-10 05:08:54 +00002038
2039 // This template () operator allows a PredicateFormatterFromMatcher
2040 // object to act as a predicate-formatter suitable for using with
2041 // Google Test's EXPECT_PRED_FORMAT1() macro.
2042 template <typename T>
2043 AssertionResult operator()(const char* value_text, const T& x) const {
2044 // We convert matcher_ to a Matcher<const T&> *now* instead of
2045 // when the PredicateFormatterFromMatcher object was constructed,
2046 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
2047 // know which type to instantiate it to until we actually see the
2048 // type of x here.
2049 //
zhanyong.wanf4274522013-04-24 02:49:43 +00002050 // We write SafeMatcherCast<const T&>(matcher_) instead of
shiqiane35fdd92008-12-10 05:08:54 +00002051 // Matcher<const T&>(matcher_), as the latter won't compile when
2052 // matcher_ has type Matcher<T> (e.g. An<int>()).
zhanyong.wanf4274522013-04-24 02:49:43 +00002053 // We don't write MatcherCast<const T&> either, as that allows
2054 // potentially unsafe downcasting of the matcher argument.
2055 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00002056 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002057 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00002058 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002059
2060 ::std::stringstream ss;
2061 ss << "Value of: " << value_text << "\n"
2062 << "Expected: ";
2063 matcher.DescribeTo(&ss);
2064 ss << "\n Actual: " << listener.str();
2065 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00002066 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002067
shiqiane35fdd92008-12-10 05:08:54 +00002068 private:
2069 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002070
2071 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002072};
2073
2074// A helper function for converting a matcher to a predicate-formatter
2075// without the user needing to explicitly write the type. This is
2076// used for implementing ASSERT_THAT() and EXPECT_THAT().
kosak9b1a9442015-04-28 23:06:58 +00002077// Implementation detail: 'matcher' is received by-value to force decaying.
shiqiane35fdd92008-12-10 05:08:54 +00002078template <typename M>
2079inline PredicateFormatterFromMatcher<M>
kosak9b1a9442015-04-28 23:06:58 +00002080MakePredicateFormatterFromMatcher(M matcher) {
2081 return PredicateFormatterFromMatcher<M>(internal::move(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00002082}
2083
zhanyong.wan616180e2013-06-18 18:49:51 +00002084// Implements the polymorphic floating point equality matcher, which matches
2085// two float values using ULP-based approximation or, optionally, a
2086// user-specified epsilon. The template is meant to be instantiated with
2087// FloatType being either float or double.
shiqiane35fdd92008-12-10 05:08:54 +00002088template <typename FloatType>
2089class FloatingEqMatcher {
2090 public:
2091 // Constructor for FloatingEqMatcher.
kosak6b817802015-01-08 02:38:14 +00002092 // The matcher's input will be compared with expected. The matcher treats two
shiqiane35fdd92008-12-10 05:08:54 +00002093 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
zhanyong.wan616180e2013-06-18 18:49:51 +00002094 // equality comparisons between NANs will always return false. We specify a
2095 // negative max_abs_error_ term to indicate that ULP-based approximation will
2096 // be used for comparison.
kosak6b817802015-01-08 02:38:14 +00002097 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
2098 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
zhanyong.wan616180e2013-06-18 18:49:51 +00002099 }
2100
2101 // Constructor that supports a user-specified max_abs_error that will be used
2102 // for comparison instead of ULP-based approximation. The max absolute
2103 // should be non-negative.
kosak6b817802015-01-08 02:38:14 +00002104 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
2105 FloatType max_abs_error)
2106 : expected_(expected),
2107 nan_eq_nan_(nan_eq_nan),
2108 max_abs_error_(max_abs_error) {
zhanyong.wan616180e2013-06-18 18:49:51 +00002109 GTEST_CHECK_(max_abs_error >= 0)
2110 << ", where max_abs_error is" << max_abs_error;
2111 }
shiqiane35fdd92008-12-10 05:08:54 +00002112
2113 // Implements floating point equality matcher as a Matcher<T>.
2114 template <typename T>
2115 class Impl : public MatcherInterface<T> {
2116 public:
kosak6b817802015-01-08 02:38:14 +00002117 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
2118 : expected_(expected),
2119 nan_eq_nan_(nan_eq_nan),
2120 max_abs_error_(max_abs_error) {}
shiqiane35fdd92008-12-10 05:08:54 +00002121
zhanyong.wan82113312010-01-08 21:55:40 +00002122 virtual bool MatchAndExplain(T value,
kosak6b817802015-01-08 02:38:14 +00002123 MatchResultListener* listener) const {
2124 const FloatingPoint<FloatType> actual(value), expected(expected_);
shiqiane35fdd92008-12-10 05:08:54 +00002125
2126 // Compares NaNs first, if nan_eq_nan_ is true.
kosak6b817802015-01-08 02:38:14 +00002127 if (actual.is_nan() || expected.is_nan()) {
2128 if (actual.is_nan() && expected.is_nan()) {
zhanyong.wan616180e2013-06-18 18:49:51 +00002129 return nan_eq_nan_;
2130 }
2131 // One is nan; the other is not nan.
2132 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002133 }
zhanyong.wan616180e2013-06-18 18:49:51 +00002134 if (HasMaxAbsError()) {
2135 // We perform an equality check so that inf will match inf, regardless
kosak6b817802015-01-08 02:38:14 +00002136 // of error bounds. If the result of value - expected_ would result in
zhanyong.wan616180e2013-06-18 18:49:51 +00002137 // overflow or if either value is inf, the default result is infinity,
2138 // which should only match if max_abs_error_ is also infinity.
kosak6b817802015-01-08 02:38:14 +00002139 if (value == expected_) {
2140 return true;
2141 }
2142
2143 const FloatType diff = value - expected_;
2144 if (fabs(diff) <= max_abs_error_) {
2145 return true;
2146 }
2147
2148 if (listener->IsInterested()) {
2149 *listener << "which is " << diff << " from " << expected_;
2150 }
2151 return false;
zhanyong.wan616180e2013-06-18 18:49:51 +00002152 } else {
kosak6b817802015-01-08 02:38:14 +00002153 return actual.AlmostEquals(expected);
zhanyong.wan616180e2013-06-18 18:49:51 +00002154 }
shiqiane35fdd92008-12-10 05:08:54 +00002155 }
2156
2157 virtual void DescribeTo(::std::ostream* os) const {
2158 // os->precision() returns the previously set precision, which we
2159 // store to restore the ostream to its original configuration
2160 // after outputting.
2161 const ::std::streamsize old_precision = os->precision(
2162 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00002163 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00002164 if (nan_eq_nan_) {
2165 *os << "is NaN";
2166 } else {
2167 *os << "never matches";
2168 }
2169 } else {
kosak6b817802015-01-08 02:38:14 +00002170 *os << "is approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002171 if (HasMaxAbsError()) {
2172 *os << " (absolute error <= " << max_abs_error_ << ")";
2173 }
shiqiane35fdd92008-12-10 05:08:54 +00002174 }
2175 os->precision(old_precision);
2176 }
2177
2178 virtual void DescribeNegationTo(::std::ostream* os) const {
2179 // As before, get original precision.
2180 const ::std::streamsize old_precision = os->precision(
2181 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00002182 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00002183 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002184 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00002185 } else {
2186 *os << "is anything";
2187 }
2188 } else {
kosak6b817802015-01-08 02:38:14 +00002189 *os << "isn't approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002190 if (HasMaxAbsError()) {
2191 *os << " (absolute error > " << max_abs_error_ << ")";
2192 }
shiqiane35fdd92008-12-10 05:08:54 +00002193 }
2194 // Restore original precision.
2195 os->precision(old_precision);
2196 }
2197
2198 private:
zhanyong.wan616180e2013-06-18 18:49:51 +00002199 bool HasMaxAbsError() const {
2200 return max_abs_error_ >= 0;
2201 }
2202
kosak6b817802015-01-08 02:38:14 +00002203 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002204 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002205 // max_abs_error will be used for value comparison when >= 0.
2206 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002207
2208 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002209 };
2210
kosak6b817802015-01-08 02:38:14 +00002211 // The following 3 type conversion operators allow FloatEq(expected) and
2212 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
shiqiane35fdd92008-12-10 05:08:54 +00002213 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
2214 // (While Google's C++ coding style doesn't allow arguments passed
2215 // by non-const reference, we may see them in code not conforming to
2216 // the style. Therefore Google Mock needs to support them.)
2217 operator Matcher<FloatType>() const {
kosak6b817802015-01-08 02:38:14 +00002218 return MakeMatcher(
2219 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002220 }
2221
2222 operator Matcher<const FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00002223 return MakeMatcher(
kosak6b817802015-01-08 02:38:14 +00002224 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002225 }
2226
2227 operator Matcher<FloatType&>() const {
kosak6b817802015-01-08 02:38:14 +00002228 return MakeMatcher(
2229 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002230 }
jgm79a367e2012-04-10 16:02:11 +00002231
shiqiane35fdd92008-12-10 05:08:54 +00002232 private:
kosak6b817802015-01-08 02:38:14 +00002233 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002234 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002235 // max_abs_error will be used for value comparison when >= 0.
2236 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002237
2238 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002239};
2240
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002241// A 2-tuple ("binary") wrapper around FloatingEqMatcher:
2242// FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false)
2243// against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e)
2244// against y. The former implements "Eq", the latter "Near". At present, there
2245// is no version that compares NaNs as equal.
2246template <typename FloatType>
2247class FloatingEq2Matcher {
2248 public:
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002249 FloatingEq2Matcher() { Init(-1, false); }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002250
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002251 explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002252
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002253 explicit FloatingEq2Matcher(FloatType max_abs_error) {
2254 Init(max_abs_error, false);
2255 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002256
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002257 FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) {
2258 Init(max_abs_error, nan_eq_nan);
2259 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002260
2261 template <typename T1, typename T2>
2262 operator Matcher< ::testing::tuple<T1, T2> >() const {
2263 return MakeMatcher(
2264 new Impl< ::testing::tuple<T1, T2> >(max_abs_error_, nan_eq_nan_));
2265 }
2266 template <typename T1, typename T2>
2267 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
2268 return MakeMatcher(
2269 new Impl<const ::testing::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_));
2270 }
2271
2272 private:
2273 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
2274 return os << "an almost-equal pair";
2275 }
2276
2277 template <typename Tuple>
2278 class Impl : public MatcherInterface<Tuple> {
2279 public:
2280 Impl(FloatType max_abs_error, bool nan_eq_nan) :
2281 max_abs_error_(max_abs_error),
2282 nan_eq_nan_(nan_eq_nan) {}
2283
2284 virtual bool MatchAndExplain(Tuple args,
2285 MatchResultListener* listener) const {
2286 if (max_abs_error_ == -1) {
2287 FloatingEqMatcher<FloatType> fm(::testing::get<0>(args), nan_eq_nan_);
2288 return static_cast<Matcher<FloatType> >(fm).MatchAndExplain(
2289 ::testing::get<1>(args), listener);
2290 } else {
2291 FloatingEqMatcher<FloatType> fm(::testing::get<0>(args), nan_eq_nan_,
2292 max_abs_error_);
2293 return static_cast<Matcher<FloatType> >(fm).MatchAndExplain(
2294 ::testing::get<1>(args), listener);
2295 }
2296 }
2297 virtual void DescribeTo(::std::ostream* os) const {
2298 *os << "are " << GetDesc;
2299 }
2300 virtual void DescribeNegationTo(::std::ostream* os) const {
2301 *os << "aren't " << GetDesc;
2302 }
2303
2304 private:
2305 FloatType max_abs_error_;
2306 const bool nan_eq_nan_;
2307 };
2308
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002309 void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) {
2310 max_abs_error_ = max_abs_error_val;
2311 nan_eq_nan_ = nan_eq_nan_val;
2312 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002313 FloatType max_abs_error_;
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002314 bool nan_eq_nan_;
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002315};
2316
shiqiane35fdd92008-12-10 05:08:54 +00002317// Implements the Pointee(m) matcher for matching a pointer whose
2318// pointee matches matcher m. The pointer can be either raw or smart.
2319template <typename InnerMatcher>
2320class PointeeMatcher {
2321 public:
2322 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
2323
2324 // This type conversion operator template allows Pointee(m) to be
2325 // used as a matcher for any pointer type whose pointee type is
2326 // compatible with the inner matcher, where type Pointer can be
2327 // either a raw pointer or a smart pointer.
2328 //
2329 // The reason we do this instead of relying on
2330 // MakePolymorphicMatcher() is that the latter is not flexible
2331 // enough for implementing the DescribeTo() method of Pointee().
2332 template <typename Pointer>
2333 operator Matcher<Pointer>() const {
Gennadiy Civile55089e2018-04-04 14:05:00 -04002334 return Matcher<Pointer>(
2335 new Impl<GTEST_REFERENCE_TO_CONST_(Pointer)>(matcher_));
shiqiane35fdd92008-12-10 05:08:54 +00002336 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002337
shiqiane35fdd92008-12-10 05:08:54 +00002338 private:
2339 // The monomorphic implementation that works for a particular pointer type.
2340 template <typename Pointer>
2341 class Impl : public MatcherInterface<Pointer> {
2342 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00002343 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
2344 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00002345
2346 explicit Impl(const InnerMatcher& matcher)
2347 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
2348
shiqiane35fdd92008-12-10 05:08:54 +00002349 virtual void DescribeTo(::std::ostream* os) const {
2350 *os << "points to a value that ";
2351 matcher_.DescribeTo(os);
2352 }
2353
2354 virtual void DescribeNegationTo(::std::ostream* os) const {
2355 *os << "does not point to a value that ";
2356 matcher_.DescribeTo(os);
2357 }
2358
zhanyong.wan82113312010-01-08 21:55:40 +00002359 virtual bool MatchAndExplain(Pointer pointer,
2360 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00002361 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00002362 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002363
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002364 *listener << "which points to ";
2365 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002366 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002367
shiqiane35fdd92008-12-10 05:08:54 +00002368 private:
2369 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002370
2371 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002372 };
2373
2374 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002375
2376 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002377};
2378
Scott Grahama9653c42018-05-02 11:14:39 -07002379#if GTEST_HAS_RTTI
billydonahue1f5fdea2014-05-19 17:54:51 +00002380// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2381// reference that matches inner_matcher when dynamic_cast<T> is applied.
2382// The result of dynamic_cast<To> is forwarded to the inner matcher.
2383// If To is a pointer and the cast fails, the inner matcher will receive NULL.
2384// If To is a reference and the cast fails, this matcher returns false
2385// immediately.
2386template <typename To>
2387class WhenDynamicCastToMatcherBase {
2388 public:
2389 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2390 : matcher_(matcher) {}
2391
2392 void DescribeTo(::std::ostream* os) const {
2393 GetCastTypeDescription(os);
2394 matcher_.DescribeTo(os);
2395 }
2396
2397 void DescribeNegationTo(::std::ostream* os) const {
2398 GetCastTypeDescription(os);
2399 matcher_.DescribeNegationTo(os);
2400 }
2401
2402 protected:
2403 const Matcher<To> matcher_;
2404
Nico Weber09fd5b32017-05-15 17:07:03 -04002405 static std::string GetToName() {
billydonahue1f5fdea2014-05-19 17:54:51 +00002406 return GetTypeName<To>();
billydonahue1f5fdea2014-05-19 17:54:51 +00002407 }
2408
2409 private:
2410 static void GetCastTypeDescription(::std::ostream* os) {
2411 *os << "when dynamic_cast to " << GetToName() << ", ";
2412 }
2413
2414 GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2415};
2416
2417// Primary template.
2418// To is a pointer. Cast and forward the result.
2419template <typename To>
2420class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2421 public:
2422 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2423 : WhenDynamicCastToMatcherBase<To>(matcher) {}
2424
2425 template <typename From>
2426 bool MatchAndExplain(From from, MatchResultListener* listener) const {
Gennadiy Civil265efde2018-08-14 15:04:11 -04002427 // FIXME: Add more detail on failures. ie did the dyn_cast fail?
billydonahue1f5fdea2014-05-19 17:54:51 +00002428 To to = dynamic_cast<To>(from);
2429 return MatchPrintAndExplain(to, this->matcher_, listener);
2430 }
2431};
2432
2433// Specialize for references.
2434// In this case we return false if the dynamic_cast fails.
2435template <typename To>
2436class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2437 public:
2438 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2439 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2440
2441 template <typename From>
2442 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2443 // We don't want an std::bad_cast here, so do the cast with pointers.
2444 To* to = dynamic_cast<To*>(&from);
2445 if (to == NULL) {
2446 *listener << "which cannot be dynamic_cast to " << this->GetToName();
2447 return false;
2448 }
2449 return MatchPrintAndExplain(*to, this->matcher_, listener);
2450 }
2451};
Scott Grahama9653c42018-05-02 11:14:39 -07002452#endif // GTEST_HAS_RTTI
billydonahue1f5fdea2014-05-19 17:54:51 +00002453
shiqiane35fdd92008-12-10 05:08:54 +00002454// Implements the Field() matcher for matching a field (i.e. member
2455// variable) of an object.
2456template <typename Class, typename FieldType>
2457class FieldMatcher {
2458 public:
2459 FieldMatcher(FieldType Class::*field,
2460 const Matcher<const FieldType&>& matcher)
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002461 : field_(field), matcher_(matcher), whose_field_("whose given field ") {}
2462
2463 FieldMatcher(const std::string& field_name, FieldType Class::*field,
2464 const Matcher<const FieldType&>& matcher)
2465 : field_(field),
2466 matcher_(matcher),
2467 whose_field_("whose field `" + field_name + "` ") {}
shiqiane35fdd92008-12-10 05:08:54 +00002468
shiqiane35fdd92008-12-10 05:08:54 +00002469 void DescribeTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002470 *os << "is an object " << whose_field_;
shiqiane35fdd92008-12-10 05:08:54 +00002471 matcher_.DescribeTo(os);
2472 }
2473
2474 void DescribeNegationTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002475 *os << "is an object " << whose_field_;
shiqiane35fdd92008-12-10 05:08:54 +00002476 matcher_.DescribeNegationTo(os);
2477 }
2478
zhanyong.wandb22c222010-01-28 21:52:29 +00002479 template <typename T>
2480 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2481 return MatchAndExplainImpl(
2482 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002483 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002484 value, listener);
2485 }
2486
2487 private:
2488 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002489 // Symbian's C++ compiler choose which overload to use. Its type is
2490 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002491 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2492 MatchResultListener* listener) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002493 *listener << whose_field_ << "is ";
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002494 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002495 }
2496
zhanyong.wandb22c222010-01-28 21:52:29 +00002497 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2498 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002499 if (p == NULL)
2500 return false;
2501
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002502 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002503 // Since *p has a field, it must be a class/struct/union type and
2504 // thus cannot be a pointer. Therefore we pass false_type() as
2505 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002506 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002507 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002508
shiqiane35fdd92008-12-10 05:08:54 +00002509 const FieldType Class::*field_;
2510 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002511
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002512 // Contains either "whose given field " if the name of the field is unknown
2513 // or "whose field `name_of_field` " if the name is known.
2514 const std::string whose_field_;
2515
zhanyong.wan32de5f52009-12-23 00:13:23 +00002516 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002517};
2518
shiqiane35fdd92008-12-10 05:08:54 +00002519// Implements the Property() matcher for matching a property
2520// (i.e. return value of a getter method) of an object.
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002521//
2522// Property is a const-qualified member function of Class returning
2523// PropertyType.
2524template <typename Class, typename PropertyType, typename Property>
shiqiane35fdd92008-12-10 05:08:54 +00002525class PropertyMatcher {
2526 public:
2527 // The property may have a reference type, so 'const PropertyType&'
2528 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00002529 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00002530 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00002531 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00002532
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002533 PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002534 : property_(property),
2535 matcher_(matcher),
2536 whose_property_("whose given property ") {}
2537
2538 PropertyMatcher(const std::string& property_name, Property property,
2539 const Matcher<RefToConstProperty>& matcher)
2540 : property_(property),
2541 matcher_(matcher),
2542 whose_property_("whose property `" + property_name + "` ") {}
shiqiane35fdd92008-12-10 05:08:54 +00002543
shiqiane35fdd92008-12-10 05:08:54 +00002544 void DescribeTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002545 *os << "is an object " << whose_property_;
shiqiane35fdd92008-12-10 05:08:54 +00002546 matcher_.DescribeTo(os);
2547 }
2548
2549 void DescribeNegationTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002550 *os << "is an object " << whose_property_;
shiqiane35fdd92008-12-10 05:08:54 +00002551 matcher_.DescribeNegationTo(os);
2552 }
2553
zhanyong.wandb22c222010-01-28 21:52:29 +00002554 template <typename T>
2555 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2556 return MatchAndExplainImpl(
2557 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002558 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002559 value, listener);
2560 }
2561
2562 private:
2563 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002564 // Symbian's C++ compiler choose which overload to use. Its type is
2565 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002566 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2567 MatchResultListener* listener) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002568 *listener << whose_property_ << "is ";
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002569 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2570 // which takes a non-const reference as argument.
kosak02d64792015-02-14 02:22:21 +00002571#if defined(_PREFAST_ ) && _MSC_VER == 1800
2572 // Workaround bug in VC++ 2013's /analyze parser.
2573 // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move
2574 posix::Abort(); // To make sure it is never run.
2575 return false;
2576#else
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002577 RefToConstProperty result = (obj.*property_)();
2578 return MatchPrintAndExplain(result, matcher_, listener);
kosak02d64792015-02-14 02:22:21 +00002579#endif
shiqiane35fdd92008-12-10 05:08:54 +00002580 }
2581
zhanyong.wandb22c222010-01-28 21:52:29 +00002582 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2583 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002584 if (p == NULL)
2585 return false;
2586
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002587 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002588 // Since *p has a property method, it must be a class/struct/union
2589 // type and thus cannot be a pointer. Therefore we pass
2590 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002591 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002592 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002593
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002594 Property property_;
shiqiane35fdd92008-12-10 05:08:54 +00002595 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002596
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002597 // Contains either "whose given property " if the name of the property is
2598 // unknown or "whose property `name_of_property` " if the name is known.
2599 const std::string whose_property_;
2600
zhanyong.wan32de5f52009-12-23 00:13:23 +00002601 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002602};
2603
shiqiane35fdd92008-12-10 05:08:54 +00002604// Type traits specifying various features of different functors for ResultOf.
2605// The default template specifies features for functor objects.
shiqiane35fdd92008-12-10 05:08:54 +00002606template <typename Functor>
2607struct CallableTraits {
shiqiane35fdd92008-12-10 05:08:54 +00002608 typedef Functor StorageType;
2609
zhanyong.wan32de5f52009-12-23 00:13:23 +00002610 static void CheckIsValid(Functor /* functor */) {}
Abseil Teama0e62d92018-08-24 13:30:17 -04002611
2612#if GTEST_LANG_CXX11
2613 template <typename T>
2614 static auto Invoke(Functor f, T arg) -> decltype(f(arg)) { return f(arg); }
2615#else
2616 typedef typename Functor::result_type ResultType;
shiqiane35fdd92008-12-10 05:08:54 +00002617 template <typename T>
2618 static ResultType Invoke(Functor f, T arg) { return f(arg); }
Abseil Teama0e62d92018-08-24 13:30:17 -04002619#endif
shiqiane35fdd92008-12-10 05:08:54 +00002620};
2621
2622// Specialization for function pointers.
2623template <typename ArgType, typename ResType>
2624struct CallableTraits<ResType(*)(ArgType)> {
2625 typedef ResType ResultType;
2626 typedef ResType(*StorageType)(ArgType);
2627
2628 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002629 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00002630 << "NULL function pointer is passed into ResultOf().";
2631 }
2632 template <typename T>
2633 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2634 return (*f)(arg);
2635 }
2636};
2637
2638// Implements the ResultOf() matcher for matching a return value of a
2639// unary function of an object.
Abseil Teama0e62d92018-08-24 13:30:17 -04002640template <typename Callable, typename InnerMatcher>
shiqiane35fdd92008-12-10 05:08:54 +00002641class ResultOfMatcher {
2642 public:
Abseil Teama0e62d92018-08-24 13:30:17 -04002643 ResultOfMatcher(Callable callable, InnerMatcher matcher)
2644 : callable_(internal::move(callable)), matcher_(internal::move(matcher)) {
shiqiane35fdd92008-12-10 05:08:54 +00002645 CallableTraits<Callable>::CheckIsValid(callable_);
2646 }
2647
2648 template <typename T>
2649 operator Matcher<T>() const {
2650 return Matcher<T>(new Impl<T>(callable_, matcher_));
2651 }
2652
2653 private:
2654 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2655
2656 template <typename T>
2657 class Impl : public MatcherInterface<T> {
Abseil Teama0e62d92018-08-24 13:30:17 -04002658#if GTEST_LANG_CXX11
2659 using ResultType = decltype(CallableTraits<Callable>::template Invoke<T>(
2660 std::declval<CallableStorageType>(), std::declval<T>()));
2661#else
2662 typedef typename CallableTraits<Callable>::ResultType ResultType;
2663#endif
2664
shiqiane35fdd92008-12-10 05:08:54 +00002665 public:
Abseil Teama0e62d92018-08-24 13:30:17 -04002666 template <typename M>
2667 Impl(const CallableStorageType& callable, const M& matcher)
2668 : callable_(callable), matcher_(MatcherCast<ResultType>(matcher)) {}
shiqiane35fdd92008-12-10 05:08:54 +00002669
2670 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002671 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002672 matcher_.DescribeTo(os);
2673 }
2674
2675 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002676 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002677 matcher_.DescribeNegationTo(os);
2678 }
2679
zhanyong.wan82113312010-01-08 21:55:40 +00002680 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002681 *listener << "which is mapped by the given callable to ";
Abseil Teama0e62d92018-08-24 13:30:17 -04002682 // Cannot pass the return value directly to MatchPrintAndExplain, which
2683 // takes a non-const reference as argument.
2684 // Also, specifying template argument explicitly is needed because T could
2685 // be a non-const reference (e.g. Matcher<Uncopyable&>).
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002686 ResultType result =
2687 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2688 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002689 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002690
shiqiane35fdd92008-12-10 05:08:54 +00002691 private:
2692 // Functors often define operator() as non-const method even though
Troy Holsapplec8510502018-02-07 22:06:00 -08002693 // they are actually stateless. But we need to use them even when
shiqiane35fdd92008-12-10 05:08:54 +00002694 // 'this' is a const pointer. It's the user's responsibility not to
Abseil Teama0e62d92018-08-24 13:30:17 -04002695 // use stateful callables with ResultOf(), which doesn't guarantee
shiqiane35fdd92008-12-10 05:08:54 +00002696 // how many times the callable will be invoked.
2697 mutable CallableStorageType callable_;
2698 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002699
2700 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002701 }; // class Impl
2702
2703 const CallableStorageType callable_;
Abseil Teama0e62d92018-08-24 13:30:17 -04002704 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002705
2706 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002707};
2708
zhanyong.wana31d9ce2013-03-01 01:50:17 +00002709// Implements a matcher that checks the size of an STL-style container.
2710template <typename SizeMatcher>
2711class SizeIsMatcher {
2712 public:
2713 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2714 : size_matcher_(size_matcher) {
2715 }
2716
2717 template <typename Container>
2718 operator Matcher<Container>() const {
2719 return MakeMatcher(new Impl<Container>(size_matcher_));
2720 }
2721
2722 template <typename Container>
2723 class Impl : public MatcherInterface<Container> {
2724 public:
2725 typedef internal::StlContainerView<
2726 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2727 typedef typename ContainerView::type::size_type SizeType;
2728 explicit Impl(const SizeMatcher& size_matcher)
2729 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2730
2731 virtual void DescribeTo(::std::ostream* os) const {
2732 *os << "size ";
2733 size_matcher_.DescribeTo(os);
2734 }
2735 virtual void DescribeNegationTo(::std::ostream* os) const {
2736 *os << "size ";
2737 size_matcher_.DescribeNegationTo(os);
2738 }
2739
2740 virtual bool MatchAndExplain(Container container,
2741 MatchResultListener* listener) const {
2742 SizeType size = container.size();
2743 StringMatchResultListener size_listener;
2744 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2745 *listener
2746 << "whose size " << size << (result ? " matches" : " doesn't match");
2747 PrintIfNotEmpty(size_listener.str(), listener->stream());
2748 return result;
2749 }
2750
2751 private:
2752 const Matcher<SizeType> size_matcher_;
2753 GTEST_DISALLOW_ASSIGN_(Impl);
2754 };
2755
2756 private:
2757 const SizeMatcher size_matcher_;
2758 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2759};
2760
kosakb6a34882014-03-12 21:06:46 +00002761// Implements a matcher that checks the begin()..end() distance of an STL-style
2762// container.
2763template <typename DistanceMatcher>
2764class BeginEndDistanceIsMatcher {
2765 public:
2766 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2767 : distance_matcher_(distance_matcher) {}
2768
2769 template <typename Container>
2770 operator Matcher<Container>() const {
2771 return MakeMatcher(new Impl<Container>(distance_matcher_));
2772 }
2773
2774 template <typename Container>
2775 class Impl : public MatcherInterface<Container> {
2776 public:
2777 typedef internal::StlContainerView<
2778 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2779 typedef typename std::iterator_traits<
2780 typename ContainerView::type::const_iterator>::difference_type
2781 DistanceType;
2782 explicit Impl(const DistanceMatcher& distance_matcher)
2783 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2784
2785 virtual void DescribeTo(::std::ostream* os) const {
2786 *os << "distance between begin() and end() ";
2787 distance_matcher_.DescribeTo(os);
2788 }
2789 virtual void DescribeNegationTo(::std::ostream* os) const {
2790 *os << "distance between begin() and end() ";
2791 distance_matcher_.DescribeNegationTo(os);
2792 }
2793
2794 virtual bool MatchAndExplain(Container container,
2795 MatchResultListener* listener) const {
kosak5b9cbbb2014-11-17 00:28:55 +00002796#if GTEST_HAS_STD_BEGIN_AND_END_
kosakb6a34882014-03-12 21:06:46 +00002797 using std::begin;
2798 using std::end;
2799 DistanceType distance = std::distance(begin(container), end(container));
2800#else
2801 DistanceType distance = std::distance(container.begin(), container.end());
2802#endif
2803 StringMatchResultListener distance_listener;
2804 const bool result =
2805 distance_matcher_.MatchAndExplain(distance, &distance_listener);
2806 *listener << "whose distance between begin() and end() " << distance
2807 << (result ? " matches" : " doesn't match");
2808 PrintIfNotEmpty(distance_listener.str(), listener->stream());
2809 return result;
2810 }
2811
2812 private:
2813 const Matcher<DistanceType> distance_matcher_;
2814 GTEST_DISALLOW_ASSIGN_(Impl);
2815 };
2816
2817 private:
2818 const DistanceMatcher distance_matcher_;
2819 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2820};
2821
zhanyong.wan6a896b52009-01-16 01:13:50 +00002822// Implements an equality matcher for any STL-style container whose elements
2823// support ==. This matcher is like Eq(), but its failure explanations provide
2824// more detailed information that is useful when the container is used as a set.
2825// The failure message reports elements that are in one of the operands but not
2826// the other. The failure messages do not report duplicate or out-of-order
2827// elements in the containers (which don't properly matter to sets, but can
2828// occur if the containers are vectors or lists, for example).
2829//
2830// Uses the container's const_iterator, value_type, operator ==,
2831// begin(), and end().
2832template <typename Container>
2833class ContainerEqMatcher {
2834 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002835 typedef internal::StlContainerView<Container> View;
2836 typedef typename View::type StlContainer;
2837 typedef typename View::const_reference StlContainerReference;
2838
kosak6b817802015-01-08 02:38:14 +00002839 // We make a copy of expected in case the elements in it are modified
zhanyong.wanb8243162009-06-04 05:48:20 +00002840 // after this matcher is created.
kosak6b817802015-01-08 02:38:14 +00002841 explicit ContainerEqMatcher(const Container& expected)
2842 : expected_(View::Copy(expected)) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002843 // Makes sure the user doesn't instantiate this class template
2844 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002845 (void)testing::StaticAssertTypeEq<Container,
2846 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002847 }
2848
zhanyong.wan6a896b52009-01-16 01:13:50 +00002849 void DescribeTo(::std::ostream* os) const {
2850 *os << "equals ";
kosak6b817802015-01-08 02:38:14 +00002851 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002852 }
2853 void DescribeNegationTo(::std::ostream* os) const {
2854 *os << "does not equal ";
kosak6b817802015-01-08 02:38:14 +00002855 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002856 }
2857
zhanyong.wanb8243162009-06-04 05:48:20 +00002858 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002859 bool MatchAndExplain(const LhsContainer& lhs,
2860 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002861 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002862 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002863 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002864 LhsView;
2865 typedef typename LhsView::type LhsStlContainer;
2866 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
kosak6b817802015-01-08 02:38:14 +00002867 if (lhs_stl_container == expected_)
zhanyong.wane122e452010-01-12 09:03:52 +00002868 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002869
zhanyong.wane122e452010-01-12 09:03:52 +00002870 ::std::ostream* const os = listener->stream();
2871 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002872 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002873 bool printed_header = false;
2874 for (typename LhsStlContainer::const_iterator it =
2875 lhs_stl_container.begin();
2876 it != lhs_stl_container.end(); ++it) {
kosak6b817802015-01-08 02:38:14 +00002877 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
2878 expected_.end()) {
zhanyong.wane122e452010-01-12 09:03:52 +00002879 if (printed_header) {
2880 *os << ", ";
2881 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002882 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002883 printed_header = true;
2884 }
vladloseve2e8ba42010-05-13 18:16:03 +00002885 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002886 }
zhanyong.wane122e452010-01-12 09:03:52 +00002887 }
2888
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002889 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002890 bool printed_header2 = false;
kosak6b817802015-01-08 02:38:14 +00002891 for (typename StlContainer::const_iterator it = expected_.begin();
2892 it != expected_.end(); ++it) {
zhanyong.wane122e452010-01-12 09:03:52 +00002893 if (internal::ArrayAwareFind(
2894 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2895 lhs_stl_container.end()) {
2896 if (printed_header2) {
2897 *os << ", ";
2898 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002899 *os << (printed_header ? ",\nand" : "which")
2900 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002901 printed_header2 = true;
2902 }
vladloseve2e8ba42010-05-13 18:16:03 +00002903 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002904 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002905 }
2906 }
2907
zhanyong.wane122e452010-01-12 09:03:52 +00002908 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002909 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002910
zhanyong.wan6a896b52009-01-16 01:13:50 +00002911 private:
kosak6b817802015-01-08 02:38:14 +00002912 const StlContainer expected_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002913
2914 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002915};
2916
zhanyong.wan898725c2011-09-16 16:45:39 +00002917// A comparator functor that uses the < operator to compare two values.
2918struct LessComparator {
2919 template <typename T, typename U>
2920 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2921};
2922
2923// Implements WhenSortedBy(comparator, container_matcher).
2924template <typename Comparator, typename ContainerMatcher>
2925class WhenSortedByMatcher {
2926 public:
2927 WhenSortedByMatcher(const Comparator& comparator,
2928 const ContainerMatcher& matcher)
2929 : comparator_(comparator), matcher_(matcher) {}
2930
2931 template <typename LhsContainer>
2932 operator Matcher<LhsContainer>() const {
2933 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2934 }
2935
2936 template <typename LhsContainer>
2937 class Impl : public MatcherInterface<LhsContainer> {
2938 public:
2939 typedef internal::StlContainerView<
2940 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2941 typedef typename LhsView::type LhsStlContainer;
2942 typedef typename LhsView::const_reference LhsStlContainerReference;
zhanyong.wana9a59e02013-03-27 16:14:55 +00002943 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2944 // so that we can match associative containers.
2945 typedef typename RemoveConstFromKey<
2946 typename LhsStlContainer::value_type>::type LhsValue;
zhanyong.wan898725c2011-09-16 16:45:39 +00002947
2948 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2949 : comparator_(comparator), matcher_(matcher) {}
2950
2951 virtual void DescribeTo(::std::ostream* os) const {
2952 *os << "(when sorted) ";
2953 matcher_.DescribeTo(os);
2954 }
2955
2956 virtual void DescribeNegationTo(::std::ostream* os) const {
2957 *os << "(when sorted) ";
2958 matcher_.DescribeNegationTo(os);
2959 }
2960
2961 virtual bool MatchAndExplain(LhsContainer lhs,
2962 MatchResultListener* listener) const {
2963 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wanfb25d532013-07-28 08:24:00 +00002964 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2965 lhs_stl_container.end());
2966 ::std::sort(
2967 sorted_container.begin(), sorted_container.end(), comparator_);
zhanyong.wan898725c2011-09-16 16:45:39 +00002968
2969 if (!listener->IsInterested()) {
2970 // If the listener is not interested, we do not need to
2971 // construct the inner explanation.
2972 return matcher_.Matches(sorted_container);
2973 }
2974
2975 *listener << "which is ";
2976 UniversalPrint(sorted_container, listener->stream());
2977 *listener << " when sorted";
2978
2979 StringMatchResultListener inner_listener;
2980 const bool match = matcher_.MatchAndExplain(sorted_container,
2981 &inner_listener);
2982 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2983 return match;
2984 }
2985
2986 private:
2987 const Comparator comparator_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00002988 const Matcher<const ::std::vector<LhsValue>&> matcher_;
zhanyong.wan898725c2011-09-16 16:45:39 +00002989
2990 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2991 };
2992
2993 private:
2994 const Comparator comparator_;
2995 const ContainerMatcher matcher_;
2996
2997 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2998};
2999
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003000// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
3001// must be able to be safely cast to Matcher<tuple<const T1&, const
3002// T2&> >, where T1 and T2 are the types of elements in the LHS
3003// container and the RHS container respectively.
3004template <typename TupleMatcher, typename RhsContainer>
3005class PointwiseMatcher {
Gennadiy Civil23187052018-03-26 10:16:59 -04003006 GTEST_COMPILE_ASSERT_(
3007 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value,
3008 use_UnorderedPointwise_with_hash_tables);
3009
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003010 public:
3011 typedef internal::StlContainerView<RhsContainer> RhsView;
3012 typedef typename RhsView::type RhsStlContainer;
3013 typedef typename RhsStlContainer::value_type RhsValue;
3014
3015 // Like ContainerEq, we make a copy of rhs in case the elements in
3016 // it are modified after this matcher is created.
3017 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
3018 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
3019 // Makes sure the user doesn't instantiate this class template
3020 // with a const or reference type.
3021 (void)testing::StaticAssertTypeEq<RhsContainer,
3022 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
3023 }
3024
3025 template <typename LhsContainer>
3026 operator Matcher<LhsContainer>() const {
Gennadiy Civil23187052018-03-26 10:16:59 -04003027 GTEST_COMPILE_ASSERT_(
3028 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value,
3029 use_UnorderedPointwise_with_hash_tables);
3030
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003031 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
3032 }
3033
3034 template <typename LhsContainer>
3035 class Impl : public MatcherInterface<LhsContainer> {
3036 public:
3037 typedef internal::StlContainerView<
3038 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
3039 typedef typename LhsView::type LhsStlContainer;
3040 typedef typename LhsView::const_reference LhsStlContainerReference;
3041 typedef typename LhsStlContainer::value_type LhsValue;
3042 // We pass the LHS value and the RHS value to the inner matcher by
3043 // reference, as they may be expensive to copy. We must use tuple
3044 // instead of pair here, as a pair cannot hold references (C++ 98,
3045 // 20.2.2 [lib.pairs]).
kosakbd018832014-04-02 20:30:00 +00003046 typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003047
3048 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
3049 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
3050 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
3051 rhs_(rhs) {}
3052
3053 virtual void DescribeTo(::std::ostream* os) const {
3054 *os << "contains " << rhs_.size()
3055 << " values, where each value and its corresponding value in ";
3056 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
3057 *os << " ";
3058 mono_tuple_matcher_.DescribeTo(os);
3059 }
3060 virtual void DescribeNegationTo(::std::ostream* os) const {
3061 *os << "doesn't contain exactly " << rhs_.size()
3062 << " values, or contains a value x at some index i"
3063 << " where x and the i-th value of ";
3064 UniversalPrint(rhs_, os);
3065 *os << " ";
3066 mono_tuple_matcher_.DescribeNegationTo(os);
3067 }
3068
3069 virtual bool MatchAndExplain(LhsContainer lhs,
3070 MatchResultListener* listener) const {
3071 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
3072 const size_t actual_size = lhs_stl_container.size();
3073 if (actual_size != rhs_.size()) {
3074 *listener << "which contains " << actual_size << " values";
3075 return false;
3076 }
3077
3078 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
3079 typename RhsStlContainer::const_iterator right = rhs_.begin();
3080 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003081 if (listener->IsInterested()) {
3082 StringMatchResultListener inner_listener;
Gennadiy Civil23187052018-03-26 10:16:59 -04003083 // Create InnerMatcherArg as a temporarily object to avoid it outlives
3084 // *left and *right. Dereference or the conversion to `const T&` may
3085 // return temp objects, e.g for vector<bool>.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003086 if (!mono_tuple_matcher_.MatchAndExplain(
Gennadiy Civil23187052018-03-26 10:16:59 -04003087 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
3088 ImplicitCast_<const RhsValue&>(*right)),
3089 &inner_listener)) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003090 *listener << "where the value pair (";
3091 UniversalPrint(*left, listener->stream());
3092 *listener << ", ";
3093 UniversalPrint(*right, listener->stream());
3094 *listener << ") at index #" << i << " don't match";
3095 PrintIfNotEmpty(inner_listener.str(), listener->stream());
3096 return false;
3097 }
3098 } else {
Gennadiy Civil23187052018-03-26 10:16:59 -04003099 if (!mono_tuple_matcher_.Matches(
3100 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
3101 ImplicitCast_<const RhsValue&>(*right))))
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003102 return false;
3103 }
3104 }
3105
3106 return true;
3107 }
3108
3109 private:
3110 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
3111 const RhsStlContainer rhs_;
3112
3113 GTEST_DISALLOW_ASSIGN_(Impl);
3114 };
3115
3116 private:
3117 const TupleMatcher tuple_matcher_;
3118 const RhsStlContainer rhs_;
3119
3120 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
3121};
3122
zhanyong.wan33605ba2010-04-22 23:37:47 +00003123// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00003124template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00003125class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00003126 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003127 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00003128 typedef StlContainerView<RawContainer> View;
3129 typedef typename View::type StlContainer;
3130 typedef typename View::const_reference StlContainerReference;
3131 typedef typename StlContainer::value_type Element;
3132
3133 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00003134 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00003135 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00003136 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00003137
zhanyong.wan33605ba2010-04-22 23:37:47 +00003138 // Checks whether:
3139 // * All elements in the container match, if all_elements_should_match.
3140 // * Any element in the container matches, if !all_elements_should_match.
3141 bool MatchAndExplainImpl(bool all_elements_should_match,
3142 Container container,
3143 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00003144 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00003145 size_t i = 0;
3146 for (typename StlContainer::const_iterator it = stl_container.begin();
3147 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003148 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00003149 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
3150
3151 if (matches != all_elements_should_match) {
3152 *listener << "whose element #" << i
3153 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003154 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00003155 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00003156 }
3157 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00003158 return all_elements_should_match;
3159 }
3160
3161 protected:
3162 const Matcher<const Element&> inner_matcher_;
3163
3164 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
3165};
3166
3167// Implements Contains(element_matcher) for the given argument type Container.
3168// Symmetric to EachMatcherImpl.
3169template <typename Container>
3170class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
3171 public:
3172 template <typename InnerMatcher>
3173 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
3174 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3175
3176 // Describes what this matcher does.
3177 virtual void DescribeTo(::std::ostream* os) const {
3178 *os << "contains at least one element that ";
3179 this->inner_matcher_.DescribeTo(os);
3180 }
3181
3182 virtual void DescribeNegationTo(::std::ostream* os) const {
3183 *os << "doesn't contain any element that ";
3184 this->inner_matcher_.DescribeTo(os);
3185 }
3186
3187 virtual bool MatchAndExplain(Container container,
3188 MatchResultListener* listener) const {
3189 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00003190 }
3191
3192 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003193 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00003194};
3195
zhanyong.wan33605ba2010-04-22 23:37:47 +00003196// Implements Each(element_matcher) for the given argument type Container.
3197// Symmetric to ContainsMatcherImpl.
3198template <typename Container>
3199class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
3200 public:
3201 template <typename InnerMatcher>
3202 explicit EachMatcherImpl(InnerMatcher inner_matcher)
3203 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3204
3205 // Describes what this matcher does.
3206 virtual void DescribeTo(::std::ostream* os) const {
3207 *os << "only contains elements that ";
3208 this->inner_matcher_.DescribeTo(os);
3209 }
3210
3211 virtual void DescribeNegationTo(::std::ostream* os) const {
3212 *os << "contains some element that ";
3213 this->inner_matcher_.DescribeNegationTo(os);
3214 }
3215
3216 virtual bool MatchAndExplain(Container container,
3217 MatchResultListener* listener) const {
3218 return this->MatchAndExplainImpl(true, container, listener);
3219 }
3220
3221 private:
3222 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
3223};
3224
zhanyong.wanb8243162009-06-04 05:48:20 +00003225// Implements polymorphic Contains(element_matcher).
3226template <typename M>
3227class ContainsMatcher {
3228 public:
3229 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
3230
3231 template <typename Container>
3232 operator Matcher<Container>() const {
3233 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
3234 }
3235
3236 private:
3237 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003238
3239 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00003240};
3241
zhanyong.wan33605ba2010-04-22 23:37:47 +00003242// Implements polymorphic Each(element_matcher).
3243template <typename M>
3244class EachMatcher {
3245 public:
3246 explicit EachMatcher(M m) : inner_matcher_(m) {}
3247
3248 template <typename Container>
3249 operator Matcher<Container>() const {
3250 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
3251 }
3252
3253 private:
3254 const M inner_matcher_;
3255
3256 GTEST_DISALLOW_ASSIGN_(EachMatcher);
3257};
3258
Gennadiy Civil466a49a2018-03-23 11:23:54 -04003259struct Rank1 {};
3260struct Rank0 : Rank1 {};
3261
3262namespace pair_getters {
3263#if GTEST_LANG_CXX11
3264using std::get;
3265template <typename T>
3266auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT
3267 return get<0>(x);
3268}
3269template <typename T>
3270auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT
3271 return x.first;
3272}
3273
3274template <typename T>
3275auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT
3276 return get<1>(x);
3277}
3278template <typename T>
3279auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT
3280 return x.second;
3281}
3282#else
3283template <typename T>
3284typename T::first_type& First(T& x, Rank0) { // NOLINT
3285 return x.first;
3286}
3287template <typename T>
3288const typename T::first_type& First(const T& x, Rank0) {
3289 return x.first;
3290}
3291
3292template <typename T>
3293typename T::second_type& Second(T& x, Rank0) { // NOLINT
3294 return x.second;
3295}
3296template <typename T>
3297const typename T::second_type& Second(const T& x, Rank0) {
3298 return x.second;
3299}
3300#endif // GTEST_LANG_CXX11
3301} // namespace pair_getters
3302
zhanyong.wanb5937da2009-07-16 20:26:41 +00003303// Implements Key(inner_matcher) for the given argument pair type.
3304// Key(inner_matcher) matches an std::pair whose 'first' field matches
3305// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3306// std::map that contains at least one element whose key is >= 5.
3307template <typename PairType>
3308class KeyMatcherImpl : public MatcherInterface<PairType> {
3309 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003310 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00003311 typedef typename RawPairType::first_type KeyType;
3312
3313 template <typename InnerMatcher>
3314 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
3315 : inner_matcher_(
3316 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
3317 }
3318
3319 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00003320 virtual bool MatchAndExplain(PairType key_value,
3321 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003322 StringMatchResultListener inner_listener;
Gennadiy Civil23187052018-03-26 10:16:59 -04003323 const bool match = inner_matcher_.MatchAndExplain(
3324 pair_getters::First(key_value, Rank0()), &inner_listener);
Nico Weber09fd5b32017-05-15 17:07:03 -04003325 const std::string explanation = inner_listener.str();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003326 if (explanation != "") {
3327 *listener << "whose first field is a value " << explanation;
3328 }
3329 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00003330 }
3331
3332 // Describes what this matcher does.
3333 virtual void DescribeTo(::std::ostream* os) const {
3334 *os << "has a key that ";
3335 inner_matcher_.DescribeTo(os);
3336 }
3337
3338 // Describes what the negation of this matcher does.
3339 virtual void DescribeNegationTo(::std::ostream* os) const {
3340 *os << "doesn't have a key that ";
3341 inner_matcher_.DescribeTo(os);
3342 }
3343
zhanyong.wanb5937da2009-07-16 20:26:41 +00003344 private:
3345 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003346
3347 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00003348};
3349
3350// Implements polymorphic Key(matcher_for_key).
3351template <typename M>
3352class KeyMatcher {
3353 public:
3354 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
3355
3356 template <typename PairType>
3357 operator Matcher<PairType>() const {
3358 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
3359 }
3360
3361 private:
3362 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003363
3364 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00003365};
3366
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003367// Implements Pair(first_matcher, second_matcher) for the given argument pair
3368// type with its two matchers. See Pair() function below.
3369template <typename PairType>
3370class PairMatcherImpl : public MatcherInterface<PairType> {
3371 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003372 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003373 typedef typename RawPairType::first_type FirstType;
3374 typedef typename RawPairType::second_type SecondType;
3375
3376 template <typename FirstMatcher, typename SecondMatcher>
3377 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
3378 : first_matcher_(
3379 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
3380 second_matcher_(
3381 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
3382 }
3383
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003384 // Describes what this matcher does.
3385 virtual void DescribeTo(::std::ostream* os) const {
3386 *os << "has a first field that ";
3387 first_matcher_.DescribeTo(os);
3388 *os << ", and has a second field that ";
3389 second_matcher_.DescribeTo(os);
3390 }
3391
3392 // Describes what the negation of this matcher does.
3393 virtual void DescribeNegationTo(::std::ostream* os) const {
3394 *os << "has a first field that ";
3395 first_matcher_.DescribeNegationTo(os);
3396 *os << ", or has a second field that ";
3397 second_matcher_.DescribeNegationTo(os);
3398 }
3399
zhanyong.wan82113312010-01-08 21:55:40 +00003400 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3401 // matches second_matcher.
3402 virtual bool MatchAndExplain(PairType a_pair,
3403 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003404 if (!listener->IsInterested()) {
3405 // If the listener is not interested, we don't need to construct the
3406 // explanation.
Gennadiy Civil6aae2062018-03-26 10:36:26 -04003407 return first_matcher_.Matches(pair_getters::First(a_pair, Rank0())) &&
3408 second_matcher_.Matches(pair_getters::Second(a_pair, Rank0()));
zhanyong.wan82113312010-01-08 21:55:40 +00003409 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003410 StringMatchResultListener first_inner_listener;
Gennadiy Civil6aae2062018-03-26 10:36:26 -04003411 if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank0()),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003412 &first_inner_listener)) {
3413 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003414 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003415 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003416 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003417 StringMatchResultListener second_inner_listener;
Gennadiy Civil6aae2062018-03-26 10:36:26 -04003418 if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank0()),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003419 &second_inner_listener)) {
3420 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003421 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003422 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003423 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003424 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3425 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00003426 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003427 }
3428
3429 private:
Nico Weber09fd5b32017-05-15 17:07:03 -04003430 void ExplainSuccess(const std::string& first_explanation,
3431 const std::string& second_explanation,
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003432 MatchResultListener* listener) const {
3433 *listener << "whose both fields match";
3434 if (first_explanation != "") {
3435 *listener << ", where the first field is a value " << first_explanation;
3436 }
3437 if (second_explanation != "") {
3438 *listener << ", ";
3439 if (first_explanation != "") {
3440 *listener << "and ";
3441 } else {
3442 *listener << "where ";
3443 }
3444 *listener << "the second field is a value " << second_explanation;
3445 }
3446 }
3447
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003448 const Matcher<const FirstType&> first_matcher_;
3449 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003450
3451 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003452};
3453
3454// Implements polymorphic Pair(first_matcher, second_matcher).
3455template <typename FirstMatcher, typename SecondMatcher>
3456class PairMatcher {
3457 public:
3458 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3459 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3460
3461 template <typename PairType>
3462 operator Matcher<PairType> () const {
3463 return MakeMatcher(
3464 new PairMatcherImpl<PairType>(
3465 first_matcher_, second_matcher_));
3466 }
3467
3468 private:
3469 const FirstMatcher first_matcher_;
3470 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003471
3472 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003473};
3474
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003475// Implements ElementsAre() and ElementsAreArray().
3476template <typename Container>
3477class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3478 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003479 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003480 typedef internal::StlContainerView<RawContainer> View;
3481 typedef typename View::type StlContainer;
3482 typedef typename View::const_reference StlContainerReference;
3483 typedef typename StlContainer::value_type Element;
3484
3485 // Constructs the matcher from a sequence of element values or
3486 // element matchers.
3487 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00003488 ElementsAreMatcherImpl(InputIter first, InputIter last) {
3489 while (first != last) {
3490 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003491 }
3492 }
3493
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003494 // Describes what this matcher does.
3495 virtual void DescribeTo(::std::ostream* os) const {
3496 if (count() == 0) {
3497 *os << "is empty";
3498 } else if (count() == 1) {
3499 *os << "has 1 element that ";
3500 matchers_[0].DescribeTo(os);
3501 } else {
3502 *os << "has " << Elements(count()) << " where\n";
3503 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003504 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003505 matchers_[i].DescribeTo(os);
3506 if (i + 1 < count()) {
3507 *os << ",\n";
3508 }
3509 }
3510 }
3511 }
3512
3513 // Describes what the negation of this matcher does.
3514 virtual void DescribeNegationTo(::std::ostream* os) const {
3515 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003516 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003517 return;
3518 }
3519
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003520 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003521 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003522 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003523 matchers_[i].DescribeNegationTo(os);
3524 if (i + 1 < count()) {
3525 *os << ", or\n";
3526 }
3527 }
3528 }
3529
zhanyong.wan82113312010-01-08 21:55:40 +00003530 virtual bool MatchAndExplain(Container container,
3531 MatchResultListener* listener) const {
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003532 // To work with stream-like "containers", we must only walk
3533 // through the elements in one pass.
3534
3535 const bool listener_interested = listener->IsInterested();
3536
3537 // explanations[i] is the explanation of the element at index i.
Nico Weber09fd5b32017-05-15 17:07:03 -04003538 ::std::vector<std::string> explanations(count());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003539 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003540 typename StlContainer::const_iterator it = stl_container.begin();
3541 size_t exam_pos = 0;
3542 bool mismatch_found = false; // Have we found a mismatched element yet?
3543
3544 // Go through the elements and matchers in pairs, until we reach
3545 // the end of either the elements or the matchers, or until we find a
3546 // mismatch.
3547 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3548 bool match; // Does the current element match the current matcher?
3549 if (listener_interested) {
3550 StringMatchResultListener s;
3551 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3552 explanations[exam_pos] = s.str();
3553 } else {
3554 match = matchers_[exam_pos].Matches(*it);
3555 }
3556
3557 if (!match) {
3558 mismatch_found = true;
3559 break;
3560 }
3561 }
3562 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3563
3564 // Find how many elements the actual container has. We avoid
3565 // calling size() s.t. this code works for stream-like "containers"
3566 // that don't define size().
3567 size_t actual_count = exam_pos;
3568 for (; it != stl_container.end(); ++it) {
3569 ++actual_count;
3570 }
3571
zhanyong.wan82113312010-01-08 21:55:40 +00003572 if (actual_count != count()) {
3573 // The element count doesn't match. If the container is empty,
3574 // there's no need to explain anything as Google Mock already
3575 // prints the empty container. Otherwise we just need to show
3576 // how many elements there actually are.
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003577 if (listener_interested && (actual_count != 0)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003578 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003579 }
zhanyong.wan82113312010-01-08 21:55:40 +00003580 return false;
3581 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003582
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003583 if (mismatch_found) {
3584 // The element count matches, but the exam_pos-th element doesn't match.
3585 if (listener_interested) {
3586 *listener << "whose element #" << exam_pos << " doesn't match";
3587 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003588 }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003589 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003590 }
zhanyong.wan82113312010-01-08 21:55:40 +00003591
3592 // Every element matches its expectation. We need to explain why
3593 // (the obvious ones can be skipped).
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003594 if (listener_interested) {
3595 bool reason_printed = false;
3596 for (size_t i = 0; i != count(); ++i) {
Nico Weber09fd5b32017-05-15 17:07:03 -04003597 const std::string& s = explanations[i];
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003598 if (!s.empty()) {
3599 if (reason_printed) {
3600 *listener << ",\nand ";
3601 }
3602 *listener << "whose element #" << i << " matches, " << s;
3603 reason_printed = true;
zhanyong.wan82113312010-01-08 21:55:40 +00003604 }
zhanyong.wan82113312010-01-08 21:55:40 +00003605 }
3606 }
zhanyong.wan82113312010-01-08 21:55:40 +00003607 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003608 }
3609
3610 private:
3611 static Message Elements(size_t count) {
3612 return Message() << count << (count == 1 ? " element" : " elements");
3613 }
3614
3615 size_t count() const { return matchers_.size(); }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003616
3617 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003618
3619 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003620};
3621
zhanyong.wanfb25d532013-07-28 08:24:00 +00003622// Connectivity matrix of (elements X matchers), in element-major order.
3623// Initially, there are no edges.
3624// Use NextGraph() to iterate over all possible edge configurations.
3625// Use Randomize() to generate a random edge configuration.
3626class GTEST_API_ MatchMatrix {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003627 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003628 MatchMatrix(size_t num_elements, size_t num_matchers)
3629 : num_elements_(num_elements),
3630 num_matchers_(num_matchers),
3631 matched_(num_elements_* num_matchers_, 0) {
3632 }
3633
3634 size_t LhsSize() const { return num_elements_; }
3635 size_t RhsSize() const { return num_matchers_; }
3636 bool HasEdge(size_t ilhs, size_t irhs) const {
3637 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3638 }
3639 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3640 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3641 }
3642
3643 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3644 // adds 1 to that number; returns false if incrementing the graph left it
3645 // empty.
3646 bool NextGraph();
3647
3648 void Randomize();
3649
Nico Weber09fd5b32017-05-15 17:07:03 -04003650 std::string DebugString() const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003651
3652 private:
3653 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3654 return ilhs * num_matchers_ + irhs;
3655 }
3656
3657 size_t num_elements_;
3658 size_t num_matchers_;
3659
3660 // Each element is a char interpreted as bool. They are stored as a
3661 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3662 // a (ilhs, irhs) matrix coordinate into an offset.
3663 ::std::vector<char> matched_;
3664};
3665
3666typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3667typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3668
3669// Returns a maximum bipartite matching for the specified graph 'g'.
3670// The matching is represented as a vector of {element, matcher} pairs.
3671GTEST_API_ ElementMatcherPairs
3672FindMaxBipartiteMatching(const MatchMatrix& g);
3673
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003674struct UnorderedMatcherRequire {
3675 enum Flags {
3676 Superset = 1 << 0,
3677 Subset = 1 << 1,
3678 ExactMatch = Superset | Subset,
3679 };
3680};
zhanyong.wanfb25d532013-07-28 08:24:00 +00003681
3682// Untyped base class for implementing UnorderedElementsAre. By
3683// putting logic that's not specific to the element type here, we
3684// reduce binary bloat and increase compilation speed.
3685class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3686 protected:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003687 explicit UnorderedElementsAreMatcherImplBase(
3688 UnorderedMatcherRequire::Flags matcher_flags)
3689 : match_flags_(matcher_flags) {}
3690
zhanyong.wanfb25d532013-07-28 08:24:00 +00003691 // A vector of matcher describers, one for each element matcher.
3692 // Does not own the describers (and thus can be used only when the
3693 // element matchers are alive).
3694 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3695
3696 // Describes this UnorderedElementsAre matcher.
3697 void DescribeToImpl(::std::ostream* os) const;
3698
3699 // Describes the negation of this UnorderedElementsAre matcher.
3700 void DescribeNegationToImpl(::std::ostream* os) const;
3701
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003702 bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,
3703 const MatchMatrix& matrix,
3704 MatchResultListener* listener) const;
3705
3706 bool FindPairing(const MatchMatrix& matrix,
3707 MatchResultListener* listener) const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003708
3709 MatcherDescriberVec& matcher_describers() {
3710 return matcher_describers_;
3711 }
3712
3713 static Message Elements(size_t n) {
3714 return Message() << n << " element" << (n == 1 ? "" : "s");
3715 }
3716
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003717 UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }
3718
zhanyong.wanfb25d532013-07-28 08:24:00 +00003719 private:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003720 UnorderedMatcherRequire::Flags match_flags_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003721 MatcherDescriberVec matcher_describers_;
3722
3723 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3724};
3725
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003726// Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
3727// IsSupersetOf.
zhanyong.wanfb25d532013-07-28 08:24:00 +00003728template <typename Container>
3729class UnorderedElementsAreMatcherImpl
3730 : public MatcherInterface<Container>,
3731 public UnorderedElementsAreMatcherImplBase {
3732 public:
3733 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3734 typedef internal::StlContainerView<RawContainer> View;
3735 typedef typename View::type StlContainer;
3736 typedef typename View::const_reference StlContainerReference;
3737 typedef typename StlContainer::const_iterator StlContainerConstIterator;
3738 typedef typename StlContainer::value_type Element;
3739
zhanyong.wanfb25d532013-07-28 08:24:00 +00003740 template <typename InputIter>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003741 UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,
3742 InputIter first, InputIter last)
3743 : UnorderedElementsAreMatcherImplBase(matcher_flags) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00003744 for (; first != last; ++first) {
3745 matchers_.push_back(MatcherCast<const Element&>(*first));
3746 matcher_describers().push_back(matchers_.back().GetDescriber());
3747 }
3748 }
3749
3750 // Describes what this matcher does.
3751 virtual void DescribeTo(::std::ostream* os) const {
3752 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3753 }
3754
3755 // Describes what the negation of this matcher does.
3756 virtual void DescribeNegationTo(::std::ostream* os) const {
3757 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3758 }
3759
3760 virtual bool MatchAndExplain(Container container,
3761 MatchResultListener* listener) const {
3762 StlContainerReference stl_container = View::ConstReference(container);
Nico Weber09fd5b32017-05-15 17:07:03 -04003763 ::std::vector<std::string> element_printouts;
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003764 MatchMatrix matrix =
3765 AnalyzeElements(stl_container.begin(), stl_container.end(),
3766 &element_printouts, listener);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003767
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003768 if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00003769 return true;
3770 }
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003771
3772 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
3773 if (matrix.LhsSize() != matrix.RhsSize()) {
3774 // The element count doesn't match. If the container is empty,
3775 // there's no need to explain anything as Google Mock already
3776 // prints the empty container. Otherwise we just need to show
3777 // how many elements there actually are.
3778 if (matrix.LhsSize() != 0 && listener->IsInterested()) {
3779 *listener << "which has " << Elements(matrix.LhsSize());
3780 }
3781 return false;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003782 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003783 }
3784
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003785 return VerifyMatchMatrix(element_printouts, matrix, listener) &&
zhanyong.wanfb25d532013-07-28 08:24:00 +00003786 FindPairing(matrix, listener);
3787 }
3788
3789 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003790 template <typename ElementIter>
3791 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
Nico Weber09fd5b32017-05-15 17:07:03 -04003792 ::std::vector<std::string>* element_printouts,
zhanyong.wanfb25d532013-07-28 08:24:00 +00003793 MatchResultListener* listener) const {
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003794 element_printouts->clear();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003795 ::std::vector<char> did_match;
3796 size_t num_elements = 0;
3797 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3798 if (listener->IsInterested()) {
3799 element_printouts->push_back(PrintToString(*elem_first));
3800 }
3801 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3802 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3803 }
3804 }
3805
3806 MatchMatrix matrix(num_elements, matchers_.size());
3807 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3808 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3809 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3810 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3811 }
3812 }
3813 return matrix;
3814 }
3815
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003816 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003817
3818 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3819};
3820
3821// Functor for use in TransformTuple.
3822// Performs MatcherCast<Target> on an input argument of any type.
3823template <typename Target>
3824struct CastAndAppendTransform {
3825 template <typename Arg>
3826 Matcher<Target> operator()(const Arg& a) const {
3827 return MatcherCast<Target>(a);
3828 }
3829};
3830
3831// Implements UnorderedElementsAre.
3832template <typename MatcherTuple>
3833class UnorderedElementsAreMatcher {
3834 public:
3835 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3836 : matchers_(args) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003837
3838 template <typename Container>
3839 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003840 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003841 typedef typename internal::StlContainerView<RawContainer>::type View;
3842 typedef typename View::value_type Element;
3843 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3844 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003845 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003846 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3847 ::std::back_inserter(matchers));
3848 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003849 UnorderedMatcherRequire::ExactMatch, matchers.begin(), matchers.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003850 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003851
3852 private:
3853 const MatcherTuple matchers_;
3854 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3855};
3856
3857// Implements ElementsAre.
3858template <typename MatcherTuple>
3859class ElementsAreMatcher {
3860 public:
3861 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3862
3863 template <typename Container>
3864 operator Matcher<Container>() const {
Gennadiy Civil23187052018-03-26 10:16:59 -04003865 GTEST_COMPILE_ASSERT_(
3866 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value ||
3867 ::testing::tuple_size<MatcherTuple>::value < 2,
3868 use_UnorderedElementsAre_with_hash_tables);
3869
zhanyong.wanfb25d532013-07-28 08:24:00 +00003870 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3871 typedef typename internal::StlContainerView<RawContainer>::type View;
3872 typedef typename View::value_type Element;
3873 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3874 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003875 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003876 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3877 ::std::back_inserter(matchers));
3878 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3879 matchers.begin(), matchers.end()));
3880 }
3881
3882 private:
3883 const MatcherTuple matchers_;
3884 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3885};
3886
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003887// Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
zhanyong.wanfb25d532013-07-28 08:24:00 +00003888template <typename T>
3889class UnorderedElementsAreArrayMatcher {
3890 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003891 template <typename Iter>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003892 UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,
3893 Iter first, Iter last)
3894 : match_flags_(match_flags), matchers_(first, last) {}
zhanyong.wanfb25d532013-07-28 08:24:00 +00003895
3896 template <typename Container>
3897 operator Matcher<Container>() const {
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003898 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3899 match_flags_, matchers_.begin(), matchers_.end()));
zhanyong.wanfb25d532013-07-28 08:24:00 +00003900 }
3901
3902 private:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003903 UnorderedMatcherRequire::Flags match_flags_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003904 ::std::vector<T> matchers_;
3905
3906 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003907};
3908
3909// Implements ElementsAreArray().
3910template <typename T>
3911class ElementsAreArrayMatcher {
3912 public:
jgm38513a82012-11-15 15:50:36 +00003913 template <typename Iter>
3914 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003915
3916 template <typename Container>
3917 operator Matcher<Container>() const {
Gennadiy Civil23187052018-03-26 10:16:59 -04003918 GTEST_COMPILE_ASSERT_(
3919 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value,
3920 use_UnorderedElementsAreArray_with_hash_tables);
3921
jgm38513a82012-11-15 15:50:36 +00003922 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3923 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003924 }
3925
3926 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003927 const ::std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003928
3929 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003930};
3931
kosak2336e9c2014-07-28 22:57:30 +00003932// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3933// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3934// second) is a polymorphic matcher that matches a value x iff tm
3935// matches tuple (x, second). Useful for implementing
3936// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3937//
3938// BoundSecondMatcher is copyable and assignable, as we need to put
3939// instances of this class in a vector when implementing
3940// UnorderedPointwise().
3941template <typename Tuple2Matcher, typename Second>
3942class BoundSecondMatcher {
3943 public:
3944 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3945 : tuple2_matcher_(tm), second_value_(second) {}
3946
3947 template <typename T>
3948 operator Matcher<T>() const {
3949 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3950 }
3951
3952 // We have to define this for UnorderedPointwise() to compile in
3953 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3954 // which requires the elements to be assignable in C++98. The
3955 // compiler cannot generate the operator= for us, as Tuple2Matcher
3956 // and Second may not be assignable.
3957 //
3958 // However, this should never be called, so the implementation just
3959 // need to assert.
3960 void operator=(const BoundSecondMatcher& /*rhs*/) {
3961 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3962 }
3963
3964 private:
3965 template <typename T>
3966 class Impl : public MatcherInterface<T> {
3967 public:
3968 typedef ::testing::tuple<T, Second> ArgTuple;
3969
3970 Impl(const Tuple2Matcher& tm, const Second& second)
3971 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3972 second_value_(second) {}
3973
3974 virtual void DescribeTo(::std::ostream* os) const {
3975 *os << "and ";
3976 UniversalPrint(second_value_, os);
3977 *os << " ";
3978 mono_tuple2_matcher_.DescribeTo(os);
3979 }
3980
3981 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3982 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3983 listener);
3984 }
3985
3986 private:
3987 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3988 const Second second_value_;
3989
3990 GTEST_DISALLOW_ASSIGN_(Impl);
3991 };
3992
3993 const Tuple2Matcher tuple2_matcher_;
3994 const Second second_value_;
3995};
3996
3997// Given a 2-tuple matcher tm and a value second,
3998// MatcherBindSecond(tm, second) returns a matcher that matches a
3999// value x iff tm matches tuple (x, second). Useful for implementing
4000// UnorderedPointwise() in terms of UnorderedElementsAreArray().
4001template <typename Tuple2Matcher, typename Second>
4002BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
4003 const Tuple2Matcher& tm, const Second& second) {
4004 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
4005}
4006
zhanyong.wanb4140802010-06-08 22:53:57 +00004007// Returns the description for a matcher defined using the MATCHER*()
4008// macro where the user-supplied description string is "", if
4009// 'negation' is false; otherwise returns the description of the
4010// negation of the matcher. 'param_values' contains a list of strings
4011// that are the print-out of the matcher's parameters.
Nico Weber09fd5b32017-05-15 17:07:03 -04004012GTEST_API_ std::string FormatMatcherDescription(bool negation,
4013 const char* matcher_name,
4014 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00004015
Gennadiy Civilb907c262018-03-23 11:42:41 -04004016// Implements a matcher that checks the value of a optional<> type variable.
4017template <typename ValueMatcher>
4018class OptionalMatcher {
4019 public:
4020 explicit OptionalMatcher(const ValueMatcher& value_matcher)
4021 : value_matcher_(value_matcher) {}
4022
4023 template <typename Optional>
4024 operator Matcher<Optional>() const {
4025 return MakeMatcher(new Impl<Optional>(value_matcher_));
4026 }
4027
4028 template <typename Optional>
4029 class Impl : public MatcherInterface<Optional> {
4030 public:
4031 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView;
4032 typedef typename OptionalView::value_type ValueType;
4033 explicit Impl(const ValueMatcher& value_matcher)
4034 : value_matcher_(MatcherCast<ValueType>(value_matcher)) {}
4035
4036 virtual void DescribeTo(::std::ostream* os) const {
4037 *os << "value ";
4038 value_matcher_.DescribeTo(os);
4039 }
4040
4041 virtual void DescribeNegationTo(::std::ostream* os) const {
4042 *os << "value ";
4043 value_matcher_.DescribeNegationTo(os);
4044 }
4045
4046 virtual bool MatchAndExplain(Optional optional,
4047 MatchResultListener* listener) const {
4048 if (!optional) {
4049 *listener << "which is not engaged";
4050 return false;
4051 }
4052 const ValueType& value = *optional;
4053 StringMatchResultListener value_listener;
4054 const bool match = value_matcher_.MatchAndExplain(value, &value_listener);
4055 *listener << "whose value " << PrintToString(value)
4056 << (match ? " matches" : " doesn't match");
4057 PrintIfNotEmpty(value_listener.str(), listener->stream());
4058 return match;
4059 }
4060
4061 private:
4062 const Matcher<ValueType> value_matcher_;
4063 GTEST_DISALLOW_ASSIGN_(Impl);
4064 };
4065
4066 private:
4067 const ValueMatcher value_matcher_;
4068 GTEST_DISALLOW_ASSIGN_(OptionalMatcher);
4069};
4070
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05004071namespace variant_matcher {
4072// Overloads to allow VariantMatcher to do proper ADL lookup.
4073template <typename T>
4074void holds_alternative() {}
4075template <typename T>
4076void get() {}
4077
4078// Implements a matcher that checks the value of a variant<> type variable.
4079template <typename T>
4080class VariantMatcher {
4081 public:
4082 explicit VariantMatcher(::testing::Matcher<const T&> matcher)
4083 : matcher_(internal::move(matcher)) {}
4084
4085 template <typename Variant>
4086 bool MatchAndExplain(const Variant& value,
4087 ::testing::MatchResultListener* listener) const {
4088 if (!listener->IsInterested()) {
4089 return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));
4090 }
4091
4092 if (!holds_alternative<T>(value)) {
4093 *listener << "whose value is not of type '" << GetTypeName() << "'";
4094 return false;
4095 }
4096
4097 const T& elem = get<T>(value);
4098 StringMatchResultListener elem_listener;
4099 const bool match = matcher_.MatchAndExplain(elem, &elem_listener);
4100 *listener << "whose value " << PrintToString(elem)
4101 << (match ? " matches" : " doesn't match");
4102 PrintIfNotEmpty(elem_listener.str(), listener->stream());
4103 return match;
4104 }
4105
4106 void DescribeTo(std::ostream* os) const {
4107 *os << "is a variant<> with value of type '" << GetTypeName()
4108 << "' and the value ";
4109 matcher_.DescribeTo(os);
4110 }
4111
4112 void DescribeNegationTo(std::ostream* os) const {
4113 *os << "is a variant<> with value of type other than '" << GetTypeName()
4114 << "' or the value ";
4115 matcher_.DescribeNegationTo(os);
4116 }
4117
4118 private:
Gennadiy Civil23187052018-03-26 10:16:59 -04004119 static std::string GetTypeName() {
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05004120#if GTEST_HAS_RTTI
Gennadiy Civilab84d142018-04-11 15:24:04 -04004121 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
4122 return internal::GetTypeName<T>());
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05004123#endif
4124 return "the element type";
4125 }
4126
4127 const ::testing::Matcher<const T&> matcher_;
4128};
4129
4130} // namespace variant_matcher
4131
Gennadiy Civil466a49a2018-03-23 11:23:54 -04004132namespace any_cast_matcher {
4133
4134// Overloads to allow AnyCastMatcher to do proper ADL lookup.
4135template <typename T>
4136void any_cast() {}
4137
4138// Implements a matcher that any_casts the value.
4139template <typename T>
4140class AnyCastMatcher {
4141 public:
4142 explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher)
4143 : matcher_(matcher) {}
4144
4145 template <typename AnyType>
4146 bool MatchAndExplain(const AnyType& value,
4147 ::testing::MatchResultListener* listener) const {
4148 if (!listener->IsInterested()) {
4149 const T* ptr = any_cast<T>(&value);
4150 return ptr != NULL && matcher_.Matches(*ptr);
4151 }
4152
4153 const T* elem = any_cast<T>(&value);
4154 if (elem == NULL) {
4155 *listener << "whose value is not of type '" << GetTypeName() << "'";
4156 return false;
4157 }
4158
4159 StringMatchResultListener elem_listener;
4160 const bool match = matcher_.MatchAndExplain(*elem, &elem_listener);
4161 *listener << "whose value " << PrintToString(*elem)
4162 << (match ? " matches" : " doesn't match");
4163 PrintIfNotEmpty(elem_listener.str(), listener->stream());
4164 return match;
4165 }
4166
4167 void DescribeTo(std::ostream* os) const {
4168 *os << "is an 'any' type with value of type '" << GetTypeName()
4169 << "' and the value ";
4170 matcher_.DescribeTo(os);
4171 }
4172
4173 void DescribeNegationTo(std::ostream* os) const {
4174 *os << "is an 'any' type with value of type other than '" << GetTypeName()
4175 << "' or the value ";
4176 matcher_.DescribeNegationTo(os);
4177 }
4178
4179 private:
4180 static std::string GetTypeName() {
4181#if GTEST_HAS_RTTI
Gennadiy Civilab84d142018-04-11 15:24:04 -04004182 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
4183 return internal::GetTypeName<T>());
Gennadiy Civil466a49a2018-03-23 11:23:54 -04004184#endif
4185 return "the element type";
4186 }
4187
4188 const ::testing::Matcher<const T&> matcher_;
4189};
4190
4191} // namespace any_cast_matcher
shiqiane35fdd92008-12-10 05:08:54 +00004192} // namespace internal
4193
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004194// ElementsAreArray(iterator_first, iterator_last)
zhanyong.wanfb25d532013-07-28 08:24:00 +00004195// ElementsAreArray(pointer, count)
4196// ElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00004197// ElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004198// ElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00004199//
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004200// The ElementsAreArray() functions are like ElementsAre(...), except
4201// that they are given a homogeneous sequence rather than taking each
4202// element as a function argument. The sequence can be specified as an
4203// array, a pointer and count, a vector, an initializer list, or an
4204// STL iterator range. In each of these cases, the underlying sequence
4205// can be either a sequence of values or a sequence of matchers.
zhanyong.wanfb25d532013-07-28 08:24:00 +00004206//
4207// All forms of ElementsAreArray() make a copy of the input matcher sequence.
4208
4209template <typename Iter>
4210inline internal::ElementsAreArrayMatcher<
4211 typename ::std::iterator_traits<Iter>::value_type>
4212ElementsAreArray(Iter first, Iter last) {
4213 typedef typename ::std::iterator_traits<Iter>::value_type T;
4214 return internal::ElementsAreArrayMatcher<T>(first, last);
4215}
4216
4217template <typename T>
4218inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
4219 const T* pointer, size_t count) {
4220 return ElementsAreArray(pointer, pointer + count);
4221}
4222
4223template <typename T, size_t N>
4224inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
4225 const T (&array)[N]) {
4226 return ElementsAreArray(array, N);
4227}
4228
kosak06678922014-07-28 20:01:28 +00004229template <typename Container>
4230inline internal::ElementsAreArrayMatcher<typename Container::value_type>
4231ElementsAreArray(const Container& container) {
4232 return ElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00004233}
4234
kosak18489fa2013-12-04 23:49:07 +00004235#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004236template <typename T>
4237inline internal::ElementsAreArrayMatcher<T>
4238ElementsAreArray(::std::initializer_list<T> xs) {
4239 return ElementsAreArray(xs.begin(), xs.end());
4240}
4241#endif
4242
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004243// UnorderedElementsAreArray(iterator_first, iterator_last)
zhanyong.wanfb25d532013-07-28 08:24:00 +00004244// UnorderedElementsAreArray(pointer, count)
4245// UnorderedElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00004246// UnorderedElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004247// UnorderedElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00004248//
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004249// UnorderedElementsAreArray() verifies that a bijective mapping onto a
4250// collection of matchers exists.
4251//
4252// The matchers can be specified as an array, a pointer and count, a container,
4253// an initializer list, or an STL iterator range. In each of these cases, the
4254// underlying matchers can be either values or matchers.
4255
zhanyong.wanfb25d532013-07-28 08:24:00 +00004256template <typename Iter>
4257inline internal::UnorderedElementsAreArrayMatcher<
4258 typename ::std::iterator_traits<Iter>::value_type>
4259UnorderedElementsAreArray(Iter first, Iter last) {
4260 typedef typename ::std::iterator_traits<Iter>::value_type T;
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004261 return internal::UnorderedElementsAreArrayMatcher<T>(
4262 internal::UnorderedMatcherRequire::ExactMatch, first, last);
zhanyong.wanfb25d532013-07-28 08:24:00 +00004263}
4264
4265template <typename T>
4266inline internal::UnorderedElementsAreArrayMatcher<T>
4267UnorderedElementsAreArray(const T* pointer, size_t count) {
4268 return UnorderedElementsAreArray(pointer, pointer + count);
4269}
4270
4271template <typename T, size_t N>
4272inline internal::UnorderedElementsAreArrayMatcher<T>
4273UnorderedElementsAreArray(const T (&array)[N]) {
4274 return UnorderedElementsAreArray(array, N);
4275}
4276
kosak06678922014-07-28 20:01:28 +00004277template <typename Container>
4278inline internal::UnorderedElementsAreArrayMatcher<
4279 typename Container::value_type>
4280UnorderedElementsAreArray(const Container& container) {
4281 return UnorderedElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00004282}
4283
kosak18489fa2013-12-04 23:49:07 +00004284#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004285template <typename T>
4286inline internal::UnorderedElementsAreArrayMatcher<T>
4287UnorderedElementsAreArray(::std::initializer_list<T> xs) {
4288 return UnorderedElementsAreArray(xs.begin(), xs.end());
4289}
4290#endif
zhanyong.wanfb25d532013-07-28 08:24:00 +00004291
shiqiane35fdd92008-12-10 05:08:54 +00004292// _ is a matcher that matches anything of any type.
4293//
4294// This definition is fine as:
4295//
4296// 1. The C++ standard permits using the name _ in a namespace that
4297// is not the global namespace or ::std.
4298// 2. The AnythingMatcher class has no data member or constructor,
4299// so it's OK to create global variables of this type.
4300// 3. c-style has approved of using _ in this case.
4301const internal::AnythingMatcher _ = {};
4302// Creates a matcher that matches any value of the given type T.
4303template <typename T>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004304inline Matcher<T> A() {
4305 return Matcher<T>(new internal::AnyMatcherImpl<T>());
4306}
shiqiane35fdd92008-12-10 05:08:54 +00004307
4308// Creates a matcher that matches any value of the given type T.
4309template <typename T>
4310inline Matcher<T> An() { return A<T>(); }
4311
4312// Creates a polymorphic matcher that matches anything equal to x.
4313// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
4314// wouldn't compile.
4315template <typename T>
4316inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
4317
4318// Constructs a Matcher<T> from a 'value' of type T. The constructed
4319// matcher matches any value that's equal to 'value'.
4320template <typename T>
4321Matcher<T>::Matcher(T value) { *this = Eq(value); }
4322
Gennadiy Civil466a49a2018-03-23 11:23:54 -04004323template <typename T, typename M>
4324Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(
4325 const M& value,
4326 internal::BooleanConstant<false> /* convertible_to_matcher */,
4327 internal::BooleanConstant<false> /* convertible_to_T */) {
4328 return Eq(value);
4329}
4330
shiqiane35fdd92008-12-10 05:08:54 +00004331// Creates a monomorphic matcher that matches anything with type Lhs
4332// and equal to rhs. A user may need to use this instead of Eq(...)
4333// in order to resolve an overloading ambiguity.
4334//
4335// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
4336// or Matcher<T>(x), but more readable than the latter.
4337//
4338// We could define similar monomorphic matchers for other comparison
4339// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
4340// it yet as those are used much less than Eq() in practice. A user
4341// can always write Matcher<T>(Lt(5)) to be explicit about the type,
4342// for example.
4343template <typename Lhs, typename Rhs>
4344inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
4345
4346// Creates a polymorphic matcher that matches anything >= x.
4347template <typename Rhs>
4348inline internal::GeMatcher<Rhs> Ge(Rhs x) {
4349 return internal::GeMatcher<Rhs>(x);
4350}
4351
4352// Creates a polymorphic matcher that matches anything > x.
4353template <typename Rhs>
4354inline internal::GtMatcher<Rhs> Gt(Rhs x) {
4355 return internal::GtMatcher<Rhs>(x);
4356}
4357
4358// Creates a polymorphic matcher that matches anything <= x.
4359template <typename Rhs>
4360inline internal::LeMatcher<Rhs> Le(Rhs x) {
4361 return internal::LeMatcher<Rhs>(x);
4362}
4363
4364// Creates a polymorphic matcher that matches anything < x.
4365template <typename Rhs>
4366inline internal::LtMatcher<Rhs> Lt(Rhs x) {
4367 return internal::LtMatcher<Rhs>(x);
4368}
4369
4370// Creates a polymorphic matcher that matches anything != x.
4371template <typename Rhs>
4372inline internal::NeMatcher<Rhs> Ne(Rhs x) {
4373 return internal::NeMatcher<Rhs>(x);
4374}
4375
zhanyong.wan2d970ee2009-09-24 21:41:36 +00004376// Creates a polymorphic matcher that matches any NULL pointer.
4377inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
4378 return MakePolymorphicMatcher(internal::IsNullMatcher());
4379}
4380
shiqiane35fdd92008-12-10 05:08:54 +00004381// Creates a polymorphic matcher that matches any non-NULL pointer.
4382// This is convenient as Not(NULL) doesn't compile (the compiler
4383// thinks that that expression is comparing a pointer with an integer).
4384inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
4385 return MakePolymorphicMatcher(internal::NotNullMatcher());
4386}
4387
4388// Creates a polymorphic matcher that matches any argument that
4389// references variable x.
4390template <typename T>
4391inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
4392 return internal::RefMatcher<T&>(x);
4393}
4394
4395// Creates a matcher that matches any double argument approximately
4396// equal to rhs, where two NANs are considered unequal.
4397inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
4398 return internal::FloatingEqMatcher<double>(rhs, false);
4399}
4400
4401// Creates a matcher that matches any double argument approximately
4402// equal to rhs, including NaN values when rhs is NaN.
4403inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
4404 return internal::FloatingEqMatcher<double>(rhs, true);
4405}
4406
zhanyong.wan616180e2013-06-18 18:49:51 +00004407// Creates a matcher that matches any double argument approximately equal to
4408// rhs, up to the specified max absolute error bound, where two NANs are
4409// considered unequal. The max absolute error bound must be non-negative.
4410inline internal::FloatingEqMatcher<double> DoubleNear(
4411 double rhs, double max_abs_error) {
4412 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
4413}
4414
4415// Creates a matcher that matches any double argument approximately equal to
4416// rhs, up to the specified max absolute error bound, including NaN values when
4417// rhs is NaN. The max absolute error bound must be non-negative.
4418inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
4419 double rhs, double max_abs_error) {
4420 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
4421}
4422
shiqiane35fdd92008-12-10 05:08:54 +00004423// Creates a matcher that matches any float argument approximately
4424// equal to rhs, where two NANs are considered unequal.
4425inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
4426 return internal::FloatingEqMatcher<float>(rhs, false);
4427}
4428
zhanyong.wan616180e2013-06-18 18:49:51 +00004429// Creates a matcher that matches any float argument approximately
shiqiane35fdd92008-12-10 05:08:54 +00004430// equal to rhs, including NaN values when rhs is NaN.
4431inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
4432 return internal::FloatingEqMatcher<float>(rhs, true);
4433}
4434
zhanyong.wan616180e2013-06-18 18:49:51 +00004435// Creates a matcher that matches any float argument approximately equal to
4436// rhs, up to the specified max absolute error bound, where two NANs are
4437// considered unequal. The max absolute error bound must be non-negative.
4438inline internal::FloatingEqMatcher<float> FloatNear(
4439 float rhs, float max_abs_error) {
4440 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
4441}
4442
4443// Creates a matcher that matches any float argument approximately equal to
4444// rhs, up to the specified max absolute error bound, including NaN values when
4445// rhs is NaN. The max absolute error bound must be non-negative.
4446inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
4447 float rhs, float max_abs_error) {
4448 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
4449}
4450
shiqiane35fdd92008-12-10 05:08:54 +00004451// Creates a matcher that matches a pointer (raw or smart) that points
4452// to a value that matches inner_matcher.
4453template <typename InnerMatcher>
4454inline internal::PointeeMatcher<InnerMatcher> Pointee(
4455 const InnerMatcher& inner_matcher) {
4456 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
4457}
4458
Scott Grahama9653c42018-05-02 11:14:39 -07004459#if GTEST_HAS_RTTI
billydonahue1f5fdea2014-05-19 17:54:51 +00004460// Creates a matcher that matches a pointer or reference that matches
4461// inner_matcher when dynamic_cast<To> is applied.
4462// The result of dynamic_cast<To> is forwarded to the inner matcher.
4463// If To is a pointer and the cast fails, the inner matcher will receive NULL.
4464// If To is a reference and the cast fails, this matcher returns false
4465// immediately.
4466template <typename To>
4467inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
4468WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
4469 return MakePolymorphicMatcher(
4470 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
4471}
Scott Grahama9653c42018-05-02 11:14:39 -07004472#endif // GTEST_HAS_RTTI
billydonahue1f5fdea2014-05-19 17:54:51 +00004473
shiqiane35fdd92008-12-10 05:08:54 +00004474// Creates a matcher that matches an object whose given field matches
4475// 'matcher'. For example,
4476// Field(&Foo::number, Ge(5))
4477// matches a Foo object x iff x.number >= 5.
4478template <typename Class, typename FieldType, typename FieldMatcher>
4479inline PolymorphicMatcher<
4480 internal::FieldMatcher<Class, FieldType> > Field(
4481 FieldType Class::*field, const FieldMatcher& matcher) {
4482 return MakePolymorphicMatcher(
4483 internal::FieldMatcher<Class, FieldType>(
4484 field, MatcherCast<const FieldType&>(matcher)));
4485 // The call to MatcherCast() is required for supporting inner
4486 // matchers of compatible types. For example, it allows
4487 // Field(&Foo::bar, m)
4488 // to compile where bar is an int32 and m is a matcher for int64.
4489}
4490
Gennadiy Civilb907c262018-03-23 11:42:41 -04004491// Same as Field() but also takes the name of the field to provide better error
4492// messages.
4493template <typename Class, typename FieldType, typename FieldMatcher>
4494inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType> > Field(
4495 const std::string& field_name, FieldType Class::*field,
4496 const FieldMatcher& matcher) {
4497 return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(
4498 field_name, field, MatcherCast<const FieldType&>(matcher)));
4499}
4500
shiqiane35fdd92008-12-10 05:08:54 +00004501// Creates a matcher that matches an object whose given property
4502// matches 'matcher'. For example,
4503// Property(&Foo::str, StartsWith("hi"))
4504// matches a Foo object x iff x.str() starts with "hi".
4505template <typename Class, typename PropertyType, typename PropertyMatcher>
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004506inline PolymorphicMatcher<internal::PropertyMatcher<
4507 Class, PropertyType, PropertyType (Class::*)() const> >
4508Property(PropertyType (Class::*property)() const,
4509 const PropertyMatcher& matcher) {
shiqiane35fdd92008-12-10 05:08:54 +00004510 return MakePolymorphicMatcher(
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004511 internal::PropertyMatcher<Class, PropertyType,
4512 PropertyType (Class::*)() const>(
shiqiane35fdd92008-12-10 05:08:54 +00004513 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00004514 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00004515 // The call to MatcherCast() is required for supporting inner
4516 // matchers of compatible types. For example, it allows
4517 // Property(&Foo::bar, m)
4518 // to compile where bar() returns an int32 and m is a matcher for int64.
4519}
4520
Gennadiy Civil23187052018-03-26 10:16:59 -04004521// Same as Property() above, but also takes the name of the property to provide
4522// better error messages.
4523template <typename Class, typename PropertyType, typename PropertyMatcher>
4524inline PolymorphicMatcher<internal::PropertyMatcher<
4525 Class, PropertyType, PropertyType (Class::*)() const> >
4526Property(const std::string& property_name,
4527 PropertyType (Class::*property)() const,
4528 const PropertyMatcher& matcher) {
4529 return MakePolymorphicMatcher(
4530 internal::PropertyMatcher<Class, PropertyType,
4531 PropertyType (Class::*)() const>(
4532 property_name, property,
4533 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4534}
4535
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004536#if GTEST_LANG_CXX11
4537// The same as above but for reference-qualified member functions.
4538template <typename Class, typename PropertyType, typename PropertyMatcher>
4539inline PolymorphicMatcher<internal::PropertyMatcher<
4540 Class, PropertyType, PropertyType (Class::*)() const &> >
4541Property(PropertyType (Class::*property)() const &,
4542 const PropertyMatcher& matcher) {
4543 return MakePolymorphicMatcher(
4544 internal::PropertyMatcher<Class, PropertyType,
4545 PropertyType (Class::*)() const &>(
4546 property,
4547 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4548}
Gennadiy Civila02af2f2018-07-20 11:28:58 -04004549
4550// Three-argument form for reference-qualified member functions.
4551template <typename Class, typename PropertyType, typename PropertyMatcher>
4552inline PolymorphicMatcher<internal::PropertyMatcher<
4553 Class, PropertyType, PropertyType (Class::*)() const &> >
4554Property(const std::string& property_name,
4555 PropertyType (Class::*property)() const &,
4556 const PropertyMatcher& matcher) {
4557 return MakePolymorphicMatcher(
4558 internal::PropertyMatcher<Class, PropertyType,
4559 PropertyType (Class::*)() const &>(
4560 property_name, property,
4561 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4562}
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004563#endif
4564
shiqiane35fdd92008-12-10 05:08:54 +00004565// Creates a matcher that matches an object iff the result of applying
4566// a callable to x matches 'matcher'.
4567// For example,
4568// ResultOf(f, StartsWith("hi"))
4569// matches a Foo object x iff f(x) starts with "hi".
Abseil Teama0e62d92018-08-24 13:30:17 -04004570// `callable` parameter can be a function, function pointer, or a functor. It is
4571// required to keep no state affecting the results of the calls on it and make
4572// no assumptions about how many calls will be made. Any state it keeps must be
4573// protected from the concurrent access.
4574template <typename Callable, typename InnerMatcher>
4575internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(
4576 Callable callable, InnerMatcher matcher) {
4577 return internal::ResultOfMatcher<Callable, InnerMatcher>(
4578 internal::move(callable), internal::move(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00004579}
4580
4581// String matchers.
4582
4583// Matches a string equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04004584inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
4585 const std::string& str) {
4586 return MakePolymorphicMatcher(
4587 internal::StrEqualityMatcher<std::string>(str, true, true));
shiqiane35fdd92008-12-10 05:08:54 +00004588}
4589
4590// Matches a string not equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04004591inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
4592 const std::string& str) {
4593 return MakePolymorphicMatcher(
4594 internal::StrEqualityMatcher<std::string>(str, false, true));
shiqiane35fdd92008-12-10 05:08:54 +00004595}
4596
4597// Matches a string equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04004598inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
4599 const std::string& str) {
4600 return MakePolymorphicMatcher(
4601 internal::StrEqualityMatcher<std::string>(str, true, false));
shiqiane35fdd92008-12-10 05:08:54 +00004602}
4603
4604// Matches a string not equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04004605inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
4606 const std::string& str) {
4607 return MakePolymorphicMatcher(
4608 internal::StrEqualityMatcher<std::string>(str, false, false));
shiqiane35fdd92008-12-10 05:08:54 +00004609}
4610
4611// Creates a matcher that matches any string, std::string, or C string
4612// that contains the given substring.
Nico Weber09fd5b32017-05-15 17:07:03 -04004613inline PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
4614 const std::string& substring) {
4615 return MakePolymorphicMatcher(
4616 internal::HasSubstrMatcher<std::string>(substring));
shiqiane35fdd92008-12-10 05:08:54 +00004617}
4618
4619// Matches a string that starts with 'prefix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004620inline PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
4621 const std::string& prefix) {
4622 return MakePolymorphicMatcher(
4623 internal::StartsWithMatcher<std::string>(prefix));
shiqiane35fdd92008-12-10 05:08:54 +00004624}
4625
4626// Matches a string that ends with 'suffix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004627inline PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
4628 const std::string& suffix) {
4629 return MakePolymorphicMatcher(internal::EndsWithMatcher<std::string>(suffix));
shiqiane35fdd92008-12-10 05:08:54 +00004630}
4631
shiqiane35fdd92008-12-10 05:08:54 +00004632// Matches a string that fully matches regular expression 'regex'.
4633// The matcher takes ownership of 'regex'.
4634inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4635 const internal::RE* regex) {
4636 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
4637}
4638inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004639 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004640 return MatchesRegex(new internal::RE(regex));
4641}
4642
4643// Matches a string that contains regular expression 'regex'.
4644// The matcher takes ownership of 'regex'.
4645inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4646 const internal::RE* regex) {
4647 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4648}
4649inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004650 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004651 return ContainsRegex(new internal::RE(regex));
4652}
4653
shiqiane35fdd92008-12-10 05:08:54 +00004654#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4655// Wide string matchers.
4656
4657// Matches a string equal to str.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004658inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrEq(
4659 const std::wstring& str) {
4660 return MakePolymorphicMatcher(
4661 internal::StrEqualityMatcher<std::wstring>(str, true, true));
shiqiane35fdd92008-12-10 05:08:54 +00004662}
4663
4664// Matches a string not equal to str.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004665inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrNe(
4666 const std::wstring& str) {
4667 return MakePolymorphicMatcher(
4668 internal::StrEqualityMatcher<std::wstring>(str, false, true));
shiqiane35fdd92008-12-10 05:08:54 +00004669}
4670
4671// Matches a string equal to str, ignoring case.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004672inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
4673StrCaseEq(const std::wstring& str) {
4674 return MakePolymorphicMatcher(
4675 internal::StrEqualityMatcher<std::wstring>(str, true, false));
shiqiane35fdd92008-12-10 05:08:54 +00004676}
4677
4678// Matches a string not equal to str, ignoring case.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004679inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
4680StrCaseNe(const std::wstring& str) {
4681 return MakePolymorphicMatcher(
4682 internal::StrEqualityMatcher<std::wstring>(str, false, false));
shiqiane35fdd92008-12-10 05:08:54 +00004683}
4684
Gennadiy Civilb907c262018-03-23 11:42:41 -04004685// Creates a matcher that matches any ::wstring, std::wstring, or C wide string
shiqiane35fdd92008-12-10 05:08:54 +00004686// that contains the given substring.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004687inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring> > HasSubstr(
4688 const std::wstring& substring) {
4689 return MakePolymorphicMatcher(
4690 internal::HasSubstrMatcher<std::wstring>(substring));
shiqiane35fdd92008-12-10 05:08:54 +00004691}
4692
4693// Matches a string that starts with 'prefix' (case-sensitive).
Gennadiy Civilb907c262018-03-23 11:42:41 -04004694inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring> >
4695StartsWith(const std::wstring& prefix) {
4696 return MakePolymorphicMatcher(
4697 internal::StartsWithMatcher<std::wstring>(prefix));
shiqiane35fdd92008-12-10 05:08:54 +00004698}
4699
4700// Matches a string that ends with 'suffix' (case-sensitive).
Gennadiy Civilb907c262018-03-23 11:42:41 -04004701inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring> > EndsWith(
4702 const std::wstring& suffix) {
4703 return MakePolymorphicMatcher(
4704 internal::EndsWithMatcher<std::wstring>(suffix));
shiqiane35fdd92008-12-10 05:08:54 +00004705}
4706
4707#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4708
4709// Creates a polymorphic matcher that matches a 2-tuple where the
4710// first field == the second field.
4711inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4712
4713// Creates a polymorphic matcher that matches a 2-tuple where the
4714// first field >= the second field.
4715inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4716
4717// Creates a polymorphic matcher that matches a 2-tuple where the
4718// first field > the second field.
4719inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4720
4721// Creates a polymorphic matcher that matches a 2-tuple where the
4722// first field <= the second field.
4723inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4724
4725// Creates a polymorphic matcher that matches a 2-tuple where the
4726// first field < the second field.
4727inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4728
4729// Creates a polymorphic matcher that matches a 2-tuple where the
4730// first field != the second field.
4731inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4732
Gennadiy Civilb907c262018-03-23 11:42:41 -04004733// Creates a polymorphic matcher that matches a 2-tuple where
4734// FloatEq(first field) matches the second field.
4735inline internal::FloatingEq2Matcher<float> FloatEq() {
4736 return internal::FloatingEq2Matcher<float>();
4737}
4738
4739// Creates a polymorphic matcher that matches a 2-tuple where
4740// DoubleEq(first field) matches the second field.
4741inline internal::FloatingEq2Matcher<double> DoubleEq() {
4742 return internal::FloatingEq2Matcher<double>();
4743}
4744
4745// Creates a polymorphic matcher that matches a 2-tuple where
4746// FloatEq(first field) matches the second field with NaN equality.
4747inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() {
4748 return internal::FloatingEq2Matcher<float>(true);
4749}
4750
4751// Creates a polymorphic matcher that matches a 2-tuple where
4752// DoubleEq(first field) matches the second field with NaN equality.
4753inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() {
4754 return internal::FloatingEq2Matcher<double>(true);
4755}
4756
4757// Creates a polymorphic matcher that matches a 2-tuple where
4758// FloatNear(first field, max_abs_error) matches the second field.
4759inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) {
4760 return internal::FloatingEq2Matcher<float>(max_abs_error);
4761}
4762
4763// Creates a polymorphic matcher that matches a 2-tuple where
4764// DoubleNear(first field, max_abs_error) matches the second field.
4765inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) {
4766 return internal::FloatingEq2Matcher<double>(max_abs_error);
4767}
4768
4769// Creates a polymorphic matcher that matches a 2-tuple where
4770// FloatNear(first field, max_abs_error) matches the second field with NaN
4771// equality.
4772inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear(
4773 float max_abs_error) {
4774 return internal::FloatingEq2Matcher<float>(max_abs_error, true);
4775}
4776
4777// Creates a polymorphic matcher that matches a 2-tuple where
4778// DoubleNear(first field, max_abs_error) matches the second field with NaN
4779// equality.
4780inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear(
4781 double max_abs_error) {
4782 return internal::FloatingEq2Matcher<double>(max_abs_error, true);
4783}
4784
shiqiane35fdd92008-12-10 05:08:54 +00004785// Creates a matcher that matches any value of type T that m doesn't
4786// match.
4787template <typename InnerMatcher>
4788inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4789 return internal::NotMatcher<InnerMatcher>(m);
4790}
4791
shiqiane35fdd92008-12-10 05:08:54 +00004792// Returns a matcher that matches anything that satisfies the given
4793// predicate. The predicate can be any unary function or functor
4794// whose return type can be implicitly converted to bool.
4795template <typename Predicate>
4796inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4797Truly(Predicate pred) {
4798 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4799}
4800
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004801// Returns a matcher that matches the container size. The container must
4802// support both size() and size_type which all STL-like containers provide.
4803// Note that the parameter 'size' can be a value of type size_type as well as
4804// matcher. For instance:
4805// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
4806// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
4807template <typename SizeMatcher>
4808inline internal::SizeIsMatcher<SizeMatcher>
4809SizeIs(const SizeMatcher& size_matcher) {
4810 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4811}
4812
kosakb6a34882014-03-12 21:06:46 +00004813// Returns a matcher that matches the distance between the container's begin()
4814// iterator and its end() iterator, i.e. the size of the container. This matcher
4815// can be used instead of SizeIs with containers such as std::forward_list which
4816// do not implement size(). The container must provide const_iterator (with
4817// valid iterator_traits), begin() and end().
4818template <typename DistanceMatcher>
4819inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4820BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4821 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4822}
4823
zhanyong.wan6a896b52009-01-16 01:13:50 +00004824// Returns a matcher that matches an equal container.
4825// This matcher behaves like Eq(), but in the event of mismatch lists the
4826// values that are included in one container but not the other. (Duplicate
4827// values and order differences are not explained.)
4828template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00004829inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00004830 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004831 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00004832 // This following line is for working around a bug in MSVC 8.0,
4833 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00004834 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00004835 return MakePolymorphicMatcher(
4836 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00004837}
4838
zhanyong.wan898725c2011-09-16 16:45:39 +00004839// Returns a matcher that matches a container that, when sorted using
4840// the given comparator, matches container_matcher.
4841template <typename Comparator, typename ContainerMatcher>
4842inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4843WhenSortedBy(const Comparator& comparator,
4844 const ContainerMatcher& container_matcher) {
4845 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4846 comparator, container_matcher);
4847}
4848
4849// Returns a matcher that matches a container that, when sorted using
4850// the < operator, matches container_matcher.
4851template <typename ContainerMatcher>
4852inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4853WhenSorted(const ContainerMatcher& container_matcher) {
4854 return
4855 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4856 internal::LessComparator(), container_matcher);
4857}
4858
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004859// Matches an STL-style container or a native array that contains the
4860// same number of elements as in rhs, where its i-th element and rhs's
4861// i-th element (as a pair) satisfy the given pair matcher, for all i.
4862// TupleMatcher must be able to be safely cast to Matcher<tuple<const
4863// T1&, const T2&> >, where T1 and T2 are the types of elements in the
4864// LHS container and the RHS container respectively.
4865template <typename TupleMatcher, typename Container>
4866inline internal::PointwiseMatcher<TupleMatcher,
4867 GTEST_REMOVE_CONST_(Container)>
4868Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4869 // This following line is for working around a bug in MSVC 8.0,
kosak2336e9c2014-07-28 22:57:30 +00004870 // which causes Container to be a const type sometimes (e.g. when
4871 // rhs is a const int[])..
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004872 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4873 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4874 tuple_matcher, rhs);
4875}
4876
kosak2336e9c2014-07-28 22:57:30 +00004877#if GTEST_HAS_STD_INITIALIZER_LIST_
4878
4879// Supports the Pointwise(m, {a, b, c}) syntax.
4880template <typename TupleMatcher, typename T>
4881inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4882 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4883 return Pointwise(tuple_matcher, std::vector<T>(rhs));
4884}
4885
4886#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4887
4888// UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4889// container or a native array that contains the same number of
4890// elements as in rhs, where in some permutation of the container, its
4891// i-th element and rhs's i-th element (as a pair) satisfy the given
4892// pair matcher, for all i. Tuple2Matcher must be able to be safely
4893// cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4894// the types of elements in the LHS container and the RHS container
4895// respectively.
4896//
4897// This is like Pointwise(pair_matcher, rhs), except that the element
4898// order doesn't matter.
4899template <typename Tuple2Matcher, typename RhsContainer>
4900inline internal::UnorderedElementsAreArrayMatcher<
4901 typename internal::BoundSecondMatcher<
4902 Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4903 RhsContainer)>::type::value_type> >
4904UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4905 const RhsContainer& rhs_container) {
4906 // This following line is for working around a bug in MSVC 8.0,
4907 // which causes RhsContainer to be a const type sometimes (e.g. when
4908 // rhs_container is a const int[]).
4909 typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4910
4911 // RhsView allows the same code to handle RhsContainer being a
4912 // STL-style container and it being a native C-style array.
4913 typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4914 typedef typename RhsView::type RhsStlContainer;
4915 typedef typename RhsStlContainer::value_type Second;
4916 const RhsStlContainer& rhs_stl_container =
4917 RhsView::ConstReference(rhs_container);
4918
4919 // Create a matcher for each element in rhs_container.
4920 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4921 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4922 it != rhs_stl_container.end(); ++it) {
4923 matchers.push_back(
4924 internal::MatcherBindSecond(tuple2_matcher, *it));
4925 }
4926
4927 // Delegate the work to UnorderedElementsAreArray().
4928 return UnorderedElementsAreArray(matchers);
4929}
4930
4931#if GTEST_HAS_STD_INITIALIZER_LIST_
4932
4933// Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4934template <typename Tuple2Matcher, typename T>
4935inline internal::UnorderedElementsAreArrayMatcher<
4936 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4937UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4938 std::initializer_list<T> rhs) {
4939 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4940}
4941
4942#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4943
zhanyong.wanb8243162009-06-04 05:48:20 +00004944// Matches an STL-style container or a native array that contains at
4945// least one element matching the given value or matcher.
4946//
4947// Examples:
4948// ::std::set<int> page_ids;
4949// page_ids.insert(3);
4950// page_ids.insert(1);
4951// EXPECT_THAT(page_ids, Contains(1));
4952// EXPECT_THAT(page_ids, Contains(Gt(2)));
4953// EXPECT_THAT(page_ids, Not(Contains(4)));
4954//
4955// ::std::map<int, size_t> page_lengths;
4956// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00004957// EXPECT_THAT(page_lengths,
4958// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004959//
4960// const char* user_ids[] = { "joe", "mike", "tom" };
4961// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4962template <typename M>
4963inline internal::ContainsMatcher<M> Contains(M matcher) {
4964 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004965}
4966
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004967// IsSupersetOf(iterator_first, iterator_last)
4968// IsSupersetOf(pointer, count)
4969// IsSupersetOf(array)
4970// IsSupersetOf(container)
4971// IsSupersetOf({e1, e2, ..., en})
4972//
4973// IsSupersetOf() verifies that a surjective partial mapping onto a collection
4974// of matchers exists. In other words, a container matches
4975// IsSupersetOf({e1, ..., en}) if and only if there is a permutation
4976// {y1, ..., yn} of some of the container's elements where y1 matches e1,
4977// ..., and yn matches en. Obviously, the size of the container must be >= n
4978// in order to have a match. Examples:
4979//
4980// - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and
4981// 1 matches Ne(0).
4982// - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches
4983// both Eq(1) and Lt(2). The reason is that different matchers must be used
4984// for elements in different slots of the container.
4985// - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches
4986// Eq(1) and (the second) 1 matches Lt(2).
4987// - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)
4988// Gt(1) and 3 matches (the second) Gt(1).
4989//
4990// The matchers can be specified as an array, a pointer and count, a container,
4991// an initializer list, or an STL iterator range. In each of these cases, the
4992// underlying matchers can be either values or matchers.
4993
4994template <typename Iter>
4995inline internal::UnorderedElementsAreArrayMatcher<
4996 typename ::std::iterator_traits<Iter>::value_type>
4997IsSupersetOf(Iter first, Iter last) {
4998 typedef typename ::std::iterator_traits<Iter>::value_type T;
4999 return internal::UnorderedElementsAreArrayMatcher<T>(
5000 internal::UnorderedMatcherRequire::Superset, first, last);
5001}
5002
5003template <typename T>
5004inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
5005 const T* pointer, size_t count) {
5006 return IsSupersetOf(pointer, pointer + count);
5007}
5008
5009template <typename T, size_t N>
5010inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
5011 const T (&array)[N]) {
5012 return IsSupersetOf(array, N);
5013}
5014
5015template <typename Container>
5016inline internal::UnorderedElementsAreArrayMatcher<
5017 typename Container::value_type>
5018IsSupersetOf(const Container& container) {
5019 return IsSupersetOf(container.begin(), container.end());
5020}
5021
5022#if GTEST_HAS_STD_INITIALIZER_LIST_
5023template <typename T>
5024inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
5025 ::std::initializer_list<T> xs) {
5026 return IsSupersetOf(xs.begin(), xs.end());
5027}
5028#endif
5029
5030// IsSubsetOf(iterator_first, iterator_last)
5031// IsSubsetOf(pointer, count)
5032// IsSubsetOf(array)
5033// IsSubsetOf(container)
5034// IsSubsetOf({e1, e2, ..., en})
5035//
5036// IsSubsetOf() verifies that an injective mapping onto a collection of matchers
5037// exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and
5038// only if there is a subset of matchers {m1, ..., mk} which would match the
5039// container using UnorderedElementsAre. Obviously, the size of the container
5040// must be <= n in order to have a match. Examples:
5041//
5042// - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).
5043// - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1
5044// matches Lt(0).
5045// - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both
5046// match Gt(0). The reason is that different matchers must be used for
5047// elements in different slots of the container.
5048//
5049// The matchers can be specified as an array, a pointer and count, a container,
5050// an initializer list, or an STL iterator range. In each of these cases, the
5051// underlying matchers can be either values or matchers.
5052
5053template <typename Iter>
5054inline internal::UnorderedElementsAreArrayMatcher<
5055 typename ::std::iterator_traits<Iter>::value_type>
5056IsSubsetOf(Iter first, Iter last) {
5057 typedef typename ::std::iterator_traits<Iter>::value_type T;
5058 return internal::UnorderedElementsAreArrayMatcher<T>(
5059 internal::UnorderedMatcherRequire::Subset, first, last);
5060}
5061
5062template <typename T>
5063inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
5064 const T* pointer, size_t count) {
5065 return IsSubsetOf(pointer, pointer + count);
5066}
5067
5068template <typename T, size_t N>
5069inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
5070 const T (&array)[N]) {
5071 return IsSubsetOf(array, N);
5072}
5073
5074template <typename Container>
5075inline internal::UnorderedElementsAreArrayMatcher<
5076 typename Container::value_type>
5077IsSubsetOf(const Container& container) {
5078 return IsSubsetOf(container.begin(), container.end());
5079}
5080
5081#if GTEST_HAS_STD_INITIALIZER_LIST_
5082template <typename T>
5083inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
5084 ::std::initializer_list<T> xs) {
5085 return IsSubsetOf(xs.begin(), xs.end());
5086}
5087#endif
5088
zhanyong.wan33605ba2010-04-22 23:37:47 +00005089// Matches an STL-style container or a native array that contains only
5090// elements matching the given value or matcher.
5091//
5092// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
5093// the messages are different.
5094//
5095// Examples:
5096// ::std::set<int> page_ids;
5097// // Each(m) matches an empty container, regardless of what m is.
5098// EXPECT_THAT(page_ids, Each(Eq(1)));
5099// EXPECT_THAT(page_ids, Each(Eq(77)));
5100//
5101// page_ids.insert(3);
5102// EXPECT_THAT(page_ids, Each(Gt(0)));
5103// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
5104// page_ids.insert(1);
5105// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
5106//
5107// ::std::map<int, size_t> page_lengths;
5108// page_lengths[1] = 100;
5109// page_lengths[2] = 200;
5110// page_lengths[3] = 300;
5111// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
5112// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
5113//
5114// const char* user_ids[] = { "joe", "mike", "tom" };
5115// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
5116template <typename M>
5117inline internal::EachMatcher<M> Each(M matcher) {
5118 return internal::EachMatcher<M>(matcher);
5119}
5120
zhanyong.wanb5937da2009-07-16 20:26:41 +00005121// Key(inner_matcher) matches an std::pair whose 'first' field matches
5122// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
5123// std::map that contains at least one element whose key is >= 5.
5124template <typename M>
5125inline internal::KeyMatcher<M> Key(M inner_matcher) {
5126 return internal::KeyMatcher<M>(inner_matcher);
5127}
5128
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00005129// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
5130// matches first_matcher and whose 'second' field matches second_matcher. For
5131// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
5132// to match a std::map<int, string> that contains exactly one element whose key
5133// is >= 5 and whose value equals "foo".
5134template <typename FirstMatcher, typename SecondMatcher>
5135inline internal::PairMatcher<FirstMatcher, SecondMatcher>
5136Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
5137 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
5138 first_matcher, second_matcher);
5139}
5140
shiqiane35fdd92008-12-10 05:08:54 +00005141// Returns a predicate that is satisfied by anything that matches the
5142// given matcher.
5143template <typename M>
5144inline internal::MatcherAsPredicate<M> Matches(M matcher) {
5145 return internal::MatcherAsPredicate<M>(matcher);
5146}
5147
zhanyong.wanb8243162009-06-04 05:48:20 +00005148// Returns true iff the value matches the matcher.
5149template <typename T, typename M>
5150inline bool Value(const T& value, M matcher) {
5151 return testing::Matches(matcher)(value);
5152}
5153
zhanyong.wan34b034c2010-03-05 21:23:23 +00005154// Matches the value against the given matcher and explains the match
5155// result to listener.
5156template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00005157inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00005158 M matcher, const T& value, MatchResultListener* listener) {
5159 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
5160}
5161
Gennadiy Civilb907c262018-03-23 11:42:41 -04005162// Returns a string representation of the given matcher. Useful for description
5163// strings of matchers defined using MATCHER_P* macros that accept matchers as
5164// their arguments. For example:
5165//
5166// MATCHER_P(XAndYThat, matcher,
5167// "X that " + DescribeMatcher<int>(matcher, negation) +
5168// " and Y that " + DescribeMatcher<double>(matcher, negation)) {
5169// return ExplainMatchResult(matcher, arg.x(), result_listener) &&
5170// ExplainMatchResult(matcher, arg.y(), result_listener);
5171// }
5172template <typename T, typename M>
5173std::string DescribeMatcher(const M& matcher, bool negation = false) {
5174 ::std::stringstream ss;
5175 Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher);
5176 if (negation) {
5177 monomorphic_matcher.DescribeNegationTo(&ss);
5178 } else {
5179 monomorphic_matcher.DescribeTo(&ss);
5180 }
5181 return ss.str();
5182}
5183
zhanyong.wan616180e2013-06-18 18:49:51 +00005184#if GTEST_LANG_CXX11
5185// Define variadic matcher versions. They are overloaded in
5186// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
5187template <typename... Args>
Gennadiy Civil0c178882018-07-19 12:42:39 -04005188internal::AllOfMatcher<typename std::decay<const Args&>::type...> AllOf(
5189 const Args&... matchers) {
5190 return internal::AllOfMatcher<typename std::decay<const Args&>::type...>(
5191 matchers...);
zhanyong.wan616180e2013-06-18 18:49:51 +00005192}
5193
5194template <typename... Args>
Gennadiy Civil0c178882018-07-19 12:42:39 -04005195internal::AnyOfMatcher<typename std::decay<const Args&>::type...> AnyOf(
5196 const Args&... matchers) {
5197 return internal::AnyOfMatcher<typename std::decay<const Args&>::type...>(
5198 matchers...);
zhanyong.wan616180e2013-06-18 18:49:51 +00005199}
5200
Gennadiy Civil3f88bb12018-04-16 15:52:47 -04005201template <typename... Args>
Gennadiy Civil4707c0f2018-04-18 10:36:12 -04005202internal::ElementsAreMatcher<tuple<typename std::decay<const Args&>::type...>>
Gennadiy Civildff32af2018-04-17 16:12:04 -04005203ElementsAre(const Args&... matchers) {
5204 return internal::ElementsAreMatcher<
Gennadiy Civil4707c0f2018-04-18 10:36:12 -04005205 tuple<typename std::decay<const Args&>::type...>>(
5206 make_tuple(matchers...));
Gennadiy Civildff32af2018-04-17 16:12:04 -04005207}
5208
5209template <typename... Args>
Gennadiy Civil4707c0f2018-04-18 10:36:12 -04005210internal::UnorderedElementsAreMatcher<
5211 tuple<typename std::decay<const Args&>::type...>>
Gennadiy Civildff32af2018-04-17 16:12:04 -04005212UnorderedElementsAre(const Args&... matchers) {
5213 return internal::UnorderedElementsAreMatcher<
Gennadiy Civil4707c0f2018-04-18 10:36:12 -04005214 tuple<typename std::decay<const Args&>::type...>>(
5215 make_tuple(matchers...));
Gennadiy Civil3f88bb12018-04-16 15:52:47 -04005216}
5217
zhanyong.wan616180e2013-06-18 18:49:51 +00005218#endif // GTEST_LANG_CXX11
5219
zhanyong.wanbf550852009-06-09 06:09:53 +00005220// AllArgs(m) is a synonym of m. This is useful in
5221//
5222// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
5223//
5224// which is easier to read than
5225//
5226// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
5227template <typename InnerMatcher>
5228inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
5229
Gennadiy Civilb907c262018-03-23 11:42:41 -04005230// Returns a matcher that matches the value of an optional<> type variable.
5231// The matcher implementation only uses '!arg' and requires that the optional<>
5232// type has a 'value_type' member type and that '*arg' is of type 'value_type'
5233// and is printable using 'PrintToString'. It is compatible with
5234// std::optional/std::experimental::optional.
5235// Note that to compare an optional type variable against nullopt you should
5236// use Eq(nullopt) and not Optional(Eq(nullopt)). The latter implies that the
5237// optional value contains an optional itself.
5238template <typename ValueMatcher>
5239inline internal::OptionalMatcher<ValueMatcher> Optional(
5240 const ValueMatcher& value_matcher) {
5241 return internal::OptionalMatcher<ValueMatcher>(value_matcher);
5242}
5243
5244// Returns a matcher that matches the value of a absl::any type variable.
5245template <typename T>
5246PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T> > AnyWith(
5247 const Matcher<const T&>& matcher) {
5248 return MakePolymorphicMatcher(
5249 internal::any_cast_matcher::AnyCastMatcher<T>(matcher));
5250}
5251
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05005252// Returns a matcher that matches the value of a variant<> type variable.
5253// The matcher implementation uses ADL to find the holds_alternative and get
5254// functions.
5255// It is compatible with std::variant.
5256template <typename T>
5257PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
5258 const Matcher<const T&>& matcher) {
5259 return MakePolymorphicMatcher(
5260 internal::variant_matcher::VariantMatcher<T>(matcher));
5261}
5262
shiqiane35fdd92008-12-10 05:08:54 +00005263// These macros allow using matchers to check values in Google Test
5264// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
5265// succeed iff the value matches the matcher. If the assertion fails,
5266// the value and the description of the matcher will be printed.
5267#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
5268 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
5269#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
5270 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
5271
5272} // namespace testing
5273
Gennadiy Civil9ad73982018-08-29 22:32:08 -04005274GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
mistergdf428ec2018-08-20 14:48:45 -04005275
kosak6702b972015-07-27 23:05:57 +00005276// Include any custom callback matchers added by the local installation.
5277// We must include this header at the end to make sure it can use the
5278// declarations from this file.
5279#include "gmock/internal/custom/gmock-matchers.h"
Gennadiy Civilb907c262018-03-23 11:42:41 -04005280
shiqiane35fdd92008-12-10 05:08:54 +00005281#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_