blob: 5af330e0c2025d2accefda87264910f33879a842 [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
misterga5cc7aa2018-08-30 16:26:26 -040059GTEST_DISABLE_MSC_WARNINGS_PUSH_(
60 4251 5046 /* class A needs to have dll-interface to be used by clients of
61 class B */
62 /* Symbol involving type with internal linkage not defined */)
mistergdf428ec2018-08-20 14:48:45 -040063
shiqiane35fdd92008-12-10 05:08:54 +000064namespace testing {
65
66// To implement a matcher Foo for type T, define:
67// 1. a class FooMatcherImpl that implements the
68// MatcherInterface<T> interface, and
69// 2. a factory function that creates a Matcher<T> object from a
70// FooMatcherImpl*.
71//
72// The two-level delegation design makes it possible to allow a user
73// to write "v" instead of "Eq(v)" where a Matcher is expected, which
74// is impossible if we pass matchers by pointers. It also eases
75// ownership management as Matcher objects can now be copied like
76// plain values.
77
zhanyong.wan82113312010-01-08 21:55:40 +000078// MatchResultListener is an abstract class. Its << operator can be
79// used by a matcher to explain why a value matches or doesn't match.
80//
Gennadiy Civil265efde2018-08-14 15:04:11 -040081// FIXME: add method
zhanyong.wan82113312010-01-08 21:55:40 +000082// bool InterestedInWhy(bool result) const;
83// to indicate whether the listener is interested in why the match
84// result is 'result'.
85class MatchResultListener {
86 public:
87 // Creates a listener object with the given underlying ostream. The
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +000088 // listener does not own the ostream, and does not dereference it
89 // in the constructor or destructor.
zhanyong.wan82113312010-01-08 21:55:40 +000090 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
91 virtual ~MatchResultListener() = 0; // Makes this class abstract.
92
93 // Streams x to the underlying ostream; does nothing if the ostream
94 // is NULL.
95 template <typename T>
96 MatchResultListener& operator<<(const T& x) {
97 if (stream_ != NULL)
98 *stream_ << x;
99 return *this;
100 }
101
102 // Returns the underlying ostream.
103 ::std::ostream* stream() { return stream_; }
104
zhanyong.wana862f1d2010-03-15 21:23:04 +0000105 // Returns true iff the listener is interested in an explanation of
106 // the match result. A matcher's MatchAndExplain() method can use
107 // this information to avoid generating the explanation when no one
108 // intends to hear it.
109 bool IsInterested() const { return stream_ != NULL; }
110
zhanyong.wan82113312010-01-08 21:55:40 +0000111 private:
112 ::std::ostream* const stream_;
113
114 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
115};
116
117inline MatchResultListener::~MatchResultListener() {
118}
119
zhanyong.wanfb25d532013-07-28 08:24:00 +0000120// An instance of a subclass of this knows how to describe itself as a
121// matcher.
122class MatcherDescriberInterface {
123 public:
124 virtual ~MatcherDescriberInterface() {}
125
126 // Describes this matcher to an ostream. The function should print
127 // a verb phrase that describes the property a value matching this
128 // matcher should have. The subject of the verb phrase is the value
129 // being matched. For example, the DescribeTo() method of the Gt(7)
130 // matcher prints "is greater than 7".
131 virtual void DescribeTo(::std::ostream* os) const = 0;
132
133 // Describes the negation of this matcher to an ostream. For
134 // example, if the description of this matcher is "is greater than
135 // 7", the negated description could be "is not greater than 7".
136 // You are not required to override this when implementing
137 // MatcherInterface, but it is highly advised so that your matcher
138 // can produce good error messages.
139 virtual void DescribeNegationTo(::std::ostream* os) const {
140 *os << "not (";
141 DescribeTo(os);
142 *os << ")";
143 }
144};
145
shiqiane35fdd92008-12-10 05:08:54 +0000146// The implementation of a matcher.
147template <typename T>
zhanyong.wanfb25d532013-07-28 08:24:00 +0000148class MatcherInterface : public MatcherDescriberInterface {
shiqiane35fdd92008-12-10 05:08:54 +0000149 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000150 // Returns true iff the matcher matches x; also explains the match
zhanyong.wan83f6b082013-03-01 01:47:35 +0000151 // result to 'listener' if necessary (see the next paragraph), in
152 // the form of a non-restrictive relative clause ("which ...",
153 // "whose ...", etc) that describes x. For example, the
154 // MatchAndExplain() method of the Pointee(...) matcher should
155 // generate an explanation like "which points to ...".
156 //
157 // Implementations of MatchAndExplain() should add an explanation of
158 // the match result *if and only if* they can provide additional
159 // information that's not already present (or not obvious) in the
160 // print-out of x and the matcher's description. Whether the match
161 // succeeds is not a factor in deciding whether an explanation is
162 // needed, as sometimes the caller needs to print a failure message
163 // when the match succeeds (e.g. when the matcher is used inside
164 // Not()).
165 //
166 // For example, a "has at least 10 elements" matcher should explain
167 // what the actual element count is, regardless of the match result,
168 // as it is useful information to the reader; on the other hand, an
169 // "is empty" matcher probably only needs to explain what the actual
170 // size is when the match fails, as it's redundant to say that the
171 // size is 0 when the value is already known to be empty.
zhanyong.wan82113312010-01-08 21:55:40 +0000172 //
zhanyong.wandb22c222010-01-28 21:52:29 +0000173 // You should override this method when defining a new matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000174 //
175 // It's the responsibility of the caller (Google Mock) to guarantee
176 // that 'listener' is not NULL. This helps to simplify a matcher's
177 // implementation when it doesn't care about the performance, as it
178 // can talk to 'listener' without checking its validity first.
179 // However, in order to implement dummy listeners efficiently,
180 // listener->stream() may be NULL.
zhanyong.wandb22c222010-01-28 21:52:29 +0000181 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
shiqiane35fdd92008-12-10 05:08:54 +0000182
zhanyong.wanfb25d532013-07-28 08:24:00 +0000183 // Inherits these methods from MatcherDescriberInterface:
184 // virtual void DescribeTo(::std::ostream* os) const = 0;
185 // virtual void DescribeNegationTo(::std::ostream* os) const;
shiqiane35fdd92008-12-10 05:08:54 +0000186};
187
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400188namespace internal {
189
190// Converts a MatcherInterface<T> to a MatcherInterface<const T&>.
191template <typename T>
192class MatcherInterfaceAdapter : public MatcherInterface<const T&> {
193 public:
194 explicit MatcherInterfaceAdapter(const MatcherInterface<T>* impl)
195 : impl_(impl) {}
196 virtual ~MatcherInterfaceAdapter() { delete impl_; }
197
198 virtual void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
199
200 virtual void DescribeNegationTo(::std::ostream* os) const {
201 impl_->DescribeNegationTo(os);
202 }
203
204 virtual bool MatchAndExplain(const T& x,
205 MatchResultListener* listener) const {
206 return impl_->MatchAndExplain(x, listener);
207 }
208
209 private:
210 const MatcherInterface<T>* const impl_;
211
212 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatcherInterfaceAdapter);
213};
214
215} // namespace internal
216
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000217// A match result listener that stores the explanation in a string.
218class StringMatchResultListener : public MatchResultListener {
219 public:
220 StringMatchResultListener() : MatchResultListener(&ss_) {}
221
222 // Returns the explanation accumulated so far.
Nico Weber09fd5b32017-05-15 17:07:03 -0400223 std::string str() const { return ss_.str(); }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000224
225 // Clears the explanation accumulated so far.
226 void Clear() { ss_.str(""); }
227
228 private:
229 ::std::stringstream ss_;
230
231 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
232};
233
shiqiane35fdd92008-12-10 05:08:54 +0000234namespace internal {
235
kosak506340a2014-11-17 01:47:54 +0000236struct AnyEq {
237 template <typename A, typename B>
238 bool operator()(const A& a, const B& b) const { return a == b; }
239};
240struct AnyNe {
241 template <typename A, typename B>
242 bool operator()(const A& a, const B& b) const { return a != b; }
243};
244struct AnyLt {
245 template <typename A, typename B>
246 bool operator()(const A& a, const B& b) const { return a < b; }
247};
248struct AnyGt {
249 template <typename A, typename B>
250 bool operator()(const A& a, const B& b) const { return a > b; }
251};
252struct AnyLe {
253 template <typename A, typename B>
254 bool operator()(const A& a, const B& b) const { return a <= b; }
255};
256struct AnyGe {
257 template <typename A, typename B>
258 bool operator()(const A& a, const B& b) const { return a >= b; }
259};
260
zhanyong.wan82113312010-01-08 21:55:40 +0000261// A match result listener that ignores the explanation.
262class DummyMatchResultListener : public MatchResultListener {
263 public:
264 DummyMatchResultListener() : MatchResultListener(NULL) {}
265
266 private:
267 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
268};
269
270// A match result listener that forwards the explanation to a given
271// ostream. The difference between this and MatchResultListener is
272// that the former is concrete.
273class StreamMatchResultListener : public MatchResultListener {
274 public:
275 explicit StreamMatchResultListener(::std::ostream* os)
276 : MatchResultListener(os) {}
277
278 private:
279 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
280};
281
shiqiane35fdd92008-12-10 05:08:54 +0000282// An internal class for implementing Matcher<T>, which will derive
283// from it. We put functionalities common to all Matcher<T>
284// specializations here to avoid code duplication.
285template <typename T>
286class MatcherBase {
287 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000288 // Returns true iff the matcher matches x; also explains the match
289 // result to 'listener'.
Gennadiy Civil6aae2062018-03-26 10:36:26 -0400290 bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
291 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000292 return impl_->MatchAndExplain(x, listener);
293 }
294
shiqiane35fdd92008-12-10 05:08:54 +0000295 // Returns true iff this matcher matches x.
Gennadiy Civile55089e2018-04-04 14:05:00 -0400296 bool Matches(GTEST_REFERENCE_TO_CONST_(T) x) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000297 DummyMatchResultListener dummy;
298 return MatchAndExplain(x, &dummy);
299 }
shiqiane35fdd92008-12-10 05:08:54 +0000300
301 // Describes this matcher to an ostream.
302 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
303
304 // Describes the negation of this matcher to an ostream.
305 void DescribeNegationTo(::std::ostream* os) const {
306 impl_->DescribeNegationTo(os);
307 }
308
309 // Explains why x matches, or doesn't match, the matcher.
Gennadiy Civile55089e2018-04-04 14:05:00 -0400310 void ExplainMatchResultTo(GTEST_REFERENCE_TO_CONST_(T) x,
311 ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000312 StreamMatchResultListener listener(os);
313 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000314 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000315
zhanyong.wanfb25d532013-07-28 08:24:00 +0000316 // Returns the describer for this matcher object; retains ownership
317 // of the describer, which is only guaranteed to be alive when
318 // this matcher object is alive.
319 const MatcherDescriberInterface* GetDescriber() const {
320 return impl_.get();
321 }
322
shiqiane35fdd92008-12-10 05:08:54 +0000323 protected:
324 MatcherBase() {}
325
326 // Constructs a matcher from its implementation.
Gennadiy Civile55089e2018-04-04 14:05:00 -0400327 explicit MatcherBase(
328 const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)>* impl)
shiqiane35fdd92008-12-10 05:08:54 +0000329 : impl_(impl) {}
330
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400331 template <typename U>
332 explicit MatcherBase(
333 const MatcherInterface<U>* impl,
334 typename internal::EnableIf<
335 !internal::IsSame<U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* =
336 NULL)
337 : impl_(new internal::MatcherInterfaceAdapter<U>(impl)) {}
338
shiqiane35fdd92008-12-10 05:08:54 +0000339 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000340
shiqiane35fdd92008-12-10 05:08:54 +0000341 private:
342 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
343 // interfaces. The former dynamically allocates a chunk of memory
344 // to hold the reference count, while the latter tracks all
345 // references using a circular linked list without allocating
346 // memory. It has been observed that linked_ptr performs better in
347 // typical scenarios. However, shared_ptr can out-perform
348 // linked_ptr when there are many more uses of the copy constructor
349 // than the default constructor.
350 //
351 // If performance becomes a problem, we should see if using
352 // shared_ptr helps.
Gennadiy Civile55089e2018-04-04 14:05:00 -0400353 ::testing::internal::linked_ptr<
354 const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> >
355 impl_;
shiqiane35fdd92008-12-10 05:08:54 +0000356};
357
shiqiane35fdd92008-12-10 05:08:54 +0000358} // namespace internal
359
360// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
361// object that can check whether a value of type T matches. The
362// implementation of Matcher<T> is just a linked_ptr to const
363// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
364// from Matcher!
365template <typename T>
366class Matcher : public internal::MatcherBase<T> {
367 public:
vladlosev88032d82010-11-17 23:29:21 +0000368 // Constructs a null matcher. Needed for storing Matcher objects in STL
369 // containers. A default-constructed matcher is not yet initialized. You
370 // cannot use it until a valid value has been assigned to it.
kosakd86a7232015-07-13 21:19:43 +0000371 explicit Matcher() {} // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000372
373 // Constructs a matcher from its implementation.
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400374 explicit Matcher(const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)>* impl)
375 : internal::MatcherBase<T>(impl) {}
376
377 template <typename U>
378 explicit Matcher(const MatcherInterface<U>* impl,
379 typename internal::EnableIf<!internal::IsSame<
380 U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* = NULL)
shiqiane35fdd92008-12-10 05:08:54 +0000381 : internal::MatcherBase<T>(impl) {}
382
zhanyong.wan18490652009-05-11 18:54:08 +0000383 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000384 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
385 Matcher(T value); // NOLINT
386};
387
388// The following two specializations allow the user to write str
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400389// instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
shiqiane35fdd92008-12-10 05:08:54 +0000390// matcher is expected.
391template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400392class GTEST_API_ Matcher<const std::string&>
393 : public internal::MatcherBase<const std::string&> {
shiqiane35fdd92008-12-10 05:08:54 +0000394 public:
395 Matcher() {}
396
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400397 explicit Matcher(const MatcherInterface<const std::string&>* impl)
398 : internal::MatcherBase<const std::string&>(impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000399
400 // Allows the user to write str instead of Eq(str) sometimes, where
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400401 // str is a std::string object.
402 Matcher(const std::string& s); // NOLINT
403
404#if GTEST_HAS_GLOBAL_STRING
405 // Allows the user to write str instead of Eq(str) sometimes, where
406 // str is a ::string object.
407 Matcher(const ::string& s); // NOLINT
408#endif // GTEST_HAS_GLOBAL_STRING
shiqiane35fdd92008-12-10 05:08:54 +0000409
410 // Allows the user to write "foo" instead of Eq("foo") sometimes.
411 Matcher(const char* s); // NOLINT
412};
413
414template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400415class GTEST_API_ Matcher<std::string>
416 : public internal::MatcherBase<std::string> {
shiqiane35fdd92008-12-10 05:08:54 +0000417 public:
418 Matcher() {}
419
Gennadiy Civile55089e2018-04-04 14:05:00 -0400420 explicit Matcher(const MatcherInterface<const std::string&>* impl)
421 : internal::MatcherBase<std::string>(impl) {}
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400422 explicit Matcher(const MatcherInterface<std::string>* impl)
423 : internal::MatcherBase<std::string>(impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000424
425 // Allows the user to write str instead of Eq(str) sometimes, where
426 // str is a string object.
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400427 Matcher(const std::string& s); // NOLINT
428
429#if GTEST_HAS_GLOBAL_STRING
430 // Allows the user to write str instead of Eq(str) sometimes, where
431 // str is a ::string object.
432 Matcher(const ::string& s); // NOLINT
433#endif // GTEST_HAS_GLOBAL_STRING
shiqiane35fdd92008-12-10 05:08:54 +0000434
435 // Allows the user to write "foo" instead of Eq("foo") sometimes.
436 Matcher(const char* s); // NOLINT
437};
438
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400439#if GTEST_HAS_GLOBAL_STRING
zhanyong.wan1f122a02013-03-25 16:27:03 +0000440// The following two specializations allow the user to write str
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400441// instead of Eq(str) and "foo" instead of Eq("foo") when a ::string
zhanyong.wan1f122a02013-03-25 16:27:03 +0000442// matcher is expected.
443template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400444class GTEST_API_ Matcher<const ::string&>
445 : public internal::MatcherBase<const ::string&> {
zhanyong.wan1f122a02013-03-25 16:27:03 +0000446 public:
447 Matcher() {}
448
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400449 explicit Matcher(const MatcherInterface<const ::string&>* impl)
450 : internal::MatcherBase<const ::string&>(impl) {}
zhanyong.wan1f122a02013-03-25 16:27:03 +0000451
452 // Allows the user to write str instead of Eq(str) sometimes, where
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400453 // str is a std::string object.
454 Matcher(const std::string& s); // NOLINT
455
456 // Allows the user to write str instead of Eq(str) sometimes, where
457 // str is a ::string object.
458 Matcher(const ::string& s); // NOLINT
zhanyong.wan1f122a02013-03-25 16:27:03 +0000459
460 // Allows the user to write "foo" instead of Eq("foo") sometimes.
461 Matcher(const char* s); // NOLINT
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400462};
zhanyong.wan1f122a02013-03-25 16:27:03 +0000463
zhanyong.wan1f122a02013-03-25 16:27:03 +0000464template <>
Gennadiy Civile55089e2018-04-04 14:05:00 -0400465class GTEST_API_ Matcher< ::string>
466 : public internal::MatcherBase< ::string> {
zhanyong.wan1f122a02013-03-25 16:27:03 +0000467 public:
468 Matcher() {}
469
Gennadiy Civile55089e2018-04-04 14:05:00 -0400470 explicit Matcher(const MatcherInterface<const ::string&>* impl)
471 : internal::MatcherBase< ::string>(impl) {}
472 explicit Matcher(const MatcherInterface< ::string>* impl)
473 : internal::MatcherBase< ::string>(impl) {}
zhanyong.wan1f122a02013-03-25 16:27:03 +0000474
475 // Allows the user to write str instead of Eq(str) sometimes, where
Gennadiy Civile55089e2018-04-04 14:05:00 -0400476 // str is a std::string object.
477 Matcher(const std::string& s); // NOLINT
478
479 // Allows the user to write str instead of Eq(str) sometimes, where
480 // str is a ::string object.
481 Matcher(const ::string& s); // NOLINT
482
483 // Allows the user to write "foo" instead of Eq("foo") sometimes.
484 Matcher(const char* s); // NOLINT
485};
486#endif // GTEST_HAS_GLOBAL_STRING
487
488#if GTEST_HAS_ABSL
489// The following two specializations allow the user to write str
490// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
491// matcher is expected.
492template <>
493class GTEST_API_ Matcher<const absl::string_view&>
494 : public internal::MatcherBase<const absl::string_view&> {
495 public:
496 Matcher() {}
497
498 explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
499 : internal::MatcherBase<const absl::string_view&>(impl) {}
500
501 // Allows the user to write str instead of Eq(str) sometimes, where
502 // str is a std::string object.
503 Matcher(const std::string& s); // NOLINT
504
505#if GTEST_HAS_GLOBAL_STRING
506 // Allows the user to write str instead of Eq(str) sometimes, where
507 // str is a ::string object.
508 Matcher(const ::string& s); // NOLINT
509#endif // GTEST_HAS_GLOBAL_STRING
zhanyong.wan1f122a02013-03-25 16:27:03 +0000510
511 // Allows the user to write "foo" instead of Eq("foo") sometimes.
512 Matcher(const char* s); // NOLINT
513
Gennadiy Civile55089e2018-04-04 14:05:00 -0400514 // Allows the user to pass absl::string_views directly.
515 Matcher(absl::string_view s); // NOLINT
zhanyong.wan1f122a02013-03-25 16:27:03 +0000516};
Gennadiy Civile55089e2018-04-04 14:05:00 -0400517
518template <>
519class GTEST_API_ Matcher<absl::string_view>
520 : public internal::MatcherBase<absl::string_view> {
521 public:
522 Matcher() {}
523
524 explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
525 : internal::MatcherBase<absl::string_view>(impl) {}
526 explicit Matcher(const MatcherInterface<absl::string_view>* impl)
527 : internal::MatcherBase<absl::string_view>(impl) {}
528
529 // Allows the user to write str instead of Eq(str) sometimes, where
530 // str is a std::string object.
531 Matcher(const std::string& s); // NOLINT
532
533#if GTEST_HAS_GLOBAL_STRING
534 // Allows the user to write str instead of Eq(str) sometimes, where
535 // str is a ::string object.
536 Matcher(const ::string& s); // NOLINT
537#endif // GTEST_HAS_GLOBAL_STRING
538
539 // Allows the user to write "foo" instead of Eq("foo") sometimes.
540 Matcher(const char* s); // NOLINT
541
542 // Allows the user to pass absl::string_views directly.
543 Matcher(absl::string_view s); // NOLINT
544};
545#endif // GTEST_HAS_ABSL
546
547// Prints a matcher in a human-readable format.
548template <typename T>
549std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
550 matcher.DescribeTo(&os);
551 return os;
552}
zhanyong.wan1f122a02013-03-25 16:27:03 +0000553
shiqiane35fdd92008-12-10 05:08:54 +0000554// The PolymorphicMatcher class template makes it easy to implement a
555// polymorphic matcher (i.e. a matcher that can match values of more
556// than one type, e.g. Eq(n) and NotNull()).
557//
zhanyong.wandb22c222010-01-28 21:52:29 +0000558// To define a polymorphic matcher, a user should provide an Impl
559// class that has a DescribeTo() method and a DescribeNegationTo()
560// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000561//
zhanyong.wandb22c222010-01-28 21:52:29 +0000562// bool MatchAndExplain(const Value& value,
563// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000564//
565// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000566template <class Impl>
567class PolymorphicMatcher {
568 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000569 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000570
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000571 // Returns a mutable reference to the underlying matcher
572 // implementation object.
573 Impl& mutable_impl() { return impl_; }
574
575 // Returns an immutable reference to the underlying matcher
576 // implementation object.
577 const Impl& impl() const { return impl_; }
578
shiqiane35fdd92008-12-10 05:08:54 +0000579 template <typename T>
580 operator Matcher<T>() const {
Gennadiy Civile55089e2018-04-04 14:05:00 -0400581 return Matcher<T>(new MonomorphicImpl<GTEST_REFERENCE_TO_CONST_(T)>(impl_));
shiqiane35fdd92008-12-10 05:08:54 +0000582 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000583
shiqiane35fdd92008-12-10 05:08:54 +0000584 private:
585 template <typename T>
586 class MonomorphicImpl : public MatcherInterface<T> {
587 public:
588 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
589
shiqiane35fdd92008-12-10 05:08:54 +0000590 virtual void DescribeTo(::std::ostream* os) const {
591 impl_.DescribeTo(os);
592 }
593
594 virtual void DescribeNegationTo(::std::ostream* os) const {
595 impl_.DescribeNegationTo(os);
596 }
597
zhanyong.wan82113312010-01-08 21:55:40 +0000598 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000599 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000600 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000601
shiqiane35fdd92008-12-10 05:08:54 +0000602 private:
603 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000604
605 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000606 };
607
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000608 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000609
610 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000611};
612
613// Creates a matcher from its implementation. This is easier to use
614// than the Matcher<T> constructor as it doesn't require you to
615// explicitly write the template argument, e.g.
616//
617// MakeMatcher(foo);
618// vs
619// Matcher<const string&>(foo);
620template <typename T>
621inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
622 return Matcher<T>(impl);
zhanyong.wan2eab17b2013-03-08 17:53:24 +0000623}
shiqiane35fdd92008-12-10 05:08:54 +0000624
625// Creates a polymorphic matcher from its implementation. This is
626// easier to use than the PolymorphicMatcher<Impl> constructor as it
627// doesn't require you to explicitly write the template argument, e.g.
628//
629// MakePolymorphicMatcher(foo);
630// vs
631// PolymorphicMatcher<TypeOfFoo>(foo);
632template <class Impl>
633inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
634 return PolymorphicMatcher<Impl>(impl);
635}
636
jgm79a367e2012-04-10 16:02:11 +0000637// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
638// and MUST NOT BE USED IN USER CODE!!!
639namespace internal {
640
641// The MatcherCastImpl class template is a helper for implementing
642// MatcherCast(). We need this helper in order to partially
643// specialize the implementation of MatcherCast() (C++ allows
644// class/struct templates to be partially specialized, but not
645// function templates.).
646
647// This general version is used when MatcherCast()'s argument is a
648// polymorphic matcher (i.e. something that can be converted to a
649// Matcher but is not one yet; for example, Eq(value)) or a value (for
650// example, "hello").
651template <typename T, typename M>
652class MatcherCastImpl {
653 public:
kosak5f2a6ca2013-12-03 01:43:07 +0000654 static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
Gennadiy Civil2bd17502018-02-27 13:51:09 -0500655 // M can be a polymorphic matcher, in which case we want to use
jgm79a367e2012-04-10 16:02:11 +0000656 // its conversion operator to create Matcher<T>. Or it can be a value
657 // that should be passed to the Matcher<T>'s constructor.
658 //
659 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
660 // polymorphic matcher because it'll be ambiguous if T has an implicit
661 // constructor from M (this usually happens when T has an implicit
662 // constructor from any type).
663 //
664 // It won't work to unconditionally implict_cast
665 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
666 // a user-defined conversion from M to T if one exists (assuming M is
667 // a value).
668 return CastImpl(
669 polymorphic_matcher_or_value,
670 BooleanConstant<
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400671 internal::ImplicitlyConvertible<M, Matcher<T> >::value>(),
672 BooleanConstant<
673 internal::ImplicitlyConvertible<M, T>::value>());
jgm79a367e2012-04-10 16:02:11 +0000674 }
675
676 private:
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400677 template <bool Ignore>
kosak5f2a6ca2013-12-03 01:43:07 +0000678 static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400679 BooleanConstant<true> /* convertible_to_matcher */,
680 BooleanConstant<Ignore>) {
jgm79a367e2012-04-10 16:02:11 +0000681 // M is implicitly convertible to Matcher<T>, which means that either
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400682 // M is a polymorphic matcher or Matcher<T> has an implicit constructor
jgm79a367e2012-04-10 16:02:11 +0000683 // from M. In both cases using the implicit conversion will produce a
684 // matcher.
685 //
686 // Even if T has an implicit constructor from M, it won't be called because
687 // creating Matcher<T> would require a chain of two user-defined conversions
688 // (first to create T from M and then to create Matcher<T> from T).
689 return polymorphic_matcher_or_value;
690 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400691
692 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
693 // matcher. It's a value of a type implicitly convertible to T. Use direct
694 // initialization to create a matcher.
695 static Matcher<T> CastImpl(
696 const M& value, BooleanConstant<false> /* convertible_to_matcher */,
697 BooleanConstant<true> /* convertible_to_T */) {
698 return Matcher<T>(ImplicitCast_<T>(value));
699 }
700
701 // M can't be implicitly converted to either Matcher<T> or T. Attempt to use
702 // polymorphic matcher Eq(value) in this case.
703 //
704 // Note that we first attempt to perform an implicit cast on the value and
705 // only fall back to the polymorphic Eq() matcher afterwards because the
706 // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end
707 // which might be undefined even when Rhs is implicitly convertible to Lhs
708 // (e.g. std::pair<const int, int> vs. std::pair<int, int>).
709 //
710 // We don't define this method inline as we need the declaration of Eq().
711 static Matcher<T> CastImpl(
712 const M& value, BooleanConstant<false> /* convertible_to_matcher */,
713 BooleanConstant<false> /* convertible_to_T */);
jgm79a367e2012-04-10 16:02:11 +0000714};
715
716// This more specialized version is used when MatcherCast()'s argument
717// is already a Matcher. This only compiles when type T can be
718// statically converted to type U.
719template <typename T, typename U>
720class MatcherCastImpl<T, Matcher<U> > {
721 public:
722 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
723 return Matcher<T>(new Impl(source_matcher));
724 }
725
726 private:
727 class Impl : public MatcherInterface<T> {
728 public:
729 explicit Impl(const Matcher<U>& source_matcher)
730 : source_matcher_(source_matcher) {}
731
732 // We delegate the matching logic to the source matcher.
733 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
Gennadiy Civilb907c262018-03-23 11:42:41 -0400734#if GTEST_LANG_CXX11
735 using FromType = typename std::remove_cv<typename std::remove_pointer<
736 typename std::remove_reference<T>::type>::type>::type;
737 using ToType = typename std::remove_cv<typename std::remove_pointer<
738 typename std::remove_reference<U>::type>::type>::type;
739 // Do not allow implicitly converting base*/& to derived*/&.
740 static_assert(
741 // Do not trigger if only one of them is a pointer. That implies a
742 // regular conversion and not a down_cast.
743 (std::is_pointer<typename std::remove_reference<T>::type>::value !=
744 std::is_pointer<typename std::remove_reference<U>::type>::value) ||
745 std::is_same<FromType, ToType>::value ||
746 !std::is_base_of<FromType, ToType>::value,
747 "Can't implicitly convert from <base> to <derived>");
748#endif // GTEST_LANG_CXX11
749
jgm79a367e2012-04-10 16:02:11 +0000750 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
751 }
752
753 virtual void DescribeTo(::std::ostream* os) const {
754 source_matcher_.DescribeTo(os);
755 }
756
757 virtual void DescribeNegationTo(::std::ostream* os) const {
758 source_matcher_.DescribeNegationTo(os);
759 }
760
761 private:
762 const Matcher<U> source_matcher_;
763
764 GTEST_DISALLOW_ASSIGN_(Impl);
765 };
766};
767
768// This even more specialized version is used for efficiently casting
769// a matcher to its own type.
770template <typename T>
771class MatcherCastImpl<T, Matcher<T> > {
772 public:
773 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
774};
775
776} // namespace internal
777
shiqiane35fdd92008-12-10 05:08:54 +0000778// In order to be safe and clear, casting between different matcher
779// types is done explicitly via MatcherCast<T>(m), which takes a
780// matcher m and returns a Matcher<T>. It compiles only when T can be
781// statically converted to the argument type of m.
782template <typename T, typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000783inline Matcher<T> MatcherCast(const M& matcher) {
jgm79a367e2012-04-10 16:02:11 +0000784 return internal::MatcherCastImpl<T, M>::Cast(matcher);
785}
shiqiane35fdd92008-12-10 05:08:54 +0000786
zhanyong.wan18490652009-05-11 18:54:08 +0000787// Implements SafeMatcherCast().
788//
zhanyong.wan95b12332009-09-25 18:55:50 +0000789// We use an intermediate class to do the actual safe casting as Nokia's
790// Symbian compiler cannot decide between
791// template <T, M> ... (M) and
792// template <T, U> ... (const Matcher<U>&)
793// for function templates but can for member function templates.
794template <typename T>
795class SafeMatcherCastImpl {
796 public:
jgm79a367e2012-04-10 16:02:11 +0000797 // This overload handles polymorphic matchers and values only since
798 // monomorphic matchers are handled by the next one.
zhanyong.wan95b12332009-09-25 18:55:50 +0000799 template <typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000800 static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
jgm79a367e2012-04-10 16:02:11 +0000801 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
zhanyong.wan95b12332009-09-25 18:55:50 +0000802 }
zhanyong.wan18490652009-05-11 18:54:08 +0000803
zhanyong.wan95b12332009-09-25 18:55:50 +0000804 // This overload handles monomorphic matchers.
805 //
806 // In general, if type T can be implicitly converted to type U, we can
807 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
808 // contravariant): just keep a copy of the original Matcher<U>, convert the
809 // argument from type T to U, and then pass it to the underlying Matcher<U>.
810 // The only exception is when U is a reference and T is not, as the
811 // underlying Matcher<U> may be interested in the argument's address, which
812 // is not preserved in the conversion from T to U.
813 template <typename U>
814 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
815 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000816 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000817 T_must_be_implicitly_convertible_to_U);
818 // Enforce that we are not converting a non-reference type T to a reference
819 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000820 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000821 internal::is_reference<T>::value || !internal::is_reference<U>::value,
Hector Dearman24054ff2017-06-19 18:27:33 +0100822 cannot_convert_non_reference_arg_to_reference);
zhanyong.wan95b12332009-09-25 18:55:50 +0000823 // In case both T and U are arithmetic types, enforce that the
824 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000825 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
826 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000827 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
828 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000829 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000830 kTIsOther || kUIsOther ||
831 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
832 conversion_of_arithmetic_types_must_be_lossless);
833 return MatcherCast<T>(matcher);
834 }
835};
836
837template <typename T, typename M>
838inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
839 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000840}
841
shiqiane35fdd92008-12-10 05:08:54 +0000842// A<T>() returns a matcher that matches any value of type T.
843template <typename T>
844Matcher<T> A();
845
846// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
847// and MUST NOT BE USED IN USER CODE!!!
848namespace internal {
849
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000850// If the explanation is not empty, prints it to the ostream.
Nico Weber09fd5b32017-05-15 17:07:03 -0400851inline void PrintIfNotEmpty(const std::string& explanation,
zhanyong.wanfb25d532013-07-28 08:24:00 +0000852 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000853 if (explanation != "" && os != NULL) {
854 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000855 }
856}
857
zhanyong.wan736baa82010-09-27 17:44:16 +0000858// Returns true if the given type name is easy to read by a human.
859// This is used to decide whether printing the type of a value might
860// be helpful.
Nico Weber09fd5b32017-05-15 17:07:03 -0400861inline bool IsReadableTypeName(const std::string& type_name) {
zhanyong.wan736baa82010-09-27 17:44:16 +0000862 // We consider a type name readable if it's short or doesn't contain
863 // a template or function type.
864 return (type_name.length() <= 20 ||
Nico Weber09fd5b32017-05-15 17:07:03 -0400865 type_name.find_first_of("<(") == std::string::npos);
zhanyong.wan736baa82010-09-27 17:44:16 +0000866}
867
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000868// Matches the value against the given matcher, prints the value and explains
869// the match result to the listener. Returns the match result.
870// 'listener' must not be NULL.
871// Value cannot be passed by const reference, because some matchers take a
872// non-const argument.
873template <typename Value, typename T>
874bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
875 MatchResultListener* listener) {
876 if (!listener->IsInterested()) {
877 // If the listener is not interested, we do not need to construct the
878 // inner explanation.
879 return matcher.Matches(value);
880 }
881
882 StringMatchResultListener inner_listener;
883 const bool match = matcher.MatchAndExplain(value, &inner_listener);
884
885 UniversalPrint(value, listener->stream());
zhanyong.wan736baa82010-09-27 17:44:16 +0000886#if GTEST_HAS_RTTI
Nico Weber09fd5b32017-05-15 17:07:03 -0400887 const std::string& type_name = GetTypeName<Value>();
zhanyong.wan736baa82010-09-27 17:44:16 +0000888 if (IsReadableTypeName(type_name))
889 *listener->stream() << " (of type " << type_name << ")";
890#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000891 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000892
893 return match;
894}
895
shiqiane35fdd92008-12-10 05:08:54 +0000896// An internal helper class for doing compile-time loop on a tuple's
897// fields.
898template <size_t N>
899class TuplePrefix {
900 public:
901 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
902 // iff the first N fields of matcher_tuple matches the first N
903 // fields of value_tuple, respectively.
904 template <typename MatcherTuple, typename ValueTuple>
905 static bool Matches(const MatcherTuple& matcher_tuple,
906 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000907 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
908 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
909 }
910
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000911 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000912 // describes failures in matching the first N fields of matchers
913 // against the first N fields of values. If there is no failure,
914 // nothing will be streamed to os.
915 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000916 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
917 const ValueTuple& values,
918 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000919 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000920 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000921
922 // Then describes the failure (if any) in the (N - 1)-th (0-based)
923 // field.
924 typename tuple_element<N - 1, MatcherTuple>::type matcher =
925 get<N - 1>(matchers);
926 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
Gennadiy Civile55089e2018-04-04 14:05:00 -0400927 GTEST_REFERENCE_TO_CONST_(Value) value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000928 StringMatchResultListener listener;
929 if (!matcher.MatchAndExplain(value, &listener)) {
Gennadiy Civil265efde2018-08-14 15:04:11 -0400930 // FIXME: include in the message the name of the parameter
shiqiane35fdd92008-12-10 05:08:54 +0000931 // as used in MOCK_METHOD*() when possible.
932 *os << " Expected arg #" << N - 1 << ": ";
933 get<N - 1>(matchers).DescribeTo(os);
934 *os << "\n Actual: ";
935 // We remove the reference in type Value to prevent the
936 // universal printer from printing the address of value, which
937 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000938 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000939 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000940 internal::UniversalPrint(value, os);
941 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000942 *os << "\n";
943 }
944 }
945};
946
947// The base case.
948template <>
949class TuplePrefix<0> {
950 public:
951 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000952 static bool Matches(const MatcherTuple& /* matcher_tuple */,
953 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000954 return true;
955 }
956
957 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000958 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
959 const ValueTuple& /* values */,
960 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000961};
962
963// TupleMatches(matcher_tuple, value_tuple) returns true iff all
964// matchers in matcher_tuple match the corresponding fields in
965// value_tuple. It is a compiler error if matcher_tuple and
966// value_tuple have different number of fields or incompatible field
967// types.
968template <typename MatcherTuple, typename ValueTuple>
969bool TupleMatches(const MatcherTuple& matcher_tuple,
970 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000971 // Makes sure that matcher_tuple and value_tuple have the same
972 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000973 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000974 tuple_size<ValueTuple>::value,
975 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000976 return TuplePrefix<tuple_size<ValueTuple>::value>::
977 Matches(matcher_tuple, value_tuple);
978}
979
980// Describes failures in matching matchers against values. If there
981// is no failure, nothing will be streamed to os.
982template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000983void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
984 const ValueTuple& values,
985 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000986 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000987 matchers, values, os);
988}
989
zhanyong.wanfb25d532013-07-28 08:24:00 +0000990// TransformTupleValues and its helper.
991//
992// TransformTupleValuesHelper hides the internal machinery that
993// TransformTupleValues uses to implement a tuple traversal.
994template <typename Tuple, typename Func, typename OutIter>
995class TransformTupleValuesHelper {
996 private:
kosakbd018832014-04-02 20:30:00 +0000997 typedef ::testing::tuple_size<Tuple> TupleSize;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000998
999 public:
1000 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
1001 // Returns the final value of 'out' in case the caller needs it.
1002 static OutIter Run(Func f, const Tuple& t, OutIter out) {
1003 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
1004 }
1005
1006 private:
1007 template <typename Tup, size_t kRemainingSize>
1008 struct IterateOverTuple {
1009 OutIter operator() (Func f, const Tup& t, OutIter out) const {
kosakbd018832014-04-02 20:30:00 +00001010 *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
zhanyong.wanfb25d532013-07-28 08:24:00 +00001011 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
1012 }
1013 };
1014 template <typename Tup>
1015 struct IterateOverTuple<Tup, 0> {
1016 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
1017 return out;
1018 }
1019 };
1020};
1021
1022// Successively invokes 'f(element)' on each element of the tuple 't',
1023// appending each result to the 'out' iterator. Returns the final value
1024// of 'out'.
1025template <typename Tuple, typename Func, typename OutIter>
1026OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
1027 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
1028}
1029
shiqiane35fdd92008-12-10 05:08:54 +00001030// Implements A<T>().
1031template <typename T>
Gennadiy Civile55089e2018-04-04 14:05:00 -04001032class AnyMatcherImpl : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
shiqiane35fdd92008-12-10 05:08:54 +00001033 public:
Gennadiy Civile55089e2018-04-04 14:05:00 -04001034 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) /* x */,
1035 MatchResultListener* /* listener */) const {
1036 return true;
1037 }
shiqiane35fdd92008-12-10 05:08:54 +00001038 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
1039 virtual void DescribeNegationTo(::std::ostream* os) const {
1040 // This is mostly for completeness' safe, as it's not very useful
1041 // to write Not(A<bool>()). However we cannot completely rule out
1042 // such a possibility, and it doesn't hurt to be prepared.
1043 *os << "never matches";
1044 }
1045};
1046
1047// Implements _, a matcher that matches any value of any
1048// type. This is a polymorphic matcher, so we need a template type
1049// conversion operator to make it appearing as a Matcher<T> for any
1050// type T.
1051class AnythingMatcher {
1052 public:
1053 template <typename T>
1054 operator Matcher<T>() const { return A<T>(); }
1055};
1056
1057// Implements a matcher that compares a given value with a
1058// pre-supplied value using one of the ==, <=, <, etc, operators. The
1059// two values being compared don't have to have the same type.
1060//
1061// The matcher defined here is polymorphic (for example, Eq(5) can be
1062// used to match an int, a short, a double, etc). Therefore we use
1063// a template type conversion operator in the implementation.
1064//
shiqiane35fdd92008-12-10 05:08:54 +00001065// The following template definition assumes that the Rhs parameter is
1066// a "bare" type (i.e. neither 'const T' nor 'T&').
kosak506340a2014-11-17 01:47:54 +00001067template <typename D, typename Rhs, typename Op>
1068class ComparisonBase {
1069 public:
1070 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
1071 template <typename Lhs>
1072 operator Matcher<Lhs>() const {
1073 return MakeMatcher(new Impl<Lhs>(rhs_));
shiqiane35fdd92008-12-10 05:08:54 +00001074 }
1075
kosak506340a2014-11-17 01:47:54 +00001076 private:
1077 template <typename Lhs>
1078 class Impl : public MatcherInterface<Lhs> {
1079 public:
1080 explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
1081 virtual bool MatchAndExplain(
1082 Lhs lhs, MatchResultListener* /* listener */) const {
1083 return Op()(lhs, rhs_);
1084 }
1085 virtual void DescribeTo(::std::ostream* os) const {
1086 *os << D::Desc() << " ";
1087 UniversalPrint(rhs_, os);
1088 }
1089 virtual void DescribeNegationTo(::std::ostream* os) const {
1090 *os << D::NegatedDesc() << " ";
1091 UniversalPrint(rhs_, os);
1092 }
1093 private:
1094 Rhs rhs_;
1095 GTEST_DISALLOW_ASSIGN_(Impl);
1096 };
1097 Rhs rhs_;
1098 GTEST_DISALLOW_ASSIGN_(ComparisonBase);
1099};
shiqiane35fdd92008-12-10 05:08:54 +00001100
kosak506340a2014-11-17 01:47:54 +00001101template <typename Rhs>
1102class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
1103 public:
1104 explicit EqMatcher(const Rhs& rhs)
1105 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
1106 static const char* Desc() { return "is equal to"; }
1107 static const char* NegatedDesc() { return "isn't equal to"; }
1108};
1109template <typename Rhs>
1110class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
1111 public:
1112 explicit NeMatcher(const Rhs& rhs)
1113 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
1114 static const char* Desc() { return "isn't equal to"; }
1115 static const char* NegatedDesc() { return "is equal to"; }
1116};
1117template <typename Rhs>
1118class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
1119 public:
1120 explicit LtMatcher(const Rhs& rhs)
1121 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
1122 static const char* Desc() { return "is <"; }
1123 static const char* NegatedDesc() { return "isn't <"; }
1124};
1125template <typename Rhs>
1126class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
1127 public:
1128 explicit GtMatcher(const Rhs& rhs)
1129 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
1130 static const char* Desc() { return "is >"; }
1131 static const char* NegatedDesc() { return "isn't >"; }
1132};
1133template <typename Rhs>
1134class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
1135 public:
1136 explicit LeMatcher(const Rhs& rhs)
1137 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
1138 static const char* Desc() { return "is <="; }
1139 static const char* NegatedDesc() { return "isn't <="; }
1140};
1141template <typename Rhs>
1142class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
1143 public:
1144 explicit GeMatcher(const Rhs& rhs)
1145 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
1146 static const char* Desc() { return "is >="; }
1147 static const char* NegatedDesc() { return "isn't >="; }
1148};
shiqiane35fdd92008-12-10 05:08:54 +00001149
vladlosev79b83502009-11-18 00:43:37 +00001150// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001151// pointer that is NULL.
1152class IsNullMatcher {
1153 public:
vladlosev79b83502009-11-18 00:43:37 +00001154 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +00001155 bool MatchAndExplain(const Pointer& p,
1156 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001157#if GTEST_LANG_CXX11
1158 return p == nullptr;
1159#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001160 return GetRawPointer(p) == NULL;
kosak6305ff52015-04-28 22:36:31 +00001161#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001162 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001163
1164 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
1165 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001166 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001167 }
1168};
1169
vladlosev79b83502009-11-18 00:43:37 +00001170// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +00001171// pointer that is not NULL.
1172class NotNullMatcher {
1173 public:
vladlosev79b83502009-11-18 00:43:37 +00001174 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +00001175 bool MatchAndExplain(const Pointer& p,
1176 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001177#if GTEST_LANG_CXX11
1178 return p != nullptr;
1179#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001180 return GetRawPointer(p) != NULL;
kosak6305ff52015-04-28 22:36:31 +00001181#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001182 }
shiqiane35fdd92008-12-10 05:08:54 +00001183
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001184 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +00001185 void DescribeNegationTo(::std::ostream* os) const {
1186 *os << "is NULL";
1187 }
1188};
1189
1190// Ref(variable) matches any argument that is a reference to
1191// 'variable'. This matcher is polymorphic as it can match any
1192// super type of the type of 'variable'.
1193//
1194// The RefMatcher template class implements Ref(variable). It can
1195// only be instantiated with a reference type. This prevents a user
1196// from mistakenly using Ref(x) to match a non-reference function
1197// argument. For example, the following will righteously cause a
1198// compiler error:
1199//
1200// int n;
1201// Matcher<int> m1 = Ref(n); // This won't compile.
1202// Matcher<int&> m2 = Ref(n); // This will compile.
1203template <typename T>
1204class RefMatcher;
1205
1206template <typename T>
1207class RefMatcher<T&> {
1208 // Google Mock is a generic framework and thus needs to support
1209 // mocking any function types, including those that take non-const
1210 // reference arguments. Therefore the template parameter T (and
1211 // Super below) can be instantiated to either a const type or a
1212 // non-const type.
1213 public:
1214 // RefMatcher() takes a T& instead of const T&, as we want the
1215 // compiler to catch using Ref(const_value) as a matcher for a
1216 // non-const reference.
1217 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
1218
1219 template <typename Super>
1220 operator Matcher<Super&>() const {
1221 // By passing object_ (type T&) to Impl(), which expects a Super&,
1222 // we make sure that Super is a super type of T. In particular,
1223 // this catches using Ref(const_value) as a matcher for a
1224 // non-const reference, as you cannot implicitly convert a const
1225 // reference to a non-const reference.
1226 return MakeMatcher(new Impl<Super>(object_));
1227 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001228
shiqiane35fdd92008-12-10 05:08:54 +00001229 private:
1230 template <typename Super>
1231 class Impl : public MatcherInterface<Super&> {
1232 public:
1233 explicit Impl(Super& x) : object_(x) {} // NOLINT
1234
zhanyong.wandb22c222010-01-28 21:52:29 +00001235 // MatchAndExplain() takes a Super& (as opposed to const Super&)
1236 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +00001237 virtual bool MatchAndExplain(
1238 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001239 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +00001240 return &x == &object_;
1241 }
shiqiane35fdd92008-12-10 05:08:54 +00001242
1243 virtual void DescribeTo(::std::ostream* os) const {
1244 *os << "references the variable ";
1245 UniversalPrinter<Super&>::Print(object_, os);
1246 }
1247
1248 virtual void DescribeNegationTo(::std::ostream* os) const {
1249 *os << "does not reference the variable ";
1250 UniversalPrinter<Super&>::Print(object_, os);
1251 }
1252
shiqiane35fdd92008-12-10 05:08:54 +00001253 private:
1254 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001255
1256 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001257 };
1258
1259 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001260
1261 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001262};
1263
1264// Polymorphic helper functions for narrow and wide string matchers.
1265inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1266 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1267}
1268
1269inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1270 const wchar_t* rhs) {
1271 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1272}
1273
1274// String comparison for narrow or wide strings that can have embedded NUL
1275// characters.
1276template <typename StringType>
1277bool CaseInsensitiveStringEquals(const StringType& s1,
1278 const StringType& s2) {
1279 // Are the heads equal?
1280 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1281 return false;
1282 }
1283
1284 // Skip the equal heads.
1285 const typename StringType::value_type nul = 0;
1286 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1287
1288 // Are we at the end of either s1 or s2?
1289 if (i1 == StringType::npos || i2 == StringType::npos) {
1290 return i1 == i2;
1291 }
1292
1293 // Are the tails equal?
1294 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1295}
1296
1297// String matchers.
1298
1299// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1300template <typename StringType>
1301class StrEqualityMatcher {
1302 public:
shiqiane35fdd92008-12-10 05:08:54 +00001303 StrEqualityMatcher(const StringType& str, bool expect_eq,
1304 bool case_sensitive)
1305 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1306
Gennadiy Civile55089e2018-04-04 14:05:00 -04001307#if GTEST_HAS_ABSL
1308 bool MatchAndExplain(const absl::string_view& s,
1309 MatchResultListener* listener) const {
1310 if (s.data() == NULL) {
1311 return !expect_eq_;
1312 }
1313 // This should fail to compile if absl::string_view is used with wide
1314 // strings.
1315 const StringType& str = string(s);
1316 return MatchAndExplain(str, listener);
1317 }
1318#endif // GTEST_HAS_ABSL
1319
jgm38513a82012-11-15 15:50:36 +00001320 // Accepts pointer types, particularly:
1321 // const char*
1322 // char*
1323 // const wchar_t*
1324 // wchar_t*
1325 template <typename CharType>
1326 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001327 if (s == NULL) {
1328 return !expect_eq_;
1329 }
zhanyong.wandb22c222010-01-28 21:52:29 +00001330 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001331 }
1332
jgm38513a82012-11-15 15:50:36 +00001333 // Matches anything that can convert to StringType.
1334 //
1335 // This is a template, not just a plain function with const StringType&,
Gennadiy Civile55089e2018-04-04 14:05:00 -04001336 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001337 template <typename MatcheeStringType>
1338 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001339 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001340 const StringType& s2(s);
1341 const bool eq = case_sensitive_ ? s2 == string_ :
1342 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +00001343 return expect_eq_ == eq;
1344 }
1345
1346 void DescribeTo(::std::ostream* os) const {
1347 DescribeToHelper(expect_eq_, os);
1348 }
1349
1350 void DescribeNegationTo(::std::ostream* os) const {
1351 DescribeToHelper(!expect_eq_, os);
1352 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001353
shiqiane35fdd92008-12-10 05:08:54 +00001354 private:
1355 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001356 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +00001357 *os << "equal to ";
1358 if (!case_sensitive_) {
1359 *os << "(ignoring case) ";
1360 }
vladloseve2e8ba42010-05-13 18:16:03 +00001361 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001362 }
1363
1364 const StringType string_;
1365 const bool expect_eq_;
1366 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001367
1368 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001369};
1370
1371// Implements the polymorphic HasSubstr(substring) matcher, which
1372// can be used as a Matcher<T> as long as T can be converted to a
1373// string.
1374template <typename StringType>
1375class HasSubstrMatcher {
1376 public:
shiqiane35fdd92008-12-10 05:08:54 +00001377 explicit HasSubstrMatcher(const StringType& substring)
1378 : substring_(substring) {}
1379
Gennadiy Civile55089e2018-04-04 14:05:00 -04001380#if GTEST_HAS_ABSL
1381 bool MatchAndExplain(const absl::string_view& s,
1382 MatchResultListener* listener) const {
1383 if (s.data() == NULL) {
1384 return false;
1385 }
1386 // This should fail to compile if absl::string_view is used with wide
1387 // strings.
1388 const StringType& str = string(s);
1389 return MatchAndExplain(str, listener);
1390 }
1391#endif // GTEST_HAS_ABSL
1392
jgm38513a82012-11-15 15:50:36 +00001393 // Accepts pointer types, particularly:
1394 // const char*
1395 // char*
1396 // const wchar_t*
1397 // wchar_t*
1398 template <typename CharType>
1399 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001400 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001401 }
1402
jgm38513a82012-11-15 15:50:36 +00001403 // Matches anything that can convert to StringType.
1404 //
1405 // This is a template, not just a plain function with const StringType&,
Gennadiy Civile55089e2018-04-04 14:05:00 -04001406 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001407 template <typename MatcheeStringType>
1408 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001409 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001410 const StringType& s2(s);
1411 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001412 }
1413
1414 // Describes what this matcher matches.
1415 void DescribeTo(::std::ostream* os) const {
1416 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001417 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001418 }
1419
1420 void DescribeNegationTo(::std::ostream* os) const {
1421 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001422 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001423 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001424
shiqiane35fdd92008-12-10 05:08:54 +00001425 private:
1426 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001427
1428 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001429};
1430
1431// Implements the polymorphic StartsWith(substring) matcher, which
1432// can be used as a Matcher<T> as long as T can be converted to a
1433// string.
1434template <typename StringType>
1435class StartsWithMatcher {
1436 public:
shiqiane35fdd92008-12-10 05:08:54 +00001437 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1438 }
1439
Gennadiy Civile55089e2018-04-04 14:05:00 -04001440#if GTEST_HAS_ABSL
1441 bool MatchAndExplain(const absl::string_view& s,
1442 MatchResultListener* listener) const {
1443 if (s.data() == NULL) {
1444 return false;
1445 }
1446 // This should fail to compile if absl::string_view is used with wide
1447 // strings.
1448 const StringType& str = string(s);
1449 return MatchAndExplain(str, listener);
1450 }
1451#endif // GTEST_HAS_ABSL
1452
jgm38513a82012-11-15 15:50:36 +00001453 // Accepts pointer types, particularly:
1454 // const char*
1455 // char*
1456 // const wchar_t*
1457 // wchar_t*
1458 template <typename CharType>
1459 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001460 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001461 }
1462
jgm38513a82012-11-15 15:50:36 +00001463 // Matches anything that can convert to StringType.
1464 //
1465 // This is a template, not just a plain function with const StringType&,
Gennadiy Civile55089e2018-04-04 14:05:00 -04001466 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001467 template <typename MatcheeStringType>
1468 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001469 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001470 const StringType& s2(s);
1471 return s2.length() >= prefix_.length() &&
1472 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001473 }
1474
1475 void DescribeTo(::std::ostream* os) const {
1476 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001477 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001478 }
1479
1480 void DescribeNegationTo(::std::ostream* os) const {
1481 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001482 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001483 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001484
shiqiane35fdd92008-12-10 05:08:54 +00001485 private:
1486 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001487
1488 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001489};
1490
1491// Implements the polymorphic EndsWith(substring) matcher, which
1492// can be used as a Matcher<T> as long as T can be converted to a
1493// string.
1494template <typename StringType>
1495class EndsWithMatcher {
1496 public:
shiqiane35fdd92008-12-10 05:08:54 +00001497 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1498
Gennadiy Civile55089e2018-04-04 14:05:00 -04001499#if GTEST_HAS_ABSL
1500 bool MatchAndExplain(const absl::string_view& s,
1501 MatchResultListener* listener) const {
1502 if (s.data() == NULL) {
1503 return false;
1504 }
1505 // This should fail to compile if absl::string_view is used with wide
1506 // strings.
1507 const StringType& str = string(s);
1508 return MatchAndExplain(str, listener);
1509 }
1510#endif // GTEST_HAS_ABSL
1511
jgm38513a82012-11-15 15:50:36 +00001512 // Accepts pointer types, particularly:
1513 // const char*
1514 // char*
1515 // const wchar_t*
1516 // wchar_t*
1517 template <typename CharType>
1518 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001519 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001520 }
1521
jgm38513a82012-11-15 15:50:36 +00001522 // Matches anything that can convert to StringType.
1523 //
1524 // This is a template, not just a plain function with const StringType&,
Gennadiy Civile55089e2018-04-04 14:05:00 -04001525 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001526 template <typename MatcheeStringType>
1527 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001528 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001529 const StringType& s2(s);
1530 return s2.length() >= suffix_.length() &&
1531 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001532 }
1533
1534 void DescribeTo(::std::ostream* os) const {
1535 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001536 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001537 }
1538
1539 void DescribeNegationTo(::std::ostream* os) const {
1540 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001541 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001542 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001543
shiqiane35fdd92008-12-10 05:08:54 +00001544 private:
1545 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001546
1547 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001548};
1549
shiqiane35fdd92008-12-10 05:08:54 +00001550// Implements polymorphic matchers MatchesRegex(regex) and
1551// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1552// T can be converted to a string.
1553class MatchesRegexMatcher {
1554 public:
1555 MatchesRegexMatcher(const RE* regex, bool full_match)
1556 : regex_(regex), full_match_(full_match) {}
1557
Gennadiy Civile55089e2018-04-04 14:05:00 -04001558#if GTEST_HAS_ABSL
1559 bool MatchAndExplain(const absl::string_view& s,
1560 MatchResultListener* listener) const {
1561 return s.data() && MatchAndExplain(string(s), listener);
1562 }
1563#endif // GTEST_HAS_ABSL
1564
jgm38513a82012-11-15 15:50:36 +00001565 // Accepts pointer types, particularly:
1566 // const char*
1567 // char*
1568 // const wchar_t*
1569 // wchar_t*
1570 template <typename CharType>
1571 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001572 return s != NULL && MatchAndExplain(std::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001573 }
1574
Nico Weber09fd5b32017-05-15 17:07:03 -04001575 // Matches anything that can convert to std::string.
jgm38513a82012-11-15 15:50:36 +00001576 //
Nico Weber09fd5b32017-05-15 17:07:03 -04001577 // This is a template, not just a plain function with const std::string&,
Gennadiy Civilb7c56832018-03-22 15:35:37 -04001578 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001579 template <class MatcheeStringType>
1580 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001581 MatchResultListener* /* listener */) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001582 const std::string& s2(s);
jgm38513a82012-11-15 15:50:36 +00001583 return full_match_ ? RE::FullMatch(s2, *regex_) :
1584 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001585 }
1586
1587 void DescribeTo(::std::ostream* os) const {
1588 *os << (full_match_ ? "matches" : "contains")
1589 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001590 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001591 }
1592
1593 void DescribeNegationTo(::std::ostream* os) const {
1594 *os << "doesn't " << (full_match_ ? "match" : "contain")
1595 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001596 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001597 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001598
shiqiane35fdd92008-12-10 05:08:54 +00001599 private:
1600 const internal::linked_ptr<const RE> regex_;
1601 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001602
1603 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001604};
1605
shiqiane35fdd92008-12-10 05:08:54 +00001606// Implements a matcher that compares the two fields of a 2-tuple
1607// using one of the ==, <=, <, etc, operators. The two fields being
1608// compared don't have to have the same type.
1609//
1610// The matcher defined here is polymorphic (for example, Eq() can be
1611// used to match a tuple<int, short>, a tuple<const long&, double>,
1612// etc). Therefore we use a template type conversion operator in the
1613// implementation.
kosak506340a2014-11-17 01:47:54 +00001614template <typename D, typename Op>
1615class PairMatchBase {
1616 public:
1617 template <typename T1, typename T2>
1618 operator Matcher< ::testing::tuple<T1, T2> >() const {
1619 return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >);
1620 }
1621 template <typename T1, typename T2>
1622 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
1623 return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>);
shiqiane35fdd92008-12-10 05:08:54 +00001624 }
1625
kosak506340a2014-11-17 01:47:54 +00001626 private:
1627 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
1628 return os << D::Desc();
1629 }
shiqiane35fdd92008-12-10 05:08:54 +00001630
kosak506340a2014-11-17 01:47:54 +00001631 template <typename Tuple>
1632 class Impl : public MatcherInterface<Tuple> {
1633 public:
1634 virtual bool MatchAndExplain(
1635 Tuple args,
1636 MatchResultListener* /* listener */) const {
1637 return Op()(::testing::get<0>(args), ::testing::get<1>(args));
1638 }
1639 virtual void DescribeTo(::std::ostream* os) const {
1640 *os << "are " << GetDesc;
1641 }
1642 virtual void DescribeNegationTo(::std::ostream* os) const {
1643 *os << "aren't " << GetDesc;
1644 }
1645 };
1646};
1647
1648class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
1649 public:
1650 static const char* Desc() { return "an equal pair"; }
1651};
1652class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
1653 public:
1654 static const char* Desc() { return "an unequal pair"; }
1655};
1656class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
1657 public:
1658 static const char* Desc() { return "a pair where the first < the second"; }
1659};
1660class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
1661 public:
1662 static const char* Desc() { return "a pair where the first > the second"; }
1663};
1664class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
1665 public:
1666 static const char* Desc() { return "a pair where the first <= the second"; }
1667};
1668class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
1669 public:
1670 static const char* Desc() { return "a pair where the first >= the second"; }
1671};
shiqiane35fdd92008-12-10 05:08:54 +00001672
zhanyong.wanc6a41232009-05-13 23:38:40 +00001673// Implements the Not(...) matcher for a particular argument type T.
1674// We do not nest it inside the NotMatcher class template, as that
1675// will prevent different instantiations of NotMatcher from sharing
1676// the same NotMatcherImpl<T> class.
1677template <typename T>
Gennadiy Civile55089e2018-04-04 14:05:00 -04001678class NotMatcherImpl : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001679 public:
1680 explicit NotMatcherImpl(const Matcher<T>& matcher)
1681 : matcher_(matcher) {}
1682
Gennadiy Civile55089e2018-04-04 14:05:00 -04001683 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
1684 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001685 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001686 }
1687
1688 virtual void DescribeTo(::std::ostream* os) const {
1689 matcher_.DescribeNegationTo(os);
1690 }
1691
1692 virtual void DescribeNegationTo(::std::ostream* os) const {
1693 matcher_.DescribeTo(os);
1694 }
1695
zhanyong.wanc6a41232009-05-13 23:38:40 +00001696 private:
1697 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001698
1699 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001700};
1701
shiqiane35fdd92008-12-10 05:08:54 +00001702// Implements the Not(m) matcher, which matches a value that doesn't
1703// match matcher m.
1704template <typename InnerMatcher>
1705class NotMatcher {
1706 public:
1707 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1708
1709 // This template type conversion operator allows Not(m) to be used
1710 // to match any type m can match.
1711 template <typename T>
1712 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001713 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001714 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001715
shiqiane35fdd92008-12-10 05:08:54 +00001716 private:
shiqiane35fdd92008-12-10 05:08:54 +00001717 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001718
1719 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001720};
1721
zhanyong.wanc6a41232009-05-13 23:38:40 +00001722// Implements the AllOf(m1, m2) matcher for a particular argument type
1723// T. We do not nest it inside the BothOfMatcher class template, as
1724// that will prevent different instantiations of BothOfMatcher from
1725// sharing the same BothOfMatcherImpl<T> class.
1726template <typename T>
Gennadiy Civilb5391672018-04-25 13:10:41 -04001727class AllOfMatcherImpl
Gennadiy Civile55089e2018-04-04 14:05:00 -04001728 : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001729 public:
Gennadiy Civilb5391672018-04-25 13:10:41 -04001730 explicit AllOfMatcherImpl(std::vector<Matcher<T> > matchers)
1731 : matchers_(internal::move(matchers)) {}
zhanyong.wanc6a41232009-05-13 23:38:40 +00001732
zhanyong.wanc6a41232009-05-13 23:38:40 +00001733 virtual void DescribeTo(::std::ostream* os) const {
1734 *os << "(";
Gennadiy Civilb5391672018-04-25 13:10:41 -04001735 for (size_t i = 0; i < matchers_.size(); ++i) {
1736 if (i != 0) *os << ") and (";
1737 matchers_[i].DescribeTo(os);
1738 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001739 *os << ")";
1740 }
1741
1742 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001743 *os << "(";
Gennadiy Civilb5391672018-04-25 13:10:41 -04001744 for (size_t i = 0; i < matchers_.size(); ++i) {
1745 if (i != 0) *os << ") or (";
1746 matchers_[i].DescribeNegationTo(os);
1747 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001748 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001749 }
1750
Gennadiy Civile55089e2018-04-04 14:05:00 -04001751 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
1752 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001753 // If either matcher1_ or matcher2_ doesn't match x, we only need
1754 // to explain why one of them fails.
Gennadiy Civilb5391672018-04-25 13:10:41 -04001755 std::string all_match_result;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001756
Gennadiy Civilb5391672018-04-25 13:10:41 -04001757 for (size_t i = 0; i < matchers_.size(); ++i) {
1758 StringMatchResultListener slistener;
1759 if (matchers_[i].MatchAndExplain(x, &slistener)) {
1760 if (all_match_result.empty()) {
1761 all_match_result = slistener.str();
1762 } else {
1763 std::string result = slistener.str();
1764 if (!result.empty()) {
1765 all_match_result += ", and ";
1766 all_match_result += result;
1767 }
1768 }
1769 } else {
1770 *listener << slistener.str();
1771 return false;
1772 }
zhanyong.wan82113312010-01-08 21:55:40 +00001773 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001774
zhanyong.wan82113312010-01-08 21:55:40 +00001775 // Otherwise we need to explain why *both* of them match.
Gennadiy Civilb5391672018-04-25 13:10:41 -04001776 *listener << all_match_result;
zhanyong.wan82113312010-01-08 21:55:40 +00001777 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001778 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001779
zhanyong.wanc6a41232009-05-13 23:38:40 +00001780 private:
Gennadiy Civilb5391672018-04-25 13:10:41 -04001781 const std::vector<Matcher<T> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001782
Gennadiy Civilb5391672018-04-25 13:10:41 -04001783 GTEST_DISALLOW_ASSIGN_(AllOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001784};
1785
zhanyong.wan616180e2013-06-18 18:49:51 +00001786#if GTEST_LANG_CXX11
zhanyong.wan616180e2013-06-18 18:49:51 +00001787// VariadicMatcher is used for the variadic implementation of
1788// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1789// CombiningMatcher<T> is used to recursively combine the provided matchers
1790// (of type Args...).
1791template <template <typename T> class CombiningMatcher, typename... Args>
1792class VariadicMatcher {
1793 public:
1794 VariadicMatcher(const Args&... matchers) // NOLINT
Gennadiy Civilb5391672018-04-25 13:10:41 -04001795 : matchers_(matchers...) {
1796 static_assert(sizeof...(Args) > 0, "Must have at least one matcher.");
1797 }
zhanyong.wan616180e2013-06-18 18:49:51 +00001798
1799 // This template type conversion operator allows an
1800 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1801 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1802 template <typename T>
1803 operator Matcher<T>() const {
Gennadiy Civilb5391672018-04-25 13:10:41 -04001804 std::vector<Matcher<T> > values;
1805 CreateVariadicMatcher<T>(&values, std::integral_constant<size_t, 0>());
1806 return Matcher<T>(new CombiningMatcher<T>(internal::move(values)));
zhanyong.wan616180e2013-06-18 18:49:51 +00001807 }
1808
1809 private:
Gennadiy Civilb5391672018-04-25 13:10:41 -04001810 template <typename T, size_t I>
1811 void CreateVariadicMatcher(std::vector<Matcher<T> >* values,
1812 std::integral_constant<size_t, I>) const {
1813 values->push_back(SafeMatcherCast<T>(std::get<I>(matchers_)));
1814 CreateVariadicMatcher<T>(values, std::integral_constant<size_t, I + 1>());
1815 }
zhanyong.wan616180e2013-06-18 18:49:51 +00001816
Gennadiy Civilb5391672018-04-25 13:10:41 -04001817 template <typename T>
1818 void CreateVariadicMatcher(
1819 std::vector<Matcher<T> >*,
1820 std::integral_constant<size_t, sizeof...(Args)>) const {}
1821
1822 tuple<Args...> matchers_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001823
1824 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1825};
1826
1827template <typename... Args>
Gennadiy Civilb5391672018-04-25 13:10:41 -04001828using AllOfMatcher = VariadicMatcher<AllOfMatcherImpl, Args...>;
zhanyong.wan616180e2013-06-18 18:49:51 +00001829
1830#endif // GTEST_LANG_CXX11
1831
shiqiane35fdd92008-12-10 05:08:54 +00001832// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1833// matches a value that matches all of the matchers m_1, ..., and m_n.
1834template <typename Matcher1, typename Matcher2>
1835class BothOfMatcher {
1836 public:
1837 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1838 : matcher1_(matcher1), matcher2_(matcher2) {}
1839
1840 // This template type conversion operator allows a
1841 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1842 // both Matcher1 and Matcher2 can match.
1843 template <typename T>
1844 operator Matcher<T>() const {
Gennadiy Civilb5391672018-04-25 13:10:41 -04001845 std::vector<Matcher<T> > values;
1846 values.push_back(SafeMatcherCast<T>(matcher1_));
1847 values.push_back(SafeMatcherCast<T>(matcher2_));
1848 return Matcher<T>(new AllOfMatcherImpl<T>(internal::move(values)));
shiqiane35fdd92008-12-10 05:08:54 +00001849 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001850
shiqiane35fdd92008-12-10 05:08:54 +00001851 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001852 Matcher1 matcher1_;
1853 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001854
1855 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001856};
shiqiane35fdd92008-12-10 05:08:54 +00001857
zhanyong.wanc6a41232009-05-13 23:38:40 +00001858// Implements the AnyOf(m1, m2) matcher for a particular argument type
1859// T. We do not nest it inside the AnyOfMatcher class template, as
1860// that will prevent different instantiations of AnyOfMatcher from
1861// sharing the same EitherOfMatcherImpl<T> class.
1862template <typename T>
Gennadiy Civilb5391672018-04-25 13:10:41 -04001863class AnyOfMatcherImpl
Gennadiy Civile55089e2018-04-04 14:05:00 -04001864 : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001865 public:
Gennadiy Civilb5391672018-04-25 13:10:41 -04001866 explicit AnyOfMatcherImpl(std::vector<Matcher<T> > matchers)
1867 : matchers_(internal::move(matchers)) {}
shiqiane35fdd92008-12-10 05:08:54 +00001868
zhanyong.wanc6a41232009-05-13 23:38:40 +00001869 virtual void DescribeTo(::std::ostream* os) const {
1870 *os << "(";
Gennadiy Civilb5391672018-04-25 13:10:41 -04001871 for (size_t i = 0; i < matchers_.size(); ++i) {
1872 if (i != 0) *os << ") or (";
1873 matchers_[i].DescribeTo(os);
1874 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001875 *os << ")";
1876 }
shiqiane35fdd92008-12-10 05:08:54 +00001877
zhanyong.wanc6a41232009-05-13 23:38:40 +00001878 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001879 *os << "(";
Gennadiy Civilb5391672018-04-25 13:10:41 -04001880 for (size_t i = 0; i < matchers_.size(); ++i) {
1881 if (i != 0) *os << ") and (";
1882 matchers_[i].DescribeNegationTo(os);
1883 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001884 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001885 }
shiqiane35fdd92008-12-10 05:08:54 +00001886
Gennadiy Civile55089e2018-04-04 14:05:00 -04001887 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
1888 MatchResultListener* listener) const {
Gennadiy Civilb5391672018-04-25 13:10:41 -04001889 std::string no_match_result;
1890
zhanyong.wan82113312010-01-08 21:55:40 +00001891 // If either matcher1_ or matcher2_ matches x, we just need to
1892 // explain why *one* of them matches.
Gennadiy Civilb5391672018-04-25 13:10:41 -04001893 for (size_t i = 0; i < matchers_.size(); ++i) {
1894 StringMatchResultListener slistener;
1895 if (matchers_[i].MatchAndExplain(x, &slistener)) {
1896 *listener << slistener.str();
1897 return true;
1898 } else {
1899 if (no_match_result.empty()) {
1900 no_match_result = slistener.str();
1901 } else {
1902 std::string result = slistener.str();
1903 if (!result.empty()) {
1904 no_match_result += ", and ";
1905 no_match_result += result;
1906 }
1907 }
1908 }
zhanyong.wan82113312010-01-08 21:55:40 +00001909 }
1910
1911 // Otherwise we need to explain why *both* of them fail.
Gennadiy Civilb5391672018-04-25 13:10:41 -04001912 *listener << no_match_result;
zhanyong.wan82113312010-01-08 21:55:40 +00001913 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001914 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001915
zhanyong.wanc6a41232009-05-13 23:38:40 +00001916 private:
Gennadiy Civilb5391672018-04-25 13:10:41 -04001917 const std::vector<Matcher<T> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001918
Gennadiy Civilb5391672018-04-25 13:10:41 -04001919 GTEST_DISALLOW_ASSIGN_(AnyOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001920};
1921
zhanyong.wan616180e2013-06-18 18:49:51 +00001922#if GTEST_LANG_CXX11
1923// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1924template <typename... Args>
Gennadiy Civilb5391672018-04-25 13:10:41 -04001925using AnyOfMatcher = VariadicMatcher<AnyOfMatcherImpl, Args...>;
zhanyong.wan616180e2013-06-18 18:49:51 +00001926
1927#endif // GTEST_LANG_CXX11
1928
shiqiane35fdd92008-12-10 05:08:54 +00001929// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1930// matches a value that matches at least one of the matchers m_1, ...,
1931// and m_n.
1932template <typename Matcher1, typename Matcher2>
1933class EitherOfMatcher {
1934 public:
1935 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1936 : matcher1_(matcher1), matcher2_(matcher2) {}
1937
1938 // This template type conversion operator allows a
1939 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1940 // both Matcher1 and Matcher2 can match.
1941 template <typename T>
1942 operator Matcher<T>() const {
Gennadiy Civilb5391672018-04-25 13:10:41 -04001943 std::vector<Matcher<T> > values;
1944 values.push_back(SafeMatcherCast<T>(matcher1_));
1945 values.push_back(SafeMatcherCast<T>(matcher2_));
1946 return Matcher<T>(new AnyOfMatcherImpl<T>(internal::move(values)));
shiqiane35fdd92008-12-10 05:08:54 +00001947 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001948
shiqiane35fdd92008-12-10 05:08:54 +00001949 private:
shiqiane35fdd92008-12-10 05:08:54 +00001950 Matcher1 matcher1_;
1951 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001952
1953 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001954};
1955
1956// Used for implementing Truly(pred), which turns a predicate into a
1957// matcher.
1958template <typename Predicate>
1959class TrulyMatcher {
1960 public:
1961 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1962
1963 // This method template allows Truly(pred) to be used as a matcher
1964 // for type T where T is the argument type of predicate 'pred'. The
1965 // argument is passed by reference as the predicate may be
1966 // interested in the address of the argument.
1967 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001968 bool MatchAndExplain(T& x, // NOLINT
1969 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001970 // Without the if-statement, MSVC sometimes warns about converting
1971 // a value to bool (warning 4800).
1972 //
1973 // We cannot write 'return !!predicate_(x);' as that doesn't work
1974 // when predicate_(x) returns a class convertible to bool but
1975 // having no operator!().
1976 if (predicate_(x))
1977 return true;
1978 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001979 }
1980
1981 void DescribeTo(::std::ostream* os) const {
1982 *os << "satisfies the given predicate";
1983 }
1984
1985 void DescribeNegationTo(::std::ostream* os) const {
1986 *os << "doesn't satisfy the given predicate";
1987 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001988
shiqiane35fdd92008-12-10 05:08:54 +00001989 private:
1990 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001991
1992 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001993};
1994
1995// Used for implementing Matches(matcher), which turns a matcher into
1996// a predicate.
1997template <typename M>
1998class MatcherAsPredicate {
1999 public:
2000 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
2001
2002 // This template operator() allows Matches(m) to be used as a
2003 // predicate on type T where m is a matcher on type T.
2004 //
2005 // The argument x is passed by reference instead of by value, as
2006 // some matcher may be interested in its address (e.g. as in
2007 // Matches(Ref(n))(x)).
2008 template <typename T>
2009 bool operator()(const T& x) const {
2010 // We let matcher_ commit to a particular type here instead of
2011 // when the MatcherAsPredicate object was constructed. This
2012 // allows us to write Matches(m) where m is a polymorphic matcher
2013 // (e.g. Eq(5)).
2014 //
2015 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
2016 // compile when matcher_ has type Matcher<const T&>; if we write
2017 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
2018 // when matcher_ has type Matcher<T>; if we just write
2019 // matcher_.Matches(x), it won't compile when matcher_ is
2020 // polymorphic, e.g. Eq(5).
2021 //
2022 // MatcherCast<const T&>() is necessary for making the code work
2023 // in all of the above situations.
2024 return MatcherCast<const T&>(matcher_).Matches(x);
2025 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002026
shiqiane35fdd92008-12-10 05:08:54 +00002027 private:
2028 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002029
2030 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00002031};
2032
2033// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
2034// argument M must be a type that can be converted to a matcher.
2035template <typename M>
2036class PredicateFormatterFromMatcher {
2037 public:
kosak9b1a9442015-04-28 23:06:58 +00002038 explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {}
shiqiane35fdd92008-12-10 05:08:54 +00002039
2040 // This template () operator allows a PredicateFormatterFromMatcher
2041 // object to act as a predicate-formatter suitable for using with
2042 // Google Test's EXPECT_PRED_FORMAT1() macro.
2043 template <typename T>
2044 AssertionResult operator()(const char* value_text, const T& x) const {
2045 // We convert matcher_ to a Matcher<const T&> *now* instead of
2046 // when the PredicateFormatterFromMatcher object was constructed,
2047 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
2048 // know which type to instantiate it to until we actually see the
2049 // type of x here.
2050 //
zhanyong.wanf4274522013-04-24 02:49:43 +00002051 // We write SafeMatcherCast<const T&>(matcher_) instead of
shiqiane35fdd92008-12-10 05:08:54 +00002052 // Matcher<const T&>(matcher_), as the latter won't compile when
2053 // matcher_ has type Matcher<T> (e.g. An<int>()).
zhanyong.wanf4274522013-04-24 02:49:43 +00002054 // We don't write MatcherCast<const T&> either, as that allows
2055 // potentially unsafe downcasting of the matcher argument.
2056 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00002057 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002058 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00002059 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002060
2061 ::std::stringstream ss;
2062 ss << "Value of: " << value_text << "\n"
2063 << "Expected: ";
2064 matcher.DescribeTo(&ss);
2065 ss << "\n Actual: " << listener.str();
2066 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00002067 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002068
shiqiane35fdd92008-12-10 05:08:54 +00002069 private:
2070 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002071
2072 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002073};
2074
2075// A helper function for converting a matcher to a predicate-formatter
2076// without the user needing to explicitly write the type. This is
2077// used for implementing ASSERT_THAT() and EXPECT_THAT().
kosak9b1a9442015-04-28 23:06:58 +00002078// Implementation detail: 'matcher' is received by-value to force decaying.
shiqiane35fdd92008-12-10 05:08:54 +00002079template <typename M>
2080inline PredicateFormatterFromMatcher<M>
kosak9b1a9442015-04-28 23:06:58 +00002081MakePredicateFormatterFromMatcher(M matcher) {
2082 return PredicateFormatterFromMatcher<M>(internal::move(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00002083}
2084
zhanyong.wan616180e2013-06-18 18:49:51 +00002085// Implements the polymorphic floating point equality matcher, which matches
2086// two float values using ULP-based approximation or, optionally, a
2087// user-specified epsilon. The template is meant to be instantiated with
2088// FloatType being either float or double.
shiqiane35fdd92008-12-10 05:08:54 +00002089template <typename FloatType>
2090class FloatingEqMatcher {
2091 public:
2092 // Constructor for FloatingEqMatcher.
kosak6b817802015-01-08 02:38:14 +00002093 // The matcher's input will be compared with expected. The matcher treats two
shiqiane35fdd92008-12-10 05:08:54 +00002094 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
zhanyong.wan616180e2013-06-18 18:49:51 +00002095 // equality comparisons between NANs will always return false. We specify a
2096 // negative max_abs_error_ term to indicate that ULP-based approximation will
2097 // be used for comparison.
kosak6b817802015-01-08 02:38:14 +00002098 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
2099 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
zhanyong.wan616180e2013-06-18 18:49:51 +00002100 }
2101
2102 // Constructor that supports a user-specified max_abs_error that will be used
2103 // for comparison instead of ULP-based approximation. The max absolute
2104 // should be non-negative.
kosak6b817802015-01-08 02:38:14 +00002105 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
2106 FloatType max_abs_error)
2107 : expected_(expected),
2108 nan_eq_nan_(nan_eq_nan),
2109 max_abs_error_(max_abs_error) {
zhanyong.wan616180e2013-06-18 18:49:51 +00002110 GTEST_CHECK_(max_abs_error >= 0)
2111 << ", where max_abs_error is" << max_abs_error;
2112 }
shiqiane35fdd92008-12-10 05:08:54 +00002113
2114 // Implements floating point equality matcher as a Matcher<T>.
2115 template <typename T>
2116 class Impl : public MatcherInterface<T> {
2117 public:
kosak6b817802015-01-08 02:38:14 +00002118 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
2119 : expected_(expected),
2120 nan_eq_nan_(nan_eq_nan),
2121 max_abs_error_(max_abs_error) {}
shiqiane35fdd92008-12-10 05:08:54 +00002122
zhanyong.wan82113312010-01-08 21:55:40 +00002123 virtual bool MatchAndExplain(T value,
kosak6b817802015-01-08 02:38:14 +00002124 MatchResultListener* listener) const {
2125 const FloatingPoint<FloatType> actual(value), expected(expected_);
shiqiane35fdd92008-12-10 05:08:54 +00002126
2127 // Compares NaNs first, if nan_eq_nan_ is true.
kosak6b817802015-01-08 02:38:14 +00002128 if (actual.is_nan() || expected.is_nan()) {
2129 if (actual.is_nan() && expected.is_nan()) {
zhanyong.wan616180e2013-06-18 18:49:51 +00002130 return nan_eq_nan_;
2131 }
2132 // One is nan; the other is not nan.
2133 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002134 }
zhanyong.wan616180e2013-06-18 18:49:51 +00002135 if (HasMaxAbsError()) {
2136 // We perform an equality check so that inf will match inf, regardless
kosak6b817802015-01-08 02:38:14 +00002137 // of error bounds. If the result of value - expected_ would result in
zhanyong.wan616180e2013-06-18 18:49:51 +00002138 // overflow or if either value is inf, the default result is infinity,
2139 // which should only match if max_abs_error_ is also infinity.
kosak6b817802015-01-08 02:38:14 +00002140 if (value == expected_) {
2141 return true;
2142 }
2143
2144 const FloatType diff = value - expected_;
2145 if (fabs(diff) <= max_abs_error_) {
2146 return true;
2147 }
2148
2149 if (listener->IsInterested()) {
2150 *listener << "which is " << diff << " from " << expected_;
2151 }
2152 return false;
zhanyong.wan616180e2013-06-18 18:49:51 +00002153 } else {
kosak6b817802015-01-08 02:38:14 +00002154 return actual.AlmostEquals(expected);
zhanyong.wan616180e2013-06-18 18:49:51 +00002155 }
shiqiane35fdd92008-12-10 05:08:54 +00002156 }
2157
2158 virtual void DescribeTo(::std::ostream* os) const {
2159 // os->precision() returns the previously set precision, which we
2160 // store to restore the ostream to its original configuration
2161 // after outputting.
2162 const ::std::streamsize old_precision = os->precision(
2163 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00002164 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00002165 if (nan_eq_nan_) {
2166 *os << "is NaN";
2167 } else {
2168 *os << "never matches";
2169 }
2170 } else {
kosak6b817802015-01-08 02:38:14 +00002171 *os << "is approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002172 if (HasMaxAbsError()) {
2173 *os << " (absolute error <= " << max_abs_error_ << ")";
2174 }
shiqiane35fdd92008-12-10 05:08:54 +00002175 }
2176 os->precision(old_precision);
2177 }
2178
2179 virtual void DescribeNegationTo(::std::ostream* os) const {
2180 // As before, get original precision.
2181 const ::std::streamsize old_precision = os->precision(
2182 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00002183 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00002184 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002185 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00002186 } else {
2187 *os << "is anything";
2188 }
2189 } else {
kosak6b817802015-01-08 02:38:14 +00002190 *os << "isn't approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002191 if (HasMaxAbsError()) {
2192 *os << " (absolute error > " << max_abs_error_ << ")";
2193 }
shiqiane35fdd92008-12-10 05:08:54 +00002194 }
2195 // Restore original precision.
2196 os->precision(old_precision);
2197 }
2198
2199 private:
zhanyong.wan616180e2013-06-18 18:49:51 +00002200 bool HasMaxAbsError() const {
2201 return max_abs_error_ >= 0;
2202 }
2203
kosak6b817802015-01-08 02:38:14 +00002204 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002205 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002206 // max_abs_error will be used for value comparison when >= 0.
2207 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002208
2209 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002210 };
2211
kosak6b817802015-01-08 02:38:14 +00002212 // The following 3 type conversion operators allow FloatEq(expected) and
2213 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
shiqiane35fdd92008-12-10 05:08:54 +00002214 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
2215 // (While Google's C++ coding style doesn't allow arguments passed
2216 // by non-const reference, we may see them in code not conforming to
2217 // the style. Therefore Google Mock needs to support them.)
2218 operator Matcher<FloatType>() const {
kosak6b817802015-01-08 02:38:14 +00002219 return MakeMatcher(
2220 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002221 }
2222
2223 operator Matcher<const FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00002224 return MakeMatcher(
kosak6b817802015-01-08 02:38:14 +00002225 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002226 }
2227
2228 operator Matcher<FloatType&>() const {
kosak6b817802015-01-08 02:38:14 +00002229 return MakeMatcher(
2230 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002231 }
jgm79a367e2012-04-10 16:02:11 +00002232
shiqiane35fdd92008-12-10 05:08:54 +00002233 private:
kosak6b817802015-01-08 02:38:14 +00002234 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002235 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002236 // max_abs_error will be used for value comparison when >= 0.
2237 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002238
2239 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002240};
2241
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002242// A 2-tuple ("binary") wrapper around FloatingEqMatcher:
2243// FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false)
2244// against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e)
2245// against y. The former implements "Eq", the latter "Near". At present, there
2246// is no version that compares NaNs as equal.
2247template <typename FloatType>
2248class FloatingEq2Matcher {
2249 public:
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002250 FloatingEq2Matcher() { Init(-1, false); }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002251
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002252 explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002253
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002254 explicit FloatingEq2Matcher(FloatType max_abs_error) {
2255 Init(max_abs_error, false);
2256 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002257
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002258 FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) {
2259 Init(max_abs_error, nan_eq_nan);
2260 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002261
2262 template <typename T1, typename T2>
2263 operator Matcher< ::testing::tuple<T1, T2> >() const {
2264 return MakeMatcher(
2265 new Impl< ::testing::tuple<T1, T2> >(max_abs_error_, nan_eq_nan_));
2266 }
2267 template <typename T1, typename T2>
2268 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
2269 return MakeMatcher(
2270 new Impl<const ::testing::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_));
2271 }
2272
2273 private:
2274 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
2275 return os << "an almost-equal pair";
2276 }
2277
2278 template <typename Tuple>
2279 class Impl : public MatcherInterface<Tuple> {
2280 public:
2281 Impl(FloatType max_abs_error, bool nan_eq_nan) :
2282 max_abs_error_(max_abs_error),
2283 nan_eq_nan_(nan_eq_nan) {}
2284
2285 virtual bool MatchAndExplain(Tuple args,
2286 MatchResultListener* listener) const {
2287 if (max_abs_error_ == -1) {
2288 FloatingEqMatcher<FloatType> fm(::testing::get<0>(args), nan_eq_nan_);
2289 return static_cast<Matcher<FloatType> >(fm).MatchAndExplain(
2290 ::testing::get<1>(args), listener);
2291 } else {
2292 FloatingEqMatcher<FloatType> fm(::testing::get<0>(args), nan_eq_nan_,
2293 max_abs_error_);
2294 return static_cast<Matcher<FloatType> >(fm).MatchAndExplain(
2295 ::testing::get<1>(args), listener);
2296 }
2297 }
2298 virtual void DescribeTo(::std::ostream* os) const {
2299 *os << "are " << GetDesc;
2300 }
2301 virtual void DescribeNegationTo(::std::ostream* os) const {
2302 *os << "aren't " << GetDesc;
2303 }
2304
2305 private:
2306 FloatType max_abs_error_;
2307 const bool nan_eq_nan_;
2308 };
2309
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002310 void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) {
2311 max_abs_error_ = max_abs_error_val;
2312 nan_eq_nan_ = nan_eq_nan_val;
2313 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002314 FloatType max_abs_error_;
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002315 bool nan_eq_nan_;
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002316};
2317
shiqiane35fdd92008-12-10 05:08:54 +00002318// Implements the Pointee(m) matcher for matching a pointer whose
2319// pointee matches matcher m. The pointer can be either raw or smart.
2320template <typename InnerMatcher>
2321class PointeeMatcher {
2322 public:
2323 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
2324
2325 // This type conversion operator template allows Pointee(m) to be
2326 // used as a matcher for any pointer type whose pointee type is
2327 // compatible with the inner matcher, where type Pointer can be
2328 // either a raw pointer or a smart pointer.
2329 //
2330 // The reason we do this instead of relying on
2331 // MakePolymorphicMatcher() is that the latter is not flexible
2332 // enough for implementing the DescribeTo() method of Pointee().
2333 template <typename Pointer>
2334 operator Matcher<Pointer>() const {
Gennadiy Civile55089e2018-04-04 14:05:00 -04002335 return Matcher<Pointer>(
2336 new Impl<GTEST_REFERENCE_TO_CONST_(Pointer)>(matcher_));
shiqiane35fdd92008-12-10 05:08:54 +00002337 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002338
shiqiane35fdd92008-12-10 05:08:54 +00002339 private:
2340 // The monomorphic implementation that works for a particular pointer type.
2341 template <typename Pointer>
2342 class Impl : public MatcherInterface<Pointer> {
2343 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00002344 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
2345 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00002346
2347 explicit Impl(const InnerMatcher& matcher)
2348 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
2349
shiqiane35fdd92008-12-10 05:08:54 +00002350 virtual void DescribeTo(::std::ostream* os) const {
2351 *os << "points to a value that ";
2352 matcher_.DescribeTo(os);
2353 }
2354
2355 virtual void DescribeNegationTo(::std::ostream* os) const {
2356 *os << "does not point to a value that ";
2357 matcher_.DescribeTo(os);
2358 }
2359
zhanyong.wan82113312010-01-08 21:55:40 +00002360 virtual bool MatchAndExplain(Pointer pointer,
2361 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00002362 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00002363 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002364
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002365 *listener << "which points to ";
2366 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002367 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002368
shiqiane35fdd92008-12-10 05:08:54 +00002369 private:
2370 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002371
2372 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002373 };
2374
2375 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002376
2377 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002378};
2379
Scott Grahama9653c42018-05-02 11:14:39 -07002380#if GTEST_HAS_RTTI
billydonahue1f5fdea2014-05-19 17:54:51 +00002381// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2382// reference that matches inner_matcher when dynamic_cast<T> is applied.
2383// The result of dynamic_cast<To> is forwarded to the inner matcher.
2384// If To is a pointer and the cast fails, the inner matcher will receive NULL.
2385// If To is a reference and the cast fails, this matcher returns false
2386// immediately.
2387template <typename To>
2388class WhenDynamicCastToMatcherBase {
2389 public:
2390 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2391 : matcher_(matcher) {}
2392
2393 void DescribeTo(::std::ostream* os) const {
2394 GetCastTypeDescription(os);
2395 matcher_.DescribeTo(os);
2396 }
2397
2398 void DescribeNegationTo(::std::ostream* os) const {
2399 GetCastTypeDescription(os);
2400 matcher_.DescribeNegationTo(os);
2401 }
2402
2403 protected:
2404 const Matcher<To> matcher_;
2405
Nico Weber09fd5b32017-05-15 17:07:03 -04002406 static std::string GetToName() {
billydonahue1f5fdea2014-05-19 17:54:51 +00002407 return GetTypeName<To>();
billydonahue1f5fdea2014-05-19 17:54:51 +00002408 }
2409
2410 private:
2411 static void GetCastTypeDescription(::std::ostream* os) {
2412 *os << "when dynamic_cast to " << GetToName() << ", ";
2413 }
2414
2415 GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2416};
2417
2418// Primary template.
2419// To is a pointer. Cast and forward the result.
2420template <typename To>
2421class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2422 public:
2423 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2424 : WhenDynamicCastToMatcherBase<To>(matcher) {}
2425
2426 template <typename From>
2427 bool MatchAndExplain(From from, MatchResultListener* listener) const {
Gennadiy Civil265efde2018-08-14 15:04:11 -04002428 // FIXME: Add more detail on failures. ie did the dyn_cast fail?
billydonahue1f5fdea2014-05-19 17:54:51 +00002429 To to = dynamic_cast<To>(from);
2430 return MatchPrintAndExplain(to, this->matcher_, listener);
2431 }
2432};
2433
2434// Specialize for references.
2435// In this case we return false if the dynamic_cast fails.
2436template <typename To>
2437class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2438 public:
2439 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2440 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2441
2442 template <typename From>
2443 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2444 // We don't want an std::bad_cast here, so do the cast with pointers.
2445 To* to = dynamic_cast<To*>(&from);
2446 if (to == NULL) {
2447 *listener << "which cannot be dynamic_cast to " << this->GetToName();
2448 return false;
2449 }
2450 return MatchPrintAndExplain(*to, this->matcher_, listener);
2451 }
2452};
Scott Grahama9653c42018-05-02 11:14:39 -07002453#endif // GTEST_HAS_RTTI
billydonahue1f5fdea2014-05-19 17:54:51 +00002454
shiqiane35fdd92008-12-10 05:08:54 +00002455// Implements the Field() matcher for matching a field (i.e. member
2456// variable) of an object.
2457template <typename Class, typename FieldType>
2458class FieldMatcher {
2459 public:
2460 FieldMatcher(FieldType Class::*field,
2461 const Matcher<const FieldType&>& matcher)
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002462 : field_(field), matcher_(matcher), whose_field_("whose given field ") {}
2463
2464 FieldMatcher(const std::string& field_name, FieldType Class::*field,
2465 const Matcher<const FieldType&>& matcher)
2466 : field_(field),
2467 matcher_(matcher),
2468 whose_field_("whose field `" + field_name + "` ") {}
shiqiane35fdd92008-12-10 05:08:54 +00002469
shiqiane35fdd92008-12-10 05:08:54 +00002470 void DescribeTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002471 *os << "is an object " << whose_field_;
shiqiane35fdd92008-12-10 05:08:54 +00002472 matcher_.DescribeTo(os);
2473 }
2474
2475 void DescribeNegationTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002476 *os << "is an object " << whose_field_;
shiqiane35fdd92008-12-10 05:08:54 +00002477 matcher_.DescribeNegationTo(os);
2478 }
2479
zhanyong.wandb22c222010-01-28 21:52:29 +00002480 template <typename T>
2481 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2482 return MatchAndExplainImpl(
2483 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002484 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002485 value, listener);
2486 }
2487
2488 private:
2489 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002490 // Symbian's C++ compiler choose which overload to use. Its type is
2491 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002492 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2493 MatchResultListener* listener) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002494 *listener << whose_field_ << "is ";
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002495 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002496 }
2497
zhanyong.wandb22c222010-01-28 21:52:29 +00002498 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2499 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002500 if (p == NULL)
2501 return false;
2502
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002503 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002504 // Since *p has a field, it must be a class/struct/union type and
2505 // thus cannot be a pointer. Therefore we pass false_type() as
2506 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002507 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002508 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002509
shiqiane35fdd92008-12-10 05:08:54 +00002510 const FieldType Class::*field_;
2511 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002512
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002513 // Contains either "whose given field " if the name of the field is unknown
2514 // or "whose field `name_of_field` " if the name is known.
2515 const std::string whose_field_;
2516
zhanyong.wan32de5f52009-12-23 00:13:23 +00002517 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002518};
2519
shiqiane35fdd92008-12-10 05:08:54 +00002520// Implements the Property() matcher for matching a property
2521// (i.e. return value of a getter method) of an object.
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002522//
2523// Property is a const-qualified member function of Class returning
2524// PropertyType.
2525template <typename Class, typename PropertyType, typename Property>
shiqiane35fdd92008-12-10 05:08:54 +00002526class PropertyMatcher {
2527 public:
2528 // The property may have a reference type, so 'const PropertyType&'
2529 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00002530 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00002531 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00002532 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00002533
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002534 PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002535 : property_(property),
2536 matcher_(matcher),
2537 whose_property_("whose given property ") {}
2538
2539 PropertyMatcher(const std::string& property_name, Property property,
2540 const Matcher<RefToConstProperty>& matcher)
2541 : property_(property),
2542 matcher_(matcher),
2543 whose_property_("whose property `" + property_name + "` ") {}
shiqiane35fdd92008-12-10 05:08:54 +00002544
shiqiane35fdd92008-12-10 05:08:54 +00002545 void DescribeTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002546 *os << "is an object " << whose_property_;
shiqiane35fdd92008-12-10 05:08:54 +00002547 matcher_.DescribeTo(os);
2548 }
2549
2550 void DescribeNegationTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002551 *os << "is an object " << whose_property_;
shiqiane35fdd92008-12-10 05:08:54 +00002552 matcher_.DescribeNegationTo(os);
2553 }
2554
zhanyong.wandb22c222010-01-28 21:52:29 +00002555 template <typename T>
2556 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2557 return MatchAndExplainImpl(
2558 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002559 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002560 value, listener);
2561 }
2562
2563 private:
2564 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002565 // Symbian's C++ compiler choose which overload to use. Its type is
2566 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002567 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2568 MatchResultListener* listener) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002569 *listener << whose_property_ << "is ";
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002570 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2571 // which takes a non-const reference as argument.
kosak02d64792015-02-14 02:22:21 +00002572#if defined(_PREFAST_ ) && _MSC_VER == 1800
2573 // Workaround bug in VC++ 2013's /analyze parser.
2574 // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move
2575 posix::Abort(); // To make sure it is never run.
2576 return false;
2577#else
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002578 RefToConstProperty result = (obj.*property_)();
2579 return MatchPrintAndExplain(result, matcher_, listener);
kosak02d64792015-02-14 02:22:21 +00002580#endif
shiqiane35fdd92008-12-10 05:08:54 +00002581 }
2582
zhanyong.wandb22c222010-01-28 21:52:29 +00002583 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2584 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002585 if (p == NULL)
2586 return false;
2587
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002588 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002589 // Since *p has a property method, it must be a class/struct/union
2590 // type and thus cannot be a pointer. Therefore we pass
2591 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002592 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002593 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002594
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002595 Property property_;
shiqiane35fdd92008-12-10 05:08:54 +00002596 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002597
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002598 // Contains either "whose given property " if the name of the property is
2599 // unknown or "whose property `name_of_property` " if the name is known.
2600 const std::string whose_property_;
2601
zhanyong.wan32de5f52009-12-23 00:13:23 +00002602 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002603};
2604
shiqiane35fdd92008-12-10 05:08:54 +00002605// Type traits specifying various features of different functors for ResultOf.
2606// The default template specifies features for functor objects.
shiqiane35fdd92008-12-10 05:08:54 +00002607template <typename Functor>
2608struct CallableTraits {
shiqiane35fdd92008-12-10 05:08:54 +00002609 typedef Functor StorageType;
2610
zhanyong.wan32de5f52009-12-23 00:13:23 +00002611 static void CheckIsValid(Functor /* functor */) {}
Abseil Teama0e62d92018-08-24 13:30:17 -04002612
2613#if GTEST_LANG_CXX11
2614 template <typename T>
2615 static auto Invoke(Functor f, T arg) -> decltype(f(arg)) { return f(arg); }
2616#else
2617 typedef typename Functor::result_type ResultType;
shiqiane35fdd92008-12-10 05:08:54 +00002618 template <typename T>
2619 static ResultType Invoke(Functor f, T arg) { return f(arg); }
Abseil Teama0e62d92018-08-24 13:30:17 -04002620#endif
shiqiane35fdd92008-12-10 05:08:54 +00002621};
2622
2623// Specialization for function pointers.
2624template <typename ArgType, typename ResType>
2625struct CallableTraits<ResType(*)(ArgType)> {
2626 typedef ResType ResultType;
2627 typedef ResType(*StorageType)(ArgType);
2628
2629 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002630 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00002631 << "NULL function pointer is passed into ResultOf().";
2632 }
2633 template <typename T>
2634 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2635 return (*f)(arg);
2636 }
2637};
2638
2639// Implements the ResultOf() matcher for matching a return value of a
2640// unary function of an object.
Abseil Teama0e62d92018-08-24 13:30:17 -04002641template <typename Callable, typename InnerMatcher>
shiqiane35fdd92008-12-10 05:08:54 +00002642class ResultOfMatcher {
2643 public:
Abseil Teama0e62d92018-08-24 13:30:17 -04002644 ResultOfMatcher(Callable callable, InnerMatcher matcher)
2645 : callable_(internal::move(callable)), matcher_(internal::move(matcher)) {
shiqiane35fdd92008-12-10 05:08:54 +00002646 CallableTraits<Callable>::CheckIsValid(callable_);
2647 }
2648
2649 template <typename T>
2650 operator Matcher<T>() const {
2651 return Matcher<T>(new Impl<T>(callable_, matcher_));
2652 }
2653
2654 private:
2655 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2656
2657 template <typename T>
2658 class Impl : public MatcherInterface<T> {
Abseil Teama0e62d92018-08-24 13:30:17 -04002659#if GTEST_LANG_CXX11
2660 using ResultType = decltype(CallableTraits<Callable>::template Invoke<T>(
2661 std::declval<CallableStorageType>(), std::declval<T>()));
2662#else
2663 typedef typename CallableTraits<Callable>::ResultType ResultType;
2664#endif
2665
shiqiane35fdd92008-12-10 05:08:54 +00002666 public:
Abseil Teama0e62d92018-08-24 13:30:17 -04002667 template <typename M>
2668 Impl(const CallableStorageType& callable, const M& matcher)
2669 : callable_(callable), matcher_(MatcherCast<ResultType>(matcher)) {}
shiqiane35fdd92008-12-10 05:08:54 +00002670
2671 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002672 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002673 matcher_.DescribeTo(os);
2674 }
2675
2676 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002677 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002678 matcher_.DescribeNegationTo(os);
2679 }
2680
zhanyong.wan82113312010-01-08 21:55:40 +00002681 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002682 *listener << "which is mapped by the given callable to ";
Abseil Teama0e62d92018-08-24 13:30:17 -04002683 // Cannot pass the return value directly to MatchPrintAndExplain, which
2684 // takes a non-const reference as argument.
2685 // Also, specifying template argument explicitly is needed because T could
2686 // be a non-const reference (e.g. Matcher<Uncopyable&>).
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002687 ResultType result =
2688 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2689 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002690 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002691
shiqiane35fdd92008-12-10 05:08:54 +00002692 private:
2693 // Functors often define operator() as non-const method even though
Troy Holsapplec8510502018-02-07 22:06:00 -08002694 // they are actually stateless. But we need to use them even when
shiqiane35fdd92008-12-10 05:08:54 +00002695 // 'this' is a const pointer. It's the user's responsibility not to
Abseil Teama0e62d92018-08-24 13:30:17 -04002696 // use stateful callables with ResultOf(), which doesn't guarantee
shiqiane35fdd92008-12-10 05:08:54 +00002697 // how many times the callable will be invoked.
2698 mutable CallableStorageType callable_;
2699 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002700
2701 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002702 }; // class Impl
2703
2704 const CallableStorageType callable_;
Abseil Teama0e62d92018-08-24 13:30:17 -04002705 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002706
2707 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002708};
2709
zhanyong.wana31d9ce2013-03-01 01:50:17 +00002710// Implements a matcher that checks the size of an STL-style container.
2711template <typename SizeMatcher>
2712class SizeIsMatcher {
2713 public:
2714 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2715 : size_matcher_(size_matcher) {
2716 }
2717
2718 template <typename Container>
2719 operator Matcher<Container>() const {
2720 return MakeMatcher(new Impl<Container>(size_matcher_));
2721 }
2722
2723 template <typename Container>
2724 class Impl : public MatcherInterface<Container> {
2725 public:
2726 typedef internal::StlContainerView<
2727 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2728 typedef typename ContainerView::type::size_type SizeType;
2729 explicit Impl(const SizeMatcher& size_matcher)
2730 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2731
2732 virtual void DescribeTo(::std::ostream* os) const {
2733 *os << "size ";
2734 size_matcher_.DescribeTo(os);
2735 }
2736 virtual void DescribeNegationTo(::std::ostream* os) const {
2737 *os << "size ";
2738 size_matcher_.DescribeNegationTo(os);
2739 }
2740
2741 virtual bool MatchAndExplain(Container container,
2742 MatchResultListener* listener) const {
2743 SizeType size = container.size();
2744 StringMatchResultListener size_listener;
2745 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2746 *listener
2747 << "whose size " << size << (result ? " matches" : " doesn't match");
2748 PrintIfNotEmpty(size_listener.str(), listener->stream());
2749 return result;
2750 }
2751
2752 private:
2753 const Matcher<SizeType> size_matcher_;
2754 GTEST_DISALLOW_ASSIGN_(Impl);
2755 };
2756
2757 private:
2758 const SizeMatcher size_matcher_;
2759 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2760};
2761
kosakb6a34882014-03-12 21:06:46 +00002762// Implements a matcher that checks the begin()..end() distance of an STL-style
2763// container.
2764template <typename DistanceMatcher>
2765class BeginEndDistanceIsMatcher {
2766 public:
2767 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2768 : distance_matcher_(distance_matcher) {}
2769
2770 template <typename Container>
2771 operator Matcher<Container>() const {
2772 return MakeMatcher(new Impl<Container>(distance_matcher_));
2773 }
2774
2775 template <typename Container>
2776 class Impl : public MatcherInterface<Container> {
2777 public:
2778 typedef internal::StlContainerView<
2779 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2780 typedef typename std::iterator_traits<
2781 typename ContainerView::type::const_iterator>::difference_type
2782 DistanceType;
2783 explicit Impl(const DistanceMatcher& distance_matcher)
2784 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2785
2786 virtual void DescribeTo(::std::ostream* os) const {
2787 *os << "distance between begin() and end() ";
2788 distance_matcher_.DescribeTo(os);
2789 }
2790 virtual void DescribeNegationTo(::std::ostream* os) const {
2791 *os << "distance between begin() and end() ";
2792 distance_matcher_.DescribeNegationTo(os);
2793 }
2794
2795 virtual bool MatchAndExplain(Container container,
2796 MatchResultListener* listener) const {
kosak5b9cbbb2014-11-17 00:28:55 +00002797#if GTEST_HAS_STD_BEGIN_AND_END_
kosakb6a34882014-03-12 21:06:46 +00002798 using std::begin;
2799 using std::end;
2800 DistanceType distance = std::distance(begin(container), end(container));
2801#else
2802 DistanceType distance = std::distance(container.begin(), container.end());
2803#endif
2804 StringMatchResultListener distance_listener;
2805 const bool result =
2806 distance_matcher_.MatchAndExplain(distance, &distance_listener);
2807 *listener << "whose distance between begin() and end() " << distance
2808 << (result ? " matches" : " doesn't match");
2809 PrintIfNotEmpty(distance_listener.str(), listener->stream());
2810 return result;
2811 }
2812
2813 private:
2814 const Matcher<DistanceType> distance_matcher_;
2815 GTEST_DISALLOW_ASSIGN_(Impl);
2816 };
2817
2818 private:
2819 const DistanceMatcher distance_matcher_;
2820 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2821};
2822
zhanyong.wan6a896b52009-01-16 01:13:50 +00002823// Implements an equality matcher for any STL-style container whose elements
2824// support ==. This matcher is like Eq(), but its failure explanations provide
2825// more detailed information that is useful when the container is used as a set.
2826// The failure message reports elements that are in one of the operands but not
2827// the other. The failure messages do not report duplicate or out-of-order
2828// elements in the containers (which don't properly matter to sets, but can
2829// occur if the containers are vectors or lists, for example).
2830//
2831// Uses the container's const_iterator, value_type, operator ==,
2832// begin(), and end().
2833template <typename Container>
2834class ContainerEqMatcher {
2835 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002836 typedef internal::StlContainerView<Container> View;
2837 typedef typename View::type StlContainer;
2838 typedef typename View::const_reference StlContainerReference;
2839
kosak6b817802015-01-08 02:38:14 +00002840 // We make a copy of expected in case the elements in it are modified
zhanyong.wanb8243162009-06-04 05:48:20 +00002841 // after this matcher is created.
kosak6b817802015-01-08 02:38:14 +00002842 explicit ContainerEqMatcher(const Container& expected)
2843 : expected_(View::Copy(expected)) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002844 // Makes sure the user doesn't instantiate this class template
2845 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002846 (void)testing::StaticAssertTypeEq<Container,
2847 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002848 }
2849
zhanyong.wan6a896b52009-01-16 01:13:50 +00002850 void DescribeTo(::std::ostream* os) const {
2851 *os << "equals ";
kosak6b817802015-01-08 02:38:14 +00002852 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002853 }
2854 void DescribeNegationTo(::std::ostream* os) const {
2855 *os << "does not equal ";
kosak6b817802015-01-08 02:38:14 +00002856 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002857 }
2858
zhanyong.wanb8243162009-06-04 05:48:20 +00002859 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002860 bool MatchAndExplain(const LhsContainer& lhs,
2861 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002862 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002863 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002864 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002865 LhsView;
2866 typedef typename LhsView::type LhsStlContainer;
2867 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
kosak6b817802015-01-08 02:38:14 +00002868 if (lhs_stl_container == expected_)
zhanyong.wane122e452010-01-12 09:03:52 +00002869 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002870
zhanyong.wane122e452010-01-12 09:03:52 +00002871 ::std::ostream* const os = listener->stream();
2872 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002873 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002874 bool printed_header = false;
2875 for (typename LhsStlContainer::const_iterator it =
2876 lhs_stl_container.begin();
2877 it != lhs_stl_container.end(); ++it) {
kosak6b817802015-01-08 02:38:14 +00002878 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
2879 expected_.end()) {
zhanyong.wane122e452010-01-12 09:03:52 +00002880 if (printed_header) {
2881 *os << ", ";
2882 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002883 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002884 printed_header = true;
2885 }
vladloseve2e8ba42010-05-13 18:16:03 +00002886 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002887 }
zhanyong.wane122e452010-01-12 09:03:52 +00002888 }
2889
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002890 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002891 bool printed_header2 = false;
kosak6b817802015-01-08 02:38:14 +00002892 for (typename StlContainer::const_iterator it = expected_.begin();
2893 it != expected_.end(); ++it) {
zhanyong.wane122e452010-01-12 09:03:52 +00002894 if (internal::ArrayAwareFind(
2895 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2896 lhs_stl_container.end()) {
2897 if (printed_header2) {
2898 *os << ", ";
2899 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002900 *os << (printed_header ? ",\nand" : "which")
2901 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002902 printed_header2 = true;
2903 }
vladloseve2e8ba42010-05-13 18:16:03 +00002904 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002905 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002906 }
2907 }
2908
zhanyong.wane122e452010-01-12 09:03:52 +00002909 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002910 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002911
zhanyong.wan6a896b52009-01-16 01:13:50 +00002912 private:
kosak6b817802015-01-08 02:38:14 +00002913 const StlContainer expected_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002914
2915 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002916};
2917
zhanyong.wan898725c2011-09-16 16:45:39 +00002918// A comparator functor that uses the < operator to compare two values.
2919struct LessComparator {
2920 template <typename T, typename U>
2921 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2922};
2923
2924// Implements WhenSortedBy(comparator, container_matcher).
2925template <typename Comparator, typename ContainerMatcher>
2926class WhenSortedByMatcher {
2927 public:
2928 WhenSortedByMatcher(const Comparator& comparator,
2929 const ContainerMatcher& matcher)
2930 : comparator_(comparator), matcher_(matcher) {}
2931
2932 template <typename LhsContainer>
2933 operator Matcher<LhsContainer>() const {
2934 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2935 }
2936
2937 template <typename LhsContainer>
2938 class Impl : public MatcherInterface<LhsContainer> {
2939 public:
2940 typedef internal::StlContainerView<
2941 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2942 typedef typename LhsView::type LhsStlContainer;
2943 typedef typename LhsView::const_reference LhsStlContainerReference;
zhanyong.wana9a59e02013-03-27 16:14:55 +00002944 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2945 // so that we can match associative containers.
2946 typedef typename RemoveConstFromKey<
2947 typename LhsStlContainer::value_type>::type LhsValue;
zhanyong.wan898725c2011-09-16 16:45:39 +00002948
2949 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2950 : comparator_(comparator), matcher_(matcher) {}
2951
2952 virtual void DescribeTo(::std::ostream* os) const {
2953 *os << "(when sorted) ";
2954 matcher_.DescribeTo(os);
2955 }
2956
2957 virtual void DescribeNegationTo(::std::ostream* os) const {
2958 *os << "(when sorted) ";
2959 matcher_.DescribeNegationTo(os);
2960 }
2961
2962 virtual bool MatchAndExplain(LhsContainer lhs,
2963 MatchResultListener* listener) const {
2964 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wanfb25d532013-07-28 08:24:00 +00002965 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2966 lhs_stl_container.end());
2967 ::std::sort(
2968 sorted_container.begin(), sorted_container.end(), comparator_);
zhanyong.wan898725c2011-09-16 16:45:39 +00002969
2970 if (!listener->IsInterested()) {
2971 // If the listener is not interested, we do not need to
2972 // construct the inner explanation.
2973 return matcher_.Matches(sorted_container);
2974 }
2975
2976 *listener << "which is ";
2977 UniversalPrint(sorted_container, listener->stream());
2978 *listener << " when sorted";
2979
2980 StringMatchResultListener inner_listener;
2981 const bool match = matcher_.MatchAndExplain(sorted_container,
2982 &inner_listener);
2983 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2984 return match;
2985 }
2986
2987 private:
2988 const Comparator comparator_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00002989 const Matcher<const ::std::vector<LhsValue>&> matcher_;
zhanyong.wan898725c2011-09-16 16:45:39 +00002990
2991 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2992 };
2993
2994 private:
2995 const Comparator comparator_;
2996 const ContainerMatcher matcher_;
2997
2998 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2999};
3000
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003001// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
3002// must be able to be safely cast to Matcher<tuple<const T1&, const
3003// T2&> >, where T1 and T2 are the types of elements in the LHS
3004// container and the RHS container respectively.
3005template <typename TupleMatcher, typename RhsContainer>
3006class PointwiseMatcher {
Gennadiy Civil23187052018-03-26 10:16:59 -04003007 GTEST_COMPILE_ASSERT_(
3008 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value,
3009 use_UnorderedPointwise_with_hash_tables);
3010
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003011 public:
3012 typedef internal::StlContainerView<RhsContainer> RhsView;
3013 typedef typename RhsView::type RhsStlContainer;
3014 typedef typename RhsStlContainer::value_type RhsValue;
3015
3016 // Like ContainerEq, we make a copy of rhs in case the elements in
3017 // it are modified after this matcher is created.
3018 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
3019 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
3020 // Makes sure the user doesn't instantiate this class template
3021 // with a const or reference type.
3022 (void)testing::StaticAssertTypeEq<RhsContainer,
3023 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
3024 }
3025
3026 template <typename LhsContainer>
3027 operator Matcher<LhsContainer>() const {
Gennadiy Civil23187052018-03-26 10:16:59 -04003028 GTEST_COMPILE_ASSERT_(
3029 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value,
3030 use_UnorderedPointwise_with_hash_tables);
3031
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003032 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
3033 }
3034
3035 template <typename LhsContainer>
3036 class Impl : public MatcherInterface<LhsContainer> {
3037 public:
3038 typedef internal::StlContainerView<
3039 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
3040 typedef typename LhsView::type LhsStlContainer;
3041 typedef typename LhsView::const_reference LhsStlContainerReference;
3042 typedef typename LhsStlContainer::value_type LhsValue;
3043 // We pass the LHS value and the RHS value to the inner matcher by
3044 // reference, as they may be expensive to copy. We must use tuple
3045 // instead of pair here, as a pair cannot hold references (C++ 98,
3046 // 20.2.2 [lib.pairs]).
kosakbd018832014-04-02 20:30:00 +00003047 typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003048
3049 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
3050 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
3051 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
3052 rhs_(rhs) {}
3053
3054 virtual void DescribeTo(::std::ostream* os) const {
3055 *os << "contains " << rhs_.size()
3056 << " values, where each value and its corresponding value in ";
3057 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
3058 *os << " ";
3059 mono_tuple_matcher_.DescribeTo(os);
3060 }
3061 virtual void DescribeNegationTo(::std::ostream* os) const {
3062 *os << "doesn't contain exactly " << rhs_.size()
3063 << " values, or contains a value x at some index i"
3064 << " where x and the i-th value of ";
3065 UniversalPrint(rhs_, os);
3066 *os << " ";
3067 mono_tuple_matcher_.DescribeNegationTo(os);
3068 }
3069
3070 virtual bool MatchAndExplain(LhsContainer lhs,
3071 MatchResultListener* listener) const {
3072 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
3073 const size_t actual_size = lhs_stl_container.size();
3074 if (actual_size != rhs_.size()) {
3075 *listener << "which contains " << actual_size << " values";
3076 return false;
3077 }
3078
3079 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
3080 typename RhsStlContainer::const_iterator right = rhs_.begin();
3081 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003082 if (listener->IsInterested()) {
3083 StringMatchResultListener inner_listener;
Gennadiy Civil23187052018-03-26 10:16:59 -04003084 // Create InnerMatcherArg as a temporarily object to avoid it outlives
3085 // *left and *right. Dereference or the conversion to `const T&` may
3086 // return temp objects, e.g for vector<bool>.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003087 if (!mono_tuple_matcher_.MatchAndExplain(
Gennadiy Civil23187052018-03-26 10:16:59 -04003088 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
3089 ImplicitCast_<const RhsValue&>(*right)),
3090 &inner_listener)) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003091 *listener << "where the value pair (";
3092 UniversalPrint(*left, listener->stream());
3093 *listener << ", ";
3094 UniversalPrint(*right, listener->stream());
3095 *listener << ") at index #" << i << " don't match";
3096 PrintIfNotEmpty(inner_listener.str(), listener->stream());
3097 return false;
3098 }
3099 } else {
Gennadiy Civil23187052018-03-26 10:16:59 -04003100 if (!mono_tuple_matcher_.Matches(
3101 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
3102 ImplicitCast_<const RhsValue&>(*right))))
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003103 return false;
3104 }
3105 }
3106
3107 return true;
3108 }
3109
3110 private:
3111 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
3112 const RhsStlContainer rhs_;
3113
3114 GTEST_DISALLOW_ASSIGN_(Impl);
3115 };
3116
3117 private:
3118 const TupleMatcher tuple_matcher_;
3119 const RhsStlContainer rhs_;
3120
3121 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
3122};
3123
zhanyong.wan33605ba2010-04-22 23:37:47 +00003124// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00003125template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00003126class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00003127 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003128 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00003129 typedef StlContainerView<RawContainer> View;
3130 typedef typename View::type StlContainer;
3131 typedef typename View::const_reference StlContainerReference;
3132 typedef typename StlContainer::value_type Element;
3133
3134 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00003135 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00003136 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00003137 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00003138
zhanyong.wan33605ba2010-04-22 23:37:47 +00003139 // Checks whether:
3140 // * All elements in the container match, if all_elements_should_match.
3141 // * Any element in the container matches, if !all_elements_should_match.
3142 bool MatchAndExplainImpl(bool all_elements_should_match,
3143 Container container,
3144 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00003145 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00003146 size_t i = 0;
Olivier Deprez78d05192021-04-20 17:55:57 +02003147 for (auto it = stl_container.begin();
zhanyong.wan82113312010-01-08 21:55:40 +00003148 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003149 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00003150 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
3151
3152 if (matches != all_elements_should_match) {
3153 *listener << "whose element #" << i
3154 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003155 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00003156 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00003157 }
3158 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00003159 return all_elements_should_match;
3160 }
3161
3162 protected:
3163 const Matcher<const Element&> inner_matcher_;
3164
3165 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
3166};
3167
3168// Implements Contains(element_matcher) for the given argument type Container.
3169// Symmetric to EachMatcherImpl.
3170template <typename Container>
3171class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
3172 public:
3173 template <typename InnerMatcher>
3174 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
3175 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3176
3177 // Describes what this matcher does.
3178 virtual void DescribeTo(::std::ostream* os) const {
3179 *os << "contains at least one element that ";
3180 this->inner_matcher_.DescribeTo(os);
3181 }
3182
3183 virtual void DescribeNegationTo(::std::ostream* os) const {
3184 *os << "doesn't contain any element that ";
3185 this->inner_matcher_.DescribeTo(os);
3186 }
3187
3188 virtual bool MatchAndExplain(Container container,
3189 MatchResultListener* listener) const {
3190 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00003191 }
3192
3193 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003194 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00003195};
3196
zhanyong.wan33605ba2010-04-22 23:37:47 +00003197// Implements Each(element_matcher) for the given argument type Container.
3198// Symmetric to ContainsMatcherImpl.
3199template <typename Container>
3200class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
3201 public:
3202 template <typename InnerMatcher>
3203 explicit EachMatcherImpl(InnerMatcher inner_matcher)
3204 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3205
3206 // Describes what this matcher does.
3207 virtual void DescribeTo(::std::ostream* os) const {
3208 *os << "only contains elements that ";
3209 this->inner_matcher_.DescribeTo(os);
3210 }
3211
3212 virtual void DescribeNegationTo(::std::ostream* os) const {
3213 *os << "contains some element that ";
3214 this->inner_matcher_.DescribeNegationTo(os);
3215 }
3216
3217 virtual bool MatchAndExplain(Container container,
3218 MatchResultListener* listener) const {
3219 return this->MatchAndExplainImpl(true, container, listener);
3220 }
3221
3222 private:
3223 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
3224};
3225
zhanyong.wanb8243162009-06-04 05:48:20 +00003226// Implements polymorphic Contains(element_matcher).
3227template <typename M>
3228class ContainsMatcher {
3229 public:
3230 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
3231
3232 template <typename Container>
3233 operator Matcher<Container>() const {
3234 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
3235 }
3236
3237 private:
3238 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003239
3240 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00003241};
3242
zhanyong.wan33605ba2010-04-22 23:37:47 +00003243// Implements polymorphic Each(element_matcher).
3244template <typename M>
3245class EachMatcher {
3246 public:
3247 explicit EachMatcher(M m) : inner_matcher_(m) {}
3248
3249 template <typename Container>
3250 operator Matcher<Container>() const {
3251 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
3252 }
3253
3254 private:
3255 const M inner_matcher_;
3256
3257 GTEST_DISALLOW_ASSIGN_(EachMatcher);
3258};
3259
Gennadiy Civil466a49a2018-03-23 11:23:54 -04003260struct Rank1 {};
3261struct Rank0 : Rank1 {};
3262
3263namespace pair_getters {
3264#if GTEST_LANG_CXX11
3265using std::get;
3266template <typename T>
3267auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT
3268 return get<0>(x);
3269}
3270template <typename T>
3271auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT
3272 return x.first;
3273}
3274
3275template <typename T>
3276auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT
3277 return get<1>(x);
3278}
3279template <typename T>
3280auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT
3281 return x.second;
3282}
3283#else
3284template <typename T>
3285typename T::first_type& First(T& x, Rank0) { // NOLINT
3286 return x.first;
3287}
3288template <typename T>
3289const typename T::first_type& First(const T& x, Rank0) {
3290 return x.first;
3291}
3292
3293template <typename T>
3294typename T::second_type& Second(T& x, Rank0) { // NOLINT
3295 return x.second;
3296}
3297template <typename T>
3298const typename T::second_type& Second(const T& x, Rank0) {
3299 return x.second;
3300}
3301#endif // GTEST_LANG_CXX11
3302} // namespace pair_getters
3303
zhanyong.wanb5937da2009-07-16 20:26:41 +00003304// Implements Key(inner_matcher) for the given argument pair type.
3305// Key(inner_matcher) matches an std::pair whose 'first' field matches
3306// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3307// std::map that contains at least one element whose key is >= 5.
3308template <typename PairType>
3309class KeyMatcherImpl : public MatcherInterface<PairType> {
3310 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003311 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00003312 typedef typename RawPairType::first_type KeyType;
3313
3314 template <typename InnerMatcher>
3315 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
3316 : inner_matcher_(
3317 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
3318 }
3319
3320 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00003321 virtual bool MatchAndExplain(PairType key_value,
3322 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003323 StringMatchResultListener inner_listener;
Gennadiy Civil23187052018-03-26 10:16:59 -04003324 const bool match = inner_matcher_.MatchAndExplain(
3325 pair_getters::First(key_value, Rank0()), &inner_listener);
Nico Weber09fd5b32017-05-15 17:07:03 -04003326 const std::string explanation = inner_listener.str();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003327 if (explanation != "") {
3328 *listener << "whose first field is a value " << explanation;
3329 }
3330 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00003331 }
3332
3333 // Describes what this matcher does.
3334 virtual void DescribeTo(::std::ostream* os) const {
3335 *os << "has a key that ";
3336 inner_matcher_.DescribeTo(os);
3337 }
3338
3339 // Describes what the negation of this matcher does.
3340 virtual void DescribeNegationTo(::std::ostream* os) const {
3341 *os << "doesn't have a key that ";
3342 inner_matcher_.DescribeTo(os);
3343 }
3344
zhanyong.wanb5937da2009-07-16 20:26:41 +00003345 private:
3346 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003347
3348 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00003349};
3350
3351// Implements polymorphic Key(matcher_for_key).
3352template <typename M>
3353class KeyMatcher {
3354 public:
3355 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
3356
3357 template <typename PairType>
3358 operator Matcher<PairType>() const {
3359 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
3360 }
3361
3362 private:
3363 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003364
3365 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00003366};
3367
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003368// Implements Pair(first_matcher, second_matcher) for the given argument pair
3369// type with its two matchers. See Pair() function below.
3370template <typename PairType>
3371class PairMatcherImpl : public MatcherInterface<PairType> {
3372 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003373 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003374 typedef typename RawPairType::first_type FirstType;
3375 typedef typename RawPairType::second_type SecondType;
3376
3377 template <typename FirstMatcher, typename SecondMatcher>
3378 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
3379 : first_matcher_(
3380 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
3381 second_matcher_(
3382 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
3383 }
3384
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003385 // Describes what this matcher does.
3386 virtual void DescribeTo(::std::ostream* os) const {
3387 *os << "has a first field that ";
3388 first_matcher_.DescribeTo(os);
3389 *os << ", and has a second field that ";
3390 second_matcher_.DescribeTo(os);
3391 }
3392
3393 // Describes what the negation of this matcher does.
3394 virtual void DescribeNegationTo(::std::ostream* os) const {
3395 *os << "has a first field that ";
3396 first_matcher_.DescribeNegationTo(os);
3397 *os << ", or has a second field that ";
3398 second_matcher_.DescribeNegationTo(os);
3399 }
3400
zhanyong.wan82113312010-01-08 21:55:40 +00003401 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3402 // matches second_matcher.
3403 virtual bool MatchAndExplain(PairType a_pair,
3404 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003405 if (!listener->IsInterested()) {
3406 // If the listener is not interested, we don't need to construct the
3407 // explanation.
Gennadiy Civil6aae2062018-03-26 10:36:26 -04003408 return first_matcher_.Matches(pair_getters::First(a_pair, Rank0())) &&
3409 second_matcher_.Matches(pair_getters::Second(a_pair, Rank0()));
zhanyong.wan82113312010-01-08 21:55:40 +00003410 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003411 StringMatchResultListener first_inner_listener;
Gennadiy Civil6aae2062018-03-26 10:36:26 -04003412 if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank0()),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003413 &first_inner_listener)) {
3414 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003415 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003416 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003417 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003418 StringMatchResultListener second_inner_listener;
Gennadiy Civil6aae2062018-03-26 10:36:26 -04003419 if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank0()),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003420 &second_inner_listener)) {
3421 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003422 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003423 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003424 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003425 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3426 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00003427 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003428 }
3429
3430 private:
Nico Weber09fd5b32017-05-15 17:07:03 -04003431 void ExplainSuccess(const std::string& first_explanation,
3432 const std::string& second_explanation,
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003433 MatchResultListener* listener) const {
3434 *listener << "whose both fields match";
3435 if (first_explanation != "") {
3436 *listener << ", where the first field is a value " << first_explanation;
3437 }
3438 if (second_explanation != "") {
3439 *listener << ", ";
3440 if (first_explanation != "") {
3441 *listener << "and ";
3442 } else {
3443 *listener << "where ";
3444 }
3445 *listener << "the second field is a value " << second_explanation;
3446 }
3447 }
3448
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003449 const Matcher<const FirstType&> first_matcher_;
3450 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003451
3452 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003453};
3454
3455// Implements polymorphic Pair(first_matcher, second_matcher).
3456template <typename FirstMatcher, typename SecondMatcher>
3457class PairMatcher {
3458 public:
3459 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3460 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3461
3462 template <typename PairType>
3463 operator Matcher<PairType> () const {
3464 return MakeMatcher(
3465 new PairMatcherImpl<PairType>(
3466 first_matcher_, second_matcher_));
3467 }
3468
3469 private:
3470 const FirstMatcher first_matcher_;
3471 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003472
3473 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003474};
3475
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003476// Implements ElementsAre() and ElementsAreArray().
3477template <typename Container>
3478class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3479 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003480 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003481 typedef internal::StlContainerView<RawContainer> View;
3482 typedef typename View::type StlContainer;
3483 typedef typename View::const_reference StlContainerReference;
3484 typedef typename StlContainer::value_type Element;
3485
3486 // Constructs the matcher from a sequence of element values or
3487 // element matchers.
3488 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00003489 ElementsAreMatcherImpl(InputIter first, InputIter last) {
3490 while (first != last) {
3491 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003492 }
3493 }
3494
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003495 // Describes what this matcher does.
3496 virtual void DescribeTo(::std::ostream* os) const {
3497 if (count() == 0) {
3498 *os << "is empty";
3499 } else if (count() == 1) {
3500 *os << "has 1 element that ";
3501 matchers_[0].DescribeTo(os);
3502 } else {
3503 *os << "has " << Elements(count()) << " where\n";
3504 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003505 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003506 matchers_[i].DescribeTo(os);
3507 if (i + 1 < count()) {
3508 *os << ",\n";
3509 }
3510 }
3511 }
3512 }
3513
3514 // Describes what the negation of this matcher does.
3515 virtual void DescribeNegationTo(::std::ostream* os) const {
3516 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003517 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003518 return;
3519 }
3520
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003521 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003522 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003523 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003524 matchers_[i].DescribeNegationTo(os);
3525 if (i + 1 < count()) {
3526 *os << ", or\n";
3527 }
3528 }
3529 }
3530
zhanyong.wan82113312010-01-08 21:55:40 +00003531 virtual bool MatchAndExplain(Container container,
3532 MatchResultListener* listener) const {
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003533 // To work with stream-like "containers", we must only walk
3534 // through the elements in one pass.
3535
3536 const bool listener_interested = listener->IsInterested();
3537
3538 // explanations[i] is the explanation of the element at index i.
Nico Weber09fd5b32017-05-15 17:07:03 -04003539 ::std::vector<std::string> explanations(count());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003540 StlContainerReference stl_container = View::ConstReference(container);
Olivier Deprez78d05192021-04-20 17:55:57 +02003541 auto it = stl_container.begin();
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003542 size_t exam_pos = 0;
3543 bool mismatch_found = false; // Have we found a mismatched element yet?
3544
3545 // Go through the elements and matchers in pairs, until we reach
3546 // the end of either the elements or the matchers, or until we find a
3547 // mismatch.
3548 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3549 bool match; // Does the current element match the current matcher?
3550 if (listener_interested) {
3551 StringMatchResultListener s;
3552 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3553 explanations[exam_pos] = s.str();
3554 } else {
3555 match = matchers_[exam_pos].Matches(*it);
3556 }
3557
3558 if (!match) {
3559 mismatch_found = true;
3560 break;
3561 }
3562 }
3563 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3564
3565 // Find how many elements the actual container has. We avoid
3566 // calling size() s.t. this code works for stream-like "containers"
3567 // that don't define size().
3568 size_t actual_count = exam_pos;
3569 for (; it != stl_container.end(); ++it) {
3570 ++actual_count;
3571 }
3572
zhanyong.wan82113312010-01-08 21:55:40 +00003573 if (actual_count != count()) {
3574 // The element count doesn't match. If the container is empty,
3575 // there's no need to explain anything as Google Mock already
3576 // prints the empty container. Otherwise we just need to show
3577 // how many elements there actually are.
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003578 if (listener_interested && (actual_count != 0)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003579 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003580 }
zhanyong.wan82113312010-01-08 21:55:40 +00003581 return false;
3582 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003583
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003584 if (mismatch_found) {
3585 // The element count matches, but the exam_pos-th element doesn't match.
3586 if (listener_interested) {
3587 *listener << "whose element #" << exam_pos << " doesn't match";
3588 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003589 }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003590 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003591 }
zhanyong.wan82113312010-01-08 21:55:40 +00003592
3593 // Every element matches its expectation. We need to explain why
3594 // (the obvious ones can be skipped).
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003595 if (listener_interested) {
3596 bool reason_printed = false;
3597 for (size_t i = 0; i != count(); ++i) {
Nico Weber09fd5b32017-05-15 17:07:03 -04003598 const std::string& s = explanations[i];
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003599 if (!s.empty()) {
3600 if (reason_printed) {
3601 *listener << ",\nand ";
3602 }
3603 *listener << "whose element #" << i << " matches, " << s;
3604 reason_printed = true;
zhanyong.wan82113312010-01-08 21:55:40 +00003605 }
zhanyong.wan82113312010-01-08 21:55:40 +00003606 }
3607 }
zhanyong.wan82113312010-01-08 21:55:40 +00003608 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003609 }
3610
3611 private:
3612 static Message Elements(size_t count) {
3613 return Message() << count << (count == 1 ? " element" : " elements");
3614 }
3615
3616 size_t count() const { return matchers_.size(); }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003617
3618 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003619
3620 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003621};
3622
zhanyong.wanfb25d532013-07-28 08:24:00 +00003623// Connectivity matrix of (elements X matchers), in element-major order.
3624// Initially, there are no edges.
3625// Use NextGraph() to iterate over all possible edge configurations.
3626// Use Randomize() to generate a random edge configuration.
3627class GTEST_API_ MatchMatrix {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003628 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003629 MatchMatrix(size_t num_elements, size_t num_matchers)
3630 : num_elements_(num_elements),
3631 num_matchers_(num_matchers),
3632 matched_(num_elements_* num_matchers_, 0) {
3633 }
3634
3635 size_t LhsSize() const { return num_elements_; }
3636 size_t RhsSize() const { return num_matchers_; }
3637 bool HasEdge(size_t ilhs, size_t irhs) const {
3638 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3639 }
3640 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3641 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3642 }
3643
3644 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3645 // adds 1 to that number; returns false if incrementing the graph left it
3646 // empty.
3647 bool NextGraph();
3648
3649 void Randomize();
3650
Nico Weber09fd5b32017-05-15 17:07:03 -04003651 std::string DebugString() const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003652
3653 private:
3654 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3655 return ilhs * num_matchers_ + irhs;
3656 }
3657
3658 size_t num_elements_;
3659 size_t num_matchers_;
3660
3661 // Each element is a char interpreted as bool. They are stored as a
3662 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3663 // a (ilhs, irhs) matrix coordinate into an offset.
3664 ::std::vector<char> matched_;
3665};
3666
3667typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3668typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3669
3670// Returns a maximum bipartite matching for the specified graph 'g'.
3671// The matching is represented as a vector of {element, matcher} pairs.
3672GTEST_API_ ElementMatcherPairs
3673FindMaxBipartiteMatching(const MatchMatrix& g);
3674
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003675struct UnorderedMatcherRequire {
3676 enum Flags {
3677 Superset = 1 << 0,
3678 Subset = 1 << 1,
3679 ExactMatch = Superset | Subset,
3680 };
3681};
zhanyong.wanfb25d532013-07-28 08:24:00 +00003682
3683// Untyped base class for implementing UnorderedElementsAre. By
3684// putting logic that's not specific to the element type here, we
3685// reduce binary bloat and increase compilation speed.
3686class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3687 protected:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003688 explicit UnorderedElementsAreMatcherImplBase(
3689 UnorderedMatcherRequire::Flags matcher_flags)
3690 : match_flags_(matcher_flags) {}
3691
zhanyong.wanfb25d532013-07-28 08:24:00 +00003692 // A vector of matcher describers, one for each element matcher.
3693 // Does not own the describers (and thus can be used only when the
3694 // element matchers are alive).
3695 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3696
3697 // Describes this UnorderedElementsAre matcher.
3698 void DescribeToImpl(::std::ostream* os) const;
3699
3700 // Describes the negation of this UnorderedElementsAre matcher.
3701 void DescribeNegationToImpl(::std::ostream* os) const;
3702
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003703 bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,
3704 const MatchMatrix& matrix,
3705 MatchResultListener* listener) const;
3706
3707 bool FindPairing(const MatchMatrix& matrix,
3708 MatchResultListener* listener) const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003709
3710 MatcherDescriberVec& matcher_describers() {
3711 return matcher_describers_;
3712 }
3713
3714 static Message Elements(size_t n) {
3715 return Message() << n << " element" << (n == 1 ? "" : "s");
3716 }
3717
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003718 UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }
3719
zhanyong.wanfb25d532013-07-28 08:24:00 +00003720 private:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003721 UnorderedMatcherRequire::Flags match_flags_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003722 MatcherDescriberVec matcher_describers_;
3723
3724 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3725};
3726
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003727// Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
3728// IsSupersetOf.
zhanyong.wanfb25d532013-07-28 08:24:00 +00003729template <typename Container>
3730class UnorderedElementsAreMatcherImpl
3731 : public MatcherInterface<Container>,
3732 public UnorderedElementsAreMatcherImplBase {
3733 public:
3734 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3735 typedef internal::StlContainerView<RawContainer> View;
3736 typedef typename View::type StlContainer;
3737 typedef typename View::const_reference StlContainerReference;
3738 typedef typename StlContainer::const_iterator StlContainerConstIterator;
3739 typedef typename StlContainer::value_type Element;
3740
zhanyong.wanfb25d532013-07-28 08:24:00 +00003741 template <typename InputIter>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003742 UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,
3743 InputIter first, InputIter last)
3744 : UnorderedElementsAreMatcherImplBase(matcher_flags) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00003745 for (; first != last; ++first) {
3746 matchers_.push_back(MatcherCast<const Element&>(*first));
3747 matcher_describers().push_back(matchers_.back().GetDescriber());
3748 }
3749 }
3750
3751 // Describes what this matcher does.
3752 virtual void DescribeTo(::std::ostream* os) const {
3753 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3754 }
3755
3756 // Describes what the negation of this matcher does.
3757 virtual void DescribeNegationTo(::std::ostream* os) const {
3758 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3759 }
3760
3761 virtual bool MatchAndExplain(Container container,
3762 MatchResultListener* listener) const {
3763 StlContainerReference stl_container = View::ConstReference(container);
Nico Weber09fd5b32017-05-15 17:07:03 -04003764 ::std::vector<std::string> element_printouts;
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003765 MatchMatrix matrix =
3766 AnalyzeElements(stl_container.begin(), stl_container.end(),
3767 &element_printouts, listener);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003768
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003769 if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00003770 return true;
3771 }
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003772
3773 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
3774 if (matrix.LhsSize() != matrix.RhsSize()) {
3775 // The element count doesn't match. If the container is empty,
3776 // there's no need to explain anything as Google Mock already
3777 // prints the empty container. Otherwise we just need to show
3778 // how many elements there actually are.
3779 if (matrix.LhsSize() != 0 && listener->IsInterested()) {
3780 *listener << "which has " << Elements(matrix.LhsSize());
3781 }
3782 return false;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003783 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003784 }
3785
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003786 return VerifyMatchMatrix(element_printouts, matrix, listener) &&
zhanyong.wanfb25d532013-07-28 08:24:00 +00003787 FindPairing(matrix, listener);
3788 }
3789
3790 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003791 template <typename ElementIter>
3792 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
Nico Weber09fd5b32017-05-15 17:07:03 -04003793 ::std::vector<std::string>* element_printouts,
zhanyong.wanfb25d532013-07-28 08:24:00 +00003794 MatchResultListener* listener) const {
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003795 element_printouts->clear();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003796 ::std::vector<char> did_match;
3797 size_t num_elements = 0;
3798 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3799 if (listener->IsInterested()) {
3800 element_printouts->push_back(PrintToString(*elem_first));
3801 }
3802 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3803 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3804 }
3805 }
3806
3807 MatchMatrix matrix(num_elements, matchers_.size());
3808 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3809 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3810 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3811 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3812 }
3813 }
3814 return matrix;
3815 }
3816
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003817 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003818
3819 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3820};
3821
3822// Functor for use in TransformTuple.
3823// Performs MatcherCast<Target> on an input argument of any type.
3824template <typename Target>
3825struct CastAndAppendTransform {
3826 template <typename Arg>
3827 Matcher<Target> operator()(const Arg& a) const {
3828 return MatcherCast<Target>(a);
3829 }
3830};
3831
3832// Implements UnorderedElementsAre.
3833template <typename MatcherTuple>
3834class UnorderedElementsAreMatcher {
3835 public:
3836 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3837 : matchers_(args) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003838
3839 template <typename Container>
3840 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003841 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003842 typedef typename internal::StlContainerView<RawContainer>::type View;
3843 typedef typename View::value_type Element;
3844 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3845 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003846 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003847 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3848 ::std::back_inserter(matchers));
3849 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003850 UnorderedMatcherRequire::ExactMatch, matchers.begin(), matchers.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003851 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003852
3853 private:
3854 const MatcherTuple matchers_;
3855 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3856};
3857
3858// Implements ElementsAre.
3859template <typename MatcherTuple>
3860class ElementsAreMatcher {
3861 public:
3862 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3863
3864 template <typename Container>
3865 operator Matcher<Container>() const {
Gennadiy Civil23187052018-03-26 10:16:59 -04003866 GTEST_COMPILE_ASSERT_(
3867 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value ||
3868 ::testing::tuple_size<MatcherTuple>::value < 2,
3869 use_UnorderedElementsAre_with_hash_tables);
3870
zhanyong.wanfb25d532013-07-28 08:24:00 +00003871 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3872 typedef typename internal::StlContainerView<RawContainer>::type View;
3873 typedef typename View::value_type Element;
3874 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3875 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003876 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003877 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3878 ::std::back_inserter(matchers));
3879 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3880 matchers.begin(), matchers.end()));
3881 }
3882
3883 private:
3884 const MatcherTuple matchers_;
3885 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3886};
3887
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003888// Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
zhanyong.wanfb25d532013-07-28 08:24:00 +00003889template <typename T>
3890class UnorderedElementsAreArrayMatcher {
3891 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003892 template <typename Iter>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003893 UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,
3894 Iter first, Iter last)
3895 : match_flags_(match_flags), matchers_(first, last) {}
zhanyong.wanfb25d532013-07-28 08:24:00 +00003896
3897 template <typename Container>
3898 operator Matcher<Container>() const {
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003899 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3900 match_flags_, matchers_.begin(), matchers_.end()));
zhanyong.wanfb25d532013-07-28 08:24:00 +00003901 }
3902
3903 private:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003904 UnorderedMatcherRequire::Flags match_flags_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003905 ::std::vector<T> matchers_;
3906
3907 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003908};
3909
3910// Implements ElementsAreArray().
3911template <typename T>
3912class ElementsAreArrayMatcher {
3913 public:
jgm38513a82012-11-15 15:50:36 +00003914 template <typename Iter>
3915 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003916
3917 template <typename Container>
3918 operator Matcher<Container>() const {
Gennadiy Civil23187052018-03-26 10:16:59 -04003919 GTEST_COMPILE_ASSERT_(
3920 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value,
3921 use_UnorderedElementsAreArray_with_hash_tables);
3922
jgm38513a82012-11-15 15:50:36 +00003923 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3924 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003925 }
3926
3927 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003928 const ::std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003929
3930 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003931};
3932
kosak2336e9c2014-07-28 22:57:30 +00003933// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3934// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3935// second) is a polymorphic matcher that matches a value x iff tm
3936// matches tuple (x, second). Useful for implementing
3937// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3938//
3939// BoundSecondMatcher is copyable and assignable, as we need to put
3940// instances of this class in a vector when implementing
3941// UnorderedPointwise().
3942template <typename Tuple2Matcher, typename Second>
3943class BoundSecondMatcher {
3944 public:
3945 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3946 : tuple2_matcher_(tm), second_value_(second) {}
3947
3948 template <typename T>
3949 operator Matcher<T>() const {
3950 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3951 }
3952
3953 // We have to define this for UnorderedPointwise() to compile in
3954 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3955 // which requires the elements to be assignable in C++98. The
3956 // compiler cannot generate the operator= for us, as Tuple2Matcher
3957 // and Second may not be assignable.
3958 //
3959 // However, this should never be called, so the implementation just
3960 // need to assert.
3961 void operator=(const BoundSecondMatcher& /*rhs*/) {
3962 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3963 }
3964
3965 private:
3966 template <typename T>
3967 class Impl : public MatcherInterface<T> {
3968 public:
3969 typedef ::testing::tuple<T, Second> ArgTuple;
3970
3971 Impl(const Tuple2Matcher& tm, const Second& second)
3972 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3973 second_value_(second) {}
3974
3975 virtual void DescribeTo(::std::ostream* os) const {
3976 *os << "and ";
3977 UniversalPrint(second_value_, os);
3978 *os << " ";
3979 mono_tuple2_matcher_.DescribeTo(os);
3980 }
3981
3982 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3983 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3984 listener);
3985 }
3986
3987 private:
3988 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3989 const Second second_value_;
3990
3991 GTEST_DISALLOW_ASSIGN_(Impl);
3992 };
3993
3994 const Tuple2Matcher tuple2_matcher_;
3995 const Second second_value_;
3996};
3997
3998// Given a 2-tuple matcher tm and a value second,
3999// MatcherBindSecond(tm, second) returns a matcher that matches a
4000// value x iff tm matches tuple (x, second). Useful for implementing
4001// UnorderedPointwise() in terms of UnorderedElementsAreArray().
4002template <typename Tuple2Matcher, typename Second>
4003BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
4004 const Tuple2Matcher& tm, const Second& second) {
4005 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
4006}
4007
zhanyong.wanb4140802010-06-08 22:53:57 +00004008// Returns the description for a matcher defined using the MATCHER*()
4009// macro where the user-supplied description string is "", if
4010// 'negation' is false; otherwise returns the description of the
4011// negation of the matcher. 'param_values' contains a list of strings
4012// that are the print-out of the matcher's parameters.
Nico Weber09fd5b32017-05-15 17:07:03 -04004013GTEST_API_ std::string FormatMatcherDescription(bool negation,
4014 const char* matcher_name,
4015 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00004016
Gennadiy Civilb907c262018-03-23 11:42:41 -04004017// Implements a matcher that checks the value of a optional<> type variable.
4018template <typename ValueMatcher>
4019class OptionalMatcher {
4020 public:
4021 explicit OptionalMatcher(const ValueMatcher& value_matcher)
4022 : value_matcher_(value_matcher) {}
4023
4024 template <typename Optional>
4025 operator Matcher<Optional>() const {
4026 return MakeMatcher(new Impl<Optional>(value_matcher_));
4027 }
4028
4029 template <typename Optional>
4030 class Impl : public MatcherInterface<Optional> {
4031 public:
4032 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView;
4033 typedef typename OptionalView::value_type ValueType;
4034 explicit Impl(const ValueMatcher& value_matcher)
4035 : value_matcher_(MatcherCast<ValueType>(value_matcher)) {}
4036
4037 virtual void DescribeTo(::std::ostream* os) const {
4038 *os << "value ";
4039 value_matcher_.DescribeTo(os);
4040 }
4041
4042 virtual void DescribeNegationTo(::std::ostream* os) const {
4043 *os << "value ";
4044 value_matcher_.DescribeNegationTo(os);
4045 }
4046
4047 virtual bool MatchAndExplain(Optional optional,
4048 MatchResultListener* listener) const {
4049 if (!optional) {
4050 *listener << "which is not engaged";
4051 return false;
4052 }
4053 const ValueType& value = *optional;
4054 StringMatchResultListener value_listener;
4055 const bool match = value_matcher_.MatchAndExplain(value, &value_listener);
4056 *listener << "whose value " << PrintToString(value)
4057 << (match ? " matches" : " doesn't match");
4058 PrintIfNotEmpty(value_listener.str(), listener->stream());
4059 return match;
4060 }
4061
4062 private:
4063 const Matcher<ValueType> value_matcher_;
4064 GTEST_DISALLOW_ASSIGN_(Impl);
4065 };
4066
4067 private:
4068 const ValueMatcher value_matcher_;
4069 GTEST_DISALLOW_ASSIGN_(OptionalMatcher);
4070};
4071
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05004072namespace variant_matcher {
4073// Overloads to allow VariantMatcher to do proper ADL lookup.
4074template <typename T>
4075void holds_alternative() {}
4076template <typename T>
4077void get() {}
4078
4079// Implements a matcher that checks the value of a variant<> type variable.
4080template <typename T>
4081class VariantMatcher {
4082 public:
4083 explicit VariantMatcher(::testing::Matcher<const T&> matcher)
4084 : matcher_(internal::move(matcher)) {}
4085
4086 template <typename Variant>
4087 bool MatchAndExplain(const Variant& value,
4088 ::testing::MatchResultListener* listener) const {
4089 if (!listener->IsInterested()) {
4090 return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));
4091 }
4092
4093 if (!holds_alternative<T>(value)) {
4094 *listener << "whose value is not of type '" << GetTypeName() << "'";
4095 return false;
4096 }
4097
4098 const T& elem = get<T>(value);
4099 StringMatchResultListener elem_listener;
4100 const bool match = matcher_.MatchAndExplain(elem, &elem_listener);
4101 *listener << "whose value " << PrintToString(elem)
4102 << (match ? " matches" : " doesn't match");
4103 PrintIfNotEmpty(elem_listener.str(), listener->stream());
4104 return match;
4105 }
4106
4107 void DescribeTo(std::ostream* os) const {
4108 *os << "is a variant<> with value of type '" << GetTypeName()
4109 << "' and the value ";
4110 matcher_.DescribeTo(os);
4111 }
4112
4113 void DescribeNegationTo(std::ostream* os) const {
4114 *os << "is a variant<> with value of type other than '" << GetTypeName()
4115 << "' or the value ";
4116 matcher_.DescribeNegationTo(os);
4117 }
4118
4119 private:
Gennadiy Civil23187052018-03-26 10:16:59 -04004120 static std::string GetTypeName() {
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05004121#if GTEST_HAS_RTTI
Gennadiy Civilab84d142018-04-11 15:24:04 -04004122 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
4123 return internal::GetTypeName<T>());
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05004124#endif
4125 return "the element type";
4126 }
4127
4128 const ::testing::Matcher<const T&> matcher_;
4129};
4130
4131} // namespace variant_matcher
4132
Gennadiy Civil466a49a2018-03-23 11:23:54 -04004133namespace any_cast_matcher {
4134
4135// Overloads to allow AnyCastMatcher to do proper ADL lookup.
4136template <typename T>
4137void any_cast() {}
4138
4139// Implements a matcher that any_casts the value.
4140template <typename T>
4141class AnyCastMatcher {
4142 public:
4143 explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher)
4144 : matcher_(matcher) {}
4145
4146 template <typename AnyType>
4147 bool MatchAndExplain(const AnyType& value,
4148 ::testing::MatchResultListener* listener) const {
4149 if (!listener->IsInterested()) {
4150 const T* ptr = any_cast<T>(&value);
4151 return ptr != NULL && matcher_.Matches(*ptr);
4152 }
4153
4154 const T* elem = any_cast<T>(&value);
4155 if (elem == NULL) {
4156 *listener << "whose value is not of type '" << GetTypeName() << "'";
4157 return false;
4158 }
4159
4160 StringMatchResultListener elem_listener;
4161 const bool match = matcher_.MatchAndExplain(*elem, &elem_listener);
4162 *listener << "whose value " << PrintToString(*elem)
4163 << (match ? " matches" : " doesn't match");
4164 PrintIfNotEmpty(elem_listener.str(), listener->stream());
4165 return match;
4166 }
4167
4168 void DescribeTo(std::ostream* os) const {
4169 *os << "is an 'any' type with value of type '" << GetTypeName()
4170 << "' and the value ";
4171 matcher_.DescribeTo(os);
4172 }
4173
4174 void DescribeNegationTo(std::ostream* os) const {
4175 *os << "is an 'any' type with value of type other than '" << GetTypeName()
4176 << "' or the value ";
4177 matcher_.DescribeNegationTo(os);
4178 }
4179
4180 private:
4181 static std::string GetTypeName() {
4182#if GTEST_HAS_RTTI
Gennadiy Civilab84d142018-04-11 15:24:04 -04004183 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
4184 return internal::GetTypeName<T>());
Gennadiy Civil466a49a2018-03-23 11:23:54 -04004185#endif
4186 return "the element type";
4187 }
4188
4189 const ::testing::Matcher<const T&> matcher_;
4190};
4191
4192} // namespace any_cast_matcher
shiqiane35fdd92008-12-10 05:08:54 +00004193} // namespace internal
4194
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004195// ElementsAreArray(iterator_first, iterator_last)
zhanyong.wanfb25d532013-07-28 08:24:00 +00004196// ElementsAreArray(pointer, count)
4197// ElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00004198// ElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004199// ElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00004200//
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004201// The ElementsAreArray() functions are like ElementsAre(...), except
4202// that they are given a homogeneous sequence rather than taking each
4203// element as a function argument. The sequence can be specified as an
4204// array, a pointer and count, a vector, an initializer list, or an
4205// STL iterator range. In each of these cases, the underlying sequence
4206// can be either a sequence of values or a sequence of matchers.
zhanyong.wanfb25d532013-07-28 08:24:00 +00004207//
4208// All forms of ElementsAreArray() make a copy of the input matcher sequence.
4209
4210template <typename Iter>
4211inline internal::ElementsAreArrayMatcher<
4212 typename ::std::iterator_traits<Iter>::value_type>
4213ElementsAreArray(Iter first, Iter last) {
4214 typedef typename ::std::iterator_traits<Iter>::value_type T;
4215 return internal::ElementsAreArrayMatcher<T>(first, last);
4216}
4217
4218template <typename T>
4219inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
4220 const T* pointer, size_t count) {
4221 return ElementsAreArray(pointer, pointer + count);
4222}
4223
4224template <typename T, size_t N>
4225inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
4226 const T (&array)[N]) {
4227 return ElementsAreArray(array, N);
4228}
4229
kosak06678922014-07-28 20:01:28 +00004230template <typename Container>
4231inline internal::ElementsAreArrayMatcher<typename Container::value_type>
4232ElementsAreArray(const Container& container) {
4233 return ElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00004234}
4235
kosak18489fa2013-12-04 23:49:07 +00004236#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004237template <typename T>
4238inline internal::ElementsAreArrayMatcher<T>
4239ElementsAreArray(::std::initializer_list<T> xs) {
4240 return ElementsAreArray(xs.begin(), xs.end());
4241}
4242#endif
4243
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004244// UnorderedElementsAreArray(iterator_first, iterator_last)
zhanyong.wanfb25d532013-07-28 08:24:00 +00004245// UnorderedElementsAreArray(pointer, count)
4246// UnorderedElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00004247// UnorderedElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004248// UnorderedElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00004249//
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004250// UnorderedElementsAreArray() verifies that a bijective mapping onto a
4251// collection of matchers exists.
4252//
4253// The matchers can be specified as an array, a pointer and count, a container,
4254// an initializer list, or an STL iterator range. In each of these cases, the
4255// underlying matchers can be either values or matchers.
4256
zhanyong.wanfb25d532013-07-28 08:24:00 +00004257template <typename Iter>
4258inline internal::UnorderedElementsAreArrayMatcher<
4259 typename ::std::iterator_traits<Iter>::value_type>
4260UnorderedElementsAreArray(Iter first, Iter last) {
4261 typedef typename ::std::iterator_traits<Iter>::value_type T;
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004262 return internal::UnorderedElementsAreArrayMatcher<T>(
4263 internal::UnorderedMatcherRequire::ExactMatch, first, last);
zhanyong.wanfb25d532013-07-28 08:24:00 +00004264}
4265
4266template <typename T>
4267inline internal::UnorderedElementsAreArrayMatcher<T>
4268UnorderedElementsAreArray(const T* pointer, size_t count) {
4269 return UnorderedElementsAreArray(pointer, pointer + count);
4270}
4271
4272template <typename T, size_t N>
4273inline internal::UnorderedElementsAreArrayMatcher<T>
4274UnorderedElementsAreArray(const T (&array)[N]) {
4275 return UnorderedElementsAreArray(array, N);
4276}
4277
kosak06678922014-07-28 20:01:28 +00004278template <typename Container>
4279inline internal::UnorderedElementsAreArrayMatcher<
4280 typename Container::value_type>
4281UnorderedElementsAreArray(const Container& container) {
4282 return UnorderedElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00004283}
4284
kosak18489fa2013-12-04 23:49:07 +00004285#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004286template <typename T>
4287inline internal::UnorderedElementsAreArrayMatcher<T>
4288UnorderedElementsAreArray(::std::initializer_list<T> xs) {
4289 return UnorderedElementsAreArray(xs.begin(), xs.end());
4290}
4291#endif
zhanyong.wanfb25d532013-07-28 08:24:00 +00004292
shiqiane35fdd92008-12-10 05:08:54 +00004293// _ is a matcher that matches anything of any type.
4294//
4295// This definition is fine as:
4296//
4297// 1. The C++ standard permits using the name _ in a namespace that
4298// is not the global namespace or ::std.
4299// 2. The AnythingMatcher class has no data member or constructor,
4300// so it's OK to create global variables of this type.
4301// 3. c-style has approved of using _ in this case.
4302const internal::AnythingMatcher _ = {};
4303// Creates a matcher that matches any value of the given type T.
4304template <typename T>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004305inline Matcher<T> A() {
4306 return Matcher<T>(new internal::AnyMatcherImpl<T>());
4307}
shiqiane35fdd92008-12-10 05:08:54 +00004308
4309// Creates a matcher that matches any value of the given type T.
4310template <typename T>
4311inline Matcher<T> An() { return A<T>(); }
4312
4313// Creates a polymorphic matcher that matches anything equal to x.
4314// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
4315// wouldn't compile.
4316template <typename T>
4317inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
4318
4319// Constructs a Matcher<T> from a 'value' of type T. The constructed
4320// matcher matches any value that's equal to 'value'.
4321template <typename T>
4322Matcher<T>::Matcher(T value) { *this = Eq(value); }
4323
Gennadiy Civil466a49a2018-03-23 11:23:54 -04004324template <typename T, typename M>
4325Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(
4326 const M& value,
4327 internal::BooleanConstant<false> /* convertible_to_matcher */,
4328 internal::BooleanConstant<false> /* convertible_to_T */) {
4329 return Eq(value);
4330}
4331
shiqiane35fdd92008-12-10 05:08:54 +00004332// Creates a monomorphic matcher that matches anything with type Lhs
4333// and equal to rhs. A user may need to use this instead of Eq(...)
4334// in order to resolve an overloading ambiguity.
4335//
4336// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
4337// or Matcher<T>(x), but more readable than the latter.
4338//
4339// We could define similar monomorphic matchers for other comparison
4340// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
4341// it yet as those are used much less than Eq() in practice. A user
4342// can always write Matcher<T>(Lt(5)) to be explicit about the type,
4343// for example.
4344template <typename Lhs, typename Rhs>
4345inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
4346
4347// Creates a polymorphic matcher that matches anything >= x.
4348template <typename Rhs>
4349inline internal::GeMatcher<Rhs> Ge(Rhs x) {
4350 return internal::GeMatcher<Rhs>(x);
4351}
4352
4353// Creates a polymorphic matcher that matches anything > x.
4354template <typename Rhs>
4355inline internal::GtMatcher<Rhs> Gt(Rhs x) {
4356 return internal::GtMatcher<Rhs>(x);
4357}
4358
4359// Creates a polymorphic matcher that matches anything <= x.
4360template <typename Rhs>
4361inline internal::LeMatcher<Rhs> Le(Rhs x) {
4362 return internal::LeMatcher<Rhs>(x);
4363}
4364
4365// Creates a polymorphic matcher that matches anything < x.
4366template <typename Rhs>
4367inline internal::LtMatcher<Rhs> Lt(Rhs x) {
4368 return internal::LtMatcher<Rhs>(x);
4369}
4370
4371// Creates a polymorphic matcher that matches anything != x.
4372template <typename Rhs>
4373inline internal::NeMatcher<Rhs> Ne(Rhs x) {
4374 return internal::NeMatcher<Rhs>(x);
4375}
4376
zhanyong.wan2d970ee2009-09-24 21:41:36 +00004377// Creates a polymorphic matcher that matches any NULL pointer.
4378inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
4379 return MakePolymorphicMatcher(internal::IsNullMatcher());
4380}
4381
shiqiane35fdd92008-12-10 05:08:54 +00004382// Creates a polymorphic matcher that matches any non-NULL pointer.
4383// This is convenient as Not(NULL) doesn't compile (the compiler
4384// thinks that that expression is comparing a pointer with an integer).
4385inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
4386 return MakePolymorphicMatcher(internal::NotNullMatcher());
4387}
4388
4389// Creates a polymorphic matcher that matches any argument that
4390// references variable x.
4391template <typename T>
4392inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
4393 return internal::RefMatcher<T&>(x);
4394}
4395
4396// Creates a matcher that matches any double argument approximately
4397// equal to rhs, where two NANs are considered unequal.
4398inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
4399 return internal::FloatingEqMatcher<double>(rhs, false);
4400}
4401
4402// Creates a matcher that matches any double argument approximately
4403// equal to rhs, including NaN values when rhs is NaN.
4404inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
4405 return internal::FloatingEqMatcher<double>(rhs, true);
4406}
4407
zhanyong.wan616180e2013-06-18 18:49:51 +00004408// Creates a matcher that matches any double argument approximately equal to
4409// rhs, up to the specified max absolute error bound, where two NANs are
4410// considered unequal. The max absolute error bound must be non-negative.
4411inline internal::FloatingEqMatcher<double> DoubleNear(
4412 double rhs, double max_abs_error) {
4413 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
4414}
4415
4416// Creates a matcher that matches any double argument approximately equal to
4417// rhs, up to the specified max absolute error bound, including NaN values when
4418// rhs is NaN. The max absolute error bound must be non-negative.
4419inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
4420 double rhs, double max_abs_error) {
4421 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
4422}
4423
shiqiane35fdd92008-12-10 05:08:54 +00004424// Creates a matcher that matches any float argument approximately
4425// equal to rhs, where two NANs are considered unequal.
4426inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
4427 return internal::FloatingEqMatcher<float>(rhs, false);
4428}
4429
zhanyong.wan616180e2013-06-18 18:49:51 +00004430// Creates a matcher that matches any float argument approximately
shiqiane35fdd92008-12-10 05:08:54 +00004431// equal to rhs, including NaN values when rhs is NaN.
4432inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
4433 return internal::FloatingEqMatcher<float>(rhs, true);
4434}
4435
zhanyong.wan616180e2013-06-18 18:49:51 +00004436// Creates a matcher that matches any float argument approximately equal to
4437// rhs, up to the specified max absolute error bound, where two NANs are
4438// considered unequal. The max absolute error bound must be non-negative.
4439inline internal::FloatingEqMatcher<float> FloatNear(
4440 float rhs, float max_abs_error) {
4441 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
4442}
4443
4444// Creates a matcher that matches any float argument approximately equal to
4445// rhs, up to the specified max absolute error bound, including NaN values when
4446// rhs is NaN. The max absolute error bound must be non-negative.
4447inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
4448 float rhs, float max_abs_error) {
4449 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
4450}
4451
shiqiane35fdd92008-12-10 05:08:54 +00004452// Creates a matcher that matches a pointer (raw or smart) that points
4453// to a value that matches inner_matcher.
4454template <typename InnerMatcher>
4455inline internal::PointeeMatcher<InnerMatcher> Pointee(
4456 const InnerMatcher& inner_matcher) {
4457 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
4458}
4459
Scott Grahama9653c42018-05-02 11:14:39 -07004460#if GTEST_HAS_RTTI
billydonahue1f5fdea2014-05-19 17:54:51 +00004461// Creates a matcher that matches a pointer or reference that matches
4462// inner_matcher when dynamic_cast<To> is applied.
4463// The result of dynamic_cast<To> is forwarded to the inner matcher.
4464// If To is a pointer and the cast fails, the inner matcher will receive NULL.
4465// If To is a reference and the cast fails, this matcher returns false
4466// immediately.
4467template <typename To>
4468inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
4469WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
4470 return MakePolymorphicMatcher(
4471 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
4472}
Scott Grahama9653c42018-05-02 11:14:39 -07004473#endif // GTEST_HAS_RTTI
billydonahue1f5fdea2014-05-19 17:54:51 +00004474
shiqiane35fdd92008-12-10 05:08:54 +00004475// Creates a matcher that matches an object whose given field matches
4476// 'matcher'. For example,
4477// Field(&Foo::number, Ge(5))
4478// matches a Foo object x iff x.number >= 5.
4479template <typename Class, typename FieldType, typename FieldMatcher>
4480inline PolymorphicMatcher<
4481 internal::FieldMatcher<Class, FieldType> > Field(
4482 FieldType Class::*field, const FieldMatcher& matcher) {
4483 return MakePolymorphicMatcher(
4484 internal::FieldMatcher<Class, FieldType>(
4485 field, MatcherCast<const FieldType&>(matcher)));
4486 // The call to MatcherCast() is required for supporting inner
4487 // matchers of compatible types. For example, it allows
4488 // Field(&Foo::bar, m)
4489 // to compile where bar is an int32 and m is a matcher for int64.
4490}
4491
Gennadiy Civilb907c262018-03-23 11:42:41 -04004492// Same as Field() but also takes the name of the field to provide better error
4493// messages.
4494template <typename Class, typename FieldType, typename FieldMatcher>
4495inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType> > Field(
4496 const std::string& field_name, FieldType Class::*field,
4497 const FieldMatcher& matcher) {
4498 return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(
4499 field_name, field, MatcherCast<const FieldType&>(matcher)));
4500}
4501
shiqiane35fdd92008-12-10 05:08:54 +00004502// Creates a matcher that matches an object whose given property
4503// matches 'matcher'. For example,
4504// Property(&Foo::str, StartsWith("hi"))
4505// matches a Foo object x iff x.str() starts with "hi".
4506template <typename Class, typename PropertyType, typename PropertyMatcher>
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004507inline PolymorphicMatcher<internal::PropertyMatcher<
4508 Class, PropertyType, PropertyType (Class::*)() const> >
4509Property(PropertyType (Class::*property)() const,
4510 const PropertyMatcher& matcher) {
shiqiane35fdd92008-12-10 05:08:54 +00004511 return MakePolymorphicMatcher(
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004512 internal::PropertyMatcher<Class, PropertyType,
4513 PropertyType (Class::*)() const>(
shiqiane35fdd92008-12-10 05:08:54 +00004514 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00004515 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00004516 // The call to MatcherCast() is required for supporting inner
4517 // matchers of compatible types. For example, it allows
4518 // Property(&Foo::bar, m)
4519 // to compile where bar() returns an int32 and m is a matcher for int64.
4520}
4521
Gennadiy Civil23187052018-03-26 10:16:59 -04004522// Same as Property() above, but also takes the name of the property to provide
4523// better error messages.
4524template <typename Class, typename PropertyType, typename PropertyMatcher>
4525inline PolymorphicMatcher<internal::PropertyMatcher<
4526 Class, PropertyType, PropertyType (Class::*)() const> >
4527Property(const std::string& property_name,
4528 PropertyType (Class::*property)() const,
4529 const PropertyMatcher& matcher) {
4530 return MakePolymorphicMatcher(
4531 internal::PropertyMatcher<Class, PropertyType,
4532 PropertyType (Class::*)() const>(
4533 property_name, property,
4534 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4535}
4536
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004537#if GTEST_LANG_CXX11
4538// The same as above but for reference-qualified member functions.
4539template <typename Class, typename PropertyType, typename PropertyMatcher>
4540inline PolymorphicMatcher<internal::PropertyMatcher<
4541 Class, PropertyType, PropertyType (Class::*)() const &> >
4542Property(PropertyType (Class::*property)() const &,
4543 const PropertyMatcher& matcher) {
4544 return MakePolymorphicMatcher(
4545 internal::PropertyMatcher<Class, PropertyType,
4546 PropertyType (Class::*)() const &>(
4547 property,
4548 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4549}
Gennadiy Civila02af2f2018-07-20 11:28:58 -04004550
4551// Three-argument form for reference-qualified member functions.
4552template <typename Class, typename PropertyType, typename PropertyMatcher>
4553inline PolymorphicMatcher<internal::PropertyMatcher<
4554 Class, PropertyType, PropertyType (Class::*)() const &> >
4555Property(const std::string& property_name,
4556 PropertyType (Class::*property)() const &,
4557 const PropertyMatcher& matcher) {
4558 return MakePolymorphicMatcher(
4559 internal::PropertyMatcher<Class, PropertyType,
4560 PropertyType (Class::*)() const &>(
4561 property_name, property,
4562 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4563}
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004564#endif
4565
shiqiane35fdd92008-12-10 05:08:54 +00004566// Creates a matcher that matches an object iff the result of applying
4567// a callable to x matches 'matcher'.
4568// For example,
4569// ResultOf(f, StartsWith("hi"))
4570// matches a Foo object x iff f(x) starts with "hi".
Abseil Teama0e62d92018-08-24 13:30:17 -04004571// `callable` parameter can be a function, function pointer, or a functor. It is
4572// required to keep no state affecting the results of the calls on it and make
4573// no assumptions about how many calls will be made. Any state it keeps must be
4574// protected from the concurrent access.
4575template <typename Callable, typename InnerMatcher>
4576internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(
4577 Callable callable, InnerMatcher matcher) {
4578 return internal::ResultOfMatcher<Callable, InnerMatcher>(
4579 internal::move(callable), internal::move(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00004580}
4581
4582// String matchers.
4583
4584// Matches a string equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04004585inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
4586 const std::string& str) {
4587 return MakePolymorphicMatcher(
4588 internal::StrEqualityMatcher<std::string>(str, true, true));
shiqiane35fdd92008-12-10 05:08:54 +00004589}
4590
4591// Matches a string not equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04004592inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
4593 const std::string& str) {
4594 return MakePolymorphicMatcher(
4595 internal::StrEqualityMatcher<std::string>(str, false, true));
shiqiane35fdd92008-12-10 05:08:54 +00004596}
4597
4598// Matches a string equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04004599inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
4600 const std::string& str) {
4601 return MakePolymorphicMatcher(
4602 internal::StrEqualityMatcher<std::string>(str, true, false));
shiqiane35fdd92008-12-10 05:08:54 +00004603}
4604
4605// Matches a string not equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04004606inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
4607 const std::string& str) {
4608 return MakePolymorphicMatcher(
4609 internal::StrEqualityMatcher<std::string>(str, false, false));
shiqiane35fdd92008-12-10 05:08:54 +00004610}
4611
4612// Creates a matcher that matches any string, std::string, or C string
4613// that contains the given substring.
Nico Weber09fd5b32017-05-15 17:07:03 -04004614inline PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
4615 const std::string& substring) {
4616 return MakePolymorphicMatcher(
4617 internal::HasSubstrMatcher<std::string>(substring));
shiqiane35fdd92008-12-10 05:08:54 +00004618}
4619
4620// Matches a string that starts with 'prefix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004621inline PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
4622 const std::string& prefix) {
4623 return MakePolymorphicMatcher(
4624 internal::StartsWithMatcher<std::string>(prefix));
shiqiane35fdd92008-12-10 05:08:54 +00004625}
4626
4627// Matches a string that ends with 'suffix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004628inline PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
4629 const std::string& suffix) {
4630 return MakePolymorphicMatcher(internal::EndsWithMatcher<std::string>(suffix));
shiqiane35fdd92008-12-10 05:08:54 +00004631}
4632
shiqiane35fdd92008-12-10 05:08:54 +00004633// Matches a string that fully matches regular expression 'regex'.
4634// The matcher takes ownership of 'regex'.
4635inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4636 const internal::RE* regex) {
4637 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
4638}
4639inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004640 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004641 return MatchesRegex(new internal::RE(regex));
4642}
4643
4644// Matches a string that contains regular expression 'regex'.
4645// The matcher takes ownership of 'regex'.
4646inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4647 const internal::RE* regex) {
4648 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4649}
4650inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004651 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004652 return ContainsRegex(new internal::RE(regex));
4653}
4654
shiqiane35fdd92008-12-10 05:08:54 +00004655#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4656// Wide string matchers.
4657
4658// Matches a string equal to str.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004659inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrEq(
4660 const std::wstring& str) {
4661 return MakePolymorphicMatcher(
4662 internal::StrEqualityMatcher<std::wstring>(str, true, true));
shiqiane35fdd92008-12-10 05:08:54 +00004663}
4664
4665// Matches a string not equal to str.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004666inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrNe(
4667 const std::wstring& str) {
4668 return MakePolymorphicMatcher(
4669 internal::StrEqualityMatcher<std::wstring>(str, false, true));
shiqiane35fdd92008-12-10 05:08:54 +00004670}
4671
4672// Matches a string equal to str, ignoring case.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004673inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
4674StrCaseEq(const std::wstring& str) {
4675 return MakePolymorphicMatcher(
4676 internal::StrEqualityMatcher<std::wstring>(str, true, false));
shiqiane35fdd92008-12-10 05:08:54 +00004677}
4678
4679// Matches a string not equal to str, ignoring case.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004680inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
4681StrCaseNe(const std::wstring& str) {
4682 return MakePolymorphicMatcher(
4683 internal::StrEqualityMatcher<std::wstring>(str, false, false));
shiqiane35fdd92008-12-10 05:08:54 +00004684}
4685
Gennadiy Civilb907c262018-03-23 11:42:41 -04004686// Creates a matcher that matches any ::wstring, std::wstring, or C wide string
shiqiane35fdd92008-12-10 05:08:54 +00004687// that contains the given substring.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004688inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring> > HasSubstr(
4689 const std::wstring& substring) {
4690 return MakePolymorphicMatcher(
4691 internal::HasSubstrMatcher<std::wstring>(substring));
shiqiane35fdd92008-12-10 05:08:54 +00004692}
4693
4694// Matches a string that starts with 'prefix' (case-sensitive).
Gennadiy Civilb907c262018-03-23 11:42:41 -04004695inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring> >
4696StartsWith(const std::wstring& prefix) {
4697 return MakePolymorphicMatcher(
4698 internal::StartsWithMatcher<std::wstring>(prefix));
shiqiane35fdd92008-12-10 05:08:54 +00004699}
4700
4701// Matches a string that ends with 'suffix' (case-sensitive).
Gennadiy Civilb907c262018-03-23 11:42:41 -04004702inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring> > EndsWith(
4703 const std::wstring& suffix) {
4704 return MakePolymorphicMatcher(
4705 internal::EndsWithMatcher<std::wstring>(suffix));
shiqiane35fdd92008-12-10 05:08:54 +00004706}
4707
4708#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4709
4710// Creates a polymorphic matcher that matches a 2-tuple where the
4711// first field == the second field.
4712inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4713
4714// Creates a polymorphic matcher that matches a 2-tuple where the
4715// first field >= the second field.
4716inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4717
4718// Creates a polymorphic matcher that matches a 2-tuple where the
4719// first field > the second field.
4720inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4721
4722// Creates a polymorphic matcher that matches a 2-tuple where the
4723// first field <= the second field.
4724inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4725
4726// Creates a polymorphic matcher that matches a 2-tuple where the
4727// first field < the second field.
4728inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4729
4730// Creates a polymorphic matcher that matches a 2-tuple where the
4731// first field != the second field.
4732inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4733
Gennadiy Civilb907c262018-03-23 11:42:41 -04004734// Creates a polymorphic matcher that matches a 2-tuple where
4735// FloatEq(first field) matches the second field.
4736inline internal::FloatingEq2Matcher<float> FloatEq() {
4737 return internal::FloatingEq2Matcher<float>();
4738}
4739
4740// Creates a polymorphic matcher that matches a 2-tuple where
4741// DoubleEq(first field) matches the second field.
4742inline internal::FloatingEq2Matcher<double> DoubleEq() {
4743 return internal::FloatingEq2Matcher<double>();
4744}
4745
4746// Creates a polymorphic matcher that matches a 2-tuple where
4747// FloatEq(first field) matches the second field with NaN equality.
4748inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() {
4749 return internal::FloatingEq2Matcher<float>(true);
4750}
4751
4752// Creates a polymorphic matcher that matches a 2-tuple where
4753// DoubleEq(first field) matches the second field with NaN equality.
4754inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() {
4755 return internal::FloatingEq2Matcher<double>(true);
4756}
4757
4758// Creates a polymorphic matcher that matches a 2-tuple where
4759// FloatNear(first field, max_abs_error) matches the second field.
4760inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) {
4761 return internal::FloatingEq2Matcher<float>(max_abs_error);
4762}
4763
4764// Creates a polymorphic matcher that matches a 2-tuple where
4765// DoubleNear(first field, max_abs_error) matches the second field.
4766inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) {
4767 return internal::FloatingEq2Matcher<double>(max_abs_error);
4768}
4769
4770// Creates a polymorphic matcher that matches a 2-tuple where
4771// FloatNear(first field, max_abs_error) matches the second field with NaN
4772// equality.
4773inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear(
4774 float max_abs_error) {
4775 return internal::FloatingEq2Matcher<float>(max_abs_error, true);
4776}
4777
4778// Creates a polymorphic matcher that matches a 2-tuple where
4779// DoubleNear(first field, max_abs_error) matches the second field with NaN
4780// equality.
4781inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear(
4782 double max_abs_error) {
4783 return internal::FloatingEq2Matcher<double>(max_abs_error, true);
4784}
4785
shiqiane35fdd92008-12-10 05:08:54 +00004786// Creates a matcher that matches any value of type T that m doesn't
4787// match.
4788template <typename InnerMatcher>
4789inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4790 return internal::NotMatcher<InnerMatcher>(m);
4791}
4792
shiqiane35fdd92008-12-10 05:08:54 +00004793// Returns a matcher that matches anything that satisfies the given
4794// predicate. The predicate can be any unary function or functor
4795// whose return type can be implicitly converted to bool.
4796template <typename Predicate>
4797inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4798Truly(Predicate pred) {
4799 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4800}
4801
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004802// Returns a matcher that matches the container size. The container must
4803// support both size() and size_type which all STL-like containers provide.
4804// Note that the parameter 'size' can be a value of type size_type as well as
4805// matcher. For instance:
4806// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
4807// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
4808template <typename SizeMatcher>
4809inline internal::SizeIsMatcher<SizeMatcher>
4810SizeIs(const SizeMatcher& size_matcher) {
4811 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4812}
4813
kosakb6a34882014-03-12 21:06:46 +00004814// Returns a matcher that matches the distance between the container's begin()
4815// iterator and its end() iterator, i.e. the size of the container. This matcher
4816// can be used instead of SizeIs with containers such as std::forward_list which
4817// do not implement size(). The container must provide const_iterator (with
4818// valid iterator_traits), begin() and end().
4819template <typename DistanceMatcher>
4820inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4821BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4822 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4823}
4824
zhanyong.wan6a896b52009-01-16 01:13:50 +00004825// Returns a matcher that matches an equal container.
4826// This matcher behaves like Eq(), but in the event of mismatch lists the
4827// values that are included in one container but not the other. (Duplicate
4828// values and order differences are not explained.)
4829template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00004830inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00004831 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004832 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00004833 // This following line is for working around a bug in MSVC 8.0,
4834 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00004835 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00004836 return MakePolymorphicMatcher(
4837 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00004838}
4839
zhanyong.wan898725c2011-09-16 16:45:39 +00004840// Returns a matcher that matches a container that, when sorted using
4841// the given comparator, matches container_matcher.
4842template <typename Comparator, typename ContainerMatcher>
4843inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4844WhenSortedBy(const Comparator& comparator,
4845 const ContainerMatcher& container_matcher) {
4846 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4847 comparator, container_matcher);
4848}
4849
4850// Returns a matcher that matches a container that, when sorted using
4851// the < operator, matches container_matcher.
4852template <typename ContainerMatcher>
4853inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4854WhenSorted(const ContainerMatcher& container_matcher) {
4855 return
4856 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4857 internal::LessComparator(), container_matcher);
4858}
4859
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004860// Matches an STL-style container or a native array that contains the
4861// same number of elements as in rhs, where its i-th element and rhs's
4862// i-th element (as a pair) satisfy the given pair matcher, for all i.
4863// TupleMatcher must be able to be safely cast to Matcher<tuple<const
4864// T1&, const T2&> >, where T1 and T2 are the types of elements in the
4865// LHS container and the RHS container respectively.
4866template <typename TupleMatcher, typename Container>
4867inline internal::PointwiseMatcher<TupleMatcher,
4868 GTEST_REMOVE_CONST_(Container)>
4869Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4870 // This following line is for working around a bug in MSVC 8.0,
kosak2336e9c2014-07-28 22:57:30 +00004871 // which causes Container to be a const type sometimes (e.g. when
4872 // rhs is a const int[])..
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004873 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4874 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4875 tuple_matcher, rhs);
4876}
4877
kosak2336e9c2014-07-28 22:57:30 +00004878#if GTEST_HAS_STD_INITIALIZER_LIST_
4879
4880// Supports the Pointwise(m, {a, b, c}) syntax.
4881template <typename TupleMatcher, typename T>
4882inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4883 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4884 return Pointwise(tuple_matcher, std::vector<T>(rhs));
4885}
4886
4887#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4888
4889// UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4890// container or a native array that contains the same number of
4891// elements as in rhs, where in some permutation of the container, its
4892// i-th element and rhs's i-th element (as a pair) satisfy the given
4893// pair matcher, for all i. Tuple2Matcher must be able to be safely
4894// cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4895// the types of elements in the LHS container and the RHS container
4896// respectively.
4897//
4898// This is like Pointwise(pair_matcher, rhs), except that the element
4899// order doesn't matter.
4900template <typename Tuple2Matcher, typename RhsContainer>
4901inline internal::UnorderedElementsAreArrayMatcher<
4902 typename internal::BoundSecondMatcher<
4903 Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4904 RhsContainer)>::type::value_type> >
4905UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4906 const RhsContainer& rhs_container) {
4907 // This following line is for working around a bug in MSVC 8.0,
4908 // which causes RhsContainer to be a const type sometimes (e.g. when
4909 // rhs_container is a const int[]).
4910 typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4911
4912 // RhsView allows the same code to handle RhsContainer being a
4913 // STL-style container and it being a native C-style array.
4914 typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4915 typedef typename RhsView::type RhsStlContainer;
4916 typedef typename RhsStlContainer::value_type Second;
4917 const RhsStlContainer& rhs_stl_container =
4918 RhsView::ConstReference(rhs_container);
4919
4920 // Create a matcher for each element in rhs_container.
4921 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4922 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4923 it != rhs_stl_container.end(); ++it) {
4924 matchers.push_back(
4925 internal::MatcherBindSecond(tuple2_matcher, *it));
4926 }
4927
4928 // Delegate the work to UnorderedElementsAreArray().
4929 return UnorderedElementsAreArray(matchers);
4930}
4931
4932#if GTEST_HAS_STD_INITIALIZER_LIST_
4933
4934// Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4935template <typename Tuple2Matcher, typename T>
4936inline internal::UnorderedElementsAreArrayMatcher<
4937 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4938UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4939 std::initializer_list<T> rhs) {
4940 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4941}
4942
4943#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4944
zhanyong.wanb8243162009-06-04 05:48:20 +00004945// Matches an STL-style container or a native array that contains at
4946// least one element matching the given value or matcher.
4947//
4948// Examples:
4949// ::std::set<int> page_ids;
4950// page_ids.insert(3);
4951// page_ids.insert(1);
4952// EXPECT_THAT(page_ids, Contains(1));
4953// EXPECT_THAT(page_ids, Contains(Gt(2)));
4954// EXPECT_THAT(page_ids, Not(Contains(4)));
4955//
4956// ::std::map<int, size_t> page_lengths;
4957// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00004958// EXPECT_THAT(page_lengths,
4959// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004960//
4961// const char* user_ids[] = { "joe", "mike", "tom" };
4962// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4963template <typename M>
4964inline internal::ContainsMatcher<M> Contains(M matcher) {
4965 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004966}
4967
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004968// IsSupersetOf(iterator_first, iterator_last)
4969// IsSupersetOf(pointer, count)
4970// IsSupersetOf(array)
4971// IsSupersetOf(container)
4972// IsSupersetOf({e1, e2, ..., en})
4973//
4974// IsSupersetOf() verifies that a surjective partial mapping onto a collection
4975// of matchers exists. In other words, a container matches
4976// IsSupersetOf({e1, ..., en}) if and only if there is a permutation
4977// {y1, ..., yn} of some of the container's elements where y1 matches e1,
4978// ..., and yn matches en. Obviously, the size of the container must be >= n
4979// in order to have a match. Examples:
4980//
4981// - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and
4982// 1 matches Ne(0).
4983// - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches
4984// both Eq(1) and Lt(2). The reason is that different matchers must be used
4985// for elements in different slots of the container.
4986// - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches
4987// Eq(1) and (the second) 1 matches Lt(2).
4988// - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)
4989// Gt(1) and 3 matches (the second) Gt(1).
4990//
4991// The matchers can be specified as an array, a pointer and count, a container,
4992// an initializer list, or an STL iterator range. In each of these cases, the
4993// underlying matchers can be either values or matchers.
4994
4995template <typename Iter>
4996inline internal::UnorderedElementsAreArrayMatcher<
4997 typename ::std::iterator_traits<Iter>::value_type>
4998IsSupersetOf(Iter first, Iter last) {
4999 typedef typename ::std::iterator_traits<Iter>::value_type T;
5000 return internal::UnorderedElementsAreArrayMatcher<T>(
5001 internal::UnorderedMatcherRequire::Superset, first, last);
5002}
5003
5004template <typename T>
5005inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
5006 const T* pointer, size_t count) {
5007 return IsSupersetOf(pointer, pointer + count);
5008}
5009
5010template <typename T, size_t N>
5011inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
5012 const T (&array)[N]) {
5013 return IsSupersetOf(array, N);
5014}
5015
5016template <typename Container>
5017inline internal::UnorderedElementsAreArrayMatcher<
5018 typename Container::value_type>
5019IsSupersetOf(const Container& container) {
5020 return IsSupersetOf(container.begin(), container.end());
5021}
5022
5023#if GTEST_HAS_STD_INITIALIZER_LIST_
5024template <typename T>
5025inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
5026 ::std::initializer_list<T> xs) {
5027 return IsSupersetOf(xs.begin(), xs.end());
5028}
5029#endif
5030
5031// IsSubsetOf(iterator_first, iterator_last)
5032// IsSubsetOf(pointer, count)
5033// IsSubsetOf(array)
5034// IsSubsetOf(container)
5035// IsSubsetOf({e1, e2, ..., en})
5036//
5037// IsSubsetOf() verifies that an injective mapping onto a collection of matchers
5038// exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and
5039// only if there is a subset of matchers {m1, ..., mk} which would match the
5040// container using UnorderedElementsAre. Obviously, the size of the container
5041// must be <= n in order to have a match. Examples:
5042//
5043// - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).
5044// - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1
5045// matches Lt(0).
5046// - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both
5047// match Gt(0). The reason is that different matchers must be used for
5048// elements in different slots of the container.
5049//
5050// The matchers can be specified as an array, a pointer and count, a container,
5051// an initializer list, or an STL iterator range. In each of these cases, the
5052// underlying matchers can be either values or matchers.
5053
5054template <typename Iter>
5055inline internal::UnorderedElementsAreArrayMatcher<
5056 typename ::std::iterator_traits<Iter>::value_type>
5057IsSubsetOf(Iter first, Iter last) {
5058 typedef typename ::std::iterator_traits<Iter>::value_type T;
5059 return internal::UnorderedElementsAreArrayMatcher<T>(
5060 internal::UnorderedMatcherRequire::Subset, first, last);
5061}
5062
5063template <typename T>
5064inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
5065 const T* pointer, size_t count) {
5066 return IsSubsetOf(pointer, pointer + count);
5067}
5068
5069template <typename T, size_t N>
5070inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
5071 const T (&array)[N]) {
5072 return IsSubsetOf(array, N);
5073}
5074
5075template <typename Container>
5076inline internal::UnorderedElementsAreArrayMatcher<
5077 typename Container::value_type>
5078IsSubsetOf(const Container& container) {
5079 return IsSubsetOf(container.begin(), container.end());
5080}
5081
5082#if GTEST_HAS_STD_INITIALIZER_LIST_
5083template <typename T>
5084inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
5085 ::std::initializer_list<T> xs) {
5086 return IsSubsetOf(xs.begin(), xs.end());
5087}
5088#endif
5089
zhanyong.wan33605ba2010-04-22 23:37:47 +00005090// Matches an STL-style container or a native array that contains only
5091// elements matching the given value or matcher.
5092//
5093// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
5094// the messages are different.
5095//
5096// Examples:
5097// ::std::set<int> page_ids;
5098// // Each(m) matches an empty container, regardless of what m is.
5099// EXPECT_THAT(page_ids, Each(Eq(1)));
5100// EXPECT_THAT(page_ids, Each(Eq(77)));
5101//
5102// page_ids.insert(3);
5103// EXPECT_THAT(page_ids, Each(Gt(0)));
5104// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
5105// page_ids.insert(1);
5106// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
5107//
5108// ::std::map<int, size_t> page_lengths;
5109// page_lengths[1] = 100;
5110// page_lengths[2] = 200;
5111// page_lengths[3] = 300;
5112// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
5113// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
5114//
5115// const char* user_ids[] = { "joe", "mike", "tom" };
5116// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
5117template <typename M>
5118inline internal::EachMatcher<M> Each(M matcher) {
5119 return internal::EachMatcher<M>(matcher);
5120}
5121
zhanyong.wanb5937da2009-07-16 20:26:41 +00005122// Key(inner_matcher) matches an std::pair whose 'first' field matches
5123// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
5124// std::map that contains at least one element whose key is >= 5.
5125template <typename M>
5126inline internal::KeyMatcher<M> Key(M inner_matcher) {
5127 return internal::KeyMatcher<M>(inner_matcher);
5128}
5129
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00005130// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
5131// matches first_matcher and whose 'second' field matches second_matcher. For
5132// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
5133// to match a std::map<int, string> that contains exactly one element whose key
5134// is >= 5 and whose value equals "foo".
5135template <typename FirstMatcher, typename SecondMatcher>
5136inline internal::PairMatcher<FirstMatcher, SecondMatcher>
5137Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
5138 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
5139 first_matcher, second_matcher);
5140}
5141
shiqiane35fdd92008-12-10 05:08:54 +00005142// Returns a predicate that is satisfied by anything that matches the
5143// given matcher.
5144template <typename M>
5145inline internal::MatcherAsPredicate<M> Matches(M matcher) {
5146 return internal::MatcherAsPredicate<M>(matcher);
5147}
5148
zhanyong.wanb8243162009-06-04 05:48:20 +00005149// Returns true iff the value matches the matcher.
5150template <typename T, typename M>
5151inline bool Value(const T& value, M matcher) {
5152 return testing::Matches(matcher)(value);
5153}
5154
zhanyong.wan34b034c2010-03-05 21:23:23 +00005155// Matches the value against the given matcher and explains the match
5156// result to listener.
5157template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00005158inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00005159 M matcher, const T& value, MatchResultListener* listener) {
5160 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
5161}
5162
Gennadiy Civilb907c262018-03-23 11:42:41 -04005163// Returns a string representation of the given matcher. Useful for description
5164// strings of matchers defined using MATCHER_P* macros that accept matchers as
5165// their arguments. For example:
5166//
5167// MATCHER_P(XAndYThat, matcher,
5168// "X that " + DescribeMatcher<int>(matcher, negation) +
5169// " and Y that " + DescribeMatcher<double>(matcher, negation)) {
5170// return ExplainMatchResult(matcher, arg.x(), result_listener) &&
5171// ExplainMatchResult(matcher, arg.y(), result_listener);
5172// }
5173template <typename T, typename M>
5174std::string DescribeMatcher(const M& matcher, bool negation = false) {
5175 ::std::stringstream ss;
5176 Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher);
5177 if (negation) {
5178 monomorphic_matcher.DescribeNegationTo(&ss);
5179 } else {
5180 monomorphic_matcher.DescribeTo(&ss);
5181 }
5182 return ss.str();
5183}
5184
zhanyong.wan616180e2013-06-18 18:49:51 +00005185#if GTEST_LANG_CXX11
5186// Define variadic matcher versions. They are overloaded in
5187// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
5188template <typename... Args>
Gennadiy Civil0c178882018-07-19 12:42:39 -04005189internal::AllOfMatcher<typename std::decay<const Args&>::type...> AllOf(
5190 const Args&... matchers) {
5191 return internal::AllOfMatcher<typename std::decay<const Args&>::type...>(
5192 matchers...);
zhanyong.wan616180e2013-06-18 18:49:51 +00005193}
5194
5195template <typename... Args>
Gennadiy Civil0c178882018-07-19 12:42:39 -04005196internal::AnyOfMatcher<typename std::decay<const Args&>::type...> AnyOf(
5197 const Args&... matchers) {
5198 return internal::AnyOfMatcher<typename std::decay<const Args&>::type...>(
5199 matchers...);
zhanyong.wan616180e2013-06-18 18:49:51 +00005200}
5201
Gennadiy Civil3f88bb12018-04-16 15:52:47 -04005202template <typename... Args>
Gennadiy Civil4707c0f2018-04-18 10:36:12 -04005203internal::ElementsAreMatcher<tuple<typename std::decay<const Args&>::type...>>
Gennadiy Civildff32af2018-04-17 16:12:04 -04005204ElementsAre(const Args&... matchers) {
5205 return internal::ElementsAreMatcher<
Gennadiy Civil4707c0f2018-04-18 10:36:12 -04005206 tuple<typename std::decay<const Args&>::type...>>(
5207 make_tuple(matchers...));
Gennadiy Civildff32af2018-04-17 16:12:04 -04005208}
5209
5210template <typename... Args>
Gennadiy Civil4707c0f2018-04-18 10:36:12 -04005211internal::UnorderedElementsAreMatcher<
5212 tuple<typename std::decay<const Args&>::type...>>
Gennadiy Civildff32af2018-04-17 16:12:04 -04005213UnorderedElementsAre(const Args&... matchers) {
5214 return internal::UnorderedElementsAreMatcher<
Gennadiy Civil4707c0f2018-04-18 10:36:12 -04005215 tuple<typename std::decay<const Args&>::type...>>(
5216 make_tuple(matchers...));
Gennadiy Civil3f88bb12018-04-16 15:52:47 -04005217}
5218
zhanyong.wan616180e2013-06-18 18:49:51 +00005219#endif // GTEST_LANG_CXX11
5220
zhanyong.wanbf550852009-06-09 06:09:53 +00005221// AllArgs(m) is a synonym of m. This is useful in
5222//
5223// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
5224//
5225// which is easier to read than
5226//
5227// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
5228template <typename InnerMatcher>
5229inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
5230
Gennadiy Civilb907c262018-03-23 11:42:41 -04005231// Returns a matcher that matches the value of an optional<> type variable.
5232// The matcher implementation only uses '!arg' and requires that the optional<>
5233// type has a 'value_type' member type and that '*arg' is of type 'value_type'
5234// and is printable using 'PrintToString'. It is compatible with
5235// std::optional/std::experimental::optional.
5236// Note that to compare an optional type variable against nullopt you should
5237// use Eq(nullopt) and not Optional(Eq(nullopt)). The latter implies that the
5238// optional value contains an optional itself.
5239template <typename ValueMatcher>
5240inline internal::OptionalMatcher<ValueMatcher> Optional(
5241 const ValueMatcher& value_matcher) {
5242 return internal::OptionalMatcher<ValueMatcher>(value_matcher);
5243}
5244
5245// Returns a matcher that matches the value of a absl::any type variable.
5246template <typename T>
5247PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T> > AnyWith(
5248 const Matcher<const T&>& matcher) {
5249 return MakePolymorphicMatcher(
5250 internal::any_cast_matcher::AnyCastMatcher<T>(matcher));
5251}
5252
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05005253// Returns a matcher that matches the value of a variant<> type variable.
5254// The matcher implementation uses ADL to find the holds_alternative and get
5255// functions.
5256// It is compatible with std::variant.
5257template <typename T>
5258PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
5259 const Matcher<const T&>& matcher) {
5260 return MakePolymorphicMatcher(
5261 internal::variant_matcher::VariantMatcher<T>(matcher));
5262}
5263
shiqiane35fdd92008-12-10 05:08:54 +00005264// These macros allow using matchers to check values in Google Test
5265// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
5266// succeed iff the value matches the matcher. If the assertion fails,
5267// the value and the description of the matcher will be printed.
5268#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
5269 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
5270#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
5271 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
5272
5273} // namespace testing
5274
misterga5cc7aa2018-08-30 16:26:26 -04005275GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
mistergdf428ec2018-08-20 14:48:45 -04005276
kosak6702b972015-07-27 23:05:57 +00005277// Include any custom callback matchers added by the local installation.
5278// We must include this header at the end to make sure it can use the
5279// declarations from this file.
5280#include "gmock/internal/custom/gmock-matchers.h"
Gennadiy Civilb907c262018-03-23 11:42:41 -04005281
shiqiane35fdd92008-12-10 05:08:54 +00005282#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_