blob: 3975cd07179801e4ec407cc1c09b5af5864ea772 [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
mistergdf428ec2018-08-20 14:48:45 -040059GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
60/* class A needs to have dll-interface to be used by clients of class B */)
61
shiqiane35fdd92008-12-10 05:08:54 +000062namespace testing {
63
64// To implement a matcher Foo for type T, define:
65// 1. a class FooMatcherImpl that implements the
66// MatcherInterface<T> interface, and
67// 2. a factory function that creates a Matcher<T> object from a
68// FooMatcherImpl*.
69//
70// The two-level delegation design makes it possible to allow a user
71// to write "v" instead of "Eq(v)" where a Matcher is expected, which
72// is impossible if we pass matchers by pointers. It also eases
73// ownership management as Matcher objects can now be copied like
74// plain values.
75
zhanyong.wan82113312010-01-08 21:55:40 +000076// MatchResultListener is an abstract class. Its << operator can be
77// used by a matcher to explain why a value matches or doesn't match.
78//
Gennadiy Civil265efde2018-08-14 15:04:11 -040079// FIXME: add method
zhanyong.wan82113312010-01-08 21:55:40 +000080// bool InterestedInWhy(bool result) const;
81// to indicate whether the listener is interested in why the match
82// result is 'result'.
83class MatchResultListener {
84 public:
85 // Creates a listener object with the given underlying ostream. The
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +000086 // listener does not own the ostream, and does not dereference it
87 // in the constructor or destructor.
zhanyong.wan82113312010-01-08 21:55:40 +000088 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
89 virtual ~MatchResultListener() = 0; // Makes this class abstract.
90
91 // Streams x to the underlying ostream; does nothing if the ostream
92 // is NULL.
93 template <typename T>
94 MatchResultListener& operator<<(const T& x) {
95 if (stream_ != NULL)
96 *stream_ << x;
97 return *this;
98 }
99
100 // Returns the underlying ostream.
101 ::std::ostream* stream() { return stream_; }
102
zhanyong.wana862f1d2010-03-15 21:23:04 +0000103 // Returns true iff the listener is interested in an explanation of
104 // the match result. A matcher's MatchAndExplain() method can use
105 // this information to avoid generating the explanation when no one
106 // intends to hear it.
107 bool IsInterested() const { return stream_ != NULL; }
108
zhanyong.wan82113312010-01-08 21:55:40 +0000109 private:
110 ::std::ostream* const stream_;
111
112 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
113};
114
115inline MatchResultListener::~MatchResultListener() {
116}
117
zhanyong.wanfb25d532013-07-28 08:24:00 +0000118// An instance of a subclass of this knows how to describe itself as a
119// matcher.
120class MatcherDescriberInterface {
121 public:
122 virtual ~MatcherDescriberInterface() {}
123
124 // Describes this matcher to an ostream. The function should print
125 // a verb phrase that describes the property a value matching this
126 // matcher should have. The subject of the verb phrase is the value
127 // being matched. For example, the DescribeTo() method of the Gt(7)
128 // matcher prints "is greater than 7".
129 virtual void DescribeTo(::std::ostream* os) const = 0;
130
131 // Describes the negation of this matcher to an ostream. For
132 // example, if the description of this matcher is "is greater than
133 // 7", the negated description could be "is not greater than 7".
134 // You are not required to override this when implementing
135 // MatcherInterface, but it is highly advised so that your matcher
136 // can produce good error messages.
137 virtual void DescribeNegationTo(::std::ostream* os) const {
138 *os << "not (";
139 DescribeTo(os);
140 *os << ")";
141 }
142};
143
shiqiane35fdd92008-12-10 05:08:54 +0000144// The implementation of a matcher.
145template <typename T>
zhanyong.wanfb25d532013-07-28 08:24:00 +0000146class MatcherInterface : public MatcherDescriberInterface {
shiqiane35fdd92008-12-10 05:08:54 +0000147 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000148 // Returns true iff the matcher matches x; also explains the match
zhanyong.wan83f6b082013-03-01 01:47:35 +0000149 // result to 'listener' if necessary (see the next paragraph), in
150 // the form of a non-restrictive relative clause ("which ...",
151 // "whose ...", etc) that describes x. For example, the
152 // MatchAndExplain() method of the Pointee(...) matcher should
153 // generate an explanation like "which points to ...".
154 //
155 // Implementations of MatchAndExplain() should add an explanation of
156 // the match result *if and only if* they can provide additional
157 // information that's not already present (or not obvious) in the
158 // print-out of x and the matcher's description. Whether the match
159 // succeeds is not a factor in deciding whether an explanation is
160 // needed, as sometimes the caller needs to print a failure message
161 // when the match succeeds (e.g. when the matcher is used inside
162 // Not()).
163 //
164 // For example, a "has at least 10 elements" matcher should explain
165 // what the actual element count is, regardless of the match result,
166 // as it is useful information to the reader; on the other hand, an
167 // "is empty" matcher probably only needs to explain what the actual
168 // size is when the match fails, as it's redundant to say that the
169 // size is 0 when the value is already known to be empty.
zhanyong.wan82113312010-01-08 21:55:40 +0000170 //
zhanyong.wandb22c222010-01-28 21:52:29 +0000171 // You should override this method when defining a new matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000172 //
173 // It's the responsibility of the caller (Google Mock) to guarantee
174 // that 'listener' is not NULL. This helps to simplify a matcher's
175 // implementation when it doesn't care about the performance, as it
176 // can talk to 'listener' without checking its validity first.
177 // However, in order to implement dummy listeners efficiently,
178 // listener->stream() may be NULL.
zhanyong.wandb22c222010-01-28 21:52:29 +0000179 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
shiqiane35fdd92008-12-10 05:08:54 +0000180
zhanyong.wanfb25d532013-07-28 08:24:00 +0000181 // Inherits these methods from MatcherDescriberInterface:
182 // virtual void DescribeTo(::std::ostream* os) const = 0;
183 // virtual void DescribeNegationTo(::std::ostream* os) const;
shiqiane35fdd92008-12-10 05:08:54 +0000184};
185
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400186namespace internal {
187
188// Converts a MatcherInterface<T> to a MatcherInterface<const T&>.
189template <typename T>
190class MatcherInterfaceAdapter : public MatcherInterface<const T&> {
191 public:
192 explicit MatcherInterfaceAdapter(const MatcherInterface<T>* impl)
193 : impl_(impl) {}
194 virtual ~MatcherInterfaceAdapter() { delete impl_; }
195
196 virtual void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
197
198 virtual void DescribeNegationTo(::std::ostream* os) const {
199 impl_->DescribeNegationTo(os);
200 }
201
202 virtual bool MatchAndExplain(const T& x,
203 MatchResultListener* listener) const {
204 return impl_->MatchAndExplain(x, listener);
205 }
206
207 private:
208 const MatcherInterface<T>* const impl_;
209
210 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatcherInterfaceAdapter);
211};
212
213} // namespace internal
214
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000215// A match result listener that stores the explanation in a string.
216class StringMatchResultListener : public MatchResultListener {
217 public:
218 StringMatchResultListener() : MatchResultListener(&ss_) {}
219
220 // Returns the explanation accumulated so far.
Nico Weber09fd5b32017-05-15 17:07:03 -0400221 std::string str() const { return ss_.str(); }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000222
223 // Clears the explanation accumulated so far.
224 void Clear() { ss_.str(""); }
225
226 private:
227 ::std::stringstream ss_;
228
229 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
230};
231
shiqiane35fdd92008-12-10 05:08:54 +0000232namespace internal {
233
kosak506340a2014-11-17 01:47:54 +0000234struct AnyEq {
235 template <typename A, typename B>
236 bool operator()(const A& a, const B& b) const { return a == b; }
237};
238struct AnyNe {
239 template <typename A, typename B>
240 bool operator()(const A& a, const B& b) const { return a != b; }
241};
242struct AnyLt {
243 template <typename A, typename B>
244 bool operator()(const A& a, const B& b) const { return a < b; }
245};
246struct AnyGt {
247 template <typename A, typename B>
248 bool operator()(const A& a, const B& b) const { return a > b; }
249};
250struct AnyLe {
251 template <typename A, typename B>
252 bool operator()(const A& a, const B& b) const { return a <= b; }
253};
254struct AnyGe {
255 template <typename A, typename B>
256 bool operator()(const A& a, const B& b) const { return a >= b; }
257};
258
zhanyong.wan82113312010-01-08 21:55:40 +0000259// A match result listener that ignores the explanation.
260class DummyMatchResultListener : public MatchResultListener {
261 public:
262 DummyMatchResultListener() : MatchResultListener(NULL) {}
263
264 private:
265 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
266};
267
268// A match result listener that forwards the explanation to a given
269// ostream. The difference between this and MatchResultListener is
270// that the former is concrete.
271class StreamMatchResultListener : public MatchResultListener {
272 public:
273 explicit StreamMatchResultListener(::std::ostream* os)
274 : MatchResultListener(os) {}
275
276 private:
277 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
278};
279
shiqiane35fdd92008-12-10 05:08:54 +0000280// An internal class for implementing Matcher<T>, which will derive
281// from it. We put functionalities common to all Matcher<T>
282// specializations here to avoid code duplication.
283template <typename T>
284class MatcherBase {
285 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000286 // Returns true iff the matcher matches x; also explains the match
287 // result to 'listener'.
Gennadiy Civil6aae2062018-03-26 10:36:26 -0400288 bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
289 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000290 return impl_->MatchAndExplain(x, listener);
291 }
292
shiqiane35fdd92008-12-10 05:08:54 +0000293 // Returns true iff this matcher matches x.
Gennadiy Civile55089e2018-04-04 14:05:00 -0400294 bool Matches(GTEST_REFERENCE_TO_CONST_(T) x) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000295 DummyMatchResultListener dummy;
296 return MatchAndExplain(x, &dummy);
297 }
shiqiane35fdd92008-12-10 05:08:54 +0000298
299 // Describes this matcher to an ostream.
300 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
301
302 // Describes the negation of this matcher to an ostream.
303 void DescribeNegationTo(::std::ostream* os) const {
304 impl_->DescribeNegationTo(os);
305 }
306
307 // Explains why x matches, or doesn't match, the matcher.
Gennadiy Civile55089e2018-04-04 14:05:00 -0400308 void ExplainMatchResultTo(GTEST_REFERENCE_TO_CONST_(T) x,
309 ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000310 StreamMatchResultListener listener(os);
311 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000312 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000313
zhanyong.wanfb25d532013-07-28 08:24:00 +0000314 // Returns the describer for this matcher object; retains ownership
315 // of the describer, which is only guaranteed to be alive when
316 // this matcher object is alive.
317 const MatcherDescriberInterface* GetDescriber() const {
318 return impl_.get();
319 }
320
shiqiane35fdd92008-12-10 05:08:54 +0000321 protected:
322 MatcherBase() {}
323
324 // Constructs a matcher from its implementation.
Gennadiy Civile55089e2018-04-04 14:05:00 -0400325 explicit MatcherBase(
326 const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)>* impl)
shiqiane35fdd92008-12-10 05:08:54 +0000327 : impl_(impl) {}
328
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400329 template <typename U>
330 explicit MatcherBase(
331 const MatcherInterface<U>* impl,
332 typename internal::EnableIf<
333 !internal::IsSame<U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* =
334 NULL)
335 : impl_(new internal::MatcherInterfaceAdapter<U>(impl)) {}
336
shiqiane35fdd92008-12-10 05:08:54 +0000337 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000338
shiqiane35fdd92008-12-10 05:08:54 +0000339 private:
340 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
341 // interfaces. The former dynamically allocates a chunk of memory
342 // to hold the reference count, while the latter tracks all
343 // references using a circular linked list without allocating
344 // memory. It has been observed that linked_ptr performs better in
345 // typical scenarios. However, shared_ptr can out-perform
346 // linked_ptr when there are many more uses of the copy constructor
347 // than the default constructor.
348 //
349 // If performance becomes a problem, we should see if using
350 // shared_ptr helps.
Gennadiy Civile55089e2018-04-04 14:05:00 -0400351 ::testing::internal::linked_ptr<
352 const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> >
353 impl_;
shiqiane35fdd92008-12-10 05:08:54 +0000354};
355
shiqiane35fdd92008-12-10 05:08:54 +0000356} // namespace internal
357
358// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
359// object that can check whether a value of type T matches. The
360// implementation of Matcher<T> is just a linked_ptr to const
361// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
362// from Matcher!
363template <typename T>
364class Matcher : public internal::MatcherBase<T> {
365 public:
vladlosev88032d82010-11-17 23:29:21 +0000366 // Constructs a null matcher. Needed for storing Matcher objects in STL
367 // containers. A default-constructed matcher is not yet initialized. You
368 // cannot use it until a valid value has been assigned to it.
kosakd86a7232015-07-13 21:19:43 +0000369 explicit Matcher() {} // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000370
371 // Constructs a matcher from its implementation.
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400372 explicit Matcher(const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)>* impl)
373 : internal::MatcherBase<T>(impl) {}
374
375 template <typename U>
376 explicit Matcher(const MatcherInterface<U>* impl,
377 typename internal::EnableIf<!internal::IsSame<
378 U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* = NULL)
shiqiane35fdd92008-12-10 05:08:54 +0000379 : internal::MatcherBase<T>(impl) {}
380
zhanyong.wan18490652009-05-11 18:54:08 +0000381 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000382 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
383 Matcher(T value); // NOLINT
384};
385
386// The following two specializations allow the user to write str
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400387// instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
shiqiane35fdd92008-12-10 05:08:54 +0000388// matcher is expected.
389template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400390class GTEST_API_ Matcher<const std::string&>
391 : public internal::MatcherBase<const std::string&> {
shiqiane35fdd92008-12-10 05:08:54 +0000392 public:
393 Matcher() {}
394
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400395 explicit Matcher(const MatcherInterface<const std::string&>* impl)
396 : internal::MatcherBase<const std::string&>(impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000397
398 // Allows the user to write str instead of Eq(str) sometimes, where
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400399 // str is a std::string object.
400 Matcher(const std::string& s); // NOLINT
401
402#if GTEST_HAS_GLOBAL_STRING
403 // Allows the user to write str instead of Eq(str) sometimes, where
404 // str is a ::string object.
405 Matcher(const ::string& s); // NOLINT
406#endif // GTEST_HAS_GLOBAL_STRING
shiqiane35fdd92008-12-10 05:08:54 +0000407
408 // Allows the user to write "foo" instead of Eq("foo") sometimes.
409 Matcher(const char* s); // NOLINT
410};
411
412template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400413class GTEST_API_ Matcher<std::string>
414 : public internal::MatcherBase<std::string> {
shiqiane35fdd92008-12-10 05:08:54 +0000415 public:
416 Matcher() {}
417
Gennadiy Civile55089e2018-04-04 14:05:00 -0400418 explicit Matcher(const MatcherInterface<const std::string&>* impl)
419 : internal::MatcherBase<std::string>(impl) {}
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400420 explicit Matcher(const MatcherInterface<std::string>* impl)
421 : internal::MatcherBase<std::string>(impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000422
423 // Allows the user to write str instead of Eq(str) sometimes, where
424 // str is a string object.
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400425 Matcher(const std::string& s); // NOLINT
426
427#if GTEST_HAS_GLOBAL_STRING
428 // Allows the user to write str instead of Eq(str) sometimes, where
429 // str is a ::string object.
430 Matcher(const ::string& s); // NOLINT
431#endif // GTEST_HAS_GLOBAL_STRING
shiqiane35fdd92008-12-10 05:08:54 +0000432
433 // Allows the user to write "foo" instead of Eq("foo") sometimes.
434 Matcher(const char* s); // NOLINT
435};
436
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400437#if GTEST_HAS_GLOBAL_STRING
zhanyong.wan1f122a02013-03-25 16:27:03 +0000438// The following two specializations allow the user to write str
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400439// instead of Eq(str) and "foo" instead of Eq("foo") when a ::string
zhanyong.wan1f122a02013-03-25 16:27:03 +0000440// matcher is expected.
441template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400442class GTEST_API_ Matcher<const ::string&>
443 : public internal::MatcherBase<const ::string&> {
zhanyong.wan1f122a02013-03-25 16:27:03 +0000444 public:
445 Matcher() {}
446
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400447 explicit Matcher(const MatcherInterface<const ::string&>* impl)
448 : internal::MatcherBase<const ::string&>(impl) {}
zhanyong.wan1f122a02013-03-25 16:27:03 +0000449
450 // Allows the user to write str instead of Eq(str) sometimes, where
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400451 // str is a std::string object.
452 Matcher(const std::string& s); // NOLINT
453
454 // Allows the user to write str instead of Eq(str) sometimes, where
455 // str is a ::string object.
456 Matcher(const ::string& s); // NOLINT
zhanyong.wan1f122a02013-03-25 16:27:03 +0000457
458 // Allows the user to write "foo" instead of Eq("foo") sometimes.
459 Matcher(const char* s); // NOLINT
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400460};
zhanyong.wan1f122a02013-03-25 16:27:03 +0000461
zhanyong.wan1f122a02013-03-25 16:27:03 +0000462template <>
Gennadiy Civile55089e2018-04-04 14:05:00 -0400463class GTEST_API_ Matcher< ::string>
464 : public internal::MatcherBase< ::string> {
zhanyong.wan1f122a02013-03-25 16:27:03 +0000465 public:
466 Matcher() {}
467
Gennadiy Civile55089e2018-04-04 14:05:00 -0400468 explicit Matcher(const MatcherInterface<const ::string&>* impl)
469 : internal::MatcherBase< ::string>(impl) {}
470 explicit Matcher(const MatcherInterface< ::string>* impl)
471 : internal::MatcherBase< ::string>(impl) {}
zhanyong.wan1f122a02013-03-25 16:27:03 +0000472
473 // Allows the user to write str instead of Eq(str) sometimes, where
Gennadiy Civile55089e2018-04-04 14:05:00 -0400474 // str is a std::string object.
475 Matcher(const std::string& s); // NOLINT
476
477 // Allows the user to write str instead of Eq(str) sometimes, where
478 // str is a ::string object.
479 Matcher(const ::string& s); // NOLINT
480
481 // Allows the user to write "foo" instead of Eq("foo") sometimes.
482 Matcher(const char* s); // NOLINT
483};
484#endif // GTEST_HAS_GLOBAL_STRING
485
486#if GTEST_HAS_ABSL
487// The following two specializations allow the user to write str
488// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
489// matcher is expected.
490template <>
491class GTEST_API_ Matcher<const absl::string_view&>
492 : public internal::MatcherBase<const absl::string_view&> {
493 public:
494 Matcher() {}
495
496 explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
497 : internal::MatcherBase<const absl::string_view&>(impl) {}
498
499 // Allows the user to write str instead of Eq(str) sometimes, where
500 // str is a std::string object.
501 Matcher(const std::string& s); // NOLINT
502
503#if GTEST_HAS_GLOBAL_STRING
504 // Allows the user to write str instead of Eq(str) sometimes, where
505 // str is a ::string object.
506 Matcher(const ::string& s); // NOLINT
507#endif // GTEST_HAS_GLOBAL_STRING
zhanyong.wan1f122a02013-03-25 16:27:03 +0000508
509 // Allows the user to write "foo" instead of Eq("foo") sometimes.
510 Matcher(const char* s); // NOLINT
511
Gennadiy Civile55089e2018-04-04 14:05:00 -0400512 // Allows the user to pass absl::string_views directly.
513 Matcher(absl::string_view s); // NOLINT
zhanyong.wan1f122a02013-03-25 16:27:03 +0000514};
Gennadiy Civile55089e2018-04-04 14:05:00 -0400515
516template <>
517class GTEST_API_ Matcher<absl::string_view>
518 : public internal::MatcherBase<absl::string_view> {
519 public:
520 Matcher() {}
521
522 explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
523 : internal::MatcherBase<absl::string_view>(impl) {}
524 explicit Matcher(const MatcherInterface<absl::string_view>* impl)
525 : internal::MatcherBase<absl::string_view>(impl) {}
526
527 // Allows the user to write str instead of Eq(str) sometimes, where
528 // str is a std::string object.
529 Matcher(const std::string& s); // NOLINT
530
531#if GTEST_HAS_GLOBAL_STRING
532 // Allows the user to write str instead of Eq(str) sometimes, where
533 // str is a ::string object.
534 Matcher(const ::string& s); // NOLINT
535#endif // GTEST_HAS_GLOBAL_STRING
536
537 // Allows the user to write "foo" instead of Eq("foo") sometimes.
538 Matcher(const char* s); // NOLINT
539
540 // Allows the user to pass absl::string_views directly.
541 Matcher(absl::string_view s); // NOLINT
542};
543#endif // GTEST_HAS_ABSL
544
545// Prints a matcher in a human-readable format.
546template <typename T>
547std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
548 matcher.DescribeTo(&os);
549 return os;
550}
zhanyong.wan1f122a02013-03-25 16:27:03 +0000551
shiqiane35fdd92008-12-10 05:08:54 +0000552// The PolymorphicMatcher class template makes it easy to implement a
553// polymorphic matcher (i.e. a matcher that can match values of more
554// than one type, e.g. Eq(n) and NotNull()).
555//
zhanyong.wandb22c222010-01-28 21:52:29 +0000556// To define a polymorphic matcher, a user should provide an Impl
557// class that has a DescribeTo() method and a DescribeNegationTo()
558// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000559//
zhanyong.wandb22c222010-01-28 21:52:29 +0000560// bool MatchAndExplain(const Value& value,
561// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000562//
563// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000564template <class Impl>
565class PolymorphicMatcher {
566 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000567 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000568
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000569 // Returns a mutable reference to the underlying matcher
570 // implementation object.
571 Impl& mutable_impl() { return impl_; }
572
573 // Returns an immutable reference to the underlying matcher
574 // implementation object.
575 const Impl& impl() const { return impl_; }
576
shiqiane35fdd92008-12-10 05:08:54 +0000577 template <typename T>
578 operator Matcher<T>() const {
Gennadiy Civile55089e2018-04-04 14:05:00 -0400579 return Matcher<T>(new MonomorphicImpl<GTEST_REFERENCE_TO_CONST_(T)>(impl_));
shiqiane35fdd92008-12-10 05:08:54 +0000580 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000581
shiqiane35fdd92008-12-10 05:08:54 +0000582 private:
583 template <typename T>
584 class MonomorphicImpl : public MatcherInterface<T> {
585 public:
586 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
587
shiqiane35fdd92008-12-10 05:08:54 +0000588 virtual void DescribeTo(::std::ostream* os) const {
589 impl_.DescribeTo(os);
590 }
591
592 virtual void DescribeNegationTo(::std::ostream* os) const {
593 impl_.DescribeNegationTo(os);
594 }
595
zhanyong.wan82113312010-01-08 21:55:40 +0000596 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000597 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000598 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000599
shiqiane35fdd92008-12-10 05:08:54 +0000600 private:
601 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000602
603 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000604 };
605
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000606 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000607
608 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000609};
610
611// Creates a matcher from its implementation. This is easier to use
612// than the Matcher<T> constructor as it doesn't require you to
613// explicitly write the template argument, e.g.
614//
615// MakeMatcher(foo);
616// vs
617// Matcher<const string&>(foo);
618template <typename T>
619inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
620 return Matcher<T>(impl);
zhanyong.wan2eab17b2013-03-08 17:53:24 +0000621}
shiqiane35fdd92008-12-10 05:08:54 +0000622
623// Creates a polymorphic matcher from its implementation. This is
624// easier to use than the PolymorphicMatcher<Impl> constructor as it
625// doesn't require you to explicitly write the template argument, e.g.
626//
627// MakePolymorphicMatcher(foo);
628// vs
629// PolymorphicMatcher<TypeOfFoo>(foo);
630template <class Impl>
631inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
632 return PolymorphicMatcher<Impl>(impl);
633}
634
jgm79a367e2012-04-10 16:02:11 +0000635// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
636// and MUST NOT BE USED IN USER CODE!!!
637namespace internal {
638
639// The MatcherCastImpl class template is a helper for implementing
640// MatcherCast(). We need this helper in order to partially
641// specialize the implementation of MatcherCast() (C++ allows
642// class/struct templates to be partially specialized, but not
643// function templates.).
644
645// This general version is used when MatcherCast()'s argument is a
646// polymorphic matcher (i.e. something that can be converted to a
647// Matcher but is not one yet; for example, Eq(value)) or a value (for
648// example, "hello").
649template <typename T, typename M>
650class MatcherCastImpl {
651 public:
kosak5f2a6ca2013-12-03 01:43:07 +0000652 static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
Gennadiy Civil2bd17502018-02-27 13:51:09 -0500653 // M can be a polymorphic matcher, in which case we want to use
jgm79a367e2012-04-10 16:02:11 +0000654 // its conversion operator to create Matcher<T>. Or it can be a value
655 // that should be passed to the Matcher<T>'s constructor.
656 //
657 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
658 // polymorphic matcher because it'll be ambiguous if T has an implicit
659 // constructor from M (this usually happens when T has an implicit
660 // constructor from any type).
661 //
662 // It won't work to unconditionally implict_cast
663 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
664 // a user-defined conversion from M to T if one exists (assuming M is
665 // a value).
666 return CastImpl(
667 polymorphic_matcher_or_value,
668 BooleanConstant<
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400669 internal::ImplicitlyConvertible<M, Matcher<T> >::value>(),
670 BooleanConstant<
671 internal::ImplicitlyConvertible<M, T>::value>());
jgm79a367e2012-04-10 16:02:11 +0000672 }
673
674 private:
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400675 template <bool Ignore>
kosak5f2a6ca2013-12-03 01:43:07 +0000676 static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400677 BooleanConstant<true> /* convertible_to_matcher */,
678 BooleanConstant<Ignore>) {
jgm79a367e2012-04-10 16:02:11 +0000679 // M is implicitly convertible to Matcher<T>, which means that either
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400680 // M is a polymorphic matcher or Matcher<T> has an implicit constructor
jgm79a367e2012-04-10 16:02:11 +0000681 // from M. In both cases using the implicit conversion will produce a
682 // matcher.
683 //
684 // Even if T has an implicit constructor from M, it won't be called because
685 // creating Matcher<T> would require a chain of two user-defined conversions
686 // (first to create T from M and then to create Matcher<T> from T).
687 return polymorphic_matcher_or_value;
688 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400689
690 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
691 // matcher. It's a value of a type implicitly convertible to T. Use direct
692 // initialization to create a matcher.
693 static Matcher<T> CastImpl(
694 const M& value, BooleanConstant<false> /* convertible_to_matcher */,
695 BooleanConstant<true> /* convertible_to_T */) {
696 return Matcher<T>(ImplicitCast_<T>(value));
697 }
698
699 // M can't be implicitly converted to either Matcher<T> or T. Attempt to use
700 // polymorphic matcher Eq(value) in this case.
701 //
702 // Note that we first attempt to perform an implicit cast on the value and
703 // only fall back to the polymorphic Eq() matcher afterwards because the
704 // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end
705 // which might be undefined even when Rhs is implicitly convertible to Lhs
706 // (e.g. std::pair<const int, int> vs. std::pair<int, int>).
707 //
708 // We don't define this method inline as we need the declaration of Eq().
709 static Matcher<T> CastImpl(
710 const M& value, BooleanConstant<false> /* convertible_to_matcher */,
711 BooleanConstant<false> /* convertible_to_T */);
jgm79a367e2012-04-10 16:02:11 +0000712};
713
714// This more specialized version is used when MatcherCast()'s argument
715// is already a Matcher. This only compiles when type T can be
716// statically converted to type U.
717template <typename T, typename U>
718class MatcherCastImpl<T, Matcher<U> > {
719 public:
720 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
721 return Matcher<T>(new Impl(source_matcher));
722 }
723
724 private:
725 class Impl : public MatcherInterface<T> {
726 public:
727 explicit Impl(const Matcher<U>& source_matcher)
728 : source_matcher_(source_matcher) {}
729
730 // We delegate the matching logic to the source matcher.
731 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
Gennadiy Civilb907c262018-03-23 11:42:41 -0400732#if GTEST_LANG_CXX11
733 using FromType = typename std::remove_cv<typename std::remove_pointer<
734 typename std::remove_reference<T>::type>::type>::type;
735 using ToType = typename std::remove_cv<typename std::remove_pointer<
736 typename std::remove_reference<U>::type>::type>::type;
737 // Do not allow implicitly converting base*/& to derived*/&.
738 static_assert(
739 // Do not trigger if only one of them is a pointer. That implies a
740 // regular conversion and not a down_cast.
741 (std::is_pointer<typename std::remove_reference<T>::type>::value !=
742 std::is_pointer<typename std::remove_reference<U>::type>::value) ||
743 std::is_same<FromType, ToType>::value ||
744 !std::is_base_of<FromType, ToType>::value,
745 "Can't implicitly convert from <base> to <derived>");
746#endif // GTEST_LANG_CXX11
747
jgm79a367e2012-04-10 16:02:11 +0000748 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
749 }
750
751 virtual void DescribeTo(::std::ostream* os) const {
752 source_matcher_.DescribeTo(os);
753 }
754
755 virtual void DescribeNegationTo(::std::ostream* os) const {
756 source_matcher_.DescribeNegationTo(os);
757 }
758
759 private:
760 const Matcher<U> source_matcher_;
761
762 GTEST_DISALLOW_ASSIGN_(Impl);
763 };
764};
765
766// This even more specialized version is used for efficiently casting
767// a matcher to its own type.
768template <typename T>
769class MatcherCastImpl<T, Matcher<T> > {
770 public:
771 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
772};
773
774} // namespace internal
775
shiqiane35fdd92008-12-10 05:08:54 +0000776// In order to be safe and clear, casting between different matcher
777// types is done explicitly via MatcherCast<T>(m), which takes a
778// matcher m and returns a Matcher<T>. It compiles only when T can be
779// statically converted to the argument type of m.
780template <typename T, typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000781inline Matcher<T> MatcherCast(const M& matcher) {
jgm79a367e2012-04-10 16:02:11 +0000782 return internal::MatcherCastImpl<T, M>::Cast(matcher);
783}
shiqiane35fdd92008-12-10 05:08:54 +0000784
zhanyong.wan18490652009-05-11 18:54:08 +0000785// Implements SafeMatcherCast().
786//
zhanyong.wan95b12332009-09-25 18:55:50 +0000787// We use an intermediate class to do the actual safe casting as Nokia's
788// Symbian compiler cannot decide between
789// template <T, M> ... (M) and
790// template <T, U> ... (const Matcher<U>&)
791// for function templates but can for member function templates.
792template <typename T>
793class SafeMatcherCastImpl {
794 public:
jgm79a367e2012-04-10 16:02:11 +0000795 // This overload handles polymorphic matchers and values only since
796 // monomorphic matchers are handled by the next one.
zhanyong.wan95b12332009-09-25 18:55:50 +0000797 template <typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000798 static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
jgm79a367e2012-04-10 16:02:11 +0000799 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
zhanyong.wan95b12332009-09-25 18:55:50 +0000800 }
zhanyong.wan18490652009-05-11 18:54:08 +0000801
zhanyong.wan95b12332009-09-25 18:55:50 +0000802 // This overload handles monomorphic matchers.
803 //
804 // In general, if type T can be implicitly converted to type U, we can
805 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
806 // contravariant): just keep a copy of the original Matcher<U>, convert the
807 // argument from type T to U, and then pass it to the underlying Matcher<U>.
808 // The only exception is when U is a reference and T is not, as the
809 // underlying Matcher<U> may be interested in the argument's address, which
810 // is not preserved in the conversion from T to U.
811 template <typename U>
812 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
813 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000814 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000815 T_must_be_implicitly_convertible_to_U);
816 // Enforce that we are not converting a non-reference type T to a reference
817 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000818 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000819 internal::is_reference<T>::value || !internal::is_reference<U>::value,
Hector Dearman24054ff2017-06-19 18:27:33 +0100820 cannot_convert_non_reference_arg_to_reference);
zhanyong.wan95b12332009-09-25 18:55:50 +0000821 // In case both T and U are arithmetic types, enforce that the
822 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000823 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
824 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000825 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
826 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000827 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000828 kTIsOther || kUIsOther ||
829 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
830 conversion_of_arithmetic_types_must_be_lossless);
831 return MatcherCast<T>(matcher);
832 }
833};
834
835template <typename T, typename M>
836inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
837 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000838}
839
shiqiane35fdd92008-12-10 05:08:54 +0000840// A<T>() returns a matcher that matches any value of type T.
841template <typename T>
842Matcher<T> A();
843
844// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
845// and MUST NOT BE USED IN USER CODE!!!
846namespace internal {
847
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000848// If the explanation is not empty, prints it to the ostream.
Nico Weber09fd5b32017-05-15 17:07:03 -0400849inline void PrintIfNotEmpty(const std::string& explanation,
zhanyong.wanfb25d532013-07-28 08:24:00 +0000850 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000851 if (explanation != "" && os != NULL) {
852 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000853 }
854}
855
zhanyong.wan736baa82010-09-27 17:44:16 +0000856// Returns true if the given type name is easy to read by a human.
857// This is used to decide whether printing the type of a value might
858// be helpful.
Nico Weber09fd5b32017-05-15 17:07:03 -0400859inline bool IsReadableTypeName(const std::string& type_name) {
zhanyong.wan736baa82010-09-27 17:44:16 +0000860 // We consider a type name readable if it's short or doesn't contain
861 // a template or function type.
862 return (type_name.length() <= 20 ||
Nico Weber09fd5b32017-05-15 17:07:03 -0400863 type_name.find_first_of("<(") == std::string::npos);
zhanyong.wan736baa82010-09-27 17:44:16 +0000864}
865
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000866// Matches the value against the given matcher, prints the value and explains
867// the match result to the listener. Returns the match result.
868// 'listener' must not be NULL.
869// Value cannot be passed by const reference, because some matchers take a
870// non-const argument.
871template <typename Value, typename T>
872bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
873 MatchResultListener* listener) {
874 if (!listener->IsInterested()) {
875 // If the listener is not interested, we do not need to construct the
876 // inner explanation.
877 return matcher.Matches(value);
878 }
879
880 StringMatchResultListener inner_listener;
881 const bool match = matcher.MatchAndExplain(value, &inner_listener);
882
883 UniversalPrint(value, listener->stream());
zhanyong.wan736baa82010-09-27 17:44:16 +0000884#if GTEST_HAS_RTTI
Nico Weber09fd5b32017-05-15 17:07:03 -0400885 const std::string& type_name = GetTypeName<Value>();
zhanyong.wan736baa82010-09-27 17:44:16 +0000886 if (IsReadableTypeName(type_name))
887 *listener->stream() << " (of type " << type_name << ")";
888#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000889 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000890
891 return match;
892}
893
shiqiane35fdd92008-12-10 05:08:54 +0000894// An internal helper class for doing compile-time loop on a tuple's
895// fields.
896template <size_t N>
897class TuplePrefix {
898 public:
899 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
900 // iff the first N fields of matcher_tuple matches the first N
901 // fields of value_tuple, respectively.
902 template <typename MatcherTuple, typename ValueTuple>
903 static bool Matches(const MatcherTuple& matcher_tuple,
904 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000905 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
906 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
907 }
908
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000909 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000910 // describes failures in matching the first N fields of matchers
911 // against the first N fields of values. If there is no failure,
912 // nothing will be streamed to os.
913 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000914 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
915 const ValueTuple& values,
916 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000917 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000918 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000919
920 // Then describes the failure (if any) in the (N - 1)-th (0-based)
921 // field.
922 typename tuple_element<N - 1, MatcherTuple>::type matcher =
923 get<N - 1>(matchers);
924 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
Gennadiy Civile55089e2018-04-04 14:05:00 -0400925 GTEST_REFERENCE_TO_CONST_(Value) value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000926 StringMatchResultListener listener;
927 if (!matcher.MatchAndExplain(value, &listener)) {
Gennadiy Civil265efde2018-08-14 15:04:11 -0400928 // FIXME: include in the message the name of the parameter
shiqiane35fdd92008-12-10 05:08:54 +0000929 // as used in MOCK_METHOD*() when possible.
930 *os << " Expected arg #" << N - 1 << ": ";
931 get<N - 1>(matchers).DescribeTo(os);
932 *os << "\n Actual: ";
933 // We remove the reference in type Value to prevent the
934 // universal printer from printing the address of value, which
935 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000936 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000937 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000938 internal::UniversalPrint(value, os);
939 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000940 *os << "\n";
941 }
942 }
943};
944
945// The base case.
946template <>
947class TuplePrefix<0> {
948 public:
949 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000950 static bool Matches(const MatcherTuple& /* matcher_tuple */,
951 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000952 return true;
953 }
954
955 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000956 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
957 const ValueTuple& /* values */,
958 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000959};
960
961// TupleMatches(matcher_tuple, value_tuple) returns true iff all
962// matchers in matcher_tuple match the corresponding fields in
963// value_tuple. It is a compiler error if matcher_tuple and
964// value_tuple have different number of fields or incompatible field
965// types.
966template <typename MatcherTuple, typename ValueTuple>
967bool TupleMatches(const MatcherTuple& matcher_tuple,
968 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000969 // Makes sure that matcher_tuple and value_tuple have the same
970 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000971 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000972 tuple_size<ValueTuple>::value,
973 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000974 return TuplePrefix<tuple_size<ValueTuple>::value>::
975 Matches(matcher_tuple, value_tuple);
976}
977
978// Describes failures in matching matchers against values. If there
979// is no failure, nothing will be streamed to os.
980template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000981void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
982 const ValueTuple& values,
983 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000984 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000985 matchers, values, os);
986}
987
zhanyong.wanfb25d532013-07-28 08:24:00 +0000988// TransformTupleValues and its helper.
989//
990// TransformTupleValuesHelper hides the internal machinery that
991// TransformTupleValues uses to implement a tuple traversal.
992template <typename Tuple, typename Func, typename OutIter>
993class TransformTupleValuesHelper {
994 private:
kosakbd018832014-04-02 20:30:00 +0000995 typedef ::testing::tuple_size<Tuple> TupleSize;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000996
997 public:
998 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
999 // Returns the final value of 'out' in case the caller needs it.
1000 static OutIter Run(Func f, const Tuple& t, OutIter out) {
1001 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
1002 }
1003
1004 private:
1005 template <typename Tup, size_t kRemainingSize>
1006 struct IterateOverTuple {
1007 OutIter operator() (Func f, const Tup& t, OutIter out) const {
kosakbd018832014-04-02 20:30:00 +00001008 *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
zhanyong.wanfb25d532013-07-28 08:24:00 +00001009 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
1010 }
1011 };
1012 template <typename Tup>
1013 struct IterateOverTuple<Tup, 0> {
1014 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
1015 return out;
1016 }
1017 };
1018};
1019
1020// Successively invokes 'f(element)' on each element of the tuple 't',
1021// appending each result to the 'out' iterator. Returns the final value
1022// of 'out'.
1023template <typename Tuple, typename Func, typename OutIter>
1024OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
1025 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
1026}
1027
shiqiane35fdd92008-12-10 05:08:54 +00001028// Implements A<T>().
1029template <typename T>
Gennadiy Civile55089e2018-04-04 14:05:00 -04001030class AnyMatcherImpl : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
shiqiane35fdd92008-12-10 05:08:54 +00001031 public:
Gennadiy Civile55089e2018-04-04 14:05:00 -04001032 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) /* x */,
1033 MatchResultListener* /* listener */) const {
1034 return true;
1035 }
shiqiane35fdd92008-12-10 05:08:54 +00001036 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
1037 virtual void DescribeNegationTo(::std::ostream* os) const {
1038 // This is mostly for completeness' safe, as it's not very useful
1039 // to write Not(A<bool>()). However we cannot completely rule out
1040 // such a possibility, and it doesn't hurt to be prepared.
1041 *os << "never matches";
1042 }
1043};
1044
1045// Implements _, a matcher that matches any value of any
1046// type. This is a polymorphic matcher, so we need a template type
1047// conversion operator to make it appearing as a Matcher<T> for any
1048// type T.
1049class AnythingMatcher {
1050 public:
1051 template <typename T>
1052 operator Matcher<T>() const { return A<T>(); }
1053};
1054
1055// Implements a matcher that compares a given value with a
1056// pre-supplied value using one of the ==, <=, <, etc, operators. The
1057// two values being compared don't have to have the same type.
1058//
1059// The matcher defined here is polymorphic (for example, Eq(5) can be
1060// used to match an int, a short, a double, etc). Therefore we use
1061// a template type conversion operator in the implementation.
1062//
shiqiane35fdd92008-12-10 05:08:54 +00001063// The following template definition assumes that the Rhs parameter is
1064// a "bare" type (i.e. neither 'const T' nor 'T&').
kosak506340a2014-11-17 01:47:54 +00001065template <typename D, typename Rhs, typename Op>
1066class ComparisonBase {
1067 public:
1068 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
1069 template <typename Lhs>
1070 operator Matcher<Lhs>() const {
1071 return MakeMatcher(new Impl<Lhs>(rhs_));
shiqiane35fdd92008-12-10 05:08:54 +00001072 }
1073
kosak506340a2014-11-17 01:47:54 +00001074 private:
1075 template <typename Lhs>
1076 class Impl : public MatcherInterface<Lhs> {
1077 public:
1078 explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
1079 virtual bool MatchAndExplain(
1080 Lhs lhs, MatchResultListener* /* listener */) const {
1081 return Op()(lhs, rhs_);
1082 }
1083 virtual void DescribeTo(::std::ostream* os) const {
1084 *os << D::Desc() << " ";
1085 UniversalPrint(rhs_, os);
1086 }
1087 virtual void DescribeNegationTo(::std::ostream* os) const {
1088 *os << D::NegatedDesc() << " ";
1089 UniversalPrint(rhs_, os);
1090 }
1091 private:
1092 Rhs rhs_;
1093 GTEST_DISALLOW_ASSIGN_(Impl);
1094 };
1095 Rhs rhs_;
1096 GTEST_DISALLOW_ASSIGN_(ComparisonBase);
1097};
shiqiane35fdd92008-12-10 05:08:54 +00001098
kosak506340a2014-11-17 01:47:54 +00001099template <typename Rhs>
1100class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
1101 public:
1102 explicit EqMatcher(const Rhs& rhs)
1103 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
1104 static const char* Desc() { return "is equal to"; }
1105 static const char* NegatedDesc() { return "isn't equal to"; }
1106};
1107template <typename Rhs>
1108class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
1109 public:
1110 explicit NeMatcher(const Rhs& rhs)
1111 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
1112 static const char* Desc() { return "isn't equal to"; }
1113 static const char* NegatedDesc() { return "is equal to"; }
1114};
1115template <typename Rhs>
1116class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
1117 public:
1118 explicit LtMatcher(const Rhs& rhs)
1119 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
1120 static const char* Desc() { return "is <"; }
1121 static const char* NegatedDesc() { return "isn't <"; }
1122};
1123template <typename Rhs>
1124class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
1125 public:
1126 explicit GtMatcher(const Rhs& rhs)
1127 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
1128 static const char* Desc() { return "is >"; }
1129 static const char* NegatedDesc() { return "isn't >"; }
1130};
1131template <typename Rhs>
1132class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
1133 public:
1134 explicit LeMatcher(const Rhs& rhs)
1135 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
1136 static const char* Desc() { return "is <="; }
1137 static const char* NegatedDesc() { return "isn't <="; }
1138};
1139template <typename Rhs>
1140class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
1141 public:
1142 explicit GeMatcher(const Rhs& rhs)
1143 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
1144 static const char* Desc() { return "is >="; }
1145 static const char* NegatedDesc() { return "isn't >="; }
1146};
shiqiane35fdd92008-12-10 05:08:54 +00001147
vladlosev79b83502009-11-18 00:43:37 +00001148// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001149// pointer that is NULL.
1150class IsNullMatcher {
1151 public:
vladlosev79b83502009-11-18 00:43:37 +00001152 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +00001153 bool MatchAndExplain(const Pointer& p,
1154 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001155#if GTEST_LANG_CXX11
1156 return p == nullptr;
1157#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001158 return GetRawPointer(p) == NULL;
kosak6305ff52015-04-28 22:36:31 +00001159#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001160 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001161
1162 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
1163 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001164 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001165 }
1166};
1167
vladlosev79b83502009-11-18 00:43:37 +00001168// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +00001169// pointer that is not NULL.
1170class NotNullMatcher {
1171 public:
vladlosev79b83502009-11-18 00:43:37 +00001172 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +00001173 bool MatchAndExplain(const Pointer& p,
1174 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001175#if GTEST_LANG_CXX11
1176 return p != nullptr;
1177#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001178 return GetRawPointer(p) != NULL;
kosak6305ff52015-04-28 22:36:31 +00001179#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001180 }
shiqiane35fdd92008-12-10 05:08:54 +00001181
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001182 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +00001183 void DescribeNegationTo(::std::ostream* os) const {
1184 *os << "is NULL";
1185 }
1186};
1187
1188// Ref(variable) matches any argument that is a reference to
1189// 'variable'. This matcher is polymorphic as it can match any
1190// super type of the type of 'variable'.
1191//
1192// The RefMatcher template class implements Ref(variable). It can
1193// only be instantiated with a reference type. This prevents a user
1194// from mistakenly using Ref(x) to match a non-reference function
1195// argument. For example, the following will righteously cause a
1196// compiler error:
1197//
1198// int n;
1199// Matcher<int> m1 = Ref(n); // This won't compile.
1200// Matcher<int&> m2 = Ref(n); // This will compile.
1201template <typename T>
1202class RefMatcher;
1203
1204template <typename T>
1205class RefMatcher<T&> {
1206 // Google Mock is a generic framework and thus needs to support
1207 // mocking any function types, including those that take non-const
1208 // reference arguments. Therefore the template parameter T (and
1209 // Super below) can be instantiated to either a const type or a
1210 // non-const type.
1211 public:
1212 // RefMatcher() takes a T& instead of const T&, as we want the
1213 // compiler to catch using Ref(const_value) as a matcher for a
1214 // non-const reference.
1215 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
1216
1217 template <typename Super>
1218 operator Matcher<Super&>() const {
1219 // By passing object_ (type T&) to Impl(), which expects a Super&,
1220 // we make sure that Super is a super type of T. In particular,
1221 // this catches using Ref(const_value) as a matcher for a
1222 // non-const reference, as you cannot implicitly convert a const
1223 // reference to a non-const reference.
1224 return MakeMatcher(new Impl<Super>(object_));
1225 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001226
shiqiane35fdd92008-12-10 05:08:54 +00001227 private:
1228 template <typename Super>
1229 class Impl : public MatcherInterface<Super&> {
1230 public:
1231 explicit Impl(Super& x) : object_(x) {} // NOLINT
1232
zhanyong.wandb22c222010-01-28 21:52:29 +00001233 // MatchAndExplain() takes a Super& (as opposed to const Super&)
1234 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +00001235 virtual bool MatchAndExplain(
1236 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001237 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +00001238 return &x == &object_;
1239 }
shiqiane35fdd92008-12-10 05:08:54 +00001240
1241 virtual void DescribeTo(::std::ostream* os) const {
1242 *os << "references the variable ";
1243 UniversalPrinter<Super&>::Print(object_, os);
1244 }
1245
1246 virtual void DescribeNegationTo(::std::ostream* os) const {
1247 *os << "does not reference the variable ";
1248 UniversalPrinter<Super&>::Print(object_, os);
1249 }
1250
shiqiane35fdd92008-12-10 05:08:54 +00001251 private:
1252 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001253
1254 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001255 };
1256
1257 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001258
1259 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001260};
1261
1262// Polymorphic helper functions for narrow and wide string matchers.
1263inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1264 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1265}
1266
1267inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1268 const wchar_t* rhs) {
1269 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1270}
1271
1272// String comparison for narrow or wide strings that can have embedded NUL
1273// characters.
1274template <typename StringType>
1275bool CaseInsensitiveStringEquals(const StringType& s1,
1276 const StringType& s2) {
1277 // Are the heads equal?
1278 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1279 return false;
1280 }
1281
1282 // Skip the equal heads.
1283 const typename StringType::value_type nul = 0;
1284 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1285
1286 // Are we at the end of either s1 or s2?
1287 if (i1 == StringType::npos || i2 == StringType::npos) {
1288 return i1 == i2;
1289 }
1290
1291 // Are the tails equal?
1292 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1293}
1294
1295// String matchers.
1296
1297// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1298template <typename StringType>
1299class StrEqualityMatcher {
1300 public:
shiqiane35fdd92008-12-10 05:08:54 +00001301 StrEqualityMatcher(const StringType& str, bool expect_eq,
1302 bool case_sensitive)
1303 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1304
Gennadiy Civile55089e2018-04-04 14:05:00 -04001305#if GTEST_HAS_ABSL
1306 bool MatchAndExplain(const absl::string_view& s,
1307 MatchResultListener* listener) const {
1308 if (s.data() == NULL) {
1309 return !expect_eq_;
1310 }
1311 // This should fail to compile if absl::string_view is used with wide
1312 // strings.
1313 const StringType& str = string(s);
1314 return MatchAndExplain(str, listener);
1315 }
1316#endif // GTEST_HAS_ABSL
1317
jgm38513a82012-11-15 15:50:36 +00001318 // Accepts pointer types, particularly:
1319 // const char*
1320 // char*
1321 // const wchar_t*
1322 // wchar_t*
1323 template <typename CharType>
1324 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001325 if (s == NULL) {
1326 return !expect_eq_;
1327 }
zhanyong.wandb22c222010-01-28 21:52:29 +00001328 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001329 }
1330
jgm38513a82012-11-15 15:50:36 +00001331 // Matches anything that can convert to StringType.
1332 //
1333 // This is a template, not just a plain function with const StringType&,
Gennadiy Civile55089e2018-04-04 14:05:00 -04001334 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001335 template <typename MatcheeStringType>
1336 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001337 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001338 const StringType& s2(s);
1339 const bool eq = case_sensitive_ ? s2 == string_ :
1340 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +00001341 return expect_eq_ == eq;
1342 }
1343
1344 void DescribeTo(::std::ostream* os) const {
1345 DescribeToHelper(expect_eq_, os);
1346 }
1347
1348 void DescribeNegationTo(::std::ostream* os) const {
1349 DescribeToHelper(!expect_eq_, os);
1350 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001351
shiqiane35fdd92008-12-10 05:08:54 +00001352 private:
1353 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001354 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +00001355 *os << "equal to ";
1356 if (!case_sensitive_) {
1357 *os << "(ignoring case) ";
1358 }
vladloseve2e8ba42010-05-13 18:16:03 +00001359 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001360 }
1361
1362 const StringType string_;
1363 const bool expect_eq_;
1364 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001365
1366 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001367};
1368
1369// Implements the polymorphic HasSubstr(substring) matcher, which
1370// can be used as a Matcher<T> as long as T can be converted to a
1371// string.
1372template <typename StringType>
1373class HasSubstrMatcher {
1374 public:
shiqiane35fdd92008-12-10 05:08:54 +00001375 explicit HasSubstrMatcher(const StringType& substring)
1376 : substring_(substring) {}
1377
Gennadiy Civile55089e2018-04-04 14:05:00 -04001378#if GTEST_HAS_ABSL
1379 bool MatchAndExplain(const absl::string_view& s,
1380 MatchResultListener* listener) const {
1381 if (s.data() == NULL) {
1382 return false;
1383 }
1384 // This should fail to compile if absl::string_view is used with wide
1385 // strings.
1386 const StringType& str = string(s);
1387 return MatchAndExplain(str, listener);
1388 }
1389#endif // GTEST_HAS_ABSL
1390
jgm38513a82012-11-15 15:50:36 +00001391 // Accepts pointer types, particularly:
1392 // const char*
1393 // char*
1394 // const wchar_t*
1395 // wchar_t*
1396 template <typename CharType>
1397 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001398 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001399 }
1400
jgm38513a82012-11-15 15:50:36 +00001401 // Matches anything that can convert to StringType.
1402 //
1403 // This is a template, not just a plain function with const StringType&,
Gennadiy Civile55089e2018-04-04 14:05:00 -04001404 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001405 template <typename MatcheeStringType>
1406 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001407 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001408 const StringType& s2(s);
1409 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001410 }
1411
1412 // Describes what this matcher matches.
1413 void DescribeTo(::std::ostream* os) const {
1414 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001415 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001416 }
1417
1418 void DescribeNegationTo(::std::ostream* os) const {
1419 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001420 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001421 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001422
shiqiane35fdd92008-12-10 05:08:54 +00001423 private:
1424 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001425
1426 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001427};
1428
1429// Implements the polymorphic StartsWith(substring) matcher, which
1430// can be used as a Matcher<T> as long as T can be converted to a
1431// string.
1432template <typename StringType>
1433class StartsWithMatcher {
1434 public:
shiqiane35fdd92008-12-10 05:08:54 +00001435 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1436 }
1437
Gennadiy Civile55089e2018-04-04 14:05:00 -04001438#if GTEST_HAS_ABSL
1439 bool MatchAndExplain(const absl::string_view& s,
1440 MatchResultListener* listener) const {
1441 if (s.data() == NULL) {
1442 return false;
1443 }
1444 // This should fail to compile if absl::string_view is used with wide
1445 // strings.
1446 const StringType& str = string(s);
1447 return MatchAndExplain(str, listener);
1448 }
1449#endif // GTEST_HAS_ABSL
1450
jgm38513a82012-11-15 15:50:36 +00001451 // Accepts pointer types, particularly:
1452 // const char*
1453 // char*
1454 // const wchar_t*
1455 // wchar_t*
1456 template <typename CharType>
1457 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001458 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001459 }
1460
jgm38513a82012-11-15 15:50:36 +00001461 // Matches anything that can convert to StringType.
1462 //
1463 // This is a template, not just a plain function with const StringType&,
Gennadiy Civile55089e2018-04-04 14:05:00 -04001464 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001465 template <typename MatcheeStringType>
1466 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001467 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001468 const StringType& s2(s);
1469 return s2.length() >= prefix_.length() &&
1470 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001471 }
1472
1473 void DescribeTo(::std::ostream* os) const {
1474 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001475 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001476 }
1477
1478 void DescribeNegationTo(::std::ostream* os) const {
1479 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001480 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001481 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001482
shiqiane35fdd92008-12-10 05:08:54 +00001483 private:
1484 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001485
1486 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001487};
1488
1489// Implements the polymorphic EndsWith(substring) matcher, which
1490// can be used as a Matcher<T> as long as T can be converted to a
1491// string.
1492template <typename StringType>
1493class EndsWithMatcher {
1494 public:
shiqiane35fdd92008-12-10 05:08:54 +00001495 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1496
Gennadiy Civile55089e2018-04-04 14:05:00 -04001497#if GTEST_HAS_ABSL
1498 bool MatchAndExplain(const absl::string_view& s,
1499 MatchResultListener* listener) const {
1500 if (s.data() == NULL) {
1501 return false;
1502 }
1503 // This should fail to compile if absl::string_view is used with wide
1504 // strings.
1505 const StringType& str = string(s);
1506 return MatchAndExplain(str, listener);
1507 }
1508#endif // GTEST_HAS_ABSL
1509
jgm38513a82012-11-15 15:50:36 +00001510 // Accepts pointer types, particularly:
1511 // const char*
1512 // char*
1513 // const wchar_t*
1514 // wchar_t*
1515 template <typename CharType>
1516 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001517 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001518 }
1519
jgm38513a82012-11-15 15:50:36 +00001520 // Matches anything that can convert to StringType.
1521 //
1522 // This is a template, not just a plain function with const StringType&,
Gennadiy Civile55089e2018-04-04 14:05:00 -04001523 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001524 template <typename MatcheeStringType>
1525 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001526 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001527 const StringType& s2(s);
1528 return s2.length() >= suffix_.length() &&
1529 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001530 }
1531
1532 void DescribeTo(::std::ostream* os) const {
1533 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001534 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001535 }
1536
1537 void DescribeNegationTo(::std::ostream* os) const {
1538 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001539 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001540 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001541
shiqiane35fdd92008-12-10 05:08:54 +00001542 private:
1543 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001544
1545 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001546};
1547
shiqiane35fdd92008-12-10 05:08:54 +00001548// Implements polymorphic matchers MatchesRegex(regex) and
1549// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1550// T can be converted to a string.
1551class MatchesRegexMatcher {
1552 public:
1553 MatchesRegexMatcher(const RE* regex, bool full_match)
1554 : regex_(regex), full_match_(full_match) {}
1555
Gennadiy Civile55089e2018-04-04 14:05:00 -04001556#if GTEST_HAS_ABSL
1557 bool MatchAndExplain(const absl::string_view& s,
1558 MatchResultListener* listener) const {
1559 return s.data() && MatchAndExplain(string(s), listener);
1560 }
1561#endif // GTEST_HAS_ABSL
1562
jgm38513a82012-11-15 15:50:36 +00001563 // Accepts pointer types, particularly:
1564 // const char*
1565 // char*
1566 // const wchar_t*
1567 // wchar_t*
1568 template <typename CharType>
1569 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001570 return s != NULL && MatchAndExplain(std::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001571 }
1572
Nico Weber09fd5b32017-05-15 17:07:03 -04001573 // Matches anything that can convert to std::string.
jgm38513a82012-11-15 15:50:36 +00001574 //
Nico Weber09fd5b32017-05-15 17:07:03 -04001575 // This is a template, not just a plain function with const std::string&,
Gennadiy Civilb7c56832018-03-22 15:35:37 -04001576 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001577 template <class MatcheeStringType>
1578 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001579 MatchResultListener* /* listener */) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001580 const std::string& s2(s);
jgm38513a82012-11-15 15:50:36 +00001581 return full_match_ ? RE::FullMatch(s2, *regex_) :
1582 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001583 }
1584
1585 void DescribeTo(::std::ostream* os) const {
1586 *os << (full_match_ ? "matches" : "contains")
1587 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001588 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001589 }
1590
1591 void DescribeNegationTo(::std::ostream* os) const {
1592 *os << "doesn't " << (full_match_ ? "match" : "contain")
1593 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001594 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001595 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001596
shiqiane35fdd92008-12-10 05:08:54 +00001597 private:
1598 const internal::linked_ptr<const RE> regex_;
1599 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001600
1601 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001602};
1603
shiqiane35fdd92008-12-10 05:08:54 +00001604// Implements a matcher that compares the two fields of a 2-tuple
1605// using one of the ==, <=, <, etc, operators. The two fields being
1606// compared don't have to have the same type.
1607//
1608// The matcher defined here is polymorphic (for example, Eq() can be
1609// used to match a tuple<int, short>, a tuple<const long&, double>,
1610// etc). Therefore we use a template type conversion operator in the
1611// implementation.
kosak506340a2014-11-17 01:47:54 +00001612template <typename D, typename Op>
1613class PairMatchBase {
1614 public:
1615 template <typename T1, typename T2>
1616 operator Matcher< ::testing::tuple<T1, T2> >() const {
1617 return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >);
1618 }
1619 template <typename T1, typename T2>
1620 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
1621 return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>);
shiqiane35fdd92008-12-10 05:08:54 +00001622 }
1623
kosak506340a2014-11-17 01:47:54 +00001624 private:
1625 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
1626 return os << D::Desc();
1627 }
shiqiane35fdd92008-12-10 05:08:54 +00001628
kosak506340a2014-11-17 01:47:54 +00001629 template <typename Tuple>
1630 class Impl : public MatcherInterface<Tuple> {
1631 public:
1632 virtual bool MatchAndExplain(
1633 Tuple args,
1634 MatchResultListener* /* listener */) const {
1635 return Op()(::testing::get<0>(args), ::testing::get<1>(args));
1636 }
1637 virtual void DescribeTo(::std::ostream* os) const {
1638 *os << "are " << GetDesc;
1639 }
1640 virtual void DescribeNegationTo(::std::ostream* os) const {
1641 *os << "aren't " << GetDesc;
1642 }
1643 };
1644};
1645
1646class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
1647 public:
1648 static const char* Desc() { return "an equal pair"; }
1649};
1650class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
1651 public:
1652 static const char* Desc() { return "an unequal pair"; }
1653};
1654class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
1655 public:
1656 static const char* Desc() { return "a pair where the first < the second"; }
1657};
1658class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
1659 public:
1660 static const char* Desc() { return "a pair where the first > the second"; }
1661};
1662class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
1663 public:
1664 static const char* Desc() { return "a pair where the first <= the second"; }
1665};
1666class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
1667 public:
1668 static const char* Desc() { return "a pair where the first >= the second"; }
1669};
shiqiane35fdd92008-12-10 05:08:54 +00001670
zhanyong.wanc6a41232009-05-13 23:38:40 +00001671// Implements the Not(...) matcher for a particular argument type T.
1672// We do not nest it inside the NotMatcher class template, as that
1673// will prevent different instantiations of NotMatcher from sharing
1674// the same NotMatcherImpl<T> class.
1675template <typename T>
Gennadiy Civile55089e2018-04-04 14:05:00 -04001676class NotMatcherImpl : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001677 public:
1678 explicit NotMatcherImpl(const Matcher<T>& matcher)
1679 : matcher_(matcher) {}
1680
Gennadiy Civile55089e2018-04-04 14:05:00 -04001681 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
1682 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001683 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001684 }
1685
1686 virtual void DescribeTo(::std::ostream* os) const {
1687 matcher_.DescribeNegationTo(os);
1688 }
1689
1690 virtual void DescribeNegationTo(::std::ostream* os) const {
1691 matcher_.DescribeTo(os);
1692 }
1693
zhanyong.wanc6a41232009-05-13 23:38:40 +00001694 private:
1695 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001696
1697 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001698};
1699
shiqiane35fdd92008-12-10 05:08:54 +00001700// Implements the Not(m) matcher, which matches a value that doesn't
1701// match matcher m.
1702template <typename InnerMatcher>
1703class NotMatcher {
1704 public:
1705 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1706
1707 // This template type conversion operator allows Not(m) to be used
1708 // to match any type m can match.
1709 template <typename T>
1710 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001711 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001712 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001713
shiqiane35fdd92008-12-10 05:08:54 +00001714 private:
shiqiane35fdd92008-12-10 05:08:54 +00001715 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001716
1717 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001718};
1719
zhanyong.wanc6a41232009-05-13 23:38:40 +00001720// Implements the AllOf(m1, m2) matcher for a particular argument type
1721// T. We do not nest it inside the BothOfMatcher class template, as
1722// that will prevent different instantiations of BothOfMatcher from
1723// sharing the same BothOfMatcherImpl<T> class.
1724template <typename T>
Gennadiy Civilb5391672018-04-25 13:10:41 -04001725class AllOfMatcherImpl
Gennadiy Civile55089e2018-04-04 14:05:00 -04001726 : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001727 public:
Gennadiy Civilb5391672018-04-25 13:10:41 -04001728 explicit AllOfMatcherImpl(std::vector<Matcher<T> > matchers)
1729 : matchers_(internal::move(matchers)) {}
zhanyong.wanc6a41232009-05-13 23:38:40 +00001730
zhanyong.wanc6a41232009-05-13 23:38:40 +00001731 virtual void DescribeTo(::std::ostream* os) const {
1732 *os << "(";
Gennadiy Civilb5391672018-04-25 13:10:41 -04001733 for (size_t i = 0; i < matchers_.size(); ++i) {
1734 if (i != 0) *os << ") and (";
1735 matchers_[i].DescribeTo(os);
1736 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001737 *os << ")";
1738 }
1739
1740 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001741 *os << "(";
Gennadiy Civilb5391672018-04-25 13:10:41 -04001742 for (size_t i = 0; i < matchers_.size(); ++i) {
1743 if (i != 0) *os << ") or (";
1744 matchers_[i].DescribeNegationTo(os);
1745 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001746 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001747 }
1748
Gennadiy Civile55089e2018-04-04 14:05:00 -04001749 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
1750 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001751 // If either matcher1_ or matcher2_ doesn't match x, we only need
1752 // to explain why one of them fails.
Gennadiy Civilb5391672018-04-25 13:10:41 -04001753 std::string all_match_result;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001754
Gennadiy Civilb5391672018-04-25 13:10:41 -04001755 for (size_t i = 0; i < matchers_.size(); ++i) {
1756 StringMatchResultListener slistener;
1757 if (matchers_[i].MatchAndExplain(x, &slistener)) {
1758 if (all_match_result.empty()) {
1759 all_match_result = slistener.str();
1760 } else {
1761 std::string result = slistener.str();
1762 if (!result.empty()) {
1763 all_match_result += ", and ";
1764 all_match_result += result;
1765 }
1766 }
1767 } else {
1768 *listener << slistener.str();
1769 return false;
1770 }
zhanyong.wan82113312010-01-08 21:55:40 +00001771 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001772
zhanyong.wan82113312010-01-08 21:55:40 +00001773 // Otherwise we need to explain why *both* of them match.
Gennadiy Civilb5391672018-04-25 13:10:41 -04001774 *listener << all_match_result;
zhanyong.wan82113312010-01-08 21:55:40 +00001775 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001776 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001777
zhanyong.wanc6a41232009-05-13 23:38:40 +00001778 private:
Gennadiy Civilb5391672018-04-25 13:10:41 -04001779 const std::vector<Matcher<T> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001780
Gennadiy Civilb5391672018-04-25 13:10:41 -04001781 GTEST_DISALLOW_ASSIGN_(AllOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001782};
1783
zhanyong.wan616180e2013-06-18 18:49:51 +00001784#if GTEST_LANG_CXX11
zhanyong.wan616180e2013-06-18 18:49:51 +00001785// VariadicMatcher is used for the variadic implementation of
1786// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1787// CombiningMatcher<T> is used to recursively combine the provided matchers
1788// (of type Args...).
1789template <template <typename T> class CombiningMatcher, typename... Args>
1790class VariadicMatcher {
1791 public:
1792 VariadicMatcher(const Args&... matchers) // NOLINT
Gennadiy Civilb5391672018-04-25 13:10:41 -04001793 : matchers_(matchers...) {
1794 static_assert(sizeof...(Args) > 0, "Must have at least one matcher.");
1795 }
zhanyong.wan616180e2013-06-18 18:49:51 +00001796
1797 // This template type conversion operator allows an
1798 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1799 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1800 template <typename T>
1801 operator Matcher<T>() const {
Gennadiy Civilb5391672018-04-25 13:10:41 -04001802 std::vector<Matcher<T> > values;
1803 CreateVariadicMatcher<T>(&values, std::integral_constant<size_t, 0>());
1804 return Matcher<T>(new CombiningMatcher<T>(internal::move(values)));
zhanyong.wan616180e2013-06-18 18:49:51 +00001805 }
1806
1807 private:
Gennadiy Civilb5391672018-04-25 13:10:41 -04001808 template <typename T, size_t I>
1809 void CreateVariadicMatcher(std::vector<Matcher<T> >* values,
1810 std::integral_constant<size_t, I>) const {
1811 values->push_back(SafeMatcherCast<T>(std::get<I>(matchers_)));
1812 CreateVariadicMatcher<T>(values, std::integral_constant<size_t, I + 1>());
1813 }
zhanyong.wan616180e2013-06-18 18:49:51 +00001814
Gennadiy Civilb5391672018-04-25 13:10:41 -04001815 template <typename T>
1816 void CreateVariadicMatcher(
1817 std::vector<Matcher<T> >*,
1818 std::integral_constant<size_t, sizeof...(Args)>) const {}
1819
1820 tuple<Args...> matchers_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001821
1822 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1823};
1824
1825template <typename... Args>
Gennadiy Civilb5391672018-04-25 13:10:41 -04001826using AllOfMatcher = VariadicMatcher<AllOfMatcherImpl, Args...>;
zhanyong.wan616180e2013-06-18 18:49:51 +00001827
1828#endif // GTEST_LANG_CXX11
1829
shiqiane35fdd92008-12-10 05:08:54 +00001830// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1831// matches a value that matches all of the matchers m_1, ..., and m_n.
1832template <typename Matcher1, typename Matcher2>
1833class BothOfMatcher {
1834 public:
1835 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1836 : matcher1_(matcher1), matcher2_(matcher2) {}
1837
1838 // This template type conversion operator allows a
1839 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1840 // both Matcher1 and Matcher2 can match.
1841 template <typename T>
1842 operator Matcher<T>() const {
Gennadiy Civilb5391672018-04-25 13:10:41 -04001843 std::vector<Matcher<T> > values;
1844 values.push_back(SafeMatcherCast<T>(matcher1_));
1845 values.push_back(SafeMatcherCast<T>(matcher2_));
1846 return Matcher<T>(new AllOfMatcherImpl<T>(internal::move(values)));
shiqiane35fdd92008-12-10 05:08:54 +00001847 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001848
shiqiane35fdd92008-12-10 05:08:54 +00001849 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001850 Matcher1 matcher1_;
1851 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001852
1853 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001854};
shiqiane35fdd92008-12-10 05:08:54 +00001855
zhanyong.wanc6a41232009-05-13 23:38:40 +00001856// Implements the AnyOf(m1, m2) matcher for a particular argument type
1857// T. We do not nest it inside the AnyOfMatcher class template, as
1858// that will prevent different instantiations of AnyOfMatcher from
1859// sharing the same EitherOfMatcherImpl<T> class.
1860template <typename T>
Gennadiy Civilb5391672018-04-25 13:10:41 -04001861class AnyOfMatcherImpl
Gennadiy Civile55089e2018-04-04 14:05:00 -04001862 : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001863 public:
Gennadiy Civilb5391672018-04-25 13:10:41 -04001864 explicit AnyOfMatcherImpl(std::vector<Matcher<T> > matchers)
1865 : matchers_(internal::move(matchers)) {}
shiqiane35fdd92008-12-10 05:08:54 +00001866
zhanyong.wanc6a41232009-05-13 23:38:40 +00001867 virtual void DescribeTo(::std::ostream* os) const {
1868 *os << "(";
Gennadiy Civilb5391672018-04-25 13:10:41 -04001869 for (size_t i = 0; i < matchers_.size(); ++i) {
1870 if (i != 0) *os << ") or (";
1871 matchers_[i].DescribeTo(os);
1872 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001873 *os << ")";
1874 }
shiqiane35fdd92008-12-10 05:08:54 +00001875
zhanyong.wanc6a41232009-05-13 23:38:40 +00001876 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001877 *os << "(";
Gennadiy Civilb5391672018-04-25 13:10:41 -04001878 for (size_t i = 0; i < matchers_.size(); ++i) {
1879 if (i != 0) *os << ") and (";
1880 matchers_[i].DescribeNegationTo(os);
1881 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001882 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001883 }
shiqiane35fdd92008-12-10 05:08:54 +00001884
Gennadiy Civile55089e2018-04-04 14:05:00 -04001885 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
1886 MatchResultListener* listener) const {
Gennadiy Civilb5391672018-04-25 13:10:41 -04001887 std::string no_match_result;
1888
zhanyong.wan82113312010-01-08 21:55:40 +00001889 // If either matcher1_ or matcher2_ matches x, we just need to
1890 // explain why *one* of them matches.
Gennadiy Civilb5391672018-04-25 13:10:41 -04001891 for (size_t i = 0; i < matchers_.size(); ++i) {
1892 StringMatchResultListener slistener;
1893 if (matchers_[i].MatchAndExplain(x, &slistener)) {
1894 *listener << slistener.str();
1895 return true;
1896 } else {
1897 if (no_match_result.empty()) {
1898 no_match_result = slistener.str();
1899 } else {
1900 std::string result = slistener.str();
1901 if (!result.empty()) {
1902 no_match_result += ", and ";
1903 no_match_result += result;
1904 }
1905 }
1906 }
zhanyong.wan82113312010-01-08 21:55:40 +00001907 }
1908
1909 // Otherwise we need to explain why *both* of them fail.
Gennadiy Civilb5391672018-04-25 13:10:41 -04001910 *listener << no_match_result;
zhanyong.wan82113312010-01-08 21:55:40 +00001911 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001912 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001913
zhanyong.wanc6a41232009-05-13 23:38:40 +00001914 private:
Gennadiy Civilb5391672018-04-25 13:10:41 -04001915 const std::vector<Matcher<T> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001916
Gennadiy Civilb5391672018-04-25 13:10:41 -04001917 GTEST_DISALLOW_ASSIGN_(AnyOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001918};
1919
zhanyong.wan616180e2013-06-18 18:49:51 +00001920#if GTEST_LANG_CXX11
1921// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1922template <typename... Args>
Gennadiy Civilb5391672018-04-25 13:10:41 -04001923using AnyOfMatcher = VariadicMatcher<AnyOfMatcherImpl, Args...>;
zhanyong.wan616180e2013-06-18 18:49:51 +00001924
1925#endif // GTEST_LANG_CXX11
1926
shiqiane35fdd92008-12-10 05:08:54 +00001927// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1928// matches a value that matches at least one of the matchers m_1, ...,
1929// and m_n.
1930template <typename Matcher1, typename Matcher2>
1931class EitherOfMatcher {
1932 public:
1933 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1934 : matcher1_(matcher1), matcher2_(matcher2) {}
1935
1936 // This template type conversion operator allows a
1937 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1938 // both Matcher1 and Matcher2 can match.
1939 template <typename T>
1940 operator Matcher<T>() const {
Gennadiy Civilb5391672018-04-25 13:10:41 -04001941 std::vector<Matcher<T> > values;
1942 values.push_back(SafeMatcherCast<T>(matcher1_));
1943 values.push_back(SafeMatcherCast<T>(matcher2_));
1944 return Matcher<T>(new AnyOfMatcherImpl<T>(internal::move(values)));
shiqiane35fdd92008-12-10 05:08:54 +00001945 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001946
shiqiane35fdd92008-12-10 05:08:54 +00001947 private:
shiqiane35fdd92008-12-10 05:08:54 +00001948 Matcher1 matcher1_;
1949 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001950
1951 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001952};
1953
1954// Used for implementing Truly(pred), which turns a predicate into a
1955// matcher.
1956template <typename Predicate>
1957class TrulyMatcher {
1958 public:
1959 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1960
1961 // This method template allows Truly(pred) to be used as a matcher
1962 // for type T where T is the argument type of predicate 'pred'. The
1963 // argument is passed by reference as the predicate may be
1964 // interested in the address of the argument.
1965 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001966 bool MatchAndExplain(T& x, // NOLINT
1967 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001968 // Without the if-statement, MSVC sometimes warns about converting
1969 // a value to bool (warning 4800).
1970 //
1971 // We cannot write 'return !!predicate_(x);' as that doesn't work
1972 // when predicate_(x) returns a class convertible to bool but
1973 // having no operator!().
1974 if (predicate_(x))
1975 return true;
1976 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001977 }
1978
1979 void DescribeTo(::std::ostream* os) const {
1980 *os << "satisfies the given predicate";
1981 }
1982
1983 void DescribeNegationTo(::std::ostream* os) const {
1984 *os << "doesn't satisfy the given predicate";
1985 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001986
shiqiane35fdd92008-12-10 05:08:54 +00001987 private:
1988 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001989
1990 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001991};
1992
1993// Used for implementing Matches(matcher), which turns a matcher into
1994// a predicate.
1995template <typename M>
1996class MatcherAsPredicate {
1997 public:
1998 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1999
2000 // This template operator() allows Matches(m) to be used as a
2001 // predicate on type T where m is a matcher on type T.
2002 //
2003 // The argument x is passed by reference instead of by value, as
2004 // some matcher may be interested in its address (e.g. as in
2005 // Matches(Ref(n))(x)).
2006 template <typename T>
2007 bool operator()(const T& x) const {
2008 // We let matcher_ commit to a particular type here instead of
2009 // when the MatcherAsPredicate object was constructed. This
2010 // allows us to write Matches(m) where m is a polymorphic matcher
2011 // (e.g. Eq(5)).
2012 //
2013 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
2014 // compile when matcher_ has type Matcher<const T&>; if we write
2015 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
2016 // when matcher_ has type Matcher<T>; if we just write
2017 // matcher_.Matches(x), it won't compile when matcher_ is
2018 // polymorphic, e.g. Eq(5).
2019 //
2020 // MatcherCast<const T&>() is necessary for making the code work
2021 // in all of the above situations.
2022 return MatcherCast<const T&>(matcher_).Matches(x);
2023 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002024
shiqiane35fdd92008-12-10 05:08:54 +00002025 private:
2026 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002027
2028 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00002029};
2030
2031// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
2032// argument M must be a type that can be converted to a matcher.
2033template <typename M>
2034class PredicateFormatterFromMatcher {
2035 public:
kosak9b1a9442015-04-28 23:06:58 +00002036 explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {}
shiqiane35fdd92008-12-10 05:08:54 +00002037
2038 // This template () operator allows a PredicateFormatterFromMatcher
2039 // object to act as a predicate-formatter suitable for using with
2040 // Google Test's EXPECT_PRED_FORMAT1() macro.
2041 template <typename T>
2042 AssertionResult operator()(const char* value_text, const T& x) const {
2043 // We convert matcher_ to a Matcher<const T&> *now* instead of
2044 // when the PredicateFormatterFromMatcher object was constructed,
2045 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
2046 // know which type to instantiate it to until we actually see the
2047 // type of x here.
2048 //
zhanyong.wanf4274522013-04-24 02:49:43 +00002049 // We write SafeMatcherCast<const T&>(matcher_) instead of
shiqiane35fdd92008-12-10 05:08:54 +00002050 // Matcher<const T&>(matcher_), as the latter won't compile when
2051 // matcher_ has type Matcher<T> (e.g. An<int>()).
zhanyong.wanf4274522013-04-24 02:49:43 +00002052 // We don't write MatcherCast<const T&> either, as that allows
2053 // potentially unsafe downcasting of the matcher argument.
2054 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00002055 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002056 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00002057 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002058
2059 ::std::stringstream ss;
2060 ss << "Value of: " << value_text << "\n"
2061 << "Expected: ";
2062 matcher.DescribeTo(&ss);
2063 ss << "\n Actual: " << listener.str();
2064 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00002065 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002066
shiqiane35fdd92008-12-10 05:08:54 +00002067 private:
2068 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002069
2070 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002071};
2072
2073// A helper function for converting a matcher to a predicate-formatter
2074// without the user needing to explicitly write the type. This is
2075// used for implementing ASSERT_THAT() and EXPECT_THAT().
kosak9b1a9442015-04-28 23:06:58 +00002076// Implementation detail: 'matcher' is received by-value to force decaying.
shiqiane35fdd92008-12-10 05:08:54 +00002077template <typename M>
2078inline PredicateFormatterFromMatcher<M>
kosak9b1a9442015-04-28 23:06:58 +00002079MakePredicateFormatterFromMatcher(M matcher) {
2080 return PredicateFormatterFromMatcher<M>(internal::move(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00002081}
2082
zhanyong.wan616180e2013-06-18 18:49:51 +00002083// Implements the polymorphic floating point equality matcher, which matches
2084// two float values using ULP-based approximation or, optionally, a
2085// user-specified epsilon. The template is meant to be instantiated with
2086// FloatType being either float or double.
shiqiane35fdd92008-12-10 05:08:54 +00002087template <typename FloatType>
2088class FloatingEqMatcher {
2089 public:
2090 // Constructor for FloatingEqMatcher.
kosak6b817802015-01-08 02:38:14 +00002091 // The matcher's input will be compared with expected. The matcher treats two
shiqiane35fdd92008-12-10 05:08:54 +00002092 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
zhanyong.wan616180e2013-06-18 18:49:51 +00002093 // equality comparisons between NANs will always return false. We specify a
2094 // negative max_abs_error_ term to indicate that ULP-based approximation will
2095 // be used for comparison.
kosak6b817802015-01-08 02:38:14 +00002096 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
2097 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
zhanyong.wan616180e2013-06-18 18:49:51 +00002098 }
2099
2100 // Constructor that supports a user-specified max_abs_error that will be used
2101 // for comparison instead of ULP-based approximation. The max absolute
2102 // should be non-negative.
kosak6b817802015-01-08 02:38:14 +00002103 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
2104 FloatType max_abs_error)
2105 : expected_(expected),
2106 nan_eq_nan_(nan_eq_nan),
2107 max_abs_error_(max_abs_error) {
zhanyong.wan616180e2013-06-18 18:49:51 +00002108 GTEST_CHECK_(max_abs_error >= 0)
2109 << ", where max_abs_error is" << max_abs_error;
2110 }
shiqiane35fdd92008-12-10 05:08:54 +00002111
2112 // Implements floating point equality matcher as a Matcher<T>.
2113 template <typename T>
2114 class Impl : public MatcherInterface<T> {
2115 public:
kosak6b817802015-01-08 02:38:14 +00002116 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
2117 : expected_(expected),
2118 nan_eq_nan_(nan_eq_nan),
2119 max_abs_error_(max_abs_error) {}
shiqiane35fdd92008-12-10 05:08:54 +00002120
zhanyong.wan82113312010-01-08 21:55:40 +00002121 virtual bool MatchAndExplain(T value,
kosak6b817802015-01-08 02:38:14 +00002122 MatchResultListener* listener) const {
2123 const FloatingPoint<FloatType> actual(value), expected(expected_);
shiqiane35fdd92008-12-10 05:08:54 +00002124
2125 // Compares NaNs first, if nan_eq_nan_ is true.
kosak6b817802015-01-08 02:38:14 +00002126 if (actual.is_nan() || expected.is_nan()) {
2127 if (actual.is_nan() && expected.is_nan()) {
zhanyong.wan616180e2013-06-18 18:49:51 +00002128 return nan_eq_nan_;
2129 }
2130 // One is nan; the other is not nan.
2131 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002132 }
zhanyong.wan616180e2013-06-18 18:49:51 +00002133 if (HasMaxAbsError()) {
2134 // We perform an equality check so that inf will match inf, regardless
kosak6b817802015-01-08 02:38:14 +00002135 // of error bounds. If the result of value - expected_ would result in
zhanyong.wan616180e2013-06-18 18:49:51 +00002136 // overflow or if either value is inf, the default result is infinity,
2137 // which should only match if max_abs_error_ is also infinity.
kosak6b817802015-01-08 02:38:14 +00002138 if (value == expected_) {
2139 return true;
2140 }
2141
2142 const FloatType diff = value - expected_;
2143 if (fabs(diff) <= max_abs_error_) {
2144 return true;
2145 }
2146
2147 if (listener->IsInterested()) {
2148 *listener << "which is " << diff << " from " << expected_;
2149 }
2150 return false;
zhanyong.wan616180e2013-06-18 18:49:51 +00002151 } else {
kosak6b817802015-01-08 02:38:14 +00002152 return actual.AlmostEquals(expected);
zhanyong.wan616180e2013-06-18 18:49:51 +00002153 }
shiqiane35fdd92008-12-10 05:08:54 +00002154 }
2155
2156 virtual void DescribeTo(::std::ostream* os) const {
2157 // os->precision() returns the previously set precision, which we
2158 // store to restore the ostream to its original configuration
2159 // after outputting.
2160 const ::std::streamsize old_precision = os->precision(
2161 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00002162 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00002163 if (nan_eq_nan_) {
2164 *os << "is NaN";
2165 } else {
2166 *os << "never matches";
2167 }
2168 } else {
kosak6b817802015-01-08 02:38:14 +00002169 *os << "is approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002170 if (HasMaxAbsError()) {
2171 *os << " (absolute error <= " << max_abs_error_ << ")";
2172 }
shiqiane35fdd92008-12-10 05:08:54 +00002173 }
2174 os->precision(old_precision);
2175 }
2176
2177 virtual void DescribeNegationTo(::std::ostream* os) const {
2178 // As before, get original precision.
2179 const ::std::streamsize old_precision = os->precision(
2180 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00002181 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00002182 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002183 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00002184 } else {
2185 *os << "is anything";
2186 }
2187 } else {
kosak6b817802015-01-08 02:38:14 +00002188 *os << "isn't approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002189 if (HasMaxAbsError()) {
2190 *os << " (absolute error > " << max_abs_error_ << ")";
2191 }
shiqiane35fdd92008-12-10 05:08:54 +00002192 }
2193 // Restore original precision.
2194 os->precision(old_precision);
2195 }
2196
2197 private:
zhanyong.wan616180e2013-06-18 18:49:51 +00002198 bool HasMaxAbsError() const {
2199 return max_abs_error_ >= 0;
2200 }
2201
kosak6b817802015-01-08 02:38:14 +00002202 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002203 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002204 // max_abs_error will be used for value comparison when >= 0.
2205 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002206
2207 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002208 };
2209
kosak6b817802015-01-08 02:38:14 +00002210 // The following 3 type conversion operators allow FloatEq(expected) and
2211 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
shiqiane35fdd92008-12-10 05:08:54 +00002212 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
2213 // (While Google's C++ coding style doesn't allow arguments passed
2214 // by non-const reference, we may see them in code not conforming to
2215 // the style. Therefore Google Mock needs to support them.)
2216 operator Matcher<FloatType>() const {
kosak6b817802015-01-08 02:38:14 +00002217 return MakeMatcher(
2218 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002219 }
2220
2221 operator Matcher<const FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00002222 return MakeMatcher(
kosak6b817802015-01-08 02:38:14 +00002223 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002224 }
2225
2226 operator Matcher<FloatType&>() const {
kosak6b817802015-01-08 02:38:14 +00002227 return MakeMatcher(
2228 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002229 }
jgm79a367e2012-04-10 16:02:11 +00002230
shiqiane35fdd92008-12-10 05:08:54 +00002231 private:
kosak6b817802015-01-08 02:38:14 +00002232 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002233 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002234 // max_abs_error will be used for value comparison when >= 0.
2235 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002236
2237 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002238};
2239
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002240// A 2-tuple ("binary") wrapper around FloatingEqMatcher:
2241// FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false)
2242// against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e)
2243// against y. The former implements "Eq", the latter "Near". At present, there
2244// is no version that compares NaNs as equal.
2245template <typename FloatType>
2246class FloatingEq2Matcher {
2247 public:
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002248 FloatingEq2Matcher() { Init(-1, false); }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002249
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002250 explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002251
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002252 explicit FloatingEq2Matcher(FloatType max_abs_error) {
2253 Init(max_abs_error, false);
2254 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002255
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002256 FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) {
2257 Init(max_abs_error, nan_eq_nan);
2258 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002259
2260 template <typename T1, typename T2>
2261 operator Matcher< ::testing::tuple<T1, T2> >() const {
2262 return MakeMatcher(
2263 new Impl< ::testing::tuple<T1, T2> >(max_abs_error_, nan_eq_nan_));
2264 }
2265 template <typename T1, typename T2>
2266 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
2267 return MakeMatcher(
2268 new Impl<const ::testing::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_));
2269 }
2270
2271 private:
2272 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
2273 return os << "an almost-equal pair";
2274 }
2275
2276 template <typename Tuple>
2277 class Impl : public MatcherInterface<Tuple> {
2278 public:
2279 Impl(FloatType max_abs_error, bool nan_eq_nan) :
2280 max_abs_error_(max_abs_error),
2281 nan_eq_nan_(nan_eq_nan) {}
2282
2283 virtual bool MatchAndExplain(Tuple args,
2284 MatchResultListener* listener) const {
2285 if (max_abs_error_ == -1) {
2286 FloatingEqMatcher<FloatType> fm(::testing::get<0>(args), nan_eq_nan_);
2287 return static_cast<Matcher<FloatType> >(fm).MatchAndExplain(
2288 ::testing::get<1>(args), listener);
2289 } else {
2290 FloatingEqMatcher<FloatType> fm(::testing::get<0>(args), nan_eq_nan_,
2291 max_abs_error_);
2292 return static_cast<Matcher<FloatType> >(fm).MatchAndExplain(
2293 ::testing::get<1>(args), listener);
2294 }
2295 }
2296 virtual void DescribeTo(::std::ostream* os) const {
2297 *os << "are " << GetDesc;
2298 }
2299 virtual void DescribeNegationTo(::std::ostream* os) const {
2300 *os << "aren't " << GetDesc;
2301 }
2302
2303 private:
2304 FloatType max_abs_error_;
2305 const bool nan_eq_nan_;
2306 };
2307
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002308 void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) {
2309 max_abs_error_ = max_abs_error_val;
2310 nan_eq_nan_ = nan_eq_nan_val;
2311 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002312 FloatType max_abs_error_;
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002313 bool nan_eq_nan_;
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002314};
2315
shiqiane35fdd92008-12-10 05:08:54 +00002316// Implements the Pointee(m) matcher for matching a pointer whose
2317// pointee matches matcher m. The pointer can be either raw or smart.
2318template <typename InnerMatcher>
2319class PointeeMatcher {
2320 public:
2321 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
2322
2323 // This type conversion operator template allows Pointee(m) to be
2324 // used as a matcher for any pointer type whose pointee type is
2325 // compatible with the inner matcher, where type Pointer can be
2326 // either a raw pointer or a smart pointer.
2327 //
2328 // The reason we do this instead of relying on
2329 // MakePolymorphicMatcher() is that the latter is not flexible
2330 // enough for implementing the DescribeTo() method of Pointee().
2331 template <typename Pointer>
2332 operator Matcher<Pointer>() const {
Gennadiy Civile55089e2018-04-04 14:05:00 -04002333 return Matcher<Pointer>(
2334 new Impl<GTEST_REFERENCE_TO_CONST_(Pointer)>(matcher_));
shiqiane35fdd92008-12-10 05:08:54 +00002335 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002336
shiqiane35fdd92008-12-10 05:08:54 +00002337 private:
2338 // The monomorphic implementation that works for a particular pointer type.
2339 template <typename Pointer>
2340 class Impl : public MatcherInterface<Pointer> {
2341 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00002342 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
2343 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00002344
2345 explicit Impl(const InnerMatcher& matcher)
2346 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
2347
shiqiane35fdd92008-12-10 05:08:54 +00002348 virtual void DescribeTo(::std::ostream* os) const {
2349 *os << "points to a value that ";
2350 matcher_.DescribeTo(os);
2351 }
2352
2353 virtual void DescribeNegationTo(::std::ostream* os) const {
2354 *os << "does not point to a value that ";
2355 matcher_.DescribeTo(os);
2356 }
2357
zhanyong.wan82113312010-01-08 21:55:40 +00002358 virtual bool MatchAndExplain(Pointer pointer,
2359 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00002360 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00002361 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002362
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002363 *listener << "which points to ";
2364 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002365 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002366
shiqiane35fdd92008-12-10 05:08:54 +00002367 private:
2368 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002369
2370 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002371 };
2372
2373 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002374
2375 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002376};
2377
Scott Grahama9653c42018-05-02 11:14:39 -07002378#if GTEST_HAS_RTTI
billydonahue1f5fdea2014-05-19 17:54:51 +00002379// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2380// reference that matches inner_matcher when dynamic_cast<T> is applied.
2381// The result of dynamic_cast<To> is forwarded to the inner matcher.
2382// If To is a pointer and the cast fails, the inner matcher will receive NULL.
2383// If To is a reference and the cast fails, this matcher returns false
2384// immediately.
2385template <typename To>
2386class WhenDynamicCastToMatcherBase {
2387 public:
2388 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2389 : matcher_(matcher) {}
2390
2391 void DescribeTo(::std::ostream* os) const {
2392 GetCastTypeDescription(os);
2393 matcher_.DescribeTo(os);
2394 }
2395
2396 void DescribeNegationTo(::std::ostream* os) const {
2397 GetCastTypeDescription(os);
2398 matcher_.DescribeNegationTo(os);
2399 }
2400
2401 protected:
2402 const Matcher<To> matcher_;
2403
Nico Weber09fd5b32017-05-15 17:07:03 -04002404 static std::string GetToName() {
billydonahue1f5fdea2014-05-19 17:54:51 +00002405 return GetTypeName<To>();
billydonahue1f5fdea2014-05-19 17:54:51 +00002406 }
2407
2408 private:
2409 static void GetCastTypeDescription(::std::ostream* os) {
2410 *os << "when dynamic_cast to " << GetToName() << ", ";
2411 }
2412
2413 GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2414};
2415
2416// Primary template.
2417// To is a pointer. Cast and forward the result.
2418template <typename To>
2419class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2420 public:
2421 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2422 : WhenDynamicCastToMatcherBase<To>(matcher) {}
2423
2424 template <typename From>
2425 bool MatchAndExplain(From from, MatchResultListener* listener) const {
Gennadiy Civil265efde2018-08-14 15:04:11 -04002426 // FIXME: Add more detail on failures. ie did the dyn_cast fail?
billydonahue1f5fdea2014-05-19 17:54:51 +00002427 To to = dynamic_cast<To>(from);
2428 return MatchPrintAndExplain(to, this->matcher_, listener);
2429 }
2430};
2431
2432// Specialize for references.
2433// In this case we return false if the dynamic_cast fails.
2434template <typename To>
2435class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2436 public:
2437 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2438 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2439
2440 template <typename From>
2441 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2442 // We don't want an std::bad_cast here, so do the cast with pointers.
2443 To* to = dynamic_cast<To*>(&from);
2444 if (to == NULL) {
2445 *listener << "which cannot be dynamic_cast to " << this->GetToName();
2446 return false;
2447 }
2448 return MatchPrintAndExplain(*to, this->matcher_, listener);
2449 }
2450};
Scott Grahama9653c42018-05-02 11:14:39 -07002451#endif // GTEST_HAS_RTTI
billydonahue1f5fdea2014-05-19 17:54:51 +00002452
shiqiane35fdd92008-12-10 05:08:54 +00002453// Implements the Field() matcher for matching a field (i.e. member
2454// variable) of an object.
2455template <typename Class, typename FieldType>
2456class FieldMatcher {
2457 public:
2458 FieldMatcher(FieldType Class::*field,
2459 const Matcher<const FieldType&>& matcher)
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002460 : field_(field), matcher_(matcher), whose_field_("whose given field ") {}
2461
2462 FieldMatcher(const std::string& field_name, FieldType Class::*field,
2463 const Matcher<const FieldType&>& matcher)
2464 : field_(field),
2465 matcher_(matcher),
2466 whose_field_("whose field `" + field_name + "` ") {}
shiqiane35fdd92008-12-10 05:08:54 +00002467
shiqiane35fdd92008-12-10 05:08:54 +00002468 void DescribeTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002469 *os << "is an object " << whose_field_;
shiqiane35fdd92008-12-10 05:08:54 +00002470 matcher_.DescribeTo(os);
2471 }
2472
2473 void DescribeNegationTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002474 *os << "is an object " << whose_field_;
shiqiane35fdd92008-12-10 05:08:54 +00002475 matcher_.DescribeNegationTo(os);
2476 }
2477
zhanyong.wandb22c222010-01-28 21:52:29 +00002478 template <typename T>
2479 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2480 return MatchAndExplainImpl(
2481 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002482 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002483 value, listener);
2484 }
2485
2486 private:
2487 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002488 // Symbian's C++ compiler choose which overload to use. Its type is
2489 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002490 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2491 MatchResultListener* listener) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002492 *listener << whose_field_ << "is ";
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002493 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002494 }
2495
zhanyong.wandb22c222010-01-28 21:52:29 +00002496 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2497 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002498 if (p == NULL)
2499 return false;
2500
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002501 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002502 // Since *p has a field, it must be a class/struct/union type and
2503 // thus cannot be a pointer. Therefore we pass false_type() as
2504 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002505 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002506 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002507
shiqiane35fdd92008-12-10 05:08:54 +00002508 const FieldType Class::*field_;
2509 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002510
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002511 // Contains either "whose given field " if the name of the field is unknown
2512 // or "whose field `name_of_field` " if the name is known.
2513 const std::string whose_field_;
2514
zhanyong.wan32de5f52009-12-23 00:13:23 +00002515 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002516};
2517
shiqiane35fdd92008-12-10 05:08:54 +00002518// Implements the Property() matcher for matching a property
2519// (i.e. return value of a getter method) of an object.
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002520//
2521// Property is a const-qualified member function of Class returning
2522// PropertyType.
2523template <typename Class, typename PropertyType, typename Property>
shiqiane35fdd92008-12-10 05:08:54 +00002524class PropertyMatcher {
2525 public:
2526 // The property may have a reference type, so 'const PropertyType&'
2527 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00002528 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00002529 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00002530 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00002531
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002532 PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002533 : property_(property),
2534 matcher_(matcher),
2535 whose_property_("whose given property ") {}
2536
2537 PropertyMatcher(const std::string& property_name, Property property,
2538 const Matcher<RefToConstProperty>& matcher)
2539 : property_(property),
2540 matcher_(matcher),
2541 whose_property_("whose property `" + property_name + "` ") {}
shiqiane35fdd92008-12-10 05:08:54 +00002542
shiqiane35fdd92008-12-10 05:08:54 +00002543 void DescribeTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002544 *os << "is an object " << whose_property_;
shiqiane35fdd92008-12-10 05:08:54 +00002545 matcher_.DescribeTo(os);
2546 }
2547
2548 void DescribeNegationTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002549 *os << "is an object " << whose_property_;
shiqiane35fdd92008-12-10 05:08:54 +00002550 matcher_.DescribeNegationTo(os);
2551 }
2552
zhanyong.wandb22c222010-01-28 21:52:29 +00002553 template <typename T>
2554 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2555 return MatchAndExplainImpl(
2556 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002557 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002558 value, listener);
2559 }
2560
2561 private:
2562 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002563 // Symbian's C++ compiler choose which overload to use. Its type is
2564 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002565 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2566 MatchResultListener* listener) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002567 *listener << whose_property_ << "is ";
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002568 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2569 // which takes a non-const reference as argument.
kosak02d64792015-02-14 02:22:21 +00002570#if defined(_PREFAST_ ) && _MSC_VER == 1800
2571 // Workaround bug in VC++ 2013's /analyze parser.
2572 // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move
2573 posix::Abort(); // To make sure it is never run.
2574 return false;
2575#else
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002576 RefToConstProperty result = (obj.*property_)();
2577 return MatchPrintAndExplain(result, matcher_, listener);
kosak02d64792015-02-14 02:22:21 +00002578#endif
shiqiane35fdd92008-12-10 05:08:54 +00002579 }
2580
zhanyong.wandb22c222010-01-28 21:52:29 +00002581 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2582 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002583 if (p == NULL)
2584 return false;
2585
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002586 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002587 // Since *p has a property method, it must be a class/struct/union
2588 // type and thus cannot be a pointer. Therefore we pass
2589 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002590 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002591 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002592
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002593 Property property_;
shiqiane35fdd92008-12-10 05:08:54 +00002594 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002595
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002596 // Contains either "whose given property " if the name of the property is
2597 // unknown or "whose property `name_of_property` " if the name is known.
2598 const std::string whose_property_;
2599
zhanyong.wan32de5f52009-12-23 00:13:23 +00002600 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002601};
2602
shiqiane35fdd92008-12-10 05:08:54 +00002603// Type traits specifying various features of different functors for ResultOf.
2604// The default template specifies features for functor objects.
shiqiane35fdd92008-12-10 05:08:54 +00002605template <typename Functor>
2606struct CallableTraits {
shiqiane35fdd92008-12-10 05:08:54 +00002607 typedef Functor StorageType;
2608
zhanyong.wan32de5f52009-12-23 00:13:23 +00002609 static void CheckIsValid(Functor /* functor */) {}
Abseil Teama0e62d92018-08-24 13:30:17 -04002610
2611#if GTEST_LANG_CXX11
2612 template <typename T>
2613 static auto Invoke(Functor f, T arg) -> decltype(f(arg)) { return f(arg); }
2614#else
2615 typedef typename Functor::result_type ResultType;
shiqiane35fdd92008-12-10 05:08:54 +00002616 template <typename T>
2617 static ResultType Invoke(Functor f, T arg) { return f(arg); }
Abseil Teama0e62d92018-08-24 13:30:17 -04002618#endif
shiqiane35fdd92008-12-10 05:08:54 +00002619};
2620
2621// Specialization for function pointers.
2622template <typename ArgType, typename ResType>
2623struct CallableTraits<ResType(*)(ArgType)> {
2624 typedef ResType ResultType;
2625 typedef ResType(*StorageType)(ArgType);
2626
2627 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002628 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00002629 << "NULL function pointer is passed into ResultOf().";
2630 }
2631 template <typename T>
2632 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2633 return (*f)(arg);
2634 }
2635};
2636
2637// Implements the ResultOf() matcher for matching a return value of a
2638// unary function of an object.
Abseil Teama0e62d92018-08-24 13:30:17 -04002639template <typename Callable, typename InnerMatcher>
shiqiane35fdd92008-12-10 05:08:54 +00002640class ResultOfMatcher {
2641 public:
Abseil Teama0e62d92018-08-24 13:30:17 -04002642 ResultOfMatcher(Callable callable, InnerMatcher matcher)
2643 : callable_(internal::move(callable)), matcher_(internal::move(matcher)) {
shiqiane35fdd92008-12-10 05:08:54 +00002644 CallableTraits<Callable>::CheckIsValid(callable_);
2645 }
2646
2647 template <typename T>
2648 operator Matcher<T>() const {
2649 return Matcher<T>(new Impl<T>(callable_, matcher_));
2650 }
2651
2652 private:
2653 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2654
2655 template <typename T>
2656 class Impl : public MatcherInterface<T> {
Abseil Teama0e62d92018-08-24 13:30:17 -04002657#if GTEST_LANG_CXX11
2658 using ResultType = decltype(CallableTraits<Callable>::template Invoke<T>(
2659 std::declval<CallableStorageType>(), std::declval<T>()));
2660#else
2661 typedef typename CallableTraits<Callable>::ResultType ResultType;
2662#endif
2663
shiqiane35fdd92008-12-10 05:08:54 +00002664 public:
Abseil Teama0e62d92018-08-24 13:30:17 -04002665 template <typename M>
2666 Impl(const CallableStorageType& callable, const M& matcher)
2667 : callable_(callable), matcher_(MatcherCast<ResultType>(matcher)) {}
shiqiane35fdd92008-12-10 05:08:54 +00002668
2669 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002670 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002671 matcher_.DescribeTo(os);
2672 }
2673
2674 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002675 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002676 matcher_.DescribeNegationTo(os);
2677 }
2678
zhanyong.wan82113312010-01-08 21:55:40 +00002679 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002680 *listener << "which is mapped by the given callable to ";
Abseil Teama0e62d92018-08-24 13:30:17 -04002681 // Cannot pass the return value directly to MatchPrintAndExplain, which
2682 // takes a non-const reference as argument.
2683 // Also, specifying template argument explicitly is needed because T could
2684 // be a non-const reference (e.g. Matcher<Uncopyable&>).
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002685 ResultType result =
2686 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2687 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002688 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002689
shiqiane35fdd92008-12-10 05:08:54 +00002690 private:
2691 // Functors often define operator() as non-const method even though
Troy Holsapplec8510502018-02-07 22:06:00 -08002692 // they are actually stateless. But we need to use them even when
shiqiane35fdd92008-12-10 05:08:54 +00002693 // 'this' is a const pointer. It's the user's responsibility not to
Abseil Teama0e62d92018-08-24 13:30:17 -04002694 // use stateful callables with ResultOf(), which doesn't guarantee
shiqiane35fdd92008-12-10 05:08:54 +00002695 // how many times the callable will be invoked.
2696 mutable CallableStorageType callable_;
2697 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002698
2699 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002700 }; // class Impl
2701
2702 const CallableStorageType callable_;
Abseil Teama0e62d92018-08-24 13:30:17 -04002703 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002704
2705 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002706};
2707
zhanyong.wana31d9ce2013-03-01 01:50:17 +00002708// Implements a matcher that checks the size of an STL-style container.
2709template <typename SizeMatcher>
2710class SizeIsMatcher {
2711 public:
2712 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2713 : size_matcher_(size_matcher) {
2714 }
2715
2716 template <typename Container>
2717 operator Matcher<Container>() const {
2718 return MakeMatcher(new Impl<Container>(size_matcher_));
2719 }
2720
2721 template <typename Container>
2722 class Impl : public MatcherInterface<Container> {
2723 public:
2724 typedef internal::StlContainerView<
2725 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2726 typedef typename ContainerView::type::size_type SizeType;
2727 explicit Impl(const SizeMatcher& size_matcher)
2728 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2729
2730 virtual void DescribeTo(::std::ostream* os) const {
2731 *os << "size ";
2732 size_matcher_.DescribeTo(os);
2733 }
2734 virtual void DescribeNegationTo(::std::ostream* os) const {
2735 *os << "size ";
2736 size_matcher_.DescribeNegationTo(os);
2737 }
2738
2739 virtual bool MatchAndExplain(Container container,
2740 MatchResultListener* listener) const {
2741 SizeType size = container.size();
2742 StringMatchResultListener size_listener;
2743 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2744 *listener
2745 << "whose size " << size << (result ? " matches" : " doesn't match");
2746 PrintIfNotEmpty(size_listener.str(), listener->stream());
2747 return result;
2748 }
2749
2750 private:
2751 const Matcher<SizeType> size_matcher_;
2752 GTEST_DISALLOW_ASSIGN_(Impl);
2753 };
2754
2755 private:
2756 const SizeMatcher size_matcher_;
2757 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2758};
2759
kosakb6a34882014-03-12 21:06:46 +00002760// Implements a matcher that checks the begin()..end() distance of an STL-style
2761// container.
2762template <typename DistanceMatcher>
2763class BeginEndDistanceIsMatcher {
2764 public:
2765 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2766 : distance_matcher_(distance_matcher) {}
2767
2768 template <typename Container>
2769 operator Matcher<Container>() const {
2770 return MakeMatcher(new Impl<Container>(distance_matcher_));
2771 }
2772
2773 template <typename Container>
2774 class Impl : public MatcherInterface<Container> {
2775 public:
2776 typedef internal::StlContainerView<
2777 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2778 typedef typename std::iterator_traits<
2779 typename ContainerView::type::const_iterator>::difference_type
2780 DistanceType;
2781 explicit Impl(const DistanceMatcher& distance_matcher)
2782 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2783
2784 virtual void DescribeTo(::std::ostream* os) const {
2785 *os << "distance between begin() and end() ";
2786 distance_matcher_.DescribeTo(os);
2787 }
2788 virtual void DescribeNegationTo(::std::ostream* os) const {
2789 *os << "distance between begin() and end() ";
2790 distance_matcher_.DescribeNegationTo(os);
2791 }
2792
2793 virtual bool MatchAndExplain(Container container,
2794 MatchResultListener* listener) const {
kosak5b9cbbb2014-11-17 00:28:55 +00002795#if GTEST_HAS_STD_BEGIN_AND_END_
kosakb6a34882014-03-12 21:06:46 +00002796 using std::begin;
2797 using std::end;
2798 DistanceType distance = std::distance(begin(container), end(container));
2799#else
2800 DistanceType distance = std::distance(container.begin(), container.end());
2801#endif
2802 StringMatchResultListener distance_listener;
2803 const bool result =
2804 distance_matcher_.MatchAndExplain(distance, &distance_listener);
2805 *listener << "whose distance between begin() and end() " << distance
2806 << (result ? " matches" : " doesn't match");
2807 PrintIfNotEmpty(distance_listener.str(), listener->stream());
2808 return result;
2809 }
2810
2811 private:
2812 const Matcher<DistanceType> distance_matcher_;
2813 GTEST_DISALLOW_ASSIGN_(Impl);
2814 };
2815
2816 private:
2817 const DistanceMatcher distance_matcher_;
2818 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2819};
2820
zhanyong.wan6a896b52009-01-16 01:13:50 +00002821// Implements an equality matcher for any STL-style container whose elements
2822// support ==. This matcher is like Eq(), but its failure explanations provide
2823// more detailed information that is useful when the container is used as a set.
2824// The failure message reports elements that are in one of the operands but not
2825// the other. The failure messages do not report duplicate or out-of-order
2826// elements in the containers (which don't properly matter to sets, but can
2827// occur if the containers are vectors or lists, for example).
2828//
2829// Uses the container's const_iterator, value_type, operator ==,
2830// begin(), and end().
2831template <typename Container>
2832class ContainerEqMatcher {
2833 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002834 typedef internal::StlContainerView<Container> View;
2835 typedef typename View::type StlContainer;
2836 typedef typename View::const_reference StlContainerReference;
2837
kosak6b817802015-01-08 02:38:14 +00002838 // We make a copy of expected in case the elements in it are modified
zhanyong.wanb8243162009-06-04 05:48:20 +00002839 // after this matcher is created.
kosak6b817802015-01-08 02:38:14 +00002840 explicit ContainerEqMatcher(const Container& expected)
2841 : expected_(View::Copy(expected)) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002842 // Makes sure the user doesn't instantiate this class template
2843 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002844 (void)testing::StaticAssertTypeEq<Container,
2845 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002846 }
2847
zhanyong.wan6a896b52009-01-16 01:13:50 +00002848 void DescribeTo(::std::ostream* os) const {
2849 *os << "equals ";
kosak6b817802015-01-08 02:38:14 +00002850 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002851 }
2852 void DescribeNegationTo(::std::ostream* os) const {
2853 *os << "does not equal ";
kosak6b817802015-01-08 02:38:14 +00002854 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002855 }
2856
zhanyong.wanb8243162009-06-04 05:48:20 +00002857 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002858 bool MatchAndExplain(const LhsContainer& lhs,
2859 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002860 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002861 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002862 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002863 LhsView;
2864 typedef typename LhsView::type LhsStlContainer;
2865 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
kosak6b817802015-01-08 02:38:14 +00002866 if (lhs_stl_container == expected_)
zhanyong.wane122e452010-01-12 09:03:52 +00002867 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002868
zhanyong.wane122e452010-01-12 09:03:52 +00002869 ::std::ostream* const os = listener->stream();
2870 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002871 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002872 bool printed_header = false;
2873 for (typename LhsStlContainer::const_iterator it =
2874 lhs_stl_container.begin();
2875 it != lhs_stl_container.end(); ++it) {
kosak6b817802015-01-08 02:38:14 +00002876 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
2877 expected_.end()) {
zhanyong.wane122e452010-01-12 09:03:52 +00002878 if (printed_header) {
2879 *os << ", ";
2880 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002881 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002882 printed_header = true;
2883 }
vladloseve2e8ba42010-05-13 18:16:03 +00002884 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002885 }
zhanyong.wane122e452010-01-12 09:03:52 +00002886 }
2887
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002888 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002889 bool printed_header2 = false;
kosak6b817802015-01-08 02:38:14 +00002890 for (typename StlContainer::const_iterator it = expected_.begin();
2891 it != expected_.end(); ++it) {
zhanyong.wane122e452010-01-12 09:03:52 +00002892 if (internal::ArrayAwareFind(
2893 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2894 lhs_stl_container.end()) {
2895 if (printed_header2) {
2896 *os << ", ";
2897 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002898 *os << (printed_header ? ",\nand" : "which")
2899 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002900 printed_header2 = true;
2901 }
vladloseve2e8ba42010-05-13 18:16:03 +00002902 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002903 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002904 }
2905 }
2906
zhanyong.wane122e452010-01-12 09:03:52 +00002907 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002908 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002909
zhanyong.wan6a896b52009-01-16 01:13:50 +00002910 private:
kosak6b817802015-01-08 02:38:14 +00002911 const StlContainer expected_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002912
2913 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002914};
2915
zhanyong.wan898725c2011-09-16 16:45:39 +00002916// A comparator functor that uses the < operator to compare two values.
2917struct LessComparator {
2918 template <typename T, typename U>
2919 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2920};
2921
2922// Implements WhenSortedBy(comparator, container_matcher).
2923template <typename Comparator, typename ContainerMatcher>
2924class WhenSortedByMatcher {
2925 public:
2926 WhenSortedByMatcher(const Comparator& comparator,
2927 const ContainerMatcher& matcher)
2928 : comparator_(comparator), matcher_(matcher) {}
2929
2930 template <typename LhsContainer>
2931 operator Matcher<LhsContainer>() const {
2932 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2933 }
2934
2935 template <typename LhsContainer>
2936 class Impl : public MatcherInterface<LhsContainer> {
2937 public:
2938 typedef internal::StlContainerView<
2939 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2940 typedef typename LhsView::type LhsStlContainer;
2941 typedef typename LhsView::const_reference LhsStlContainerReference;
zhanyong.wana9a59e02013-03-27 16:14:55 +00002942 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2943 // so that we can match associative containers.
2944 typedef typename RemoveConstFromKey<
2945 typename LhsStlContainer::value_type>::type LhsValue;
zhanyong.wan898725c2011-09-16 16:45:39 +00002946
2947 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2948 : comparator_(comparator), matcher_(matcher) {}
2949
2950 virtual void DescribeTo(::std::ostream* os) const {
2951 *os << "(when sorted) ";
2952 matcher_.DescribeTo(os);
2953 }
2954
2955 virtual void DescribeNegationTo(::std::ostream* os) const {
2956 *os << "(when sorted) ";
2957 matcher_.DescribeNegationTo(os);
2958 }
2959
2960 virtual bool MatchAndExplain(LhsContainer lhs,
2961 MatchResultListener* listener) const {
2962 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wanfb25d532013-07-28 08:24:00 +00002963 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2964 lhs_stl_container.end());
2965 ::std::sort(
2966 sorted_container.begin(), sorted_container.end(), comparator_);
zhanyong.wan898725c2011-09-16 16:45:39 +00002967
2968 if (!listener->IsInterested()) {
2969 // If the listener is not interested, we do not need to
2970 // construct the inner explanation.
2971 return matcher_.Matches(sorted_container);
2972 }
2973
2974 *listener << "which is ";
2975 UniversalPrint(sorted_container, listener->stream());
2976 *listener << " when sorted";
2977
2978 StringMatchResultListener inner_listener;
2979 const bool match = matcher_.MatchAndExplain(sorted_container,
2980 &inner_listener);
2981 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2982 return match;
2983 }
2984
2985 private:
2986 const Comparator comparator_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00002987 const Matcher<const ::std::vector<LhsValue>&> matcher_;
zhanyong.wan898725c2011-09-16 16:45:39 +00002988
2989 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2990 };
2991
2992 private:
2993 const Comparator comparator_;
2994 const ContainerMatcher matcher_;
2995
2996 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2997};
2998
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002999// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
3000// must be able to be safely cast to Matcher<tuple<const T1&, const
3001// T2&> >, where T1 and T2 are the types of elements in the LHS
3002// container and the RHS container respectively.
3003template <typename TupleMatcher, typename RhsContainer>
3004class PointwiseMatcher {
Gennadiy Civil23187052018-03-26 10:16:59 -04003005 GTEST_COMPILE_ASSERT_(
3006 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value,
3007 use_UnorderedPointwise_with_hash_tables);
3008
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003009 public:
3010 typedef internal::StlContainerView<RhsContainer> RhsView;
3011 typedef typename RhsView::type RhsStlContainer;
3012 typedef typename RhsStlContainer::value_type RhsValue;
3013
3014 // Like ContainerEq, we make a copy of rhs in case the elements in
3015 // it are modified after this matcher is created.
3016 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
3017 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
3018 // Makes sure the user doesn't instantiate this class template
3019 // with a const or reference type.
3020 (void)testing::StaticAssertTypeEq<RhsContainer,
3021 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
3022 }
3023
3024 template <typename LhsContainer>
3025 operator Matcher<LhsContainer>() const {
Gennadiy Civil23187052018-03-26 10:16:59 -04003026 GTEST_COMPILE_ASSERT_(
3027 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value,
3028 use_UnorderedPointwise_with_hash_tables);
3029
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003030 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
3031 }
3032
3033 template <typename LhsContainer>
3034 class Impl : public MatcherInterface<LhsContainer> {
3035 public:
3036 typedef internal::StlContainerView<
3037 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
3038 typedef typename LhsView::type LhsStlContainer;
3039 typedef typename LhsView::const_reference LhsStlContainerReference;
3040 typedef typename LhsStlContainer::value_type LhsValue;
3041 // We pass the LHS value and the RHS value to the inner matcher by
3042 // reference, as they may be expensive to copy. We must use tuple
3043 // instead of pair here, as a pair cannot hold references (C++ 98,
3044 // 20.2.2 [lib.pairs]).
kosakbd018832014-04-02 20:30:00 +00003045 typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003046
3047 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
3048 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
3049 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
3050 rhs_(rhs) {}
3051
3052 virtual void DescribeTo(::std::ostream* os) const {
3053 *os << "contains " << rhs_.size()
3054 << " values, where each value and its corresponding value in ";
3055 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
3056 *os << " ";
3057 mono_tuple_matcher_.DescribeTo(os);
3058 }
3059 virtual void DescribeNegationTo(::std::ostream* os) const {
3060 *os << "doesn't contain exactly " << rhs_.size()
3061 << " values, or contains a value x at some index i"
3062 << " where x and the i-th value of ";
3063 UniversalPrint(rhs_, os);
3064 *os << " ";
3065 mono_tuple_matcher_.DescribeNegationTo(os);
3066 }
3067
3068 virtual bool MatchAndExplain(LhsContainer lhs,
3069 MatchResultListener* listener) const {
3070 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
3071 const size_t actual_size = lhs_stl_container.size();
3072 if (actual_size != rhs_.size()) {
3073 *listener << "which contains " << actual_size << " values";
3074 return false;
3075 }
3076
3077 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
3078 typename RhsStlContainer::const_iterator right = rhs_.begin();
3079 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003080 if (listener->IsInterested()) {
3081 StringMatchResultListener inner_listener;
Gennadiy Civil23187052018-03-26 10:16:59 -04003082 // Create InnerMatcherArg as a temporarily object to avoid it outlives
3083 // *left and *right. Dereference or the conversion to `const T&` may
3084 // return temp objects, e.g for vector<bool>.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003085 if (!mono_tuple_matcher_.MatchAndExplain(
Gennadiy Civil23187052018-03-26 10:16:59 -04003086 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
3087 ImplicitCast_<const RhsValue&>(*right)),
3088 &inner_listener)) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003089 *listener << "where the value pair (";
3090 UniversalPrint(*left, listener->stream());
3091 *listener << ", ";
3092 UniversalPrint(*right, listener->stream());
3093 *listener << ") at index #" << i << " don't match";
3094 PrintIfNotEmpty(inner_listener.str(), listener->stream());
3095 return false;
3096 }
3097 } else {
Gennadiy Civil23187052018-03-26 10:16:59 -04003098 if (!mono_tuple_matcher_.Matches(
3099 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
3100 ImplicitCast_<const RhsValue&>(*right))))
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003101 return false;
3102 }
3103 }
3104
3105 return true;
3106 }
3107
3108 private:
3109 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
3110 const RhsStlContainer rhs_;
3111
3112 GTEST_DISALLOW_ASSIGN_(Impl);
3113 };
3114
3115 private:
3116 const TupleMatcher tuple_matcher_;
3117 const RhsStlContainer rhs_;
3118
3119 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
3120};
3121
zhanyong.wan33605ba2010-04-22 23:37:47 +00003122// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00003123template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00003124class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00003125 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003126 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00003127 typedef StlContainerView<RawContainer> View;
3128 typedef typename View::type StlContainer;
3129 typedef typename View::const_reference StlContainerReference;
3130 typedef typename StlContainer::value_type Element;
3131
3132 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00003133 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00003134 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00003135 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00003136
zhanyong.wan33605ba2010-04-22 23:37:47 +00003137 // Checks whether:
3138 // * All elements in the container match, if all_elements_should_match.
3139 // * Any element in the container matches, if !all_elements_should_match.
3140 bool MatchAndExplainImpl(bool all_elements_should_match,
3141 Container container,
3142 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00003143 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00003144 size_t i = 0;
3145 for (typename StlContainer::const_iterator it = stl_container.begin();
3146 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003147 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00003148 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
3149
3150 if (matches != all_elements_should_match) {
3151 *listener << "whose element #" << i
3152 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003153 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00003154 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00003155 }
3156 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00003157 return all_elements_should_match;
3158 }
3159
3160 protected:
3161 const Matcher<const Element&> inner_matcher_;
3162
3163 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
3164};
3165
3166// Implements Contains(element_matcher) for the given argument type Container.
3167// Symmetric to EachMatcherImpl.
3168template <typename Container>
3169class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
3170 public:
3171 template <typename InnerMatcher>
3172 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
3173 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3174
3175 // Describes what this matcher does.
3176 virtual void DescribeTo(::std::ostream* os) const {
3177 *os << "contains at least one element that ";
3178 this->inner_matcher_.DescribeTo(os);
3179 }
3180
3181 virtual void DescribeNegationTo(::std::ostream* os) const {
3182 *os << "doesn't contain any element that ";
3183 this->inner_matcher_.DescribeTo(os);
3184 }
3185
3186 virtual bool MatchAndExplain(Container container,
3187 MatchResultListener* listener) const {
3188 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00003189 }
3190
3191 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003192 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00003193};
3194
zhanyong.wan33605ba2010-04-22 23:37:47 +00003195// Implements Each(element_matcher) for the given argument type Container.
3196// Symmetric to ContainsMatcherImpl.
3197template <typename Container>
3198class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
3199 public:
3200 template <typename InnerMatcher>
3201 explicit EachMatcherImpl(InnerMatcher inner_matcher)
3202 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3203
3204 // Describes what this matcher does.
3205 virtual void DescribeTo(::std::ostream* os) const {
3206 *os << "only contains elements that ";
3207 this->inner_matcher_.DescribeTo(os);
3208 }
3209
3210 virtual void DescribeNegationTo(::std::ostream* os) const {
3211 *os << "contains some element that ";
3212 this->inner_matcher_.DescribeNegationTo(os);
3213 }
3214
3215 virtual bool MatchAndExplain(Container container,
3216 MatchResultListener* listener) const {
3217 return this->MatchAndExplainImpl(true, container, listener);
3218 }
3219
3220 private:
3221 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
3222};
3223
zhanyong.wanb8243162009-06-04 05:48:20 +00003224// Implements polymorphic Contains(element_matcher).
3225template <typename M>
3226class ContainsMatcher {
3227 public:
3228 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
3229
3230 template <typename Container>
3231 operator Matcher<Container>() const {
3232 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
3233 }
3234
3235 private:
3236 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003237
3238 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00003239};
3240
zhanyong.wan33605ba2010-04-22 23:37:47 +00003241// Implements polymorphic Each(element_matcher).
3242template <typename M>
3243class EachMatcher {
3244 public:
3245 explicit EachMatcher(M m) : inner_matcher_(m) {}
3246
3247 template <typename Container>
3248 operator Matcher<Container>() const {
3249 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
3250 }
3251
3252 private:
3253 const M inner_matcher_;
3254
3255 GTEST_DISALLOW_ASSIGN_(EachMatcher);
3256};
3257
Gennadiy Civil466a49a2018-03-23 11:23:54 -04003258struct Rank1 {};
3259struct Rank0 : Rank1 {};
3260
3261namespace pair_getters {
3262#if GTEST_LANG_CXX11
3263using std::get;
3264template <typename T>
3265auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT
3266 return get<0>(x);
3267}
3268template <typename T>
3269auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT
3270 return x.first;
3271}
3272
3273template <typename T>
3274auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT
3275 return get<1>(x);
3276}
3277template <typename T>
3278auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT
3279 return x.second;
3280}
3281#else
3282template <typename T>
3283typename T::first_type& First(T& x, Rank0) { // NOLINT
3284 return x.first;
3285}
3286template <typename T>
3287const typename T::first_type& First(const T& x, Rank0) {
3288 return x.first;
3289}
3290
3291template <typename T>
3292typename T::second_type& Second(T& x, Rank0) { // NOLINT
3293 return x.second;
3294}
3295template <typename T>
3296const typename T::second_type& Second(const T& x, Rank0) {
3297 return x.second;
3298}
3299#endif // GTEST_LANG_CXX11
3300} // namespace pair_getters
3301
zhanyong.wanb5937da2009-07-16 20:26:41 +00003302// Implements Key(inner_matcher) for the given argument pair type.
3303// Key(inner_matcher) matches an std::pair whose 'first' field matches
3304// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3305// std::map that contains at least one element whose key is >= 5.
3306template <typename PairType>
3307class KeyMatcherImpl : public MatcherInterface<PairType> {
3308 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003309 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00003310 typedef typename RawPairType::first_type KeyType;
3311
3312 template <typename InnerMatcher>
3313 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
3314 : inner_matcher_(
3315 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
3316 }
3317
3318 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00003319 virtual bool MatchAndExplain(PairType key_value,
3320 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003321 StringMatchResultListener inner_listener;
Gennadiy Civil23187052018-03-26 10:16:59 -04003322 const bool match = inner_matcher_.MatchAndExplain(
3323 pair_getters::First(key_value, Rank0()), &inner_listener);
Nico Weber09fd5b32017-05-15 17:07:03 -04003324 const std::string explanation = inner_listener.str();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003325 if (explanation != "") {
3326 *listener << "whose first field is a value " << explanation;
3327 }
3328 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00003329 }
3330
3331 // Describes what this matcher does.
3332 virtual void DescribeTo(::std::ostream* os) const {
3333 *os << "has a key that ";
3334 inner_matcher_.DescribeTo(os);
3335 }
3336
3337 // Describes what the negation of this matcher does.
3338 virtual void DescribeNegationTo(::std::ostream* os) const {
3339 *os << "doesn't have a key that ";
3340 inner_matcher_.DescribeTo(os);
3341 }
3342
zhanyong.wanb5937da2009-07-16 20:26:41 +00003343 private:
3344 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003345
3346 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00003347};
3348
3349// Implements polymorphic Key(matcher_for_key).
3350template <typename M>
3351class KeyMatcher {
3352 public:
3353 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
3354
3355 template <typename PairType>
3356 operator Matcher<PairType>() const {
3357 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
3358 }
3359
3360 private:
3361 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003362
3363 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00003364};
3365
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003366// Implements Pair(first_matcher, second_matcher) for the given argument pair
3367// type with its two matchers. See Pair() function below.
3368template <typename PairType>
3369class PairMatcherImpl : public MatcherInterface<PairType> {
3370 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003371 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003372 typedef typename RawPairType::first_type FirstType;
3373 typedef typename RawPairType::second_type SecondType;
3374
3375 template <typename FirstMatcher, typename SecondMatcher>
3376 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
3377 : first_matcher_(
3378 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
3379 second_matcher_(
3380 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
3381 }
3382
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003383 // Describes what this matcher does.
3384 virtual void DescribeTo(::std::ostream* os) const {
3385 *os << "has a first field that ";
3386 first_matcher_.DescribeTo(os);
3387 *os << ", and has a second field that ";
3388 second_matcher_.DescribeTo(os);
3389 }
3390
3391 // Describes what the negation of this matcher does.
3392 virtual void DescribeNegationTo(::std::ostream* os) const {
3393 *os << "has a first field that ";
3394 first_matcher_.DescribeNegationTo(os);
3395 *os << ", or has a second field that ";
3396 second_matcher_.DescribeNegationTo(os);
3397 }
3398
zhanyong.wan82113312010-01-08 21:55:40 +00003399 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3400 // matches second_matcher.
3401 virtual bool MatchAndExplain(PairType a_pair,
3402 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003403 if (!listener->IsInterested()) {
3404 // If the listener is not interested, we don't need to construct the
3405 // explanation.
Gennadiy Civil6aae2062018-03-26 10:36:26 -04003406 return first_matcher_.Matches(pair_getters::First(a_pair, Rank0())) &&
3407 second_matcher_.Matches(pair_getters::Second(a_pair, Rank0()));
zhanyong.wan82113312010-01-08 21:55:40 +00003408 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003409 StringMatchResultListener first_inner_listener;
Gennadiy Civil6aae2062018-03-26 10:36:26 -04003410 if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank0()),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003411 &first_inner_listener)) {
3412 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003413 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003414 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003415 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003416 StringMatchResultListener second_inner_listener;
Gennadiy Civil6aae2062018-03-26 10:36:26 -04003417 if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank0()),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003418 &second_inner_listener)) {
3419 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003420 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003421 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003422 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003423 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3424 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00003425 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003426 }
3427
3428 private:
Nico Weber09fd5b32017-05-15 17:07:03 -04003429 void ExplainSuccess(const std::string& first_explanation,
3430 const std::string& second_explanation,
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003431 MatchResultListener* listener) const {
3432 *listener << "whose both fields match";
3433 if (first_explanation != "") {
3434 *listener << ", where the first field is a value " << first_explanation;
3435 }
3436 if (second_explanation != "") {
3437 *listener << ", ";
3438 if (first_explanation != "") {
3439 *listener << "and ";
3440 } else {
3441 *listener << "where ";
3442 }
3443 *listener << "the second field is a value " << second_explanation;
3444 }
3445 }
3446
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003447 const Matcher<const FirstType&> first_matcher_;
3448 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003449
3450 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003451};
3452
3453// Implements polymorphic Pair(first_matcher, second_matcher).
3454template <typename FirstMatcher, typename SecondMatcher>
3455class PairMatcher {
3456 public:
3457 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3458 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3459
3460 template <typename PairType>
3461 operator Matcher<PairType> () const {
3462 return MakeMatcher(
3463 new PairMatcherImpl<PairType>(
3464 first_matcher_, second_matcher_));
3465 }
3466
3467 private:
3468 const FirstMatcher first_matcher_;
3469 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003470
3471 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003472};
3473
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003474// Implements ElementsAre() and ElementsAreArray().
3475template <typename Container>
3476class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3477 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003478 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003479 typedef internal::StlContainerView<RawContainer> View;
3480 typedef typename View::type StlContainer;
3481 typedef typename View::const_reference StlContainerReference;
3482 typedef typename StlContainer::value_type Element;
3483
3484 // Constructs the matcher from a sequence of element values or
3485 // element matchers.
3486 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00003487 ElementsAreMatcherImpl(InputIter first, InputIter last) {
3488 while (first != last) {
3489 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003490 }
3491 }
3492
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003493 // Describes what this matcher does.
3494 virtual void DescribeTo(::std::ostream* os) const {
3495 if (count() == 0) {
3496 *os << "is empty";
3497 } else if (count() == 1) {
3498 *os << "has 1 element that ";
3499 matchers_[0].DescribeTo(os);
3500 } else {
3501 *os << "has " << Elements(count()) << " where\n";
3502 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003503 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003504 matchers_[i].DescribeTo(os);
3505 if (i + 1 < count()) {
3506 *os << ",\n";
3507 }
3508 }
3509 }
3510 }
3511
3512 // Describes what the negation of this matcher does.
3513 virtual void DescribeNegationTo(::std::ostream* os) const {
3514 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003515 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003516 return;
3517 }
3518
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003519 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003520 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003521 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003522 matchers_[i].DescribeNegationTo(os);
3523 if (i + 1 < count()) {
3524 *os << ", or\n";
3525 }
3526 }
3527 }
3528
zhanyong.wan82113312010-01-08 21:55:40 +00003529 virtual bool MatchAndExplain(Container container,
3530 MatchResultListener* listener) const {
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003531 // To work with stream-like "containers", we must only walk
3532 // through the elements in one pass.
3533
3534 const bool listener_interested = listener->IsInterested();
3535
3536 // explanations[i] is the explanation of the element at index i.
Nico Weber09fd5b32017-05-15 17:07:03 -04003537 ::std::vector<std::string> explanations(count());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003538 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003539 typename StlContainer::const_iterator it = stl_container.begin();
3540 size_t exam_pos = 0;
3541 bool mismatch_found = false; // Have we found a mismatched element yet?
3542
3543 // Go through the elements and matchers in pairs, until we reach
3544 // the end of either the elements or the matchers, or until we find a
3545 // mismatch.
3546 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3547 bool match; // Does the current element match the current matcher?
3548 if (listener_interested) {
3549 StringMatchResultListener s;
3550 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3551 explanations[exam_pos] = s.str();
3552 } else {
3553 match = matchers_[exam_pos].Matches(*it);
3554 }
3555
3556 if (!match) {
3557 mismatch_found = true;
3558 break;
3559 }
3560 }
3561 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3562
3563 // Find how many elements the actual container has. We avoid
3564 // calling size() s.t. this code works for stream-like "containers"
3565 // that don't define size().
3566 size_t actual_count = exam_pos;
3567 for (; it != stl_container.end(); ++it) {
3568 ++actual_count;
3569 }
3570
zhanyong.wan82113312010-01-08 21:55:40 +00003571 if (actual_count != count()) {
3572 // The element count doesn't match. If the container is empty,
3573 // there's no need to explain anything as Google Mock already
3574 // prints the empty container. Otherwise we just need to show
3575 // how many elements there actually are.
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003576 if (listener_interested && (actual_count != 0)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003577 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003578 }
zhanyong.wan82113312010-01-08 21:55:40 +00003579 return false;
3580 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003581
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003582 if (mismatch_found) {
3583 // The element count matches, but the exam_pos-th element doesn't match.
3584 if (listener_interested) {
3585 *listener << "whose element #" << exam_pos << " doesn't match";
3586 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003587 }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003588 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003589 }
zhanyong.wan82113312010-01-08 21:55:40 +00003590
3591 // Every element matches its expectation. We need to explain why
3592 // (the obvious ones can be skipped).
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003593 if (listener_interested) {
3594 bool reason_printed = false;
3595 for (size_t i = 0; i != count(); ++i) {
Nico Weber09fd5b32017-05-15 17:07:03 -04003596 const std::string& s = explanations[i];
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003597 if (!s.empty()) {
3598 if (reason_printed) {
3599 *listener << ",\nand ";
3600 }
3601 *listener << "whose element #" << i << " matches, " << s;
3602 reason_printed = true;
zhanyong.wan82113312010-01-08 21:55:40 +00003603 }
zhanyong.wan82113312010-01-08 21:55:40 +00003604 }
3605 }
zhanyong.wan82113312010-01-08 21:55:40 +00003606 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003607 }
3608
3609 private:
3610 static Message Elements(size_t count) {
3611 return Message() << count << (count == 1 ? " element" : " elements");
3612 }
3613
3614 size_t count() const { return matchers_.size(); }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003615
3616 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003617
3618 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003619};
3620
zhanyong.wanfb25d532013-07-28 08:24:00 +00003621// Connectivity matrix of (elements X matchers), in element-major order.
3622// Initially, there are no edges.
3623// Use NextGraph() to iterate over all possible edge configurations.
3624// Use Randomize() to generate a random edge configuration.
3625class GTEST_API_ MatchMatrix {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003626 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003627 MatchMatrix(size_t num_elements, size_t num_matchers)
3628 : num_elements_(num_elements),
3629 num_matchers_(num_matchers),
3630 matched_(num_elements_* num_matchers_, 0) {
3631 }
3632
3633 size_t LhsSize() const { return num_elements_; }
3634 size_t RhsSize() const { return num_matchers_; }
3635 bool HasEdge(size_t ilhs, size_t irhs) const {
3636 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3637 }
3638 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3639 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3640 }
3641
3642 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3643 // adds 1 to that number; returns false if incrementing the graph left it
3644 // empty.
3645 bool NextGraph();
3646
3647 void Randomize();
3648
Nico Weber09fd5b32017-05-15 17:07:03 -04003649 std::string DebugString() const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003650
3651 private:
3652 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3653 return ilhs * num_matchers_ + irhs;
3654 }
3655
3656 size_t num_elements_;
3657 size_t num_matchers_;
3658
3659 // Each element is a char interpreted as bool. They are stored as a
3660 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3661 // a (ilhs, irhs) matrix coordinate into an offset.
3662 ::std::vector<char> matched_;
3663};
3664
3665typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3666typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3667
3668// Returns a maximum bipartite matching for the specified graph 'g'.
3669// The matching is represented as a vector of {element, matcher} pairs.
3670GTEST_API_ ElementMatcherPairs
3671FindMaxBipartiteMatching(const MatchMatrix& g);
3672
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003673struct UnorderedMatcherRequire {
3674 enum Flags {
3675 Superset = 1 << 0,
3676 Subset = 1 << 1,
3677 ExactMatch = Superset | Subset,
3678 };
3679};
zhanyong.wanfb25d532013-07-28 08:24:00 +00003680
3681// Untyped base class for implementing UnorderedElementsAre. By
3682// putting logic that's not specific to the element type here, we
3683// reduce binary bloat and increase compilation speed.
3684class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3685 protected:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003686 explicit UnorderedElementsAreMatcherImplBase(
3687 UnorderedMatcherRequire::Flags matcher_flags)
3688 : match_flags_(matcher_flags) {}
3689
zhanyong.wanfb25d532013-07-28 08:24:00 +00003690 // A vector of matcher describers, one for each element matcher.
3691 // Does not own the describers (and thus can be used only when the
3692 // element matchers are alive).
3693 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3694
3695 // Describes this UnorderedElementsAre matcher.
3696 void DescribeToImpl(::std::ostream* os) const;
3697
3698 // Describes the negation of this UnorderedElementsAre matcher.
3699 void DescribeNegationToImpl(::std::ostream* os) const;
3700
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003701 bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,
3702 const MatchMatrix& matrix,
3703 MatchResultListener* listener) const;
3704
3705 bool FindPairing(const MatchMatrix& matrix,
3706 MatchResultListener* listener) const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003707
3708 MatcherDescriberVec& matcher_describers() {
3709 return matcher_describers_;
3710 }
3711
3712 static Message Elements(size_t n) {
3713 return Message() << n << " element" << (n == 1 ? "" : "s");
3714 }
3715
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003716 UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }
3717
zhanyong.wanfb25d532013-07-28 08:24:00 +00003718 private:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003719 UnorderedMatcherRequire::Flags match_flags_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003720 MatcherDescriberVec matcher_describers_;
3721
3722 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3723};
3724
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003725// Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
3726// IsSupersetOf.
zhanyong.wanfb25d532013-07-28 08:24:00 +00003727template <typename Container>
3728class UnorderedElementsAreMatcherImpl
3729 : public MatcherInterface<Container>,
3730 public UnorderedElementsAreMatcherImplBase {
3731 public:
3732 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3733 typedef internal::StlContainerView<RawContainer> View;
3734 typedef typename View::type StlContainer;
3735 typedef typename View::const_reference StlContainerReference;
3736 typedef typename StlContainer::const_iterator StlContainerConstIterator;
3737 typedef typename StlContainer::value_type Element;
3738
zhanyong.wanfb25d532013-07-28 08:24:00 +00003739 template <typename InputIter>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003740 UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,
3741 InputIter first, InputIter last)
3742 : UnorderedElementsAreMatcherImplBase(matcher_flags) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00003743 for (; first != last; ++first) {
3744 matchers_.push_back(MatcherCast<const Element&>(*first));
3745 matcher_describers().push_back(matchers_.back().GetDescriber());
3746 }
3747 }
3748
3749 // Describes what this matcher does.
3750 virtual void DescribeTo(::std::ostream* os) const {
3751 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3752 }
3753
3754 // Describes what the negation of this matcher does.
3755 virtual void DescribeNegationTo(::std::ostream* os) const {
3756 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3757 }
3758
3759 virtual bool MatchAndExplain(Container container,
3760 MatchResultListener* listener) const {
3761 StlContainerReference stl_container = View::ConstReference(container);
Nico Weber09fd5b32017-05-15 17:07:03 -04003762 ::std::vector<std::string> element_printouts;
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003763 MatchMatrix matrix =
3764 AnalyzeElements(stl_container.begin(), stl_container.end(),
3765 &element_printouts, listener);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003766
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003767 if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00003768 return true;
3769 }
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003770
3771 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
3772 if (matrix.LhsSize() != matrix.RhsSize()) {
3773 // The element count doesn't match. If the container is empty,
3774 // there's no need to explain anything as Google Mock already
3775 // prints the empty container. Otherwise we just need to show
3776 // how many elements there actually are.
3777 if (matrix.LhsSize() != 0 && listener->IsInterested()) {
3778 *listener << "which has " << Elements(matrix.LhsSize());
3779 }
3780 return false;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003781 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003782 }
3783
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003784 return VerifyMatchMatrix(element_printouts, matrix, listener) &&
zhanyong.wanfb25d532013-07-28 08:24:00 +00003785 FindPairing(matrix, listener);
3786 }
3787
3788 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003789 template <typename ElementIter>
3790 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
Nico Weber09fd5b32017-05-15 17:07:03 -04003791 ::std::vector<std::string>* element_printouts,
zhanyong.wanfb25d532013-07-28 08:24:00 +00003792 MatchResultListener* listener) const {
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003793 element_printouts->clear();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003794 ::std::vector<char> did_match;
3795 size_t num_elements = 0;
3796 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3797 if (listener->IsInterested()) {
3798 element_printouts->push_back(PrintToString(*elem_first));
3799 }
3800 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3801 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3802 }
3803 }
3804
3805 MatchMatrix matrix(num_elements, matchers_.size());
3806 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3807 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3808 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3809 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3810 }
3811 }
3812 return matrix;
3813 }
3814
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003815 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003816
3817 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3818};
3819
3820// Functor for use in TransformTuple.
3821// Performs MatcherCast<Target> on an input argument of any type.
3822template <typename Target>
3823struct CastAndAppendTransform {
3824 template <typename Arg>
3825 Matcher<Target> operator()(const Arg& a) const {
3826 return MatcherCast<Target>(a);
3827 }
3828};
3829
3830// Implements UnorderedElementsAre.
3831template <typename MatcherTuple>
3832class UnorderedElementsAreMatcher {
3833 public:
3834 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3835 : matchers_(args) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003836
3837 template <typename Container>
3838 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003839 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003840 typedef typename internal::StlContainerView<RawContainer>::type View;
3841 typedef typename View::value_type Element;
3842 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3843 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003844 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003845 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3846 ::std::back_inserter(matchers));
3847 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003848 UnorderedMatcherRequire::ExactMatch, matchers.begin(), matchers.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003849 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003850
3851 private:
3852 const MatcherTuple matchers_;
3853 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3854};
3855
3856// Implements ElementsAre.
3857template <typename MatcherTuple>
3858class ElementsAreMatcher {
3859 public:
3860 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3861
3862 template <typename Container>
3863 operator Matcher<Container>() const {
Gennadiy Civil23187052018-03-26 10:16:59 -04003864 GTEST_COMPILE_ASSERT_(
3865 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value ||
3866 ::testing::tuple_size<MatcherTuple>::value < 2,
3867 use_UnorderedElementsAre_with_hash_tables);
3868
zhanyong.wanfb25d532013-07-28 08:24:00 +00003869 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3870 typedef typename internal::StlContainerView<RawContainer>::type View;
3871 typedef typename View::value_type Element;
3872 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3873 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003874 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003875 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3876 ::std::back_inserter(matchers));
3877 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3878 matchers.begin(), matchers.end()));
3879 }
3880
3881 private:
3882 const MatcherTuple matchers_;
3883 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3884};
3885
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003886// Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
zhanyong.wanfb25d532013-07-28 08:24:00 +00003887template <typename T>
3888class UnorderedElementsAreArrayMatcher {
3889 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003890 template <typename Iter>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003891 UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,
3892 Iter first, Iter last)
3893 : match_flags_(match_flags), matchers_(first, last) {}
zhanyong.wanfb25d532013-07-28 08:24:00 +00003894
3895 template <typename Container>
3896 operator Matcher<Container>() const {
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003897 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3898 match_flags_, matchers_.begin(), matchers_.end()));
zhanyong.wanfb25d532013-07-28 08:24:00 +00003899 }
3900
3901 private:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003902 UnorderedMatcherRequire::Flags match_flags_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003903 ::std::vector<T> matchers_;
3904
3905 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003906};
3907
3908// Implements ElementsAreArray().
3909template <typename T>
3910class ElementsAreArrayMatcher {
3911 public:
jgm38513a82012-11-15 15:50:36 +00003912 template <typename Iter>
3913 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003914
3915 template <typename Container>
3916 operator Matcher<Container>() const {
Gennadiy Civil23187052018-03-26 10:16:59 -04003917 GTEST_COMPILE_ASSERT_(
3918 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value,
3919 use_UnorderedElementsAreArray_with_hash_tables);
3920
jgm38513a82012-11-15 15:50:36 +00003921 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3922 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003923 }
3924
3925 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003926 const ::std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003927
3928 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003929};
3930
kosak2336e9c2014-07-28 22:57:30 +00003931// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3932// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3933// second) is a polymorphic matcher that matches a value x iff tm
3934// matches tuple (x, second). Useful for implementing
3935// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3936//
3937// BoundSecondMatcher is copyable and assignable, as we need to put
3938// instances of this class in a vector when implementing
3939// UnorderedPointwise().
3940template <typename Tuple2Matcher, typename Second>
3941class BoundSecondMatcher {
3942 public:
3943 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3944 : tuple2_matcher_(tm), second_value_(second) {}
3945
3946 template <typename T>
3947 operator Matcher<T>() const {
3948 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3949 }
3950
3951 // We have to define this for UnorderedPointwise() to compile in
3952 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3953 // which requires the elements to be assignable in C++98. The
3954 // compiler cannot generate the operator= for us, as Tuple2Matcher
3955 // and Second may not be assignable.
3956 //
3957 // However, this should never be called, so the implementation just
3958 // need to assert.
3959 void operator=(const BoundSecondMatcher& /*rhs*/) {
3960 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3961 }
3962
3963 private:
3964 template <typename T>
3965 class Impl : public MatcherInterface<T> {
3966 public:
3967 typedef ::testing::tuple<T, Second> ArgTuple;
3968
3969 Impl(const Tuple2Matcher& tm, const Second& second)
3970 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3971 second_value_(second) {}
3972
3973 virtual void DescribeTo(::std::ostream* os) const {
3974 *os << "and ";
3975 UniversalPrint(second_value_, os);
3976 *os << " ";
3977 mono_tuple2_matcher_.DescribeTo(os);
3978 }
3979
3980 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3981 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3982 listener);
3983 }
3984
3985 private:
3986 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3987 const Second second_value_;
3988
3989 GTEST_DISALLOW_ASSIGN_(Impl);
3990 };
3991
3992 const Tuple2Matcher tuple2_matcher_;
3993 const Second second_value_;
3994};
3995
3996// Given a 2-tuple matcher tm and a value second,
3997// MatcherBindSecond(tm, second) returns a matcher that matches a
3998// value x iff tm matches tuple (x, second). Useful for implementing
3999// UnorderedPointwise() in terms of UnorderedElementsAreArray().
4000template <typename Tuple2Matcher, typename Second>
4001BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
4002 const Tuple2Matcher& tm, const Second& second) {
4003 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
4004}
4005
zhanyong.wanb4140802010-06-08 22:53:57 +00004006// Returns the description for a matcher defined using the MATCHER*()
4007// macro where the user-supplied description string is "", if
4008// 'negation' is false; otherwise returns the description of the
4009// negation of the matcher. 'param_values' contains a list of strings
4010// that are the print-out of the matcher's parameters.
Nico Weber09fd5b32017-05-15 17:07:03 -04004011GTEST_API_ std::string FormatMatcherDescription(bool negation,
4012 const char* matcher_name,
4013 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00004014
Gennadiy Civilb907c262018-03-23 11:42:41 -04004015// Implements a matcher that checks the value of a optional<> type variable.
4016template <typename ValueMatcher>
4017class OptionalMatcher {
4018 public:
4019 explicit OptionalMatcher(const ValueMatcher& value_matcher)
4020 : value_matcher_(value_matcher) {}
4021
4022 template <typename Optional>
4023 operator Matcher<Optional>() const {
4024 return MakeMatcher(new Impl<Optional>(value_matcher_));
4025 }
4026
4027 template <typename Optional>
4028 class Impl : public MatcherInterface<Optional> {
4029 public:
4030 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView;
4031 typedef typename OptionalView::value_type ValueType;
4032 explicit Impl(const ValueMatcher& value_matcher)
4033 : value_matcher_(MatcherCast<ValueType>(value_matcher)) {}
4034
4035 virtual void DescribeTo(::std::ostream* os) const {
4036 *os << "value ";
4037 value_matcher_.DescribeTo(os);
4038 }
4039
4040 virtual void DescribeNegationTo(::std::ostream* os) const {
4041 *os << "value ";
4042 value_matcher_.DescribeNegationTo(os);
4043 }
4044
4045 virtual bool MatchAndExplain(Optional optional,
4046 MatchResultListener* listener) const {
4047 if (!optional) {
4048 *listener << "which is not engaged";
4049 return false;
4050 }
4051 const ValueType& value = *optional;
4052 StringMatchResultListener value_listener;
4053 const bool match = value_matcher_.MatchAndExplain(value, &value_listener);
4054 *listener << "whose value " << PrintToString(value)
4055 << (match ? " matches" : " doesn't match");
4056 PrintIfNotEmpty(value_listener.str(), listener->stream());
4057 return match;
4058 }
4059
4060 private:
4061 const Matcher<ValueType> value_matcher_;
4062 GTEST_DISALLOW_ASSIGN_(Impl);
4063 };
4064
4065 private:
4066 const ValueMatcher value_matcher_;
4067 GTEST_DISALLOW_ASSIGN_(OptionalMatcher);
4068};
4069
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05004070namespace variant_matcher {
4071// Overloads to allow VariantMatcher to do proper ADL lookup.
4072template <typename T>
4073void holds_alternative() {}
4074template <typename T>
4075void get() {}
4076
4077// Implements a matcher that checks the value of a variant<> type variable.
4078template <typename T>
4079class VariantMatcher {
4080 public:
4081 explicit VariantMatcher(::testing::Matcher<const T&> matcher)
4082 : matcher_(internal::move(matcher)) {}
4083
4084 template <typename Variant>
4085 bool MatchAndExplain(const Variant& value,
4086 ::testing::MatchResultListener* listener) const {
4087 if (!listener->IsInterested()) {
4088 return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));
4089 }
4090
4091 if (!holds_alternative<T>(value)) {
4092 *listener << "whose value is not of type '" << GetTypeName() << "'";
4093 return false;
4094 }
4095
4096 const T& elem = get<T>(value);
4097 StringMatchResultListener elem_listener;
4098 const bool match = matcher_.MatchAndExplain(elem, &elem_listener);
4099 *listener << "whose value " << PrintToString(elem)
4100 << (match ? " matches" : " doesn't match");
4101 PrintIfNotEmpty(elem_listener.str(), listener->stream());
4102 return match;
4103 }
4104
4105 void DescribeTo(std::ostream* os) const {
4106 *os << "is a variant<> with value of type '" << GetTypeName()
4107 << "' and the value ";
4108 matcher_.DescribeTo(os);
4109 }
4110
4111 void DescribeNegationTo(std::ostream* os) const {
4112 *os << "is a variant<> with value of type other than '" << GetTypeName()
4113 << "' or the value ";
4114 matcher_.DescribeNegationTo(os);
4115 }
4116
4117 private:
Gennadiy Civil23187052018-03-26 10:16:59 -04004118 static std::string GetTypeName() {
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05004119#if GTEST_HAS_RTTI
Gennadiy Civilab84d142018-04-11 15:24:04 -04004120 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
4121 return internal::GetTypeName<T>());
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05004122#endif
4123 return "the element type";
4124 }
4125
4126 const ::testing::Matcher<const T&> matcher_;
4127};
4128
4129} // namespace variant_matcher
4130
Gennadiy Civil466a49a2018-03-23 11:23:54 -04004131namespace any_cast_matcher {
4132
4133// Overloads to allow AnyCastMatcher to do proper ADL lookup.
4134template <typename T>
4135void any_cast() {}
4136
4137// Implements a matcher that any_casts the value.
4138template <typename T>
4139class AnyCastMatcher {
4140 public:
4141 explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher)
4142 : matcher_(matcher) {}
4143
4144 template <typename AnyType>
4145 bool MatchAndExplain(const AnyType& value,
4146 ::testing::MatchResultListener* listener) const {
4147 if (!listener->IsInterested()) {
4148 const T* ptr = any_cast<T>(&value);
4149 return ptr != NULL && matcher_.Matches(*ptr);
4150 }
4151
4152 const T* elem = any_cast<T>(&value);
4153 if (elem == NULL) {
4154 *listener << "whose value is not of type '" << GetTypeName() << "'";
4155 return false;
4156 }
4157
4158 StringMatchResultListener elem_listener;
4159 const bool match = matcher_.MatchAndExplain(*elem, &elem_listener);
4160 *listener << "whose value " << PrintToString(*elem)
4161 << (match ? " matches" : " doesn't match");
4162 PrintIfNotEmpty(elem_listener.str(), listener->stream());
4163 return match;
4164 }
4165
4166 void DescribeTo(std::ostream* os) const {
4167 *os << "is an 'any' type with value of type '" << GetTypeName()
4168 << "' and the value ";
4169 matcher_.DescribeTo(os);
4170 }
4171
4172 void DescribeNegationTo(std::ostream* os) const {
4173 *os << "is an 'any' type with value of type other than '" << GetTypeName()
4174 << "' or the value ";
4175 matcher_.DescribeNegationTo(os);
4176 }
4177
4178 private:
4179 static std::string GetTypeName() {
4180#if GTEST_HAS_RTTI
Gennadiy Civilab84d142018-04-11 15:24:04 -04004181 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
4182 return internal::GetTypeName<T>());
Gennadiy Civil466a49a2018-03-23 11:23:54 -04004183#endif
4184 return "the element type";
4185 }
4186
4187 const ::testing::Matcher<const T&> matcher_;
4188};
4189
4190} // namespace any_cast_matcher
shiqiane35fdd92008-12-10 05:08:54 +00004191} // namespace internal
4192
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004193// ElementsAreArray(iterator_first, iterator_last)
zhanyong.wanfb25d532013-07-28 08:24:00 +00004194// ElementsAreArray(pointer, count)
4195// ElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00004196// ElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004197// ElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00004198//
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004199// The ElementsAreArray() functions are like ElementsAre(...), except
4200// that they are given a homogeneous sequence rather than taking each
4201// element as a function argument. The sequence can be specified as an
4202// array, a pointer and count, a vector, an initializer list, or an
4203// STL iterator range. In each of these cases, the underlying sequence
4204// can be either a sequence of values or a sequence of matchers.
zhanyong.wanfb25d532013-07-28 08:24:00 +00004205//
4206// All forms of ElementsAreArray() make a copy of the input matcher sequence.
4207
4208template <typename Iter>
4209inline internal::ElementsAreArrayMatcher<
4210 typename ::std::iterator_traits<Iter>::value_type>
4211ElementsAreArray(Iter first, Iter last) {
4212 typedef typename ::std::iterator_traits<Iter>::value_type T;
4213 return internal::ElementsAreArrayMatcher<T>(first, last);
4214}
4215
4216template <typename T>
4217inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
4218 const T* pointer, size_t count) {
4219 return ElementsAreArray(pointer, pointer + count);
4220}
4221
4222template <typename T, size_t N>
4223inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
4224 const T (&array)[N]) {
4225 return ElementsAreArray(array, N);
4226}
4227
kosak06678922014-07-28 20:01:28 +00004228template <typename Container>
4229inline internal::ElementsAreArrayMatcher<typename Container::value_type>
4230ElementsAreArray(const Container& container) {
4231 return ElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00004232}
4233
kosak18489fa2013-12-04 23:49:07 +00004234#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004235template <typename T>
4236inline internal::ElementsAreArrayMatcher<T>
4237ElementsAreArray(::std::initializer_list<T> xs) {
4238 return ElementsAreArray(xs.begin(), xs.end());
4239}
4240#endif
4241
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004242// UnorderedElementsAreArray(iterator_first, iterator_last)
zhanyong.wanfb25d532013-07-28 08:24:00 +00004243// UnorderedElementsAreArray(pointer, count)
4244// UnorderedElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00004245// UnorderedElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004246// UnorderedElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00004247//
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004248// UnorderedElementsAreArray() verifies that a bijective mapping onto a
4249// collection of matchers exists.
4250//
4251// The matchers can be specified as an array, a pointer and count, a container,
4252// an initializer list, or an STL iterator range. In each of these cases, the
4253// underlying matchers can be either values or matchers.
4254
zhanyong.wanfb25d532013-07-28 08:24:00 +00004255template <typename Iter>
4256inline internal::UnorderedElementsAreArrayMatcher<
4257 typename ::std::iterator_traits<Iter>::value_type>
4258UnorderedElementsAreArray(Iter first, Iter last) {
4259 typedef typename ::std::iterator_traits<Iter>::value_type T;
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004260 return internal::UnorderedElementsAreArrayMatcher<T>(
4261 internal::UnorderedMatcherRequire::ExactMatch, first, last);
zhanyong.wanfb25d532013-07-28 08:24:00 +00004262}
4263
4264template <typename T>
4265inline internal::UnorderedElementsAreArrayMatcher<T>
4266UnorderedElementsAreArray(const T* pointer, size_t count) {
4267 return UnorderedElementsAreArray(pointer, pointer + count);
4268}
4269
4270template <typename T, size_t N>
4271inline internal::UnorderedElementsAreArrayMatcher<T>
4272UnorderedElementsAreArray(const T (&array)[N]) {
4273 return UnorderedElementsAreArray(array, N);
4274}
4275
kosak06678922014-07-28 20:01:28 +00004276template <typename Container>
4277inline internal::UnorderedElementsAreArrayMatcher<
4278 typename Container::value_type>
4279UnorderedElementsAreArray(const Container& container) {
4280 return UnorderedElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00004281}
4282
kosak18489fa2013-12-04 23:49:07 +00004283#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004284template <typename T>
4285inline internal::UnorderedElementsAreArrayMatcher<T>
4286UnorderedElementsAreArray(::std::initializer_list<T> xs) {
4287 return UnorderedElementsAreArray(xs.begin(), xs.end());
4288}
4289#endif
zhanyong.wanfb25d532013-07-28 08:24:00 +00004290
shiqiane35fdd92008-12-10 05:08:54 +00004291// _ is a matcher that matches anything of any type.
4292//
4293// This definition is fine as:
4294//
4295// 1. The C++ standard permits using the name _ in a namespace that
4296// is not the global namespace or ::std.
4297// 2. The AnythingMatcher class has no data member or constructor,
4298// so it's OK to create global variables of this type.
4299// 3. c-style has approved of using _ in this case.
4300const internal::AnythingMatcher _ = {};
4301// Creates a matcher that matches any value of the given type T.
4302template <typename T>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004303inline Matcher<T> A() {
4304 return Matcher<T>(new internal::AnyMatcherImpl<T>());
4305}
shiqiane35fdd92008-12-10 05:08:54 +00004306
4307// Creates a matcher that matches any value of the given type T.
4308template <typename T>
4309inline Matcher<T> An() { return A<T>(); }
4310
4311// Creates a polymorphic matcher that matches anything equal to x.
4312// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
4313// wouldn't compile.
4314template <typename T>
4315inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
4316
4317// Constructs a Matcher<T> from a 'value' of type T. The constructed
4318// matcher matches any value that's equal to 'value'.
4319template <typename T>
4320Matcher<T>::Matcher(T value) { *this = Eq(value); }
4321
Gennadiy Civil466a49a2018-03-23 11:23:54 -04004322template <typename T, typename M>
4323Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(
4324 const M& value,
4325 internal::BooleanConstant<false> /* convertible_to_matcher */,
4326 internal::BooleanConstant<false> /* convertible_to_T */) {
4327 return Eq(value);
4328}
4329
shiqiane35fdd92008-12-10 05:08:54 +00004330// Creates a monomorphic matcher that matches anything with type Lhs
4331// and equal to rhs. A user may need to use this instead of Eq(...)
4332// in order to resolve an overloading ambiguity.
4333//
4334// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
4335// or Matcher<T>(x), but more readable than the latter.
4336//
4337// We could define similar monomorphic matchers for other comparison
4338// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
4339// it yet as those are used much less than Eq() in practice. A user
4340// can always write Matcher<T>(Lt(5)) to be explicit about the type,
4341// for example.
4342template <typename Lhs, typename Rhs>
4343inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
4344
4345// Creates a polymorphic matcher that matches anything >= x.
4346template <typename Rhs>
4347inline internal::GeMatcher<Rhs> Ge(Rhs x) {
4348 return internal::GeMatcher<Rhs>(x);
4349}
4350
4351// Creates a polymorphic matcher that matches anything > x.
4352template <typename Rhs>
4353inline internal::GtMatcher<Rhs> Gt(Rhs x) {
4354 return internal::GtMatcher<Rhs>(x);
4355}
4356
4357// Creates a polymorphic matcher that matches anything <= x.
4358template <typename Rhs>
4359inline internal::LeMatcher<Rhs> Le(Rhs x) {
4360 return internal::LeMatcher<Rhs>(x);
4361}
4362
4363// Creates a polymorphic matcher that matches anything < x.
4364template <typename Rhs>
4365inline internal::LtMatcher<Rhs> Lt(Rhs x) {
4366 return internal::LtMatcher<Rhs>(x);
4367}
4368
4369// Creates a polymorphic matcher that matches anything != x.
4370template <typename Rhs>
4371inline internal::NeMatcher<Rhs> Ne(Rhs x) {
4372 return internal::NeMatcher<Rhs>(x);
4373}
4374
zhanyong.wan2d970ee2009-09-24 21:41:36 +00004375// Creates a polymorphic matcher that matches any NULL pointer.
4376inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
4377 return MakePolymorphicMatcher(internal::IsNullMatcher());
4378}
4379
shiqiane35fdd92008-12-10 05:08:54 +00004380// Creates a polymorphic matcher that matches any non-NULL pointer.
4381// This is convenient as Not(NULL) doesn't compile (the compiler
4382// thinks that that expression is comparing a pointer with an integer).
4383inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
4384 return MakePolymorphicMatcher(internal::NotNullMatcher());
4385}
4386
4387// Creates a polymorphic matcher that matches any argument that
4388// references variable x.
4389template <typename T>
4390inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
4391 return internal::RefMatcher<T&>(x);
4392}
4393
4394// Creates a matcher that matches any double argument approximately
4395// equal to rhs, where two NANs are considered unequal.
4396inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
4397 return internal::FloatingEqMatcher<double>(rhs, false);
4398}
4399
4400// Creates a matcher that matches any double argument approximately
4401// equal to rhs, including NaN values when rhs is NaN.
4402inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
4403 return internal::FloatingEqMatcher<double>(rhs, true);
4404}
4405
zhanyong.wan616180e2013-06-18 18:49:51 +00004406// Creates a matcher that matches any double argument approximately equal to
4407// rhs, up to the specified max absolute error bound, where two NANs are
4408// considered unequal. The max absolute error bound must be non-negative.
4409inline internal::FloatingEqMatcher<double> DoubleNear(
4410 double rhs, double max_abs_error) {
4411 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
4412}
4413
4414// Creates a matcher that matches any double argument approximately equal to
4415// rhs, up to the specified max absolute error bound, including NaN values when
4416// rhs is NaN. The max absolute error bound must be non-negative.
4417inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
4418 double rhs, double max_abs_error) {
4419 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
4420}
4421
shiqiane35fdd92008-12-10 05:08:54 +00004422// Creates a matcher that matches any float argument approximately
4423// equal to rhs, where two NANs are considered unequal.
4424inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
4425 return internal::FloatingEqMatcher<float>(rhs, false);
4426}
4427
zhanyong.wan616180e2013-06-18 18:49:51 +00004428// Creates a matcher that matches any float argument approximately
shiqiane35fdd92008-12-10 05:08:54 +00004429// equal to rhs, including NaN values when rhs is NaN.
4430inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
4431 return internal::FloatingEqMatcher<float>(rhs, true);
4432}
4433
zhanyong.wan616180e2013-06-18 18:49:51 +00004434// Creates a matcher that matches any float argument approximately equal to
4435// rhs, up to the specified max absolute error bound, where two NANs are
4436// considered unequal. The max absolute error bound must be non-negative.
4437inline internal::FloatingEqMatcher<float> FloatNear(
4438 float rhs, float max_abs_error) {
4439 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
4440}
4441
4442// Creates a matcher that matches any float argument approximately equal to
4443// rhs, up to the specified max absolute error bound, including NaN values when
4444// rhs is NaN. The max absolute error bound must be non-negative.
4445inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
4446 float rhs, float max_abs_error) {
4447 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
4448}
4449
shiqiane35fdd92008-12-10 05:08:54 +00004450// Creates a matcher that matches a pointer (raw or smart) that points
4451// to a value that matches inner_matcher.
4452template <typename InnerMatcher>
4453inline internal::PointeeMatcher<InnerMatcher> Pointee(
4454 const InnerMatcher& inner_matcher) {
4455 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
4456}
4457
Scott Grahama9653c42018-05-02 11:14:39 -07004458#if GTEST_HAS_RTTI
billydonahue1f5fdea2014-05-19 17:54:51 +00004459// Creates a matcher that matches a pointer or reference that matches
4460// inner_matcher when dynamic_cast<To> is applied.
4461// The result of dynamic_cast<To> is forwarded to the inner matcher.
4462// If To is a pointer and the cast fails, the inner matcher will receive NULL.
4463// If To is a reference and the cast fails, this matcher returns false
4464// immediately.
4465template <typename To>
4466inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
4467WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
4468 return MakePolymorphicMatcher(
4469 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
4470}
Scott Grahama9653c42018-05-02 11:14:39 -07004471#endif // GTEST_HAS_RTTI
billydonahue1f5fdea2014-05-19 17:54:51 +00004472
shiqiane35fdd92008-12-10 05:08:54 +00004473// Creates a matcher that matches an object whose given field matches
4474// 'matcher'. For example,
4475// Field(&Foo::number, Ge(5))
4476// matches a Foo object x iff x.number >= 5.
4477template <typename Class, typename FieldType, typename FieldMatcher>
4478inline PolymorphicMatcher<
4479 internal::FieldMatcher<Class, FieldType> > Field(
4480 FieldType Class::*field, const FieldMatcher& matcher) {
4481 return MakePolymorphicMatcher(
4482 internal::FieldMatcher<Class, FieldType>(
4483 field, MatcherCast<const FieldType&>(matcher)));
4484 // The call to MatcherCast() is required for supporting inner
4485 // matchers of compatible types. For example, it allows
4486 // Field(&Foo::bar, m)
4487 // to compile where bar is an int32 and m is a matcher for int64.
4488}
4489
Gennadiy Civilb907c262018-03-23 11:42:41 -04004490// Same as Field() but also takes the name of the field to provide better error
4491// messages.
4492template <typename Class, typename FieldType, typename FieldMatcher>
4493inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType> > Field(
4494 const std::string& field_name, FieldType Class::*field,
4495 const FieldMatcher& matcher) {
4496 return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(
4497 field_name, field, MatcherCast<const FieldType&>(matcher)));
4498}
4499
shiqiane35fdd92008-12-10 05:08:54 +00004500// Creates a matcher that matches an object whose given property
4501// matches 'matcher'. For example,
4502// Property(&Foo::str, StartsWith("hi"))
4503// matches a Foo object x iff x.str() starts with "hi".
4504template <typename Class, typename PropertyType, typename PropertyMatcher>
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004505inline PolymorphicMatcher<internal::PropertyMatcher<
4506 Class, PropertyType, PropertyType (Class::*)() const> >
4507Property(PropertyType (Class::*property)() const,
4508 const PropertyMatcher& matcher) {
shiqiane35fdd92008-12-10 05:08:54 +00004509 return MakePolymorphicMatcher(
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004510 internal::PropertyMatcher<Class, PropertyType,
4511 PropertyType (Class::*)() const>(
shiqiane35fdd92008-12-10 05:08:54 +00004512 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00004513 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00004514 // The call to MatcherCast() is required for supporting inner
4515 // matchers of compatible types. For example, it allows
4516 // Property(&Foo::bar, m)
4517 // to compile where bar() returns an int32 and m is a matcher for int64.
4518}
4519
Gennadiy Civil23187052018-03-26 10:16:59 -04004520// Same as Property() above, but also takes the name of the property to provide
4521// better error messages.
4522template <typename Class, typename PropertyType, typename PropertyMatcher>
4523inline PolymorphicMatcher<internal::PropertyMatcher<
4524 Class, PropertyType, PropertyType (Class::*)() const> >
4525Property(const std::string& property_name,
4526 PropertyType (Class::*property)() const,
4527 const PropertyMatcher& matcher) {
4528 return MakePolymorphicMatcher(
4529 internal::PropertyMatcher<Class, PropertyType,
4530 PropertyType (Class::*)() const>(
4531 property_name, property,
4532 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4533}
4534
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004535#if GTEST_LANG_CXX11
4536// The same as above but for reference-qualified member functions.
4537template <typename Class, typename PropertyType, typename PropertyMatcher>
4538inline PolymorphicMatcher<internal::PropertyMatcher<
4539 Class, PropertyType, PropertyType (Class::*)() const &> >
4540Property(PropertyType (Class::*property)() const &,
4541 const PropertyMatcher& matcher) {
4542 return MakePolymorphicMatcher(
4543 internal::PropertyMatcher<Class, PropertyType,
4544 PropertyType (Class::*)() const &>(
4545 property,
4546 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4547}
Gennadiy Civila02af2f2018-07-20 11:28:58 -04004548
4549// Three-argument form for reference-qualified member functions.
4550template <typename Class, typename PropertyType, typename PropertyMatcher>
4551inline PolymorphicMatcher<internal::PropertyMatcher<
4552 Class, PropertyType, PropertyType (Class::*)() const &> >
4553Property(const std::string& property_name,
4554 PropertyType (Class::*property)() const &,
4555 const PropertyMatcher& matcher) {
4556 return MakePolymorphicMatcher(
4557 internal::PropertyMatcher<Class, PropertyType,
4558 PropertyType (Class::*)() const &>(
4559 property_name, property,
4560 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4561}
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004562#endif
4563
shiqiane35fdd92008-12-10 05:08:54 +00004564// Creates a matcher that matches an object iff the result of applying
4565// a callable to x matches 'matcher'.
4566// For example,
4567// ResultOf(f, StartsWith("hi"))
4568// matches a Foo object x iff f(x) starts with "hi".
Abseil Teama0e62d92018-08-24 13:30:17 -04004569// `callable` parameter can be a function, function pointer, or a functor. It is
4570// required to keep no state affecting the results of the calls on it and make
4571// no assumptions about how many calls will be made. Any state it keeps must be
4572// protected from the concurrent access.
4573template <typename Callable, typename InnerMatcher>
4574internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(
4575 Callable callable, InnerMatcher matcher) {
4576 return internal::ResultOfMatcher<Callable, InnerMatcher>(
4577 internal::move(callable), internal::move(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00004578}
4579
4580// String matchers.
4581
4582// Matches a string equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04004583inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
4584 const std::string& str) {
4585 return MakePolymorphicMatcher(
4586 internal::StrEqualityMatcher<std::string>(str, true, true));
shiqiane35fdd92008-12-10 05:08:54 +00004587}
4588
4589// Matches a string not equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04004590inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
4591 const std::string& str) {
4592 return MakePolymorphicMatcher(
4593 internal::StrEqualityMatcher<std::string>(str, false, true));
shiqiane35fdd92008-12-10 05:08:54 +00004594}
4595
4596// Matches a string equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04004597inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
4598 const std::string& str) {
4599 return MakePolymorphicMatcher(
4600 internal::StrEqualityMatcher<std::string>(str, true, false));
shiqiane35fdd92008-12-10 05:08:54 +00004601}
4602
4603// Matches a string not equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04004604inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
4605 const std::string& str) {
4606 return MakePolymorphicMatcher(
4607 internal::StrEqualityMatcher<std::string>(str, false, false));
shiqiane35fdd92008-12-10 05:08:54 +00004608}
4609
4610// Creates a matcher that matches any string, std::string, or C string
4611// that contains the given substring.
Nico Weber09fd5b32017-05-15 17:07:03 -04004612inline PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
4613 const std::string& substring) {
4614 return MakePolymorphicMatcher(
4615 internal::HasSubstrMatcher<std::string>(substring));
shiqiane35fdd92008-12-10 05:08:54 +00004616}
4617
4618// Matches a string that starts with 'prefix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004619inline PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
4620 const std::string& prefix) {
4621 return MakePolymorphicMatcher(
4622 internal::StartsWithMatcher<std::string>(prefix));
shiqiane35fdd92008-12-10 05:08:54 +00004623}
4624
4625// Matches a string that ends with 'suffix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004626inline PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
4627 const std::string& suffix) {
4628 return MakePolymorphicMatcher(internal::EndsWithMatcher<std::string>(suffix));
shiqiane35fdd92008-12-10 05:08:54 +00004629}
4630
shiqiane35fdd92008-12-10 05:08:54 +00004631// Matches a string that fully matches regular expression 'regex'.
4632// The matcher takes ownership of 'regex'.
4633inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4634 const internal::RE* regex) {
4635 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
4636}
4637inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004638 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004639 return MatchesRegex(new internal::RE(regex));
4640}
4641
4642// Matches a string that contains regular expression 'regex'.
4643// The matcher takes ownership of 'regex'.
4644inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4645 const internal::RE* regex) {
4646 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4647}
4648inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004649 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004650 return ContainsRegex(new internal::RE(regex));
4651}
4652
shiqiane35fdd92008-12-10 05:08:54 +00004653#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4654// Wide string matchers.
4655
4656// Matches a string equal to str.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004657inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrEq(
4658 const std::wstring& str) {
4659 return MakePolymorphicMatcher(
4660 internal::StrEqualityMatcher<std::wstring>(str, true, true));
shiqiane35fdd92008-12-10 05:08:54 +00004661}
4662
4663// Matches a string not equal to str.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004664inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrNe(
4665 const std::wstring& str) {
4666 return MakePolymorphicMatcher(
4667 internal::StrEqualityMatcher<std::wstring>(str, false, true));
shiqiane35fdd92008-12-10 05:08:54 +00004668}
4669
4670// Matches a string equal to str, ignoring case.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004671inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
4672StrCaseEq(const std::wstring& str) {
4673 return MakePolymorphicMatcher(
4674 internal::StrEqualityMatcher<std::wstring>(str, true, false));
shiqiane35fdd92008-12-10 05:08:54 +00004675}
4676
4677// Matches a string not equal to str, ignoring case.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004678inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
4679StrCaseNe(const std::wstring& str) {
4680 return MakePolymorphicMatcher(
4681 internal::StrEqualityMatcher<std::wstring>(str, false, false));
shiqiane35fdd92008-12-10 05:08:54 +00004682}
4683
Gennadiy Civilb907c262018-03-23 11:42:41 -04004684// Creates a matcher that matches any ::wstring, std::wstring, or C wide string
shiqiane35fdd92008-12-10 05:08:54 +00004685// that contains the given substring.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004686inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring> > HasSubstr(
4687 const std::wstring& substring) {
4688 return MakePolymorphicMatcher(
4689 internal::HasSubstrMatcher<std::wstring>(substring));
shiqiane35fdd92008-12-10 05:08:54 +00004690}
4691
4692// Matches a string that starts with 'prefix' (case-sensitive).
Gennadiy Civilb907c262018-03-23 11:42:41 -04004693inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring> >
4694StartsWith(const std::wstring& prefix) {
4695 return MakePolymorphicMatcher(
4696 internal::StartsWithMatcher<std::wstring>(prefix));
shiqiane35fdd92008-12-10 05:08:54 +00004697}
4698
4699// Matches a string that ends with 'suffix' (case-sensitive).
Gennadiy Civilb907c262018-03-23 11:42:41 -04004700inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring> > EndsWith(
4701 const std::wstring& suffix) {
4702 return MakePolymorphicMatcher(
4703 internal::EndsWithMatcher<std::wstring>(suffix));
shiqiane35fdd92008-12-10 05:08:54 +00004704}
4705
4706#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4707
4708// Creates a polymorphic matcher that matches a 2-tuple where the
4709// first field == the second field.
4710inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4711
4712// Creates a polymorphic matcher that matches a 2-tuple where the
4713// first field >= the second field.
4714inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4715
4716// Creates a polymorphic matcher that matches a 2-tuple where the
4717// first field > the second field.
4718inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4719
4720// Creates a polymorphic matcher that matches a 2-tuple where the
4721// first field <= the second field.
4722inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4723
4724// Creates a polymorphic matcher that matches a 2-tuple where the
4725// first field < the second field.
4726inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4727
4728// Creates a polymorphic matcher that matches a 2-tuple where the
4729// first field != the second field.
4730inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4731
Gennadiy Civilb907c262018-03-23 11:42:41 -04004732// Creates a polymorphic matcher that matches a 2-tuple where
4733// FloatEq(first field) matches the second field.
4734inline internal::FloatingEq2Matcher<float> FloatEq() {
4735 return internal::FloatingEq2Matcher<float>();
4736}
4737
4738// Creates a polymorphic matcher that matches a 2-tuple where
4739// DoubleEq(first field) matches the second field.
4740inline internal::FloatingEq2Matcher<double> DoubleEq() {
4741 return internal::FloatingEq2Matcher<double>();
4742}
4743
4744// Creates a polymorphic matcher that matches a 2-tuple where
4745// FloatEq(first field) matches the second field with NaN equality.
4746inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() {
4747 return internal::FloatingEq2Matcher<float>(true);
4748}
4749
4750// Creates a polymorphic matcher that matches a 2-tuple where
4751// DoubleEq(first field) matches the second field with NaN equality.
4752inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() {
4753 return internal::FloatingEq2Matcher<double>(true);
4754}
4755
4756// Creates a polymorphic matcher that matches a 2-tuple where
4757// FloatNear(first field, max_abs_error) matches the second field.
4758inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) {
4759 return internal::FloatingEq2Matcher<float>(max_abs_error);
4760}
4761
4762// Creates a polymorphic matcher that matches a 2-tuple where
4763// DoubleNear(first field, max_abs_error) matches the second field.
4764inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) {
4765 return internal::FloatingEq2Matcher<double>(max_abs_error);
4766}
4767
4768// Creates a polymorphic matcher that matches a 2-tuple where
4769// FloatNear(first field, max_abs_error) matches the second field with NaN
4770// equality.
4771inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear(
4772 float max_abs_error) {
4773 return internal::FloatingEq2Matcher<float>(max_abs_error, true);
4774}
4775
4776// Creates a polymorphic matcher that matches a 2-tuple where
4777// DoubleNear(first field, max_abs_error) matches the second field with NaN
4778// equality.
4779inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear(
4780 double max_abs_error) {
4781 return internal::FloatingEq2Matcher<double>(max_abs_error, true);
4782}
4783
shiqiane35fdd92008-12-10 05:08:54 +00004784// Creates a matcher that matches any value of type T that m doesn't
4785// match.
4786template <typename InnerMatcher>
4787inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4788 return internal::NotMatcher<InnerMatcher>(m);
4789}
4790
shiqiane35fdd92008-12-10 05:08:54 +00004791// Returns a matcher that matches anything that satisfies the given
4792// predicate. The predicate can be any unary function or functor
4793// whose return type can be implicitly converted to bool.
4794template <typename Predicate>
4795inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4796Truly(Predicate pred) {
4797 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4798}
4799
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004800// Returns a matcher that matches the container size. The container must
4801// support both size() and size_type which all STL-like containers provide.
4802// Note that the parameter 'size' can be a value of type size_type as well as
4803// matcher. For instance:
4804// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
4805// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
4806template <typename SizeMatcher>
4807inline internal::SizeIsMatcher<SizeMatcher>
4808SizeIs(const SizeMatcher& size_matcher) {
4809 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4810}
4811
kosakb6a34882014-03-12 21:06:46 +00004812// Returns a matcher that matches the distance between the container's begin()
4813// iterator and its end() iterator, i.e. the size of the container. This matcher
4814// can be used instead of SizeIs with containers such as std::forward_list which
4815// do not implement size(). The container must provide const_iterator (with
4816// valid iterator_traits), begin() and end().
4817template <typename DistanceMatcher>
4818inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4819BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4820 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4821}
4822
zhanyong.wan6a896b52009-01-16 01:13:50 +00004823// Returns a matcher that matches an equal container.
4824// This matcher behaves like Eq(), but in the event of mismatch lists the
4825// values that are included in one container but not the other. (Duplicate
4826// values and order differences are not explained.)
4827template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00004828inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00004829 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004830 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00004831 // This following line is for working around a bug in MSVC 8.0,
4832 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00004833 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00004834 return MakePolymorphicMatcher(
4835 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00004836}
4837
zhanyong.wan898725c2011-09-16 16:45:39 +00004838// Returns a matcher that matches a container that, when sorted using
4839// the given comparator, matches container_matcher.
4840template <typename Comparator, typename ContainerMatcher>
4841inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4842WhenSortedBy(const Comparator& comparator,
4843 const ContainerMatcher& container_matcher) {
4844 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4845 comparator, container_matcher);
4846}
4847
4848// Returns a matcher that matches a container that, when sorted using
4849// the < operator, matches container_matcher.
4850template <typename ContainerMatcher>
4851inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4852WhenSorted(const ContainerMatcher& container_matcher) {
4853 return
4854 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4855 internal::LessComparator(), container_matcher);
4856}
4857
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004858// Matches an STL-style container or a native array that contains the
4859// same number of elements as in rhs, where its i-th element and rhs's
4860// i-th element (as a pair) satisfy the given pair matcher, for all i.
4861// TupleMatcher must be able to be safely cast to Matcher<tuple<const
4862// T1&, const T2&> >, where T1 and T2 are the types of elements in the
4863// LHS container and the RHS container respectively.
4864template <typename TupleMatcher, typename Container>
4865inline internal::PointwiseMatcher<TupleMatcher,
4866 GTEST_REMOVE_CONST_(Container)>
4867Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4868 // This following line is for working around a bug in MSVC 8.0,
kosak2336e9c2014-07-28 22:57:30 +00004869 // which causes Container to be a const type sometimes (e.g. when
4870 // rhs is a const int[])..
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004871 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4872 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4873 tuple_matcher, rhs);
4874}
4875
kosak2336e9c2014-07-28 22:57:30 +00004876#if GTEST_HAS_STD_INITIALIZER_LIST_
4877
4878// Supports the Pointwise(m, {a, b, c}) syntax.
4879template <typename TupleMatcher, typename T>
4880inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4881 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4882 return Pointwise(tuple_matcher, std::vector<T>(rhs));
4883}
4884
4885#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4886
4887// UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4888// container or a native array that contains the same number of
4889// elements as in rhs, where in some permutation of the container, its
4890// i-th element and rhs's i-th element (as a pair) satisfy the given
4891// pair matcher, for all i. Tuple2Matcher must be able to be safely
4892// cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4893// the types of elements in the LHS container and the RHS container
4894// respectively.
4895//
4896// This is like Pointwise(pair_matcher, rhs), except that the element
4897// order doesn't matter.
4898template <typename Tuple2Matcher, typename RhsContainer>
4899inline internal::UnorderedElementsAreArrayMatcher<
4900 typename internal::BoundSecondMatcher<
4901 Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4902 RhsContainer)>::type::value_type> >
4903UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4904 const RhsContainer& rhs_container) {
4905 // This following line is for working around a bug in MSVC 8.0,
4906 // which causes RhsContainer to be a const type sometimes (e.g. when
4907 // rhs_container is a const int[]).
4908 typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4909
4910 // RhsView allows the same code to handle RhsContainer being a
4911 // STL-style container and it being a native C-style array.
4912 typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4913 typedef typename RhsView::type RhsStlContainer;
4914 typedef typename RhsStlContainer::value_type Second;
4915 const RhsStlContainer& rhs_stl_container =
4916 RhsView::ConstReference(rhs_container);
4917
4918 // Create a matcher for each element in rhs_container.
4919 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4920 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4921 it != rhs_stl_container.end(); ++it) {
4922 matchers.push_back(
4923 internal::MatcherBindSecond(tuple2_matcher, *it));
4924 }
4925
4926 // Delegate the work to UnorderedElementsAreArray().
4927 return UnorderedElementsAreArray(matchers);
4928}
4929
4930#if GTEST_HAS_STD_INITIALIZER_LIST_
4931
4932// Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4933template <typename Tuple2Matcher, typename T>
4934inline internal::UnorderedElementsAreArrayMatcher<
4935 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4936UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4937 std::initializer_list<T> rhs) {
4938 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4939}
4940
4941#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4942
zhanyong.wanb8243162009-06-04 05:48:20 +00004943// Matches an STL-style container or a native array that contains at
4944// least one element matching the given value or matcher.
4945//
4946// Examples:
4947// ::std::set<int> page_ids;
4948// page_ids.insert(3);
4949// page_ids.insert(1);
4950// EXPECT_THAT(page_ids, Contains(1));
4951// EXPECT_THAT(page_ids, Contains(Gt(2)));
4952// EXPECT_THAT(page_ids, Not(Contains(4)));
4953//
4954// ::std::map<int, size_t> page_lengths;
4955// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00004956// EXPECT_THAT(page_lengths,
4957// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004958//
4959// const char* user_ids[] = { "joe", "mike", "tom" };
4960// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4961template <typename M>
4962inline internal::ContainsMatcher<M> Contains(M matcher) {
4963 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004964}
4965
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004966// IsSupersetOf(iterator_first, iterator_last)
4967// IsSupersetOf(pointer, count)
4968// IsSupersetOf(array)
4969// IsSupersetOf(container)
4970// IsSupersetOf({e1, e2, ..., en})
4971//
4972// IsSupersetOf() verifies that a surjective partial mapping onto a collection
4973// of matchers exists. In other words, a container matches
4974// IsSupersetOf({e1, ..., en}) if and only if there is a permutation
4975// {y1, ..., yn} of some of the container's elements where y1 matches e1,
4976// ..., and yn matches en. Obviously, the size of the container must be >= n
4977// in order to have a match. Examples:
4978//
4979// - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and
4980// 1 matches Ne(0).
4981// - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches
4982// both Eq(1) and Lt(2). The reason is that different matchers must be used
4983// for elements in different slots of the container.
4984// - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches
4985// Eq(1) and (the second) 1 matches Lt(2).
4986// - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)
4987// Gt(1) and 3 matches (the second) Gt(1).
4988//
4989// The matchers can be specified as an array, a pointer and count, a container,
4990// an initializer list, or an STL iterator range. In each of these cases, the
4991// underlying matchers can be either values or matchers.
4992
4993template <typename Iter>
4994inline internal::UnorderedElementsAreArrayMatcher<
4995 typename ::std::iterator_traits<Iter>::value_type>
4996IsSupersetOf(Iter first, Iter last) {
4997 typedef typename ::std::iterator_traits<Iter>::value_type T;
4998 return internal::UnorderedElementsAreArrayMatcher<T>(
4999 internal::UnorderedMatcherRequire::Superset, first, last);
5000}
5001
5002template <typename T>
5003inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
5004 const T* pointer, size_t count) {
5005 return IsSupersetOf(pointer, pointer + count);
5006}
5007
5008template <typename T, size_t N>
5009inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
5010 const T (&array)[N]) {
5011 return IsSupersetOf(array, N);
5012}
5013
5014template <typename Container>
5015inline internal::UnorderedElementsAreArrayMatcher<
5016 typename Container::value_type>
5017IsSupersetOf(const Container& container) {
5018 return IsSupersetOf(container.begin(), container.end());
5019}
5020
5021#if GTEST_HAS_STD_INITIALIZER_LIST_
5022template <typename T>
5023inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
5024 ::std::initializer_list<T> xs) {
5025 return IsSupersetOf(xs.begin(), xs.end());
5026}
5027#endif
5028
5029// IsSubsetOf(iterator_first, iterator_last)
5030// IsSubsetOf(pointer, count)
5031// IsSubsetOf(array)
5032// IsSubsetOf(container)
5033// IsSubsetOf({e1, e2, ..., en})
5034//
5035// IsSubsetOf() verifies that an injective mapping onto a collection of matchers
5036// exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and
5037// only if there is a subset of matchers {m1, ..., mk} which would match the
5038// container using UnorderedElementsAre. Obviously, the size of the container
5039// must be <= n in order to have a match. Examples:
5040//
5041// - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).
5042// - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1
5043// matches Lt(0).
5044// - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both
5045// match Gt(0). The reason is that different matchers must be used for
5046// elements in different slots of the container.
5047//
5048// The matchers can be specified as an array, a pointer and count, a container,
5049// an initializer list, or an STL iterator range. In each of these cases, the
5050// underlying matchers can be either values or matchers.
5051
5052template <typename Iter>
5053inline internal::UnorderedElementsAreArrayMatcher<
5054 typename ::std::iterator_traits<Iter>::value_type>
5055IsSubsetOf(Iter first, Iter last) {
5056 typedef typename ::std::iterator_traits<Iter>::value_type T;
5057 return internal::UnorderedElementsAreArrayMatcher<T>(
5058 internal::UnorderedMatcherRequire::Subset, first, last);
5059}
5060
5061template <typename T>
5062inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
5063 const T* pointer, size_t count) {
5064 return IsSubsetOf(pointer, pointer + count);
5065}
5066
5067template <typename T, size_t N>
5068inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
5069 const T (&array)[N]) {
5070 return IsSubsetOf(array, N);
5071}
5072
5073template <typename Container>
5074inline internal::UnorderedElementsAreArrayMatcher<
5075 typename Container::value_type>
5076IsSubsetOf(const Container& container) {
5077 return IsSubsetOf(container.begin(), container.end());
5078}
5079
5080#if GTEST_HAS_STD_INITIALIZER_LIST_
5081template <typename T>
5082inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
5083 ::std::initializer_list<T> xs) {
5084 return IsSubsetOf(xs.begin(), xs.end());
5085}
5086#endif
5087
zhanyong.wan33605ba2010-04-22 23:37:47 +00005088// Matches an STL-style container or a native array that contains only
5089// elements matching the given value or matcher.
5090//
5091// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
5092// the messages are different.
5093//
5094// Examples:
5095// ::std::set<int> page_ids;
5096// // Each(m) matches an empty container, regardless of what m is.
5097// EXPECT_THAT(page_ids, Each(Eq(1)));
5098// EXPECT_THAT(page_ids, Each(Eq(77)));
5099//
5100// page_ids.insert(3);
5101// EXPECT_THAT(page_ids, Each(Gt(0)));
5102// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
5103// page_ids.insert(1);
5104// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
5105//
5106// ::std::map<int, size_t> page_lengths;
5107// page_lengths[1] = 100;
5108// page_lengths[2] = 200;
5109// page_lengths[3] = 300;
5110// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
5111// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
5112//
5113// const char* user_ids[] = { "joe", "mike", "tom" };
5114// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
5115template <typename M>
5116inline internal::EachMatcher<M> Each(M matcher) {
5117 return internal::EachMatcher<M>(matcher);
5118}
5119
zhanyong.wanb5937da2009-07-16 20:26:41 +00005120// Key(inner_matcher) matches an std::pair whose 'first' field matches
5121// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
5122// std::map that contains at least one element whose key is >= 5.
5123template <typename M>
5124inline internal::KeyMatcher<M> Key(M inner_matcher) {
5125 return internal::KeyMatcher<M>(inner_matcher);
5126}
5127
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00005128// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
5129// matches first_matcher and whose 'second' field matches second_matcher. For
5130// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
5131// to match a std::map<int, string> that contains exactly one element whose key
5132// is >= 5 and whose value equals "foo".
5133template <typename FirstMatcher, typename SecondMatcher>
5134inline internal::PairMatcher<FirstMatcher, SecondMatcher>
5135Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
5136 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
5137 first_matcher, second_matcher);
5138}
5139
shiqiane35fdd92008-12-10 05:08:54 +00005140// Returns a predicate that is satisfied by anything that matches the
5141// given matcher.
5142template <typename M>
5143inline internal::MatcherAsPredicate<M> Matches(M matcher) {
5144 return internal::MatcherAsPredicate<M>(matcher);
5145}
5146
zhanyong.wanb8243162009-06-04 05:48:20 +00005147// Returns true iff the value matches the matcher.
5148template <typename T, typename M>
5149inline bool Value(const T& value, M matcher) {
5150 return testing::Matches(matcher)(value);
5151}
5152
zhanyong.wan34b034c2010-03-05 21:23:23 +00005153// Matches the value against the given matcher and explains the match
5154// result to listener.
5155template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00005156inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00005157 M matcher, const T& value, MatchResultListener* listener) {
5158 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
5159}
5160
Gennadiy Civilb907c262018-03-23 11:42:41 -04005161// Returns a string representation of the given matcher. Useful for description
5162// strings of matchers defined using MATCHER_P* macros that accept matchers as
5163// their arguments. For example:
5164//
5165// MATCHER_P(XAndYThat, matcher,
5166// "X that " + DescribeMatcher<int>(matcher, negation) +
5167// " and Y that " + DescribeMatcher<double>(matcher, negation)) {
5168// return ExplainMatchResult(matcher, arg.x(), result_listener) &&
5169// ExplainMatchResult(matcher, arg.y(), result_listener);
5170// }
5171template <typename T, typename M>
5172std::string DescribeMatcher(const M& matcher, bool negation = false) {
5173 ::std::stringstream ss;
5174 Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher);
5175 if (negation) {
5176 monomorphic_matcher.DescribeNegationTo(&ss);
5177 } else {
5178 monomorphic_matcher.DescribeTo(&ss);
5179 }
5180 return ss.str();
5181}
5182
zhanyong.wan616180e2013-06-18 18:49:51 +00005183#if GTEST_LANG_CXX11
5184// Define variadic matcher versions. They are overloaded in
5185// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
5186template <typename... Args>
Gennadiy Civil0c178882018-07-19 12:42:39 -04005187internal::AllOfMatcher<typename std::decay<const Args&>::type...> AllOf(
5188 const Args&... matchers) {
5189 return internal::AllOfMatcher<typename std::decay<const Args&>::type...>(
5190 matchers...);
zhanyong.wan616180e2013-06-18 18:49:51 +00005191}
5192
5193template <typename... Args>
Gennadiy Civil0c178882018-07-19 12:42:39 -04005194internal::AnyOfMatcher<typename std::decay<const Args&>::type...> AnyOf(
5195 const Args&... matchers) {
5196 return internal::AnyOfMatcher<typename std::decay<const Args&>::type...>(
5197 matchers...);
zhanyong.wan616180e2013-06-18 18:49:51 +00005198}
5199
Gennadiy Civil3f88bb12018-04-16 15:52:47 -04005200template <typename... Args>
Gennadiy Civil4707c0f2018-04-18 10:36:12 -04005201internal::ElementsAreMatcher<tuple<typename std::decay<const Args&>::type...>>
Gennadiy Civildff32af2018-04-17 16:12:04 -04005202ElementsAre(const Args&... matchers) {
5203 return internal::ElementsAreMatcher<
Gennadiy Civil4707c0f2018-04-18 10:36:12 -04005204 tuple<typename std::decay<const Args&>::type...>>(
5205 make_tuple(matchers...));
Gennadiy Civildff32af2018-04-17 16:12:04 -04005206}
5207
5208template <typename... Args>
Gennadiy Civil4707c0f2018-04-18 10:36:12 -04005209internal::UnorderedElementsAreMatcher<
5210 tuple<typename std::decay<const Args&>::type...>>
Gennadiy Civildff32af2018-04-17 16:12:04 -04005211UnorderedElementsAre(const Args&... matchers) {
5212 return internal::UnorderedElementsAreMatcher<
Gennadiy Civil4707c0f2018-04-18 10:36:12 -04005213 tuple<typename std::decay<const Args&>::type...>>(
5214 make_tuple(matchers...));
Gennadiy Civil3f88bb12018-04-16 15:52:47 -04005215}
5216
zhanyong.wan616180e2013-06-18 18:49:51 +00005217#endif // GTEST_LANG_CXX11
5218
zhanyong.wanbf550852009-06-09 06:09:53 +00005219// AllArgs(m) is a synonym of m. This is useful in
5220//
5221// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
5222//
5223// which is easier to read than
5224//
5225// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
5226template <typename InnerMatcher>
5227inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
5228
Gennadiy Civilb907c262018-03-23 11:42:41 -04005229// Returns a matcher that matches the value of an optional<> type variable.
5230// The matcher implementation only uses '!arg' and requires that the optional<>
5231// type has a 'value_type' member type and that '*arg' is of type 'value_type'
5232// and is printable using 'PrintToString'. It is compatible with
5233// std::optional/std::experimental::optional.
5234// Note that to compare an optional type variable against nullopt you should
5235// use Eq(nullopt) and not Optional(Eq(nullopt)). The latter implies that the
5236// optional value contains an optional itself.
5237template <typename ValueMatcher>
5238inline internal::OptionalMatcher<ValueMatcher> Optional(
5239 const ValueMatcher& value_matcher) {
5240 return internal::OptionalMatcher<ValueMatcher>(value_matcher);
5241}
5242
5243// Returns a matcher that matches the value of a absl::any type variable.
5244template <typename T>
5245PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T> > AnyWith(
5246 const Matcher<const T&>& matcher) {
5247 return MakePolymorphicMatcher(
5248 internal::any_cast_matcher::AnyCastMatcher<T>(matcher));
5249}
5250
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05005251// Returns a matcher that matches the value of a variant<> type variable.
5252// The matcher implementation uses ADL to find the holds_alternative and get
5253// functions.
5254// It is compatible with std::variant.
5255template <typename T>
5256PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
5257 const Matcher<const T&>& matcher) {
5258 return MakePolymorphicMatcher(
5259 internal::variant_matcher::VariantMatcher<T>(matcher));
5260}
5261
shiqiane35fdd92008-12-10 05:08:54 +00005262// These macros allow using matchers to check values in Google Test
5263// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
5264// succeed iff the value matches the matcher. If the assertion fails,
5265// the value and the description of the matcher will be printed.
5266#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
5267 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
5268#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
5269 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
5270
5271} // namespace testing
5272
mistergdf428ec2018-08-20 14:48:45 -04005273GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
5274
kosak6702b972015-07-27 23:05:57 +00005275// Include any custom callback matchers added by the local installation.
5276// We must include this header at the end to make sure it can use the
5277// declarations from this file.
5278#include "gmock/internal/custom/gmock-matchers.h"
Gennadiy Civilb907c262018-03-23 11:42:41 -04005279
shiqiane35fdd92008-12-10 05:08:54 +00005280#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_