blob: 62e92338c7fc8da5b179ec212a3b81cd73d9fa2e [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.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements some commonly used argument matchers. More
35// matchers can be defined by the user implementing the
36// MatcherInterface<T> interface if necessary.
37
38#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
39#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
40
zhanyong.wan616180e2013-06-18 18:49:51 +000041#include <math.h>
zhanyong.wan6a896b52009-01-16 01:13:50 +000042#include <algorithm>
zhanyong.wanfb25d532013-07-28 08:24:00 +000043#include <iterator>
zhanyong.wan16cf4732009-05-14 20:55:30 +000044#include <limits>
shiqiane35fdd92008-12-10 05:08:54 +000045#include <ostream> // NOLINT
46#include <sstream>
47#include <string>
zhanyong.wanab5b77c2010-05-17 19:32:48 +000048#include <utility>
shiqiane35fdd92008-12-10 05:08:54 +000049#include <vector>
Gennadiy Civilfbb48a72018-01-26 11:57:58 -050050#include "gtest/gtest.h"
zhanyong.wan53e08c42010-09-14 05:38:21 +000051#include "gmock/internal/gmock-internal-utils.h"
52#include "gmock/internal/gmock-port.h"
shiqiane35fdd92008-12-10 05:08:54 +000053
kosak18489fa2013-12-04 23:49:07 +000054#if GTEST_HAS_STD_INITIALIZER_LIST_
55# include <initializer_list> // NOLINT -- must be after gtest.h
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +000056#endif
57
shiqiane35fdd92008-12-10 05:08:54 +000058namespace testing {
59
60// To implement a matcher Foo for type T, define:
61// 1. a class FooMatcherImpl that implements the
62// MatcherInterface<T> interface, and
63// 2. a factory function that creates a Matcher<T> object from a
64// FooMatcherImpl*.
65//
66// The two-level delegation design makes it possible to allow a user
67// to write "v" instead of "Eq(v)" where a Matcher is expected, which
68// is impossible if we pass matchers by pointers. It also eases
69// ownership management as Matcher objects can now be copied like
70// plain values.
71
zhanyong.wan82113312010-01-08 21:55:40 +000072// MatchResultListener is an abstract class. Its << operator can be
73// used by a matcher to explain why a value matches or doesn't match.
74//
75// TODO(wan@google.com): add method
76// bool InterestedInWhy(bool result) const;
77// to indicate whether the listener is interested in why the match
78// result is 'result'.
79class MatchResultListener {
80 public:
81 // Creates a listener object with the given underlying ostream. The
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +000082 // listener does not own the ostream, and does not dereference it
83 // in the constructor or destructor.
zhanyong.wan82113312010-01-08 21:55:40 +000084 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
85 virtual ~MatchResultListener() = 0; // Makes this class abstract.
86
87 // Streams x to the underlying ostream; does nothing if the ostream
88 // is NULL.
89 template <typename T>
90 MatchResultListener& operator<<(const T& x) {
91 if (stream_ != NULL)
92 *stream_ << x;
93 return *this;
94 }
95
96 // Returns the underlying ostream.
97 ::std::ostream* stream() { return stream_; }
98
zhanyong.wana862f1d2010-03-15 21:23:04 +000099 // Returns true iff the listener is interested in an explanation of
100 // the match result. A matcher's MatchAndExplain() method can use
101 // this information to avoid generating the explanation when no one
102 // intends to hear it.
103 bool IsInterested() const { return stream_ != NULL; }
104
zhanyong.wan82113312010-01-08 21:55:40 +0000105 private:
106 ::std::ostream* const stream_;
107
108 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
109};
110
111inline MatchResultListener::~MatchResultListener() {
112}
113
zhanyong.wanfb25d532013-07-28 08:24:00 +0000114// An instance of a subclass of this knows how to describe itself as a
115// matcher.
116class MatcherDescriberInterface {
117 public:
118 virtual ~MatcherDescriberInterface() {}
119
120 // Describes this matcher to an ostream. The function should print
121 // a verb phrase that describes the property a value matching this
122 // matcher should have. The subject of the verb phrase is the value
123 // being matched. For example, the DescribeTo() method of the Gt(7)
124 // matcher prints "is greater than 7".
125 virtual void DescribeTo(::std::ostream* os) const = 0;
126
127 // Describes the negation of this matcher to an ostream. For
128 // example, if the description of this matcher is "is greater than
129 // 7", the negated description could be "is not greater than 7".
130 // You are not required to override this when implementing
131 // MatcherInterface, but it is highly advised so that your matcher
132 // can produce good error messages.
133 virtual void DescribeNegationTo(::std::ostream* os) const {
134 *os << "not (";
135 DescribeTo(os);
136 *os << ")";
137 }
138};
139
shiqiane35fdd92008-12-10 05:08:54 +0000140// The implementation of a matcher.
141template <typename T>
zhanyong.wanfb25d532013-07-28 08:24:00 +0000142class MatcherInterface : public MatcherDescriberInterface {
shiqiane35fdd92008-12-10 05:08:54 +0000143 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000144 // Returns true iff the matcher matches x; also explains the match
zhanyong.wan83f6b082013-03-01 01:47:35 +0000145 // result to 'listener' if necessary (see the next paragraph), in
146 // the form of a non-restrictive relative clause ("which ...",
147 // "whose ...", etc) that describes x. For example, the
148 // MatchAndExplain() method of the Pointee(...) matcher should
149 // generate an explanation like "which points to ...".
150 //
151 // Implementations of MatchAndExplain() should add an explanation of
152 // the match result *if and only if* they can provide additional
153 // information that's not already present (or not obvious) in the
154 // print-out of x and the matcher's description. Whether the match
155 // succeeds is not a factor in deciding whether an explanation is
156 // needed, as sometimes the caller needs to print a failure message
157 // when the match succeeds (e.g. when the matcher is used inside
158 // Not()).
159 //
160 // For example, a "has at least 10 elements" matcher should explain
161 // what the actual element count is, regardless of the match result,
162 // as it is useful information to the reader; on the other hand, an
163 // "is empty" matcher probably only needs to explain what the actual
164 // size is when the match fails, as it's redundant to say that the
165 // size is 0 when the value is already known to be empty.
zhanyong.wan82113312010-01-08 21:55:40 +0000166 //
zhanyong.wandb22c222010-01-28 21:52:29 +0000167 // You should override this method when defining a new matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000168 //
169 // It's the responsibility of the caller (Google Mock) to guarantee
170 // that 'listener' is not NULL. This helps to simplify a matcher's
171 // implementation when it doesn't care about the performance, as it
172 // can talk to 'listener' without checking its validity first.
173 // However, in order to implement dummy listeners efficiently,
174 // listener->stream() may be NULL.
zhanyong.wandb22c222010-01-28 21:52:29 +0000175 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
shiqiane35fdd92008-12-10 05:08:54 +0000176
zhanyong.wanfb25d532013-07-28 08:24:00 +0000177 // Inherits these methods from MatcherDescriberInterface:
178 // virtual void DescribeTo(::std::ostream* os) const = 0;
179 // virtual void DescribeNegationTo(::std::ostream* os) const;
shiqiane35fdd92008-12-10 05:08:54 +0000180};
181
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400182namespace internal {
183
184// Converts a MatcherInterface<T> to a MatcherInterface<const T&>.
185template <typename T>
186class MatcherInterfaceAdapter : public MatcherInterface<const T&> {
187 public:
188 explicit MatcherInterfaceAdapter(const MatcherInterface<T>* impl)
189 : impl_(impl) {}
190 virtual ~MatcherInterfaceAdapter() { delete impl_; }
191
192 virtual void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
193
194 virtual void DescribeNegationTo(::std::ostream* os) const {
195 impl_->DescribeNegationTo(os);
196 }
197
198 virtual bool MatchAndExplain(const T& x,
199 MatchResultListener* listener) const {
200 return impl_->MatchAndExplain(x, listener);
201 }
202
203 private:
204 const MatcherInterface<T>* const impl_;
205
206 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatcherInterfaceAdapter);
207};
208
209} // namespace internal
210
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000211// A match result listener that stores the explanation in a string.
212class StringMatchResultListener : public MatchResultListener {
213 public:
214 StringMatchResultListener() : MatchResultListener(&ss_) {}
215
216 // Returns the explanation accumulated so far.
Nico Weber09fd5b32017-05-15 17:07:03 -0400217 std::string str() const { return ss_.str(); }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000218
219 // Clears the explanation accumulated so far.
220 void Clear() { ss_.str(""); }
221
222 private:
223 ::std::stringstream ss_;
224
225 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
226};
227
shiqiane35fdd92008-12-10 05:08:54 +0000228namespace internal {
229
kosak506340a2014-11-17 01:47:54 +0000230struct AnyEq {
231 template <typename A, typename B>
232 bool operator()(const A& a, const B& b) const { return a == b; }
233};
234struct AnyNe {
235 template <typename A, typename B>
236 bool operator()(const A& a, const B& b) const { return a != b; }
237};
238struct AnyLt {
239 template <typename A, typename B>
240 bool operator()(const A& a, const B& b) const { return a < b; }
241};
242struct AnyGt {
243 template <typename A, typename B>
244 bool operator()(const A& a, const B& b) const { return a > b; }
245};
246struct AnyLe {
247 template <typename A, typename B>
248 bool operator()(const A& a, const B& b) const { return a <= b; }
249};
250struct AnyGe {
251 template <typename A, typename B>
252 bool operator()(const A& a, const B& b) const { return a >= b; }
253};
254
zhanyong.wan82113312010-01-08 21:55:40 +0000255// A match result listener that ignores the explanation.
256class DummyMatchResultListener : public MatchResultListener {
257 public:
258 DummyMatchResultListener() : MatchResultListener(NULL) {}
259
260 private:
261 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
262};
263
264// A match result listener that forwards the explanation to a given
265// ostream. The difference between this and MatchResultListener is
266// that the former is concrete.
267class StreamMatchResultListener : public MatchResultListener {
268 public:
269 explicit StreamMatchResultListener(::std::ostream* os)
270 : MatchResultListener(os) {}
271
272 private:
273 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
274};
275
shiqiane35fdd92008-12-10 05:08:54 +0000276// An internal class for implementing Matcher<T>, which will derive
277// from it. We put functionalities common to all Matcher<T>
278// specializations here to avoid code duplication.
279template <typename T>
280class MatcherBase {
281 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000282 // Returns true iff the matcher matches x; also explains the match
283 // result to 'listener'.
Gennadiy Civil6aae2062018-03-26 10:36:26 -0400284 bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
285 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000286 return impl_->MatchAndExplain(x, listener);
287 }
288
shiqiane35fdd92008-12-10 05:08:54 +0000289 // Returns true iff this matcher matches x.
Gennadiy Civile55089e2018-04-04 14:05:00 -0400290 bool Matches(GTEST_REFERENCE_TO_CONST_(T) x) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000291 DummyMatchResultListener dummy;
292 return MatchAndExplain(x, &dummy);
293 }
shiqiane35fdd92008-12-10 05:08:54 +0000294
295 // Describes this matcher to an ostream.
296 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
297
298 // Describes the negation of this matcher to an ostream.
299 void DescribeNegationTo(::std::ostream* os) const {
300 impl_->DescribeNegationTo(os);
301 }
302
303 // Explains why x matches, or doesn't match, the matcher.
Gennadiy Civile55089e2018-04-04 14:05:00 -0400304 void ExplainMatchResultTo(GTEST_REFERENCE_TO_CONST_(T) x,
305 ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000306 StreamMatchResultListener listener(os);
307 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000308 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000309
zhanyong.wanfb25d532013-07-28 08:24:00 +0000310 // Returns the describer for this matcher object; retains ownership
311 // of the describer, which is only guaranteed to be alive when
312 // this matcher object is alive.
313 const MatcherDescriberInterface* GetDescriber() const {
314 return impl_.get();
315 }
316
shiqiane35fdd92008-12-10 05:08:54 +0000317 protected:
318 MatcherBase() {}
319
320 // Constructs a matcher from its implementation.
Gennadiy Civile55089e2018-04-04 14:05:00 -0400321 explicit MatcherBase(
322 const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)>* impl)
shiqiane35fdd92008-12-10 05:08:54 +0000323 : impl_(impl) {}
324
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400325 template <typename U>
326 explicit MatcherBase(
327 const MatcherInterface<U>* impl,
328 typename internal::EnableIf<
329 !internal::IsSame<U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* =
330 NULL)
331 : impl_(new internal::MatcherInterfaceAdapter<U>(impl)) {}
332
shiqiane35fdd92008-12-10 05:08:54 +0000333 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000334
shiqiane35fdd92008-12-10 05:08:54 +0000335 private:
336 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
337 // interfaces. The former dynamically allocates a chunk of memory
338 // to hold the reference count, while the latter tracks all
339 // references using a circular linked list without allocating
340 // memory. It has been observed that linked_ptr performs better in
341 // typical scenarios. However, shared_ptr can out-perform
342 // linked_ptr when there are many more uses of the copy constructor
343 // than the default constructor.
344 //
345 // If performance becomes a problem, we should see if using
346 // shared_ptr helps.
Gennadiy Civile55089e2018-04-04 14:05:00 -0400347 ::testing::internal::linked_ptr<
348 const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> >
349 impl_;
shiqiane35fdd92008-12-10 05:08:54 +0000350};
351
shiqiane35fdd92008-12-10 05:08:54 +0000352} // namespace internal
353
354// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
355// object that can check whether a value of type T matches. The
356// implementation of Matcher<T> is just a linked_ptr to const
357// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
358// from Matcher!
359template <typename T>
360class Matcher : public internal::MatcherBase<T> {
361 public:
vladlosev88032d82010-11-17 23:29:21 +0000362 // Constructs a null matcher. Needed for storing Matcher objects in STL
363 // containers. A default-constructed matcher is not yet initialized. You
364 // cannot use it until a valid value has been assigned to it.
kosakd86a7232015-07-13 21:19:43 +0000365 explicit Matcher() {} // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000366
367 // Constructs a matcher from its implementation.
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400368 explicit Matcher(const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)>* impl)
369 : internal::MatcherBase<T>(impl) {}
370
371 template <typename U>
372 explicit Matcher(const MatcherInterface<U>* impl,
373 typename internal::EnableIf<!internal::IsSame<
374 U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* = NULL)
shiqiane35fdd92008-12-10 05:08:54 +0000375 : internal::MatcherBase<T>(impl) {}
376
zhanyong.wan18490652009-05-11 18:54:08 +0000377 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000378 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
379 Matcher(T value); // NOLINT
380};
381
382// The following two specializations allow the user to write str
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400383// instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
shiqiane35fdd92008-12-10 05:08:54 +0000384// matcher is expected.
385template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400386class GTEST_API_ Matcher<const std::string&>
387 : public internal::MatcherBase<const std::string&> {
shiqiane35fdd92008-12-10 05:08:54 +0000388 public:
389 Matcher() {}
390
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400391 explicit Matcher(const MatcherInterface<const std::string&>* impl)
392 : internal::MatcherBase<const std::string&>(impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000393
394 // Allows the user to write str instead of Eq(str) sometimes, where
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400395 // str is a std::string object.
396 Matcher(const std::string& s); // NOLINT
397
398#if GTEST_HAS_GLOBAL_STRING
399 // Allows the user to write str instead of Eq(str) sometimes, where
400 // str is a ::string object.
401 Matcher(const ::string& s); // NOLINT
402#endif // GTEST_HAS_GLOBAL_STRING
shiqiane35fdd92008-12-10 05:08:54 +0000403
404 // Allows the user to write "foo" instead of Eq("foo") sometimes.
405 Matcher(const char* s); // NOLINT
406};
407
408template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400409class GTEST_API_ Matcher<std::string>
410 : public internal::MatcherBase<std::string> {
shiqiane35fdd92008-12-10 05:08:54 +0000411 public:
412 Matcher() {}
413
Gennadiy Civile55089e2018-04-04 14:05:00 -0400414 explicit Matcher(const MatcherInterface<const std::string&>* impl)
415 : internal::MatcherBase<std::string>(impl) {}
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400416 explicit Matcher(const MatcherInterface<std::string>* impl)
417 : internal::MatcherBase<std::string>(impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000418
419 // Allows the user to write str instead of Eq(str) sometimes, where
420 // str is a string object.
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400421 Matcher(const std::string& s); // NOLINT
422
423#if GTEST_HAS_GLOBAL_STRING
424 // Allows the user to write str instead of Eq(str) sometimes, where
425 // str is a ::string object.
426 Matcher(const ::string& s); // NOLINT
427#endif // GTEST_HAS_GLOBAL_STRING
shiqiane35fdd92008-12-10 05:08:54 +0000428
429 // Allows the user to write "foo" instead of Eq("foo") sometimes.
430 Matcher(const char* s); // NOLINT
431};
432
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400433#if GTEST_HAS_GLOBAL_STRING
zhanyong.wan1f122a02013-03-25 16:27:03 +0000434// The following two specializations allow the user to write str
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400435// instead of Eq(str) and "foo" instead of Eq("foo") when a ::string
zhanyong.wan1f122a02013-03-25 16:27:03 +0000436// matcher is expected.
437template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400438class GTEST_API_ Matcher<const ::string&>
439 : public internal::MatcherBase<const ::string&> {
zhanyong.wan1f122a02013-03-25 16:27:03 +0000440 public:
441 Matcher() {}
442
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400443 explicit Matcher(const MatcherInterface<const ::string&>* impl)
444 : internal::MatcherBase<const ::string&>(impl) {}
zhanyong.wan1f122a02013-03-25 16:27:03 +0000445
446 // Allows the user to write str instead of Eq(str) sometimes, where
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400447 // str is a std::string object.
448 Matcher(const std::string& s); // NOLINT
449
450 // Allows the user to write str instead of Eq(str) sometimes, where
451 // str is a ::string object.
452 Matcher(const ::string& s); // NOLINT
zhanyong.wan1f122a02013-03-25 16:27:03 +0000453
454 // Allows the user to write "foo" instead of Eq("foo") sometimes.
455 Matcher(const char* s); // NOLINT
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400456};
zhanyong.wan1f122a02013-03-25 16:27:03 +0000457
zhanyong.wan1f122a02013-03-25 16:27:03 +0000458template <>
Gennadiy Civile55089e2018-04-04 14:05:00 -0400459class GTEST_API_ Matcher< ::string>
460 : public internal::MatcherBase< ::string> {
zhanyong.wan1f122a02013-03-25 16:27:03 +0000461 public:
462 Matcher() {}
463
Gennadiy Civile55089e2018-04-04 14:05:00 -0400464 explicit Matcher(const MatcherInterface<const ::string&>* impl)
465 : internal::MatcherBase< ::string>(impl) {}
466 explicit Matcher(const MatcherInterface< ::string>* impl)
467 : internal::MatcherBase< ::string>(impl) {}
zhanyong.wan1f122a02013-03-25 16:27:03 +0000468
469 // Allows the user to write str instead of Eq(str) sometimes, where
Gennadiy Civile55089e2018-04-04 14:05:00 -0400470 // str is a std::string object.
471 Matcher(const std::string& s); // NOLINT
472
473 // Allows the user to write str instead of Eq(str) sometimes, where
474 // str is a ::string object.
475 Matcher(const ::string& s); // NOLINT
476
477 // Allows the user to write "foo" instead of Eq("foo") sometimes.
478 Matcher(const char* s); // NOLINT
479};
480#endif // GTEST_HAS_GLOBAL_STRING
481
482#if GTEST_HAS_ABSL
483// The following two specializations allow the user to write str
484// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
485// matcher is expected.
486template <>
487class GTEST_API_ Matcher<const absl::string_view&>
488 : public internal::MatcherBase<const absl::string_view&> {
489 public:
490 Matcher() {}
491
492 explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
493 : internal::MatcherBase<const absl::string_view&>(impl) {}
494
495 // Allows the user to write str instead of Eq(str) sometimes, where
496 // str is a std::string object.
497 Matcher(const std::string& s); // NOLINT
498
499#if GTEST_HAS_GLOBAL_STRING
500 // Allows the user to write str instead of Eq(str) sometimes, where
501 // str is a ::string object.
502 Matcher(const ::string& s); // NOLINT
503#endif // GTEST_HAS_GLOBAL_STRING
zhanyong.wan1f122a02013-03-25 16:27:03 +0000504
505 // Allows the user to write "foo" instead of Eq("foo") sometimes.
506 Matcher(const char* s); // NOLINT
507
Gennadiy Civile55089e2018-04-04 14:05:00 -0400508 // Allows the user to pass absl::string_views directly.
509 Matcher(absl::string_view s); // NOLINT
zhanyong.wan1f122a02013-03-25 16:27:03 +0000510};
Gennadiy Civile55089e2018-04-04 14:05:00 -0400511
512template <>
513class GTEST_API_ Matcher<absl::string_view>
514 : public internal::MatcherBase<absl::string_view> {
515 public:
516 Matcher() {}
517
518 explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
519 : internal::MatcherBase<absl::string_view>(impl) {}
520 explicit Matcher(const MatcherInterface<absl::string_view>* impl)
521 : internal::MatcherBase<absl::string_view>(impl) {}
522
523 // Allows the user to write str instead of Eq(str) sometimes, where
524 // str is a std::string object.
525 Matcher(const std::string& s); // NOLINT
526
527#if GTEST_HAS_GLOBAL_STRING
528 // Allows the user to write str instead of Eq(str) sometimes, where
529 // str is a ::string object.
530 Matcher(const ::string& s); // NOLINT
531#endif // GTEST_HAS_GLOBAL_STRING
532
533 // Allows the user to write "foo" instead of Eq("foo") sometimes.
534 Matcher(const char* s); // NOLINT
535
536 // Allows the user to pass absl::string_views directly.
537 Matcher(absl::string_view s); // NOLINT
538};
539#endif // GTEST_HAS_ABSL
540
541// Prints a matcher in a human-readable format.
542template <typename T>
543std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
544 matcher.DescribeTo(&os);
545 return os;
546}
zhanyong.wan1f122a02013-03-25 16:27:03 +0000547
shiqiane35fdd92008-12-10 05:08:54 +0000548// The PolymorphicMatcher class template makes it easy to implement a
549// polymorphic matcher (i.e. a matcher that can match values of more
550// than one type, e.g. Eq(n) and NotNull()).
551//
zhanyong.wandb22c222010-01-28 21:52:29 +0000552// To define a polymorphic matcher, a user should provide an Impl
553// class that has a DescribeTo() method and a DescribeNegationTo()
554// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000555//
zhanyong.wandb22c222010-01-28 21:52:29 +0000556// bool MatchAndExplain(const Value& value,
557// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000558//
559// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000560template <class Impl>
561class PolymorphicMatcher {
562 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000563 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000564
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000565 // Returns a mutable reference to the underlying matcher
566 // implementation object.
567 Impl& mutable_impl() { return impl_; }
568
569 // Returns an immutable reference to the underlying matcher
570 // implementation object.
571 const Impl& impl() const { return impl_; }
572
shiqiane35fdd92008-12-10 05:08:54 +0000573 template <typename T>
574 operator Matcher<T>() const {
Gennadiy Civile55089e2018-04-04 14:05:00 -0400575 return Matcher<T>(new MonomorphicImpl<GTEST_REFERENCE_TO_CONST_(T)>(impl_));
shiqiane35fdd92008-12-10 05:08:54 +0000576 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000577
shiqiane35fdd92008-12-10 05:08:54 +0000578 private:
579 template <typename T>
580 class MonomorphicImpl : public MatcherInterface<T> {
581 public:
582 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
583
shiqiane35fdd92008-12-10 05:08:54 +0000584 virtual void DescribeTo(::std::ostream* os) const {
585 impl_.DescribeTo(os);
586 }
587
588 virtual void DescribeNegationTo(::std::ostream* os) const {
589 impl_.DescribeNegationTo(os);
590 }
591
zhanyong.wan82113312010-01-08 21:55:40 +0000592 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000593 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000594 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000595
shiqiane35fdd92008-12-10 05:08:54 +0000596 private:
597 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000598
599 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000600 };
601
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000602 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000603
604 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000605};
606
607// Creates a matcher from its implementation. This is easier to use
608// than the Matcher<T> constructor as it doesn't require you to
609// explicitly write the template argument, e.g.
610//
611// MakeMatcher(foo);
612// vs
613// Matcher<const string&>(foo);
614template <typename T>
615inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
616 return Matcher<T>(impl);
zhanyong.wan2eab17b2013-03-08 17:53:24 +0000617}
shiqiane35fdd92008-12-10 05:08:54 +0000618
619// Creates a polymorphic matcher from its implementation. This is
620// easier to use than the PolymorphicMatcher<Impl> constructor as it
621// doesn't require you to explicitly write the template argument, e.g.
622//
623// MakePolymorphicMatcher(foo);
624// vs
625// PolymorphicMatcher<TypeOfFoo>(foo);
626template <class Impl>
627inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
628 return PolymorphicMatcher<Impl>(impl);
629}
630
jgm79a367e2012-04-10 16:02:11 +0000631// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
632// and MUST NOT BE USED IN USER CODE!!!
633namespace internal {
634
635// The MatcherCastImpl class template is a helper for implementing
636// MatcherCast(). We need this helper in order to partially
637// specialize the implementation of MatcherCast() (C++ allows
638// class/struct templates to be partially specialized, but not
639// function templates.).
640
641// This general version is used when MatcherCast()'s argument is a
642// polymorphic matcher (i.e. something that can be converted to a
643// Matcher but is not one yet; for example, Eq(value)) or a value (for
644// example, "hello").
645template <typename T, typename M>
646class MatcherCastImpl {
647 public:
kosak5f2a6ca2013-12-03 01:43:07 +0000648 static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
Gennadiy Civil2bd17502018-02-27 13:51:09 -0500649 // M can be a polymorphic matcher, in which case we want to use
jgm79a367e2012-04-10 16:02:11 +0000650 // its conversion operator to create Matcher<T>. Or it can be a value
651 // that should be passed to the Matcher<T>'s constructor.
652 //
653 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
654 // polymorphic matcher because it'll be ambiguous if T has an implicit
655 // constructor from M (this usually happens when T has an implicit
656 // constructor from any type).
657 //
658 // It won't work to unconditionally implict_cast
659 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
660 // a user-defined conversion from M to T if one exists (assuming M is
661 // a value).
662 return CastImpl(
663 polymorphic_matcher_or_value,
664 BooleanConstant<
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400665 internal::ImplicitlyConvertible<M, Matcher<T> >::value>(),
666 BooleanConstant<
667 internal::ImplicitlyConvertible<M, T>::value>());
jgm79a367e2012-04-10 16:02:11 +0000668 }
669
670 private:
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400671 template <bool Ignore>
kosak5f2a6ca2013-12-03 01:43:07 +0000672 static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400673 BooleanConstant<true> /* convertible_to_matcher */,
674 BooleanConstant<Ignore>) {
jgm79a367e2012-04-10 16:02:11 +0000675 // M is implicitly convertible to Matcher<T>, which means that either
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400676 // M is a polymorphic matcher or Matcher<T> has an implicit constructor
jgm79a367e2012-04-10 16:02:11 +0000677 // from M. In both cases using the implicit conversion will produce a
678 // matcher.
679 //
680 // Even if T has an implicit constructor from M, it won't be called because
681 // creating Matcher<T> would require a chain of two user-defined conversions
682 // (first to create T from M and then to create Matcher<T> from T).
683 return polymorphic_matcher_or_value;
684 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400685
686 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
687 // matcher. It's a value of a type implicitly convertible to T. Use direct
688 // initialization to create a matcher.
689 static Matcher<T> CastImpl(
690 const M& value, BooleanConstant<false> /* convertible_to_matcher */,
691 BooleanConstant<true> /* convertible_to_T */) {
692 return Matcher<T>(ImplicitCast_<T>(value));
693 }
694
695 // M can't be implicitly converted to either Matcher<T> or T. Attempt to use
696 // polymorphic matcher Eq(value) in this case.
697 //
698 // Note that we first attempt to perform an implicit cast on the value and
699 // only fall back to the polymorphic Eq() matcher afterwards because the
700 // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end
701 // which might be undefined even when Rhs is implicitly convertible to Lhs
702 // (e.g. std::pair<const int, int> vs. std::pair<int, int>).
703 //
704 // We don't define this method inline as we need the declaration of Eq().
705 static Matcher<T> CastImpl(
706 const M& value, BooleanConstant<false> /* convertible_to_matcher */,
707 BooleanConstant<false> /* convertible_to_T */);
jgm79a367e2012-04-10 16:02:11 +0000708};
709
710// This more specialized version is used when MatcherCast()'s argument
711// is already a Matcher. This only compiles when type T can be
712// statically converted to type U.
713template <typename T, typename U>
714class MatcherCastImpl<T, Matcher<U> > {
715 public:
716 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
717 return Matcher<T>(new Impl(source_matcher));
718 }
719
720 private:
721 class Impl : public MatcherInterface<T> {
722 public:
723 explicit Impl(const Matcher<U>& source_matcher)
724 : source_matcher_(source_matcher) {}
725
726 // We delegate the matching logic to the source matcher.
727 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
Gennadiy Civilb907c262018-03-23 11:42:41 -0400728#if GTEST_LANG_CXX11
729 using FromType = typename std::remove_cv<typename std::remove_pointer<
730 typename std::remove_reference<T>::type>::type>::type;
731 using ToType = typename std::remove_cv<typename std::remove_pointer<
732 typename std::remove_reference<U>::type>::type>::type;
733 // Do not allow implicitly converting base*/& to derived*/&.
734 static_assert(
735 // Do not trigger if only one of them is a pointer. That implies a
736 // regular conversion and not a down_cast.
737 (std::is_pointer<typename std::remove_reference<T>::type>::value !=
738 std::is_pointer<typename std::remove_reference<U>::type>::value) ||
739 std::is_same<FromType, ToType>::value ||
740 !std::is_base_of<FromType, ToType>::value,
741 "Can't implicitly convert from <base> to <derived>");
742#endif // GTEST_LANG_CXX11
743
jgm79a367e2012-04-10 16:02:11 +0000744 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
745 }
746
747 virtual void DescribeTo(::std::ostream* os) const {
748 source_matcher_.DescribeTo(os);
749 }
750
751 virtual void DescribeNegationTo(::std::ostream* os) const {
752 source_matcher_.DescribeNegationTo(os);
753 }
754
755 private:
756 const Matcher<U> source_matcher_;
757
758 GTEST_DISALLOW_ASSIGN_(Impl);
759 };
760};
761
762// This even more specialized version is used for efficiently casting
763// a matcher to its own type.
764template <typename T>
765class MatcherCastImpl<T, Matcher<T> > {
766 public:
767 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
768};
769
770} // namespace internal
771
shiqiane35fdd92008-12-10 05:08:54 +0000772// In order to be safe and clear, casting between different matcher
773// types is done explicitly via MatcherCast<T>(m), which takes a
774// matcher m and returns a Matcher<T>. It compiles only when T can be
775// statically converted to the argument type of m.
776template <typename T, typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000777inline Matcher<T> MatcherCast(const M& matcher) {
jgm79a367e2012-04-10 16:02:11 +0000778 return internal::MatcherCastImpl<T, M>::Cast(matcher);
779}
shiqiane35fdd92008-12-10 05:08:54 +0000780
zhanyong.wan18490652009-05-11 18:54:08 +0000781// Implements SafeMatcherCast().
782//
zhanyong.wan95b12332009-09-25 18:55:50 +0000783// We use an intermediate class to do the actual safe casting as Nokia's
784// Symbian compiler cannot decide between
785// template <T, M> ... (M) and
786// template <T, U> ... (const Matcher<U>&)
787// for function templates but can for member function templates.
788template <typename T>
789class SafeMatcherCastImpl {
790 public:
jgm79a367e2012-04-10 16:02:11 +0000791 // This overload handles polymorphic matchers and values only since
792 // monomorphic matchers are handled by the next one.
zhanyong.wan95b12332009-09-25 18:55:50 +0000793 template <typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000794 static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
jgm79a367e2012-04-10 16:02:11 +0000795 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
zhanyong.wan95b12332009-09-25 18:55:50 +0000796 }
zhanyong.wan18490652009-05-11 18:54:08 +0000797
zhanyong.wan95b12332009-09-25 18:55:50 +0000798 // This overload handles monomorphic matchers.
799 //
800 // In general, if type T can be implicitly converted to type U, we can
801 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
802 // contravariant): just keep a copy of the original Matcher<U>, convert the
803 // argument from type T to U, and then pass it to the underlying Matcher<U>.
804 // The only exception is when U is a reference and T is not, as the
805 // underlying Matcher<U> may be interested in the argument's address, which
806 // is not preserved in the conversion from T to U.
807 template <typename U>
808 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
809 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000810 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000811 T_must_be_implicitly_convertible_to_U);
812 // Enforce that we are not converting a non-reference type T to a reference
813 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000814 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000815 internal::is_reference<T>::value || !internal::is_reference<U>::value,
Hector Dearman24054ff2017-06-19 18:27:33 +0100816 cannot_convert_non_reference_arg_to_reference);
zhanyong.wan95b12332009-09-25 18:55:50 +0000817 // In case both T and U are arithmetic types, enforce that the
818 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000819 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
820 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000821 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
822 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000823 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000824 kTIsOther || kUIsOther ||
825 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
826 conversion_of_arithmetic_types_must_be_lossless);
827 return MatcherCast<T>(matcher);
828 }
829};
830
831template <typename T, typename M>
832inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
833 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000834}
835
shiqiane35fdd92008-12-10 05:08:54 +0000836// A<T>() returns a matcher that matches any value of type T.
837template <typename T>
838Matcher<T> A();
839
840// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
841// and MUST NOT BE USED IN USER CODE!!!
842namespace internal {
843
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000844// If the explanation is not empty, prints it to the ostream.
Nico Weber09fd5b32017-05-15 17:07:03 -0400845inline void PrintIfNotEmpty(const std::string& explanation,
zhanyong.wanfb25d532013-07-28 08:24:00 +0000846 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000847 if (explanation != "" && os != NULL) {
848 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000849 }
850}
851
zhanyong.wan736baa82010-09-27 17:44:16 +0000852// Returns true if the given type name is easy to read by a human.
853// This is used to decide whether printing the type of a value might
854// be helpful.
Nico Weber09fd5b32017-05-15 17:07:03 -0400855inline bool IsReadableTypeName(const std::string& type_name) {
zhanyong.wan736baa82010-09-27 17:44:16 +0000856 // We consider a type name readable if it's short or doesn't contain
857 // a template or function type.
858 return (type_name.length() <= 20 ||
Nico Weber09fd5b32017-05-15 17:07:03 -0400859 type_name.find_first_of("<(") == std::string::npos);
zhanyong.wan736baa82010-09-27 17:44:16 +0000860}
861
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000862// Matches the value against the given matcher, prints the value and explains
863// the match result to the listener. Returns the match result.
864// 'listener' must not be NULL.
865// Value cannot be passed by const reference, because some matchers take a
866// non-const argument.
867template <typename Value, typename T>
868bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
869 MatchResultListener* listener) {
870 if (!listener->IsInterested()) {
871 // If the listener is not interested, we do not need to construct the
872 // inner explanation.
873 return matcher.Matches(value);
874 }
875
876 StringMatchResultListener inner_listener;
877 const bool match = matcher.MatchAndExplain(value, &inner_listener);
878
879 UniversalPrint(value, listener->stream());
zhanyong.wan736baa82010-09-27 17:44:16 +0000880#if GTEST_HAS_RTTI
Nico Weber09fd5b32017-05-15 17:07:03 -0400881 const std::string& type_name = GetTypeName<Value>();
zhanyong.wan736baa82010-09-27 17:44:16 +0000882 if (IsReadableTypeName(type_name))
883 *listener->stream() << " (of type " << type_name << ")";
884#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000885 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000886
887 return match;
888}
889
shiqiane35fdd92008-12-10 05:08:54 +0000890// An internal helper class for doing compile-time loop on a tuple's
891// fields.
892template <size_t N>
893class TuplePrefix {
894 public:
895 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
896 // iff the first N fields of matcher_tuple matches the first N
897 // fields of value_tuple, respectively.
898 template <typename MatcherTuple, typename ValueTuple>
899 static bool Matches(const MatcherTuple& matcher_tuple,
900 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000901 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
902 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
903 }
904
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000905 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000906 // describes failures in matching the first N fields of matchers
907 // against the first N fields of values. If there is no failure,
908 // nothing will be streamed to os.
909 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000910 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
911 const ValueTuple& values,
912 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000913 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000914 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000915
916 // Then describes the failure (if any) in the (N - 1)-th (0-based)
917 // field.
918 typename tuple_element<N - 1, MatcherTuple>::type matcher =
919 get<N - 1>(matchers);
920 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
Gennadiy Civile55089e2018-04-04 14:05:00 -0400921 GTEST_REFERENCE_TO_CONST_(Value) value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000922 StringMatchResultListener listener;
923 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000924 // TODO(wan): include in the message the name of the parameter
925 // as used in MOCK_METHOD*() when possible.
926 *os << " Expected arg #" << N - 1 << ": ";
927 get<N - 1>(matchers).DescribeTo(os);
928 *os << "\n Actual: ";
929 // We remove the reference in type Value to prevent the
930 // universal printer from printing the address of value, which
931 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000932 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000933 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000934 internal::UniversalPrint(value, os);
935 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000936 *os << "\n";
937 }
938 }
939};
940
941// The base case.
942template <>
943class TuplePrefix<0> {
944 public:
945 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000946 static bool Matches(const MatcherTuple& /* matcher_tuple */,
947 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000948 return true;
949 }
950
951 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000952 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
953 const ValueTuple& /* values */,
954 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000955};
956
957// TupleMatches(matcher_tuple, value_tuple) returns true iff all
958// matchers in matcher_tuple match the corresponding fields in
959// value_tuple. It is a compiler error if matcher_tuple and
960// value_tuple have different number of fields or incompatible field
961// types.
962template <typename MatcherTuple, typename ValueTuple>
963bool TupleMatches(const MatcherTuple& matcher_tuple,
964 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000965 // Makes sure that matcher_tuple and value_tuple have the same
966 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000967 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000968 tuple_size<ValueTuple>::value,
969 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000970 return TuplePrefix<tuple_size<ValueTuple>::value>::
971 Matches(matcher_tuple, value_tuple);
972}
973
974// Describes failures in matching matchers against values. If there
975// is no failure, nothing will be streamed to os.
976template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000977void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
978 const ValueTuple& values,
979 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000980 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000981 matchers, values, os);
982}
983
zhanyong.wanfb25d532013-07-28 08:24:00 +0000984// TransformTupleValues and its helper.
985//
986// TransformTupleValuesHelper hides the internal machinery that
987// TransformTupleValues uses to implement a tuple traversal.
988template <typename Tuple, typename Func, typename OutIter>
989class TransformTupleValuesHelper {
990 private:
kosakbd018832014-04-02 20:30:00 +0000991 typedef ::testing::tuple_size<Tuple> TupleSize;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000992
993 public:
994 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
995 // Returns the final value of 'out' in case the caller needs it.
996 static OutIter Run(Func f, const Tuple& t, OutIter out) {
997 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
998 }
999
1000 private:
1001 template <typename Tup, size_t kRemainingSize>
1002 struct IterateOverTuple {
1003 OutIter operator() (Func f, const Tup& t, OutIter out) const {
kosakbd018832014-04-02 20:30:00 +00001004 *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
zhanyong.wanfb25d532013-07-28 08:24:00 +00001005 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
1006 }
1007 };
1008 template <typename Tup>
1009 struct IterateOverTuple<Tup, 0> {
1010 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
1011 return out;
1012 }
1013 };
1014};
1015
1016// Successively invokes 'f(element)' on each element of the tuple 't',
1017// appending each result to the 'out' iterator. Returns the final value
1018// of 'out'.
1019template <typename Tuple, typename Func, typename OutIter>
1020OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
1021 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
1022}
1023
shiqiane35fdd92008-12-10 05:08:54 +00001024// Implements A<T>().
1025template <typename T>
Gennadiy Civile55089e2018-04-04 14:05:00 -04001026class AnyMatcherImpl : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
shiqiane35fdd92008-12-10 05:08:54 +00001027 public:
Gennadiy Civile55089e2018-04-04 14:05:00 -04001028 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) /* x */,
1029 MatchResultListener* /* listener */) const {
1030 return true;
1031 }
shiqiane35fdd92008-12-10 05:08:54 +00001032 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
1033 virtual void DescribeNegationTo(::std::ostream* os) const {
1034 // This is mostly for completeness' safe, as it's not very useful
1035 // to write Not(A<bool>()). However we cannot completely rule out
1036 // such a possibility, and it doesn't hurt to be prepared.
1037 *os << "never matches";
1038 }
1039};
1040
1041// Implements _, a matcher that matches any value of any
1042// type. This is a polymorphic matcher, so we need a template type
1043// conversion operator to make it appearing as a Matcher<T> for any
1044// type T.
1045class AnythingMatcher {
1046 public:
1047 template <typename T>
1048 operator Matcher<T>() const { return A<T>(); }
1049};
1050
1051// Implements a matcher that compares a given value with a
1052// pre-supplied value using one of the ==, <=, <, etc, operators. The
1053// two values being compared don't have to have the same type.
1054//
1055// The matcher defined here is polymorphic (for example, Eq(5) can be
1056// used to match an int, a short, a double, etc). Therefore we use
1057// a template type conversion operator in the implementation.
1058//
shiqiane35fdd92008-12-10 05:08:54 +00001059// The following template definition assumes that the Rhs parameter is
1060// a "bare" type (i.e. neither 'const T' nor 'T&').
kosak506340a2014-11-17 01:47:54 +00001061template <typename D, typename Rhs, typename Op>
1062class ComparisonBase {
1063 public:
1064 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
1065 template <typename Lhs>
1066 operator Matcher<Lhs>() const {
1067 return MakeMatcher(new Impl<Lhs>(rhs_));
shiqiane35fdd92008-12-10 05:08:54 +00001068 }
1069
kosak506340a2014-11-17 01:47:54 +00001070 private:
1071 template <typename Lhs>
1072 class Impl : public MatcherInterface<Lhs> {
1073 public:
1074 explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
1075 virtual bool MatchAndExplain(
1076 Lhs lhs, MatchResultListener* /* listener */) const {
1077 return Op()(lhs, rhs_);
1078 }
1079 virtual void DescribeTo(::std::ostream* os) const {
1080 *os << D::Desc() << " ";
1081 UniversalPrint(rhs_, os);
1082 }
1083 virtual void DescribeNegationTo(::std::ostream* os) const {
1084 *os << D::NegatedDesc() << " ";
1085 UniversalPrint(rhs_, os);
1086 }
1087 private:
1088 Rhs rhs_;
1089 GTEST_DISALLOW_ASSIGN_(Impl);
1090 };
1091 Rhs rhs_;
1092 GTEST_DISALLOW_ASSIGN_(ComparisonBase);
1093};
shiqiane35fdd92008-12-10 05:08:54 +00001094
kosak506340a2014-11-17 01:47:54 +00001095template <typename Rhs>
1096class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
1097 public:
1098 explicit EqMatcher(const Rhs& rhs)
1099 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
1100 static const char* Desc() { return "is equal to"; }
1101 static const char* NegatedDesc() { return "isn't equal to"; }
1102};
1103template <typename Rhs>
1104class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
1105 public:
1106 explicit NeMatcher(const Rhs& rhs)
1107 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
1108 static const char* Desc() { return "isn't equal to"; }
1109 static const char* NegatedDesc() { return "is equal to"; }
1110};
1111template <typename Rhs>
1112class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
1113 public:
1114 explicit LtMatcher(const Rhs& rhs)
1115 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
1116 static const char* Desc() { return "is <"; }
1117 static const char* NegatedDesc() { return "isn't <"; }
1118};
1119template <typename Rhs>
1120class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
1121 public:
1122 explicit GtMatcher(const Rhs& rhs)
1123 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
1124 static const char* Desc() { return "is >"; }
1125 static const char* NegatedDesc() { return "isn't >"; }
1126};
1127template <typename Rhs>
1128class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
1129 public:
1130 explicit LeMatcher(const Rhs& rhs)
1131 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
1132 static const char* Desc() { return "is <="; }
1133 static const char* NegatedDesc() { return "isn't <="; }
1134};
1135template <typename Rhs>
1136class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
1137 public:
1138 explicit GeMatcher(const Rhs& rhs)
1139 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
1140 static const char* Desc() { return "is >="; }
1141 static const char* NegatedDesc() { return "isn't >="; }
1142};
shiqiane35fdd92008-12-10 05:08:54 +00001143
vladlosev79b83502009-11-18 00:43:37 +00001144// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001145// pointer that is NULL.
1146class IsNullMatcher {
1147 public:
vladlosev79b83502009-11-18 00:43:37 +00001148 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +00001149 bool MatchAndExplain(const Pointer& p,
1150 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001151#if GTEST_LANG_CXX11
1152 return p == nullptr;
1153#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001154 return GetRawPointer(p) == NULL;
kosak6305ff52015-04-28 22:36:31 +00001155#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001156 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001157
1158 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
1159 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001160 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001161 }
1162};
1163
vladlosev79b83502009-11-18 00:43:37 +00001164// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +00001165// pointer that is not NULL.
1166class NotNullMatcher {
1167 public:
vladlosev79b83502009-11-18 00:43:37 +00001168 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +00001169 bool MatchAndExplain(const Pointer& p,
1170 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001171#if GTEST_LANG_CXX11
1172 return p != nullptr;
1173#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001174 return GetRawPointer(p) != NULL;
kosak6305ff52015-04-28 22:36:31 +00001175#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001176 }
shiqiane35fdd92008-12-10 05:08:54 +00001177
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001178 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +00001179 void DescribeNegationTo(::std::ostream* os) const {
1180 *os << "is NULL";
1181 }
1182};
1183
1184// Ref(variable) matches any argument that is a reference to
1185// 'variable'. This matcher is polymorphic as it can match any
1186// super type of the type of 'variable'.
1187//
1188// The RefMatcher template class implements Ref(variable). It can
1189// only be instantiated with a reference type. This prevents a user
1190// from mistakenly using Ref(x) to match a non-reference function
1191// argument. For example, the following will righteously cause a
1192// compiler error:
1193//
1194// int n;
1195// Matcher<int> m1 = Ref(n); // This won't compile.
1196// Matcher<int&> m2 = Ref(n); // This will compile.
1197template <typename T>
1198class RefMatcher;
1199
1200template <typename T>
1201class RefMatcher<T&> {
1202 // Google Mock is a generic framework and thus needs to support
1203 // mocking any function types, including those that take non-const
1204 // reference arguments. Therefore the template parameter T (and
1205 // Super below) can be instantiated to either a const type or a
1206 // non-const type.
1207 public:
1208 // RefMatcher() takes a T& instead of const T&, as we want the
1209 // compiler to catch using Ref(const_value) as a matcher for a
1210 // non-const reference.
1211 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
1212
1213 template <typename Super>
1214 operator Matcher<Super&>() const {
1215 // By passing object_ (type T&) to Impl(), which expects a Super&,
1216 // we make sure that Super is a super type of T. In particular,
1217 // this catches using Ref(const_value) as a matcher for a
1218 // non-const reference, as you cannot implicitly convert a const
1219 // reference to a non-const reference.
1220 return MakeMatcher(new Impl<Super>(object_));
1221 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001222
shiqiane35fdd92008-12-10 05:08:54 +00001223 private:
1224 template <typename Super>
1225 class Impl : public MatcherInterface<Super&> {
1226 public:
1227 explicit Impl(Super& x) : object_(x) {} // NOLINT
1228
zhanyong.wandb22c222010-01-28 21:52:29 +00001229 // MatchAndExplain() takes a Super& (as opposed to const Super&)
1230 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +00001231 virtual bool MatchAndExplain(
1232 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001233 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +00001234 return &x == &object_;
1235 }
shiqiane35fdd92008-12-10 05:08:54 +00001236
1237 virtual void DescribeTo(::std::ostream* os) const {
1238 *os << "references the variable ";
1239 UniversalPrinter<Super&>::Print(object_, os);
1240 }
1241
1242 virtual void DescribeNegationTo(::std::ostream* os) const {
1243 *os << "does not reference the variable ";
1244 UniversalPrinter<Super&>::Print(object_, os);
1245 }
1246
shiqiane35fdd92008-12-10 05:08:54 +00001247 private:
1248 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001249
1250 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001251 };
1252
1253 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001254
1255 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001256};
1257
1258// Polymorphic helper functions for narrow and wide string matchers.
1259inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1260 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1261}
1262
1263inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1264 const wchar_t* rhs) {
1265 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1266}
1267
1268// String comparison for narrow or wide strings that can have embedded NUL
1269// characters.
1270template <typename StringType>
1271bool CaseInsensitiveStringEquals(const StringType& s1,
1272 const StringType& s2) {
1273 // Are the heads equal?
1274 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1275 return false;
1276 }
1277
1278 // Skip the equal heads.
1279 const typename StringType::value_type nul = 0;
1280 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1281
1282 // Are we at the end of either s1 or s2?
1283 if (i1 == StringType::npos || i2 == StringType::npos) {
1284 return i1 == i2;
1285 }
1286
1287 // Are the tails equal?
1288 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1289}
1290
1291// String matchers.
1292
1293// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1294template <typename StringType>
1295class StrEqualityMatcher {
1296 public:
shiqiane35fdd92008-12-10 05:08:54 +00001297 StrEqualityMatcher(const StringType& str, bool expect_eq,
1298 bool case_sensitive)
1299 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1300
Gennadiy Civile55089e2018-04-04 14:05:00 -04001301#if GTEST_HAS_ABSL
1302 bool MatchAndExplain(const absl::string_view& s,
1303 MatchResultListener* listener) const {
1304 if (s.data() == NULL) {
1305 return !expect_eq_;
1306 }
1307 // This should fail to compile if absl::string_view is used with wide
1308 // strings.
1309 const StringType& str = string(s);
1310 return MatchAndExplain(str, listener);
1311 }
1312#endif // GTEST_HAS_ABSL
1313
jgm38513a82012-11-15 15:50:36 +00001314 // Accepts pointer types, particularly:
1315 // const char*
1316 // char*
1317 // const wchar_t*
1318 // wchar_t*
1319 template <typename CharType>
1320 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001321 if (s == NULL) {
1322 return !expect_eq_;
1323 }
zhanyong.wandb22c222010-01-28 21:52:29 +00001324 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001325 }
1326
jgm38513a82012-11-15 15:50:36 +00001327 // Matches anything that can convert to StringType.
1328 //
1329 // This is a template, not just a plain function with const StringType&,
Gennadiy Civile55089e2018-04-04 14:05:00 -04001330 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001331 template <typename MatcheeStringType>
1332 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001333 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001334 const StringType& s2(s);
1335 const bool eq = case_sensitive_ ? s2 == string_ :
1336 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +00001337 return expect_eq_ == eq;
1338 }
1339
1340 void DescribeTo(::std::ostream* os) const {
1341 DescribeToHelper(expect_eq_, os);
1342 }
1343
1344 void DescribeNegationTo(::std::ostream* os) const {
1345 DescribeToHelper(!expect_eq_, os);
1346 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001347
shiqiane35fdd92008-12-10 05:08:54 +00001348 private:
1349 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001350 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +00001351 *os << "equal to ";
1352 if (!case_sensitive_) {
1353 *os << "(ignoring case) ";
1354 }
vladloseve2e8ba42010-05-13 18:16:03 +00001355 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001356 }
1357
1358 const StringType string_;
1359 const bool expect_eq_;
1360 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001361
1362 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001363};
1364
1365// Implements the polymorphic HasSubstr(substring) matcher, which
1366// can be used as a Matcher<T> as long as T can be converted to a
1367// string.
1368template <typename StringType>
1369class HasSubstrMatcher {
1370 public:
shiqiane35fdd92008-12-10 05:08:54 +00001371 explicit HasSubstrMatcher(const StringType& substring)
1372 : substring_(substring) {}
1373
Gennadiy Civile55089e2018-04-04 14:05:00 -04001374#if GTEST_HAS_ABSL
1375 bool MatchAndExplain(const absl::string_view& s,
1376 MatchResultListener* listener) const {
1377 if (s.data() == NULL) {
1378 return false;
1379 }
1380 // This should fail to compile if absl::string_view is used with wide
1381 // strings.
1382 const StringType& str = string(s);
1383 return MatchAndExplain(str, listener);
1384 }
1385#endif // GTEST_HAS_ABSL
1386
jgm38513a82012-11-15 15:50:36 +00001387 // Accepts pointer types, particularly:
1388 // const char*
1389 // char*
1390 // const wchar_t*
1391 // wchar_t*
1392 template <typename CharType>
1393 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001394 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001395 }
1396
jgm38513a82012-11-15 15:50:36 +00001397 // Matches anything that can convert to StringType.
1398 //
1399 // This is a template, not just a plain function with const StringType&,
Gennadiy Civile55089e2018-04-04 14:05:00 -04001400 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001401 template <typename MatcheeStringType>
1402 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001403 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001404 const StringType& s2(s);
1405 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001406 }
1407
1408 // Describes what this matcher matches.
1409 void DescribeTo(::std::ostream* os) const {
1410 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001411 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001412 }
1413
1414 void DescribeNegationTo(::std::ostream* os) const {
1415 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001416 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001417 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001418
shiqiane35fdd92008-12-10 05:08:54 +00001419 private:
1420 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001421
1422 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001423};
1424
1425// Implements the polymorphic StartsWith(substring) matcher, which
1426// can be used as a Matcher<T> as long as T can be converted to a
1427// string.
1428template <typename StringType>
1429class StartsWithMatcher {
1430 public:
shiqiane35fdd92008-12-10 05:08:54 +00001431 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1432 }
1433
Gennadiy Civile55089e2018-04-04 14:05:00 -04001434#if GTEST_HAS_ABSL
1435 bool MatchAndExplain(const absl::string_view& s,
1436 MatchResultListener* listener) const {
1437 if (s.data() == NULL) {
1438 return false;
1439 }
1440 // This should fail to compile if absl::string_view is used with wide
1441 // strings.
1442 const StringType& str = string(s);
1443 return MatchAndExplain(str, listener);
1444 }
1445#endif // GTEST_HAS_ABSL
1446
jgm38513a82012-11-15 15:50:36 +00001447 // Accepts pointer types, particularly:
1448 // const char*
1449 // char*
1450 // const wchar_t*
1451 // wchar_t*
1452 template <typename CharType>
1453 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001454 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001455 }
1456
jgm38513a82012-11-15 15:50:36 +00001457 // Matches anything that can convert to StringType.
1458 //
1459 // This is a template, not just a plain function with const StringType&,
Gennadiy Civile55089e2018-04-04 14:05:00 -04001460 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001461 template <typename MatcheeStringType>
1462 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001463 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001464 const StringType& s2(s);
1465 return s2.length() >= prefix_.length() &&
1466 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001467 }
1468
1469 void DescribeTo(::std::ostream* os) const {
1470 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001471 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001472 }
1473
1474 void DescribeNegationTo(::std::ostream* os) const {
1475 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001476 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001477 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001478
shiqiane35fdd92008-12-10 05:08:54 +00001479 private:
1480 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001481
1482 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001483};
1484
1485// Implements the polymorphic EndsWith(substring) matcher, which
1486// can be used as a Matcher<T> as long as T can be converted to a
1487// string.
1488template <typename StringType>
1489class EndsWithMatcher {
1490 public:
shiqiane35fdd92008-12-10 05:08:54 +00001491 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1492
Gennadiy Civile55089e2018-04-04 14:05:00 -04001493#if GTEST_HAS_ABSL
1494 bool MatchAndExplain(const absl::string_view& s,
1495 MatchResultListener* listener) const {
1496 if (s.data() == NULL) {
1497 return false;
1498 }
1499 // This should fail to compile if absl::string_view is used with wide
1500 // strings.
1501 const StringType& str = string(s);
1502 return MatchAndExplain(str, listener);
1503 }
1504#endif // GTEST_HAS_ABSL
1505
jgm38513a82012-11-15 15:50:36 +00001506 // Accepts pointer types, particularly:
1507 // const char*
1508 // char*
1509 // const wchar_t*
1510 // wchar_t*
1511 template <typename CharType>
1512 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001513 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001514 }
1515
jgm38513a82012-11-15 15:50:36 +00001516 // Matches anything that can convert to StringType.
1517 //
1518 // This is a template, not just a plain function with const StringType&,
Gennadiy Civile55089e2018-04-04 14:05:00 -04001519 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001520 template <typename MatcheeStringType>
1521 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001522 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001523 const StringType& s2(s);
1524 return s2.length() >= suffix_.length() &&
1525 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001526 }
1527
1528 void DescribeTo(::std::ostream* os) const {
1529 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001530 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001531 }
1532
1533 void DescribeNegationTo(::std::ostream* os) const {
1534 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001535 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001536 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001537
shiqiane35fdd92008-12-10 05:08:54 +00001538 private:
1539 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001540
1541 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001542};
1543
shiqiane35fdd92008-12-10 05:08:54 +00001544// Implements polymorphic matchers MatchesRegex(regex) and
1545// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1546// T can be converted to a string.
1547class MatchesRegexMatcher {
1548 public:
1549 MatchesRegexMatcher(const RE* regex, bool full_match)
1550 : regex_(regex), full_match_(full_match) {}
1551
Gennadiy Civile55089e2018-04-04 14:05:00 -04001552#if GTEST_HAS_ABSL
1553 bool MatchAndExplain(const absl::string_view& s,
1554 MatchResultListener* listener) const {
1555 return s.data() && MatchAndExplain(string(s), listener);
1556 }
1557#endif // GTEST_HAS_ABSL
1558
jgm38513a82012-11-15 15:50:36 +00001559 // Accepts pointer types, particularly:
1560 // const char*
1561 // char*
1562 // const wchar_t*
1563 // wchar_t*
1564 template <typename CharType>
1565 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001566 return s != NULL && MatchAndExplain(std::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001567 }
1568
Nico Weber09fd5b32017-05-15 17:07:03 -04001569 // Matches anything that can convert to std::string.
jgm38513a82012-11-15 15:50:36 +00001570 //
Nico Weber09fd5b32017-05-15 17:07:03 -04001571 // This is a template, not just a plain function with const std::string&,
Gennadiy Civilb7c56832018-03-22 15:35:37 -04001572 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001573 template <class MatcheeStringType>
1574 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001575 MatchResultListener* /* listener */) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001576 const std::string& s2(s);
jgm38513a82012-11-15 15:50:36 +00001577 return full_match_ ? RE::FullMatch(s2, *regex_) :
1578 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001579 }
1580
1581 void DescribeTo(::std::ostream* os) const {
1582 *os << (full_match_ ? "matches" : "contains")
1583 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001584 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001585 }
1586
1587 void DescribeNegationTo(::std::ostream* os) const {
1588 *os << "doesn't " << (full_match_ ? "match" : "contain")
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 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001592
shiqiane35fdd92008-12-10 05:08:54 +00001593 private:
1594 const internal::linked_ptr<const RE> regex_;
1595 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001596
1597 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001598};
1599
shiqiane35fdd92008-12-10 05:08:54 +00001600// Implements a matcher that compares the two fields of a 2-tuple
1601// using one of the ==, <=, <, etc, operators. The two fields being
1602// compared don't have to have the same type.
1603//
1604// The matcher defined here is polymorphic (for example, Eq() can be
1605// used to match a tuple<int, short>, a tuple<const long&, double>,
1606// etc). Therefore we use a template type conversion operator in the
1607// implementation.
kosak506340a2014-11-17 01:47:54 +00001608template <typename D, typename Op>
1609class PairMatchBase {
1610 public:
1611 template <typename T1, typename T2>
1612 operator Matcher< ::testing::tuple<T1, T2> >() const {
1613 return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >);
1614 }
1615 template <typename T1, typename T2>
1616 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
1617 return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>);
shiqiane35fdd92008-12-10 05:08:54 +00001618 }
1619
kosak506340a2014-11-17 01:47:54 +00001620 private:
1621 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
1622 return os << D::Desc();
1623 }
shiqiane35fdd92008-12-10 05:08:54 +00001624
kosak506340a2014-11-17 01:47:54 +00001625 template <typename Tuple>
1626 class Impl : public MatcherInterface<Tuple> {
1627 public:
1628 virtual bool MatchAndExplain(
1629 Tuple args,
1630 MatchResultListener* /* listener */) const {
1631 return Op()(::testing::get<0>(args), ::testing::get<1>(args));
1632 }
1633 virtual void DescribeTo(::std::ostream* os) const {
1634 *os << "are " << GetDesc;
1635 }
1636 virtual void DescribeNegationTo(::std::ostream* os) const {
1637 *os << "aren't " << GetDesc;
1638 }
1639 };
1640};
1641
1642class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
1643 public:
1644 static const char* Desc() { return "an equal pair"; }
1645};
1646class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
1647 public:
1648 static const char* Desc() { return "an unequal pair"; }
1649};
1650class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
1651 public:
1652 static const char* Desc() { return "a pair where the first < the second"; }
1653};
1654class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
1655 public:
1656 static const char* Desc() { return "a pair where the first > the second"; }
1657};
1658class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
1659 public:
1660 static const char* Desc() { return "a pair where the first <= the second"; }
1661};
1662class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
1663 public:
1664 static const char* Desc() { return "a pair where the first >= the second"; }
1665};
shiqiane35fdd92008-12-10 05:08:54 +00001666
zhanyong.wanc6a41232009-05-13 23:38:40 +00001667// Implements the Not(...) matcher for a particular argument type T.
1668// We do not nest it inside the NotMatcher class template, as that
1669// will prevent different instantiations of NotMatcher from sharing
1670// the same NotMatcherImpl<T> class.
1671template <typename T>
Gennadiy Civile55089e2018-04-04 14:05:00 -04001672class NotMatcherImpl : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001673 public:
1674 explicit NotMatcherImpl(const Matcher<T>& matcher)
1675 : matcher_(matcher) {}
1676
Gennadiy Civile55089e2018-04-04 14:05:00 -04001677 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
1678 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001679 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001680 }
1681
1682 virtual void DescribeTo(::std::ostream* os) const {
1683 matcher_.DescribeNegationTo(os);
1684 }
1685
1686 virtual void DescribeNegationTo(::std::ostream* os) const {
1687 matcher_.DescribeTo(os);
1688 }
1689
zhanyong.wanc6a41232009-05-13 23:38:40 +00001690 private:
1691 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001692
1693 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001694};
1695
shiqiane35fdd92008-12-10 05:08:54 +00001696// Implements the Not(m) matcher, which matches a value that doesn't
1697// match matcher m.
1698template <typename InnerMatcher>
1699class NotMatcher {
1700 public:
1701 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1702
1703 // This template type conversion operator allows Not(m) to be used
1704 // to match any type m can match.
1705 template <typename T>
1706 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001707 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001708 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001709
shiqiane35fdd92008-12-10 05:08:54 +00001710 private:
shiqiane35fdd92008-12-10 05:08:54 +00001711 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001712
1713 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001714};
1715
zhanyong.wanc6a41232009-05-13 23:38:40 +00001716// Implements the AllOf(m1, m2) matcher for a particular argument type
1717// T. We do not nest it inside the BothOfMatcher class template, as
1718// that will prevent different instantiations of BothOfMatcher from
1719// sharing the same BothOfMatcherImpl<T> class.
1720template <typename T>
Gennadiy Civile55089e2018-04-04 14:05:00 -04001721class BothOfMatcherImpl
1722 : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001723 public:
1724 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1725 : matcher1_(matcher1), matcher2_(matcher2) {}
1726
zhanyong.wanc6a41232009-05-13 23:38:40 +00001727 virtual void DescribeTo(::std::ostream* os) const {
1728 *os << "(";
1729 matcher1_.DescribeTo(os);
1730 *os << ") and (";
1731 matcher2_.DescribeTo(os);
1732 *os << ")";
1733 }
1734
1735 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001736 *os << "(";
1737 matcher1_.DescribeNegationTo(os);
1738 *os << ") or (";
1739 matcher2_.DescribeNegationTo(os);
1740 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001741 }
1742
Gennadiy Civile55089e2018-04-04 14:05:00 -04001743 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
1744 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001745 // If either matcher1_ or matcher2_ doesn't match x, we only need
1746 // to explain why one of them fails.
1747 StringMatchResultListener listener1;
1748 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1749 *listener << listener1.str();
1750 return false;
1751 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001752
zhanyong.wan82113312010-01-08 21:55:40 +00001753 StringMatchResultListener listener2;
1754 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1755 *listener << listener2.str();
1756 return false;
1757 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001758
zhanyong.wan82113312010-01-08 21:55:40 +00001759 // Otherwise we need to explain why *both* of them match.
Nico Weber09fd5b32017-05-15 17:07:03 -04001760 const std::string s1 = listener1.str();
1761 const std::string s2 = listener2.str();
zhanyong.wan82113312010-01-08 21:55:40 +00001762
1763 if (s1 == "") {
1764 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001765 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001766 *listener << s1;
1767 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001768 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001769 }
1770 }
zhanyong.wan82113312010-01-08 21:55:40 +00001771 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001772 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001773
zhanyong.wanc6a41232009-05-13 23:38:40 +00001774 private:
1775 const Matcher<T> matcher1_;
1776 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001777
1778 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001779};
1780
zhanyong.wan616180e2013-06-18 18:49:51 +00001781#if GTEST_LANG_CXX11
1782// MatcherList provides mechanisms for storing a variable number of matchers in
1783// a list structure (ListType) and creating a combining matcher from such a
1784// list.
Troy Holsapplec8510502018-02-07 22:06:00 -08001785// The template is defined recursively using the following template parameters:
zhanyong.wan616180e2013-06-18 18:49:51 +00001786// * kSize is the length of the MatcherList.
1787// * Head is the type of the first matcher of the list.
1788// * Tail denotes the types of the remaining matchers of the list.
1789template <int kSize, typename Head, typename... Tail>
1790struct MatcherList {
1791 typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
zhanyong.wan29897032013-06-20 18:59:15 +00001792 typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001793
1794 // BuildList stores variadic type values in a nested pair structure.
1795 // Example:
1796 // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
1797 // the corresponding result of type pair<int, pair<string, float>>.
1798 static ListType BuildList(const Head& matcher, const Tail&... tail) {
1799 return ListType(matcher, MatcherListTail::BuildList(tail...));
1800 }
1801
1802 // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
1803 // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
1804 // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
1805 // constructor taking two Matcher<T>s as input.
1806 template <typename T, template <typename /* T */> class CombiningMatcher>
1807 static Matcher<T> CreateMatcher(const ListType& matchers) {
1808 return Matcher<T>(new CombiningMatcher<T>(
1809 SafeMatcherCast<T>(matchers.first),
1810 MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
1811 matchers.second)));
1812 }
1813};
1814
1815// The following defines the base case for the recursive definition of
1816// MatcherList.
1817template <typename Matcher1, typename Matcher2>
1818struct MatcherList<2, Matcher1, Matcher2> {
zhanyong.wan29897032013-06-20 18:59:15 +00001819 typedef ::std::pair<Matcher1, Matcher2> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001820
1821 static ListType BuildList(const Matcher1& matcher1,
1822 const Matcher2& matcher2) {
zhanyong.wan29897032013-06-20 18:59:15 +00001823 return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
zhanyong.wan616180e2013-06-18 18:49:51 +00001824 }
1825
1826 template <typename T, template <typename /* T */> class CombiningMatcher>
1827 static Matcher<T> CreateMatcher(const ListType& matchers) {
1828 return Matcher<T>(new CombiningMatcher<T>(
1829 SafeMatcherCast<T>(matchers.first),
1830 SafeMatcherCast<T>(matchers.second)));
1831 }
1832};
1833
1834// VariadicMatcher is used for the variadic implementation of
1835// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1836// CombiningMatcher<T> is used to recursively combine the provided matchers
1837// (of type Args...).
1838template <template <typename T> class CombiningMatcher, typename... Args>
1839class VariadicMatcher {
1840 public:
1841 VariadicMatcher(const Args&... matchers) // NOLINT
1842 : matchers_(MatcherListType::BuildList(matchers...)) {}
1843
1844 // This template type conversion operator allows an
1845 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1846 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1847 template <typename T>
1848 operator Matcher<T>() const {
1849 return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
1850 matchers_);
1851 }
1852
1853 private:
1854 typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
1855
1856 const typename MatcherListType::ListType matchers_;
1857
1858 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1859};
1860
1861template <typename... Args>
1862using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
1863
1864#endif // GTEST_LANG_CXX11
1865
shiqiane35fdd92008-12-10 05:08:54 +00001866// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1867// matches a value that matches all of the matchers m_1, ..., and m_n.
1868template <typename Matcher1, typename Matcher2>
1869class BothOfMatcher {
1870 public:
1871 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1872 : matcher1_(matcher1), matcher2_(matcher2) {}
1873
1874 // This template type conversion operator allows a
1875 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1876 // both Matcher1 and Matcher2 can match.
1877 template <typename T>
1878 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001879 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1880 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001881 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001882
shiqiane35fdd92008-12-10 05:08:54 +00001883 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001884 Matcher1 matcher1_;
1885 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001886
1887 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001888};
shiqiane35fdd92008-12-10 05:08:54 +00001889
zhanyong.wanc6a41232009-05-13 23:38:40 +00001890// Implements the AnyOf(m1, m2) matcher for a particular argument type
1891// T. We do not nest it inside the AnyOfMatcher class template, as
1892// that will prevent different instantiations of AnyOfMatcher from
1893// sharing the same EitherOfMatcherImpl<T> class.
1894template <typename T>
Gennadiy Civile55089e2018-04-04 14:05:00 -04001895class EitherOfMatcherImpl
1896 : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001897 public:
1898 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1899 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001900
zhanyong.wanc6a41232009-05-13 23:38:40 +00001901 virtual void DescribeTo(::std::ostream* os) const {
1902 *os << "(";
1903 matcher1_.DescribeTo(os);
1904 *os << ") or (";
1905 matcher2_.DescribeTo(os);
1906 *os << ")";
1907 }
shiqiane35fdd92008-12-10 05:08:54 +00001908
zhanyong.wanc6a41232009-05-13 23:38:40 +00001909 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001910 *os << "(";
1911 matcher1_.DescribeNegationTo(os);
1912 *os << ") and (";
1913 matcher2_.DescribeNegationTo(os);
1914 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001915 }
shiqiane35fdd92008-12-10 05:08:54 +00001916
Gennadiy Civile55089e2018-04-04 14:05:00 -04001917 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
1918 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001919 // If either matcher1_ or matcher2_ matches x, we just need to
1920 // explain why *one* of them matches.
1921 StringMatchResultListener listener1;
1922 if (matcher1_.MatchAndExplain(x, &listener1)) {
1923 *listener << listener1.str();
1924 return true;
1925 }
1926
1927 StringMatchResultListener listener2;
1928 if (matcher2_.MatchAndExplain(x, &listener2)) {
1929 *listener << listener2.str();
1930 return true;
1931 }
1932
1933 // Otherwise we need to explain why *both* of them fail.
Nico Weber09fd5b32017-05-15 17:07:03 -04001934 const std::string s1 = listener1.str();
1935 const std::string s2 = listener2.str();
zhanyong.wan82113312010-01-08 21:55:40 +00001936
1937 if (s1 == "") {
1938 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001939 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001940 *listener << s1;
1941 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001942 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001943 }
1944 }
zhanyong.wan82113312010-01-08 21:55:40 +00001945 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001946 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001947
zhanyong.wanc6a41232009-05-13 23:38:40 +00001948 private:
1949 const Matcher<T> matcher1_;
1950 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001951
1952 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001953};
1954
zhanyong.wan616180e2013-06-18 18:49:51 +00001955#if GTEST_LANG_CXX11
1956// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1957template <typename... Args>
1958using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
1959
1960#endif // GTEST_LANG_CXX11
1961
shiqiane35fdd92008-12-10 05:08:54 +00001962// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1963// matches a value that matches at least one of the matchers m_1, ...,
1964// and m_n.
1965template <typename Matcher1, typename Matcher2>
1966class EitherOfMatcher {
1967 public:
1968 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1969 : matcher1_(matcher1), matcher2_(matcher2) {}
1970
1971 // This template type conversion operator allows a
1972 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1973 // both Matcher1 and Matcher2 can match.
1974 template <typename T>
1975 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001976 return Matcher<T>(new EitherOfMatcherImpl<T>(
1977 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001978 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001979
shiqiane35fdd92008-12-10 05:08:54 +00001980 private:
shiqiane35fdd92008-12-10 05:08:54 +00001981 Matcher1 matcher1_;
1982 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001983
1984 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001985};
1986
1987// Used for implementing Truly(pred), which turns a predicate into a
1988// matcher.
1989template <typename Predicate>
1990class TrulyMatcher {
1991 public:
1992 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1993
1994 // This method template allows Truly(pred) to be used as a matcher
1995 // for type T where T is the argument type of predicate 'pred'. The
1996 // argument is passed by reference as the predicate may be
1997 // interested in the address of the argument.
1998 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001999 bool MatchAndExplain(T& x, // NOLINT
2000 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00002001 // Without the if-statement, MSVC sometimes warns about converting
2002 // a value to bool (warning 4800).
2003 //
2004 // We cannot write 'return !!predicate_(x);' as that doesn't work
2005 // when predicate_(x) returns a class convertible to bool but
2006 // having no operator!().
2007 if (predicate_(x))
2008 return true;
2009 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002010 }
2011
2012 void DescribeTo(::std::ostream* os) const {
2013 *os << "satisfies the given predicate";
2014 }
2015
2016 void DescribeNegationTo(::std::ostream* os) const {
2017 *os << "doesn't satisfy the given predicate";
2018 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002019
shiqiane35fdd92008-12-10 05:08:54 +00002020 private:
2021 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002022
2023 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002024};
2025
2026// Used for implementing Matches(matcher), which turns a matcher into
2027// a predicate.
2028template <typename M>
2029class MatcherAsPredicate {
2030 public:
2031 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
2032
2033 // This template operator() allows Matches(m) to be used as a
2034 // predicate on type T where m is a matcher on type T.
2035 //
2036 // The argument x is passed by reference instead of by value, as
2037 // some matcher may be interested in its address (e.g. as in
2038 // Matches(Ref(n))(x)).
2039 template <typename T>
2040 bool operator()(const T& x) const {
2041 // We let matcher_ commit to a particular type here instead of
2042 // when the MatcherAsPredicate object was constructed. This
2043 // allows us to write Matches(m) where m is a polymorphic matcher
2044 // (e.g. Eq(5)).
2045 //
2046 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
2047 // compile when matcher_ has type Matcher<const T&>; if we write
2048 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
2049 // when matcher_ has type Matcher<T>; if we just write
2050 // matcher_.Matches(x), it won't compile when matcher_ is
2051 // polymorphic, e.g. Eq(5).
2052 //
2053 // MatcherCast<const T&>() is necessary for making the code work
2054 // in all of the above situations.
2055 return MatcherCast<const T&>(matcher_).Matches(x);
2056 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002057
shiqiane35fdd92008-12-10 05:08:54 +00002058 private:
2059 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002060
2061 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00002062};
2063
2064// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
2065// argument M must be a type that can be converted to a matcher.
2066template <typename M>
2067class PredicateFormatterFromMatcher {
2068 public:
kosak9b1a9442015-04-28 23:06:58 +00002069 explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {}
shiqiane35fdd92008-12-10 05:08:54 +00002070
2071 // This template () operator allows a PredicateFormatterFromMatcher
2072 // object to act as a predicate-formatter suitable for using with
2073 // Google Test's EXPECT_PRED_FORMAT1() macro.
2074 template <typename T>
2075 AssertionResult operator()(const char* value_text, const T& x) const {
2076 // We convert matcher_ to a Matcher<const T&> *now* instead of
2077 // when the PredicateFormatterFromMatcher object was constructed,
2078 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
2079 // know which type to instantiate it to until we actually see the
2080 // type of x here.
2081 //
zhanyong.wanf4274522013-04-24 02:49:43 +00002082 // We write SafeMatcherCast<const T&>(matcher_) instead of
shiqiane35fdd92008-12-10 05:08:54 +00002083 // Matcher<const T&>(matcher_), as the latter won't compile when
2084 // matcher_ has type Matcher<T> (e.g. An<int>()).
zhanyong.wanf4274522013-04-24 02:49:43 +00002085 // We don't write MatcherCast<const T&> either, as that allows
2086 // potentially unsafe downcasting of the matcher argument.
2087 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00002088 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002089 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00002090 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002091
2092 ::std::stringstream ss;
2093 ss << "Value of: " << value_text << "\n"
2094 << "Expected: ";
2095 matcher.DescribeTo(&ss);
2096 ss << "\n Actual: " << listener.str();
2097 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00002098 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002099
shiqiane35fdd92008-12-10 05:08:54 +00002100 private:
2101 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002102
2103 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002104};
2105
2106// A helper function for converting a matcher to a predicate-formatter
2107// without the user needing to explicitly write the type. This is
2108// used for implementing ASSERT_THAT() and EXPECT_THAT().
kosak9b1a9442015-04-28 23:06:58 +00002109// Implementation detail: 'matcher' is received by-value to force decaying.
shiqiane35fdd92008-12-10 05:08:54 +00002110template <typename M>
2111inline PredicateFormatterFromMatcher<M>
kosak9b1a9442015-04-28 23:06:58 +00002112MakePredicateFormatterFromMatcher(M matcher) {
2113 return PredicateFormatterFromMatcher<M>(internal::move(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00002114}
2115
zhanyong.wan616180e2013-06-18 18:49:51 +00002116// Implements the polymorphic floating point equality matcher, which matches
2117// two float values using ULP-based approximation or, optionally, a
2118// user-specified epsilon. The template is meant to be instantiated with
2119// FloatType being either float or double.
shiqiane35fdd92008-12-10 05:08:54 +00002120template <typename FloatType>
2121class FloatingEqMatcher {
2122 public:
2123 // Constructor for FloatingEqMatcher.
kosak6b817802015-01-08 02:38:14 +00002124 // The matcher's input will be compared with expected. The matcher treats two
shiqiane35fdd92008-12-10 05:08:54 +00002125 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
zhanyong.wan616180e2013-06-18 18:49:51 +00002126 // equality comparisons between NANs will always return false. We specify a
2127 // negative max_abs_error_ term to indicate that ULP-based approximation will
2128 // be used for comparison.
kosak6b817802015-01-08 02:38:14 +00002129 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
2130 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
zhanyong.wan616180e2013-06-18 18:49:51 +00002131 }
2132
2133 // Constructor that supports a user-specified max_abs_error that will be used
2134 // for comparison instead of ULP-based approximation. The max absolute
2135 // should be non-negative.
kosak6b817802015-01-08 02:38:14 +00002136 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
2137 FloatType max_abs_error)
2138 : expected_(expected),
2139 nan_eq_nan_(nan_eq_nan),
2140 max_abs_error_(max_abs_error) {
zhanyong.wan616180e2013-06-18 18:49:51 +00002141 GTEST_CHECK_(max_abs_error >= 0)
2142 << ", where max_abs_error is" << max_abs_error;
2143 }
shiqiane35fdd92008-12-10 05:08:54 +00002144
2145 // Implements floating point equality matcher as a Matcher<T>.
2146 template <typename T>
2147 class Impl : public MatcherInterface<T> {
2148 public:
kosak6b817802015-01-08 02:38:14 +00002149 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
2150 : expected_(expected),
2151 nan_eq_nan_(nan_eq_nan),
2152 max_abs_error_(max_abs_error) {}
shiqiane35fdd92008-12-10 05:08:54 +00002153
zhanyong.wan82113312010-01-08 21:55:40 +00002154 virtual bool MatchAndExplain(T value,
kosak6b817802015-01-08 02:38:14 +00002155 MatchResultListener* listener) const {
2156 const FloatingPoint<FloatType> actual(value), expected(expected_);
shiqiane35fdd92008-12-10 05:08:54 +00002157
2158 // Compares NaNs first, if nan_eq_nan_ is true.
kosak6b817802015-01-08 02:38:14 +00002159 if (actual.is_nan() || expected.is_nan()) {
2160 if (actual.is_nan() && expected.is_nan()) {
zhanyong.wan616180e2013-06-18 18:49:51 +00002161 return nan_eq_nan_;
2162 }
2163 // One is nan; the other is not nan.
2164 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002165 }
zhanyong.wan616180e2013-06-18 18:49:51 +00002166 if (HasMaxAbsError()) {
2167 // We perform an equality check so that inf will match inf, regardless
kosak6b817802015-01-08 02:38:14 +00002168 // of error bounds. If the result of value - expected_ would result in
zhanyong.wan616180e2013-06-18 18:49:51 +00002169 // overflow or if either value is inf, the default result is infinity,
2170 // which should only match if max_abs_error_ is also infinity.
kosak6b817802015-01-08 02:38:14 +00002171 if (value == expected_) {
2172 return true;
2173 }
2174
2175 const FloatType diff = value - expected_;
2176 if (fabs(diff) <= max_abs_error_) {
2177 return true;
2178 }
2179
2180 if (listener->IsInterested()) {
2181 *listener << "which is " << diff << " from " << expected_;
2182 }
2183 return false;
zhanyong.wan616180e2013-06-18 18:49:51 +00002184 } else {
kosak6b817802015-01-08 02:38:14 +00002185 return actual.AlmostEquals(expected);
zhanyong.wan616180e2013-06-18 18:49:51 +00002186 }
shiqiane35fdd92008-12-10 05:08:54 +00002187 }
2188
2189 virtual void DescribeTo(::std::ostream* os) const {
2190 // os->precision() returns the previously set precision, which we
2191 // store to restore the ostream to its original configuration
2192 // after outputting.
2193 const ::std::streamsize old_precision = os->precision(
2194 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00002195 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00002196 if (nan_eq_nan_) {
2197 *os << "is NaN";
2198 } else {
2199 *os << "never matches";
2200 }
2201 } else {
kosak6b817802015-01-08 02:38:14 +00002202 *os << "is approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002203 if (HasMaxAbsError()) {
2204 *os << " (absolute error <= " << max_abs_error_ << ")";
2205 }
shiqiane35fdd92008-12-10 05:08:54 +00002206 }
2207 os->precision(old_precision);
2208 }
2209
2210 virtual void DescribeNegationTo(::std::ostream* os) const {
2211 // As before, get original precision.
2212 const ::std::streamsize old_precision = os->precision(
2213 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00002214 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00002215 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002216 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00002217 } else {
2218 *os << "is anything";
2219 }
2220 } else {
kosak6b817802015-01-08 02:38:14 +00002221 *os << "isn't approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002222 if (HasMaxAbsError()) {
2223 *os << " (absolute error > " << max_abs_error_ << ")";
2224 }
shiqiane35fdd92008-12-10 05:08:54 +00002225 }
2226 // Restore original precision.
2227 os->precision(old_precision);
2228 }
2229
2230 private:
zhanyong.wan616180e2013-06-18 18:49:51 +00002231 bool HasMaxAbsError() const {
2232 return max_abs_error_ >= 0;
2233 }
2234
kosak6b817802015-01-08 02:38:14 +00002235 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002236 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002237 // max_abs_error will be used for value comparison when >= 0.
2238 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002239
2240 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002241 };
2242
kosak6b817802015-01-08 02:38:14 +00002243 // The following 3 type conversion operators allow FloatEq(expected) and
2244 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
shiqiane35fdd92008-12-10 05:08:54 +00002245 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
2246 // (While Google's C++ coding style doesn't allow arguments passed
2247 // by non-const reference, we may see them in code not conforming to
2248 // the style. Therefore Google Mock needs to support them.)
2249 operator Matcher<FloatType>() const {
kosak6b817802015-01-08 02:38:14 +00002250 return MakeMatcher(
2251 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002252 }
2253
2254 operator Matcher<const FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00002255 return MakeMatcher(
kosak6b817802015-01-08 02:38:14 +00002256 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002257 }
2258
2259 operator Matcher<FloatType&>() const {
kosak6b817802015-01-08 02:38:14 +00002260 return MakeMatcher(
2261 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002262 }
jgm79a367e2012-04-10 16:02:11 +00002263
shiqiane35fdd92008-12-10 05:08:54 +00002264 private:
kosak6b817802015-01-08 02:38:14 +00002265 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002266 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002267 // max_abs_error will be used for value comparison when >= 0.
2268 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002269
2270 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002271};
2272
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002273// A 2-tuple ("binary") wrapper around FloatingEqMatcher:
2274// FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false)
2275// against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e)
2276// against y. The former implements "Eq", the latter "Near". At present, there
2277// is no version that compares NaNs as equal.
2278template <typename FloatType>
2279class FloatingEq2Matcher {
2280 public:
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002281 FloatingEq2Matcher() { Init(-1, false); }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002282
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002283 explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002284
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002285 explicit FloatingEq2Matcher(FloatType max_abs_error) {
2286 Init(max_abs_error, false);
2287 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002288
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002289 FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) {
2290 Init(max_abs_error, nan_eq_nan);
2291 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002292
2293 template <typename T1, typename T2>
2294 operator Matcher< ::testing::tuple<T1, T2> >() const {
2295 return MakeMatcher(
2296 new Impl< ::testing::tuple<T1, T2> >(max_abs_error_, nan_eq_nan_));
2297 }
2298 template <typename T1, typename T2>
2299 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
2300 return MakeMatcher(
2301 new Impl<const ::testing::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_));
2302 }
2303
2304 private:
2305 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
2306 return os << "an almost-equal pair";
2307 }
2308
2309 template <typename Tuple>
2310 class Impl : public MatcherInterface<Tuple> {
2311 public:
2312 Impl(FloatType max_abs_error, bool nan_eq_nan) :
2313 max_abs_error_(max_abs_error),
2314 nan_eq_nan_(nan_eq_nan) {}
2315
2316 virtual bool MatchAndExplain(Tuple args,
2317 MatchResultListener* listener) const {
2318 if (max_abs_error_ == -1) {
2319 FloatingEqMatcher<FloatType> fm(::testing::get<0>(args), nan_eq_nan_);
2320 return static_cast<Matcher<FloatType> >(fm).MatchAndExplain(
2321 ::testing::get<1>(args), listener);
2322 } else {
2323 FloatingEqMatcher<FloatType> fm(::testing::get<0>(args), nan_eq_nan_,
2324 max_abs_error_);
2325 return static_cast<Matcher<FloatType> >(fm).MatchAndExplain(
2326 ::testing::get<1>(args), listener);
2327 }
2328 }
2329 virtual void DescribeTo(::std::ostream* os) const {
2330 *os << "are " << GetDesc;
2331 }
2332 virtual void DescribeNegationTo(::std::ostream* os) const {
2333 *os << "aren't " << GetDesc;
2334 }
2335
2336 private:
2337 FloatType max_abs_error_;
2338 const bool nan_eq_nan_;
2339 };
2340
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002341 void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) {
2342 max_abs_error_ = max_abs_error_val;
2343 nan_eq_nan_ = nan_eq_nan_val;
2344 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002345 FloatType max_abs_error_;
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002346 bool nan_eq_nan_;
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002347};
2348
shiqiane35fdd92008-12-10 05:08:54 +00002349// Implements the Pointee(m) matcher for matching a pointer whose
2350// pointee matches matcher m. The pointer can be either raw or smart.
2351template <typename InnerMatcher>
2352class PointeeMatcher {
2353 public:
2354 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
2355
2356 // This type conversion operator template allows Pointee(m) to be
2357 // used as a matcher for any pointer type whose pointee type is
2358 // compatible with the inner matcher, where type Pointer can be
2359 // either a raw pointer or a smart pointer.
2360 //
2361 // The reason we do this instead of relying on
2362 // MakePolymorphicMatcher() is that the latter is not flexible
2363 // enough for implementing the DescribeTo() method of Pointee().
2364 template <typename Pointer>
2365 operator Matcher<Pointer>() const {
Gennadiy Civile55089e2018-04-04 14:05:00 -04002366 return Matcher<Pointer>(
2367 new Impl<GTEST_REFERENCE_TO_CONST_(Pointer)>(matcher_));
shiqiane35fdd92008-12-10 05:08:54 +00002368 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002369
shiqiane35fdd92008-12-10 05:08:54 +00002370 private:
2371 // The monomorphic implementation that works for a particular pointer type.
2372 template <typename Pointer>
2373 class Impl : public MatcherInterface<Pointer> {
2374 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00002375 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
2376 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00002377
2378 explicit Impl(const InnerMatcher& matcher)
2379 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
2380
shiqiane35fdd92008-12-10 05:08:54 +00002381 virtual void DescribeTo(::std::ostream* os) const {
2382 *os << "points to a value that ";
2383 matcher_.DescribeTo(os);
2384 }
2385
2386 virtual void DescribeNegationTo(::std::ostream* os) const {
2387 *os << "does not point to a value that ";
2388 matcher_.DescribeTo(os);
2389 }
2390
zhanyong.wan82113312010-01-08 21:55:40 +00002391 virtual bool MatchAndExplain(Pointer pointer,
2392 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00002393 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00002394 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002395
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002396 *listener << "which points to ";
2397 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002398 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002399
shiqiane35fdd92008-12-10 05:08:54 +00002400 private:
2401 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002402
2403 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002404 };
2405
2406 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002407
2408 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002409};
2410
billydonahue1f5fdea2014-05-19 17:54:51 +00002411// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2412// reference that matches inner_matcher when dynamic_cast<T> is applied.
2413// The result of dynamic_cast<To> is forwarded to the inner matcher.
2414// If To is a pointer and the cast fails, the inner matcher will receive NULL.
2415// If To is a reference and the cast fails, this matcher returns false
2416// immediately.
2417template <typename To>
2418class WhenDynamicCastToMatcherBase {
2419 public:
2420 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2421 : matcher_(matcher) {}
2422
2423 void DescribeTo(::std::ostream* os) const {
2424 GetCastTypeDescription(os);
2425 matcher_.DescribeTo(os);
2426 }
2427
2428 void DescribeNegationTo(::std::ostream* os) const {
2429 GetCastTypeDescription(os);
2430 matcher_.DescribeNegationTo(os);
2431 }
2432
2433 protected:
2434 const Matcher<To> matcher_;
2435
Nico Weber09fd5b32017-05-15 17:07:03 -04002436 static std::string GetToName() {
billydonahue1f5fdea2014-05-19 17:54:51 +00002437#if GTEST_HAS_RTTI
2438 return GetTypeName<To>();
2439#else // GTEST_HAS_RTTI
2440 return "the target type";
2441#endif // GTEST_HAS_RTTI
2442 }
2443
2444 private:
2445 static void GetCastTypeDescription(::std::ostream* os) {
2446 *os << "when dynamic_cast to " << GetToName() << ", ";
2447 }
2448
2449 GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2450};
2451
2452// Primary template.
2453// To is a pointer. Cast and forward the result.
2454template <typename To>
2455class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2456 public:
2457 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2458 : WhenDynamicCastToMatcherBase<To>(matcher) {}
2459
2460 template <typename From>
2461 bool MatchAndExplain(From from, MatchResultListener* listener) const {
2462 // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail?
2463 To to = dynamic_cast<To>(from);
2464 return MatchPrintAndExplain(to, this->matcher_, listener);
2465 }
2466};
2467
2468// Specialize for references.
2469// In this case we return false if the dynamic_cast fails.
2470template <typename To>
2471class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2472 public:
2473 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2474 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2475
2476 template <typename From>
2477 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2478 // We don't want an std::bad_cast here, so do the cast with pointers.
2479 To* to = dynamic_cast<To*>(&from);
2480 if (to == NULL) {
2481 *listener << "which cannot be dynamic_cast to " << this->GetToName();
2482 return false;
2483 }
2484 return MatchPrintAndExplain(*to, this->matcher_, listener);
2485 }
2486};
2487
shiqiane35fdd92008-12-10 05:08:54 +00002488// Implements the Field() matcher for matching a field (i.e. member
2489// variable) of an object.
2490template <typename Class, typename FieldType>
2491class FieldMatcher {
2492 public:
2493 FieldMatcher(FieldType Class::*field,
2494 const Matcher<const FieldType&>& matcher)
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002495 : field_(field), matcher_(matcher), whose_field_("whose given field ") {}
2496
2497 FieldMatcher(const std::string& field_name, FieldType Class::*field,
2498 const Matcher<const FieldType&>& matcher)
2499 : field_(field),
2500 matcher_(matcher),
2501 whose_field_("whose field `" + field_name + "` ") {}
shiqiane35fdd92008-12-10 05:08:54 +00002502
shiqiane35fdd92008-12-10 05:08:54 +00002503 void DescribeTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002504 *os << "is an object " << whose_field_;
shiqiane35fdd92008-12-10 05:08:54 +00002505 matcher_.DescribeTo(os);
2506 }
2507
2508 void DescribeNegationTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002509 *os << "is an object " << whose_field_;
shiqiane35fdd92008-12-10 05:08:54 +00002510 matcher_.DescribeNegationTo(os);
2511 }
2512
zhanyong.wandb22c222010-01-28 21:52:29 +00002513 template <typename T>
2514 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2515 return MatchAndExplainImpl(
2516 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002517 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002518 value, listener);
2519 }
2520
2521 private:
2522 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002523 // Symbian's C++ compiler choose which overload to use. Its type is
2524 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002525 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2526 MatchResultListener* listener) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002527 *listener << whose_field_ << "is ";
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002528 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002529 }
2530
zhanyong.wandb22c222010-01-28 21:52:29 +00002531 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2532 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002533 if (p == NULL)
2534 return false;
2535
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002536 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002537 // Since *p has a field, it must be a class/struct/union type and
2538 // thus cannot be a pointer. Therefore we pass false_type() as
2539 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002540 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002541 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002542
shiqiane35fdd92008-12-10 05:08:54 +00002543 const FieldType Class::*field_;
2544 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002545
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002546 // Contains either "whose given field " if the name of the field is unknown
2547 // or "whose field `name_of_field` " if the name is known.
2548 const std::string whose_field_;
2549
zhanyong.wan32de5f52009-12-23 00:13:23 +00002550 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002551};
2552
shiqiane35fdd92008-12-10 05:08:54 +00002553// Implements the Property() matcher for matching a property
2554// (i.e. return value of a getter method) of an object.
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002555//
2556// Property is a const-qualified member function of Class returning
2557// PropertyType.
2558template <typename Class, typename PropertyType, typename Property>
shiqiane35fdd92008-12-10 05:08:54 +00002559class PropertyMatcher {
2560 public:
2561 // The property may have a reference type, so 'const PropertyType&'
2562 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00002563 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00002564 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00002565 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00002566
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002567 PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002568 : property_(property),
2569 matcher_(matcher),
2570 whose_property_("whose given property ") {}
2571
2572 PropertyMatcher(const std::string& property_name, Property property,
2573 const Matcher<RefToConstProperty>& matcher)
2574 : property_(property),
2575 matcher_(matcher),
2576 whose_property_("whose property `" + property_name + "` ") {}
shiqiane35fdd92008-12-10 05:08:54 +00002577
shiqiane35fdd92008-12-10 05:08:54 +00002578 void DescribeTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002579 *os << "is an object " << whose_property_;
shiqiane35fdd92008-12-10 05:08:54 +00002580 matcher_.DescribeTo(os);
2581 }
2582
2583 void DescribeNegationTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002584 *os << "is an object " << whose_property_;
shiqiane35fdd92008-12-10 05:08:54 +00002585 matcher_.DescribeNegationTo(os);
2586 }
2587
zhanyong.wandb22c222010-01-28 21:52:29 +00002588 template <typename T>
2589 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2590 return MatchAndExplainImpl(
2591 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002592 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002593 value, listener);
2594 }
2595
2596 private:
2597 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002598 // Symbian's C++ compiler choose which overload to use. Its type is
2599 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002600 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2601 MatchResultListener* listener) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002602 *listener << whose_property_ << "is ";
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002603 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2604 // which takes a non-const reference as argument.
kosak02d64792015-02-14 02:22:21 +00002605#if defined(_PREFAST_ ) && _MSC_VER == 1800
2606 // Workaround bug in VC++ 2013's /analyze parser.
2607 // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move
2608 posix::Abort(); // To make sure it is never run.
2609 return false;
2610#else
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002611 RefToConstProperty result = (obj.*property_)();
2612 return MatchPrintAndExplain(result, matcher_, listener);
kosak02d64792015-02-14 02:22:21 +00002613#endif
shiqiane35fdd92008-12-10 05:08:54 +00002614 }
2615
zhanyong.wandb22c222010-01-28 21:52:29 +00002616 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2617 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002618 if (p == NULL)
2619 return false;
2620
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002621 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002622 // Since *p has a property method, it must be a class/struct/union
2623 // type and thus cannot be a pointer. Therefore we pass
2624 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002625 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002626 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002627
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002628 Property property_;
shiqiane35fdd92008-12-10 05:08:54 +00002629 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002630
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002631 // Contains either "whose given property " if the name of the property is
2632 // unknown or "whose property `name_of_property` " if the name is known.
2633 const std::string whose_property_;
2634
zhanyong.wan32de5f52009-12-23 00:13:23 +00002635 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002636};
2637
shiqiane35fdd92008-12-10 05:08:54 +00002638// Type traits specifying various features of different functors for ResultOf.
2639// The default template specifies features for functor objects.
2640// Functor classes have to typedef argument_type and result_type
2641// to be compatible with ResultOf.
2642template <typename Functor>
2643struct CallableTraits {
2644 typedef typename Functor::result_type ResultType;
2645 typedef Functor StorageType;
2646
zhanyong.wan32de5f52009-12-23 00:13:23 +00002647 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00002648 template <typename T>
2649 static ResultType Invoke(Functor f, T arg) { return f(arg); }
2650};
2651
2652// Specialization for function pointers.
2653template <typename ArgType, typename ResType>
2654struct CallableTraits<ResType(*)(ArgType)> {
2655 typedef ResType ResultType;
2656 typedef ResType(*StorageType)(ArgType);
2657
2658 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002659 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00002660 << "NULL function pointer is passed into ResultOf().";
2661 }
2662 template <typename T>
2663 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2664 return (*f)(arg);
2665 }
2666};
2667
2668// Implements the ResultOf() matcher for matching a return value of a
2669// unary function of an object.
2670template <typename Callable>
2671class ResultOfMatcher {
2672 public:
2673 typedef typename CallableTraits<Callable>::ResultType ResultType;
2674
2675 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
2676 : callable_(callable), matcher_(matcher) {
2677 CallableTraits<Callable>::CheckIsValid(callable_);
2678 }
2679
2680 template <typename T>
2681 operator Matcher<T>() const {
2682 return Matcher<T>(new Impl<T>(callable_, matcher_));
2683 }
2684
2685 private:
2686 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2687
2688 template <typename T>
2689 class Impl : public MatcherInterface<T> {
2690 public:
2691 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
2692 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00002693
2694 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002695 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002696 matcher_.DescribeTo(os);
2697 }
2698
2699 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002700 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002701 matcher_.DescribeNegationTo(os);
2702 }
2703
zhanyong.wan82113312010-01-08 21:55:40 +00002704 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002705 *listener << "which is mapped by the given callable to ";
2706 // Cannot pass the return value (for example, int) to
2707 // MatchPrintAndExplain, which takes a non-const reference as argument.
2708 ResultType result =
2709 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2710 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002711 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002712
shiqiane35fdd92008-12-10 05:08:54 +00002713 private:
2714 // Functors often define operator() as non-const method even though
Troy Holsapplec8510502018-02-07 22:06:00 -08002715 // they are actually stateless. But we need to use them even when
shiqiane35fdd92008-12-10 05:08:54 +00002716 // 'this' is a const pointer. It's the user's responsibility not to
2717 // use stateful callables with ResultOf(), which does't guarantee
2718 // how many times the callable will be invoked.
2719 mutable CallableStorageType callable_;
2720 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002721
2722 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002723 }; // class Impl
2724
2725 const CallableStorageType callable_;
2726 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002727
2728 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002729};
2730
zhanyong.wana31d9ce2013-03-01 01:50:17 +00002731// Implements a matcher that checks the size of an STL-style container.
2732template <typename SizeMatcher>
2733class SizeIsMatcher {
2734 public:
2735 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2736 : size_matcher_(size_matcher) {
2737 }
2738
2739 template <typename Container>
2740 operator Matcher<Container>() const {
2741 return MakeMatcher(new Impl<Container>(size_matcher_));
2742 }
2743
2744 template <typename Container>
2745 class Impl : public MatcherInterface<Container> {
2746 public:
2747 typedef internal::StlContainerView<
2748 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2749 typedef typename ContainerView::type::size_type SizeType;
2750 explicit Impl(const SizeMatcher& size_matcher)
2751 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2752
2753 virtual void DescribeTo(::std::ostream* os) const {
2754 *os << "size ";
2755 size_matcher_.DescribeTo(os);
2756 }
2757 virtual void DescribeNegationTo(::std::ostream* os) const {
2758 *os << "size ";
2759 size_matcher_.DescribeNegationTo(os);
2760 }
2761
2762 virtual bool MatchAndExplain(Container container,
2763 MatchResultListener* listener) const {
2764 SizeType size = container.size();
2765 StringMatchResultListener size_listener;
2766 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2767 *listener
2768 << "whose size " << size << (result ? " matches" : " doesn't match");
2769 PrintIfNotEmpty(size_listener.str(), listener->stream());
2770 return result;
2771 }
2772
2773 private:
2774 const Matcher<SizeType> size_matcher_;
2775 GTEST_DISALLOW_ASSIGN_(Impl);
2776 };
2777
2778 private:
2779 const SizeMatcher size_matcher_;
2780 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2781};
2782
kosakb6a34882014-03-12 21:06:46 +00002783// Implements a matcher that checks the begin()..end() distance of an STL-style
2784// container.
2785template <typename DistanceMatcher>
2786class BeginEndDistanceIsMatcher {
2787 public:
2788 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2789 : distance_matcher_(distance_matcher) {}
2790
2791 template <typename Container>
2792 operator Matcher<Container>() const {
2793 return MakeMatcher(new Impl<Container>(distance_matcher_));
2794 }
2795
2796 template <typename Container>
2797 class Impl : public MatcherInterface<Container> {
2798 public:
2799 typedef internal::StlContainerView<
2800 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2801 typedef typename std::iterator_traits<
2802 typename ContainerView::type::const_iterator>::difference_type
2803 DistanceType;
2804 explicit Impl(const DistanceMatcher& distance_matcher)
2805 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2806
2807 virtual void DescribeTo(::std::ostream* os) const {
2808 *os << "distance between begin() and end() ";
2809 distance_matcher_.DescribeTo(os);
2810 }
2811 virtual void DescribeNegationTo(::std::ostream* os) const {
2812 *os << "distance between begin() and end() ";
2813 distance_matcher_.DescribeNegationTo(os);
2814 }
2815
2816 virtual bool MatchAndExplain(Container container,
2817 MatchResultListener* listener) const {
kosak5b9cbbb2014-11-17 00:28:55 +00002818#if GTEST_HAS_STD_BEGIN_AND_END_
kosakb6a34882014-03-12 21:06:46 +00002819 using std::begin;
2820 using std::end;
2821 DistanceType distance = std::distance(begin(container), end(container));
2822#else
2823 DistanceType distance = std::distance(container.begin(), container.end());
2824#endif
2825 StringMatchResultListener distance_listener;
2826 const bool result =
2827 distance_matcher_.MatchAndExplain(distance, &distance_listener);
2828 *listener << "whose distance between begin() and end() " << distance
2829 << (result ? " matches" : " doesn't match");
2830 PrintIfNotEmpty(distance_listener.str(), listener->stream());
2831 return result;
2832 }
2833
2834 private:
2835 const Matcher<DistanceType> distance_matcher_;
2836 GTEST_DISALLOW_ASSIGN_(Impl);
2837 };
2838
2839 private:
2840 const DistanceMatcher distance_matcher_;
2841 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2842};
2843
zhanyong.wan6a896b52009-01-16 01:13:50 +00002844// Implements an equality matcher for any STL-style container whose elements
2845// support ==. This matcher is like Eq(), but its failure explanations provide
2846// more detailed information that is useful when the container is used as a set.
2847// The failure message reports elements that are in one of the operands but not
2848// the other. The failure messages do not report duplicate or out-of-order
2849// elements in the containers (which don't properly matter to sets, but can
2850// occur if the containers are vectors or lists, for example).
2851//
2852// Uses the container's const_iterator, value_type, operator ==,
2853// begin(), and end().
2854template <typename Container>
2855class ContainerEqMatcher {
2856 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002857 typedef internal::StlContainerView<Container> View;
2858 typedef typename View::type StlContainer;
2859 typedef typename View::const_reference StlContainerReference;
2860
kosak6b817802015-01-08 02:38:14 +00002861 // We make a copy of expected in case the elements in it are modified
zhanyong.wanb8243162009-06-04 05:48:20 +00002862 // after this matcher is created.
kosak6b817802015-01-08 02:38:14 +00002863 explicit ContainerEqMatcher(const Container& expected)
2864 : expected_(View::Copy(expected)) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002865 // Makes sure the user doesn't instantiate this class template
2866 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002867 (void)testing::StaticAssertTypeEq<Container,
2868 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002869 }
2870
zhanyong.wan6a896b52009-01-16 01:13:50 +00002871 void DescribeTo(::std::ostream* os) const {
2872 *os << "equals ";
kosak6b817802015-01-08 02:38:14 +00002873 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002874 }
2875 void DescribeNegationTo(::std::ostream* os) const {
2876 *os << "does not equal ";
kosak6b817802015-01-08 02:38:14 +00002877 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002878 }
2879
zhanyong.wanb8243162009-06-04 05:48:20 +00002880 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002881 bool MatchAndExplain(const LhsContainer& lhs,
2882 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002883 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002884 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002885 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002886 LhsView;
2887 typedef typename LhsView::type LhsStlContainer;
2888 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
kosak6b817802015-01-08 02:38:14 +00002889 if (lhs_stl_container == expected_)
zhanyong.wane122e452010-01-12 09:03:52 +00002890 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002891
zhanyong.wane122e452010-01-12 09:03:52 +00002892 ::std::ostream* const os = listener->stream();
2893 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002894 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002895 bool printed_header = false;
2896 for (typename LhsStlContainer::const_iterator it =
2897 lhs_stl_container.begin();
2898 it != lhs_stl_container.end(); ++it) {
kosak6b817802015-01-08 02:38:14 +00002899 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
2900 expected_.end()) {
zhanyong.wane122e452010-01-12 09:03:52 +00002901 if (printed_header) {
2902 *os << ", ";
2903 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002904 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002905 printed_header = true;
2906 }
vladloseve2e8ba42010-05-13 18:16:03 +00002907 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002908 }
zhanyong.wane122e452010-01-12 09:03:52 +00002909 }
2910
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002911 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002912 bool printed_header2 = false;
kosak6b817802015-01-08 02:38:14 +00002913 for (typename StlContainer::const_iterator it = expected_.begin();
2914 it != expected_.end(); ++it) {
zhanyong.wane122e452010-01-12 09:03:52 +00002915 if (internal::ArrayAwareFind(
2916 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2917 lhs_stl_container.end()) {
2918 if (printed_header2) {
2919 *os << ", ";
2920 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002921 *os << (printed_header ? ",\nand" : "which")
2922 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002923 printed_header2 = true;
2924 }
vladloseve2e8ba42010-05-13 18:16:03 +00002925 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002926 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002927 }
2928 }
2929
zhanyong.wane122e452010-01-12 09:03:52 +00002930 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002931 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002932
zhanyong.wan6a896b52009-01-16 01:13:50 +00002933 private:
kosak6b817802015-01-08 02:38:14 +00002934 const StlContainer expected_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002935
2936 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002937};
2938
zhanyong.wan898725c2011-09-16 16:45:39 +00002939// A comparator functor that uses the < operator to compare two values.
2940struct LessComparator {
2941 template <typename T, typename U>
2942 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2943};
2944
2945// Implements WhenSortedBy(comparator, container_matcher).
2946template <typename Comparator, typename ContainerMatcher>
2947class WhenSortedByMatcher {
2948 public:
2949 WhenSortedByMatcher(const Comparator& comparator,
2950 const ContainerMatcher& matcher)
2951 : comparator_(comparator), matcher_(matcher) {}
2952
2953 template <typename LhsContainer>
2954 operator Matcher<LhsContainer>() const {
2955 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2956 }
2957
2958 template <typename LhsContainer>
2959 class Impl : public MatcherInterface<LhsContainer> {
2960 public:
2961 typedef internal::StlContainerView<
2962 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2963 typedef typename LhsView::type LhsStlContainer;
2964 typedef typename LhsView::const_reference LhsStlContainerReference;
zhanyong.wana9a59e02013-03-27 16:14:55 +00002965 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2966 // so that we can match associative containers.
2967 typedef typename RemoveConstFromKey<
2968 typename LhsStlContainer::value_type>::type LhsValue;
zhanyong.wan898725c2011-09-16 16:45:39 +00002969
2970 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2971 : comparator_(comparator), matcher_(matcher) {}
2972
2973 virtual void DescribeTo(::std::ostream* os) const {
2974 *os << "(when sorted) ";
2975 matcher_.DescribeTo(os);
2976 }
2977
2978 virtual void DescribeNegationTo(::std::ostream* os) const {
2979 *os << "(when sorted) ";
2980 matcher_.DescribeNegationTo(os);
2981 }
2982
2983 virtual bool MatchAndExplain(LhsContainer lhs,
2984 MatchResultListener* listener) const {
2985 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wanfb25d532013-07-28 08:24:00 +00002986 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2987 lhs_stl_container.end());
2988 ::std::sort(
2989 sorted_container.begin(), sorted_container.end(), comparator_);
zhanyong.wan898725c2011-09-16 16:45:39 +00002990
2991 if (!listener->IsInterested()) {
2992 // If the listener is not interested, we do not need to
2993 // construct the inner explanation.
2994 return matcher_.Matches(sorted_container);
2995 }
2996
2997 *listener << "which is ";
2998 UniversalPrint(sorted_container, listener->stream());
2999 *listener << " when sorted";
3000
3001 StringMatchResultListener inner_listener;
3002 const bool match = matcher_.MatchAndExplain(sorted_container,
3003 &inner_listener);
3004 PrintIfNotEmpty(inner_listener.str(), listener->stream());
3005 return match;
3006 }
3007
3008 private:
3009 const Comparator comparator_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003010 const Matcher<const ::std::vector<LhsValue>&> matcher_;
zhanyong.wan898725c2011-09-16 16:45:39 +00003011
3012 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
3013 };
3014
3015 private:
3016 const Comparator comparator_;
3017 const ContainerMatcher matcher_;
3018
3019 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
3020};
3021
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003022// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
3023// must be able to be safely cast to Matcher<tuple<const T1&, const
3024// T2&> >, where T1 and T2 are the types of elements in the LHS
3025// container and the RHS container respectively.
3026template <typename TupleMatcher, typename RhsContainer>
3027class PointwiseMatcher {
Gennadiy Civil23187052018-03-26 10:16:59 -04003028 GTEST_COMPILE_ASSERT_(
3029 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value,
3030 use_UnorderedPointwise_with_hash_tables);
3031
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003032 public:
3033 typedef internal::StlContainerView<RhsContainer> RhsView;
3034 typedef typename RhsView::type RhsStlContainer;
3035 typedef typename RhsStlContainer::value_type RhsValue;
3036
3037 // Like ContainerEq, we make a copy of rhs in case the elements in
3038 // it are modified after this matcher is created.
3039 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
3040 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
3041 // Makes sure the user doesn't instantiate this class template
3042 // with a const or reference type.
3043 (void)testing::StaticAssertTypeEq<RhsContainer,
3044 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
3045 }
3046
3047 template <typename LhsContainer>
3048 operator Matcher<LhsContainer>() const {
Gennadiy Civil23187052018-03-26 10:16:59 -04003049 GTEST_COMPILE_ASSERT_(
3050 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value,
3051 use_UnorderedPointwise_with_hash_tables);
3052
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003053 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
3054 }
3055
3056 template <typename LhsContainer>
3057 class Impl : public MatcherInterface<LhsContainer> {
3058 public:
3059 typedef internal::StlContainerView<
3060 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
3061 typedef typename LhsView::type LhsStlContainer;
3062 typedef typename LhsView::const_reference LhsStlContainerReference;
3063 typedef typename LhsStlContainer::value_type LhsValue;
3064 // We pass the LHS value and the RHS value to the inner matcher by
3065 // reference, as they may be expensive to copy. We must use tuple
3066 // instead of pair here, as a pair cannot hold references (C++ 98,
3067 // 20.2.2 [lib.pairs]).
kosakbd018832014-04-02 20:30:00 +00003068 typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003069
3070 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
3071 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
3072 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
3073 rhs_(rhs) {}
3074
3075 virtual void DescribeTo(::std::ostream* os) const {
3076 *os << "contains " << rhs_.size()
3077 << " values, where each value and its corresponding value in ";
3078 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
3079 *os << " ";
3080 mono_tuple_matcher_.DescribeTo(os);
3081 }
3082 virtual void DescribeNegationTo(::std::ostream* os) const {
3083 *os << "doesn't contain exactly " << rhs_.size()
3084 << " values, or contains a value x at some index i"
3085 << " where x and the i-th value of ";
3086 UniversalPrint(rhs_, os);
3087 *os << " ";
3088 mono_tuple_matcher_.DescribeNegationTo(os);
3089 }
3090
3091 virtual bool MatchAndExplain(LhsContainer lhs,
3092 MatchResultListener* listener) const {
3093 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
3094 const size_t actual_size = lhs_stl_container.size();
3095 if (actual_size != rhs_.size()) {
3096 *listener << "which contains " << actual_size << " values";
3097 return false;
3098 }
3099
3100 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
3101 typename RhsStlContainer::const_iterator right = rhs_.begin();
3102 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003103 if (listener->IsInterested()) {
3104 StringMatchResultListener inner_listener;
Gennadiy Civil23187052018-03-26 10:16:59 -04003105 // Create InnerMatcherArg as a temporarily object to avoid it outlives
3106 // *left and *right. Dereference or the conversion to `const T&` may
3107 // return temp objects, e.g for vector<bool>.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003108 if (!mono_tuple_matcher_.MatchAndExplain(
Gennadiy Civil23187052018-03-26 10:16:59 -04003109 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
3110 ImplicitCast_<const RhsValue&>(*right)),
3111 &inner_listener)) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003112 *listener << "where the value pair (";
3113 UniversalPrint(*left, listener->stream());
3114 *listener << ", ";
3115 UniversalPrint(*right, listener->stream());
3116 *listener << ") at index #" << i << " don't match";
3117 PrintIfNotEmpty(inner_listener.str(), listener->stream());
3118 return false;
3119 }
3120 } else {
Gennadiy Civil23187052018-03-26 10:16:59 -04003121 if (!mono_tuple_matcher_.Matches(
3122 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
3123 ImplicitCast_<const RhsValue&>(*right))))
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003124 return false;
3125 }
3126 }
3127
3128 return true;
3129 }
3130
3131 private:
3132 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
3133 const RhsStlContainer rhs_;
3134
3135 GTEST_DISALLOW_ASSIGN_(Impl);
3136 };
3137
3138 private:
3139 const TupleMatcher tuple_matcher_;
3140 const RhsStlContainer rhs_;
3141
3142 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
3143};
3144
zhanyong.wan33605ba2010-04-22 23:37:47 +00003145// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00003146template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00003147class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00003148 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003149 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00003150 typedef StlContainerView<RawContainer> View;
3151 typedef typename View::type StlContainer;
3152 typedef typename View::const_reference StlContainerReference;
3153 typedef typename StlContainer::value_type Element;
3154
3155 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00003156 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00003157 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00003158 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00003159
zhanyong.wan33605ba2010-04-22 23:37:47 +00003160 // Checks whether:
3161 // * All elements in the container match, if all_elements_should_match.
3162 // * Any element in the container matches, if !all_elements_should_match.
3163 bool MatchAndExplainImpl(bool all_elements_should_match,
3164 Container container,
3165 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00003166 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00003167 size_t i = 0;
3168 for (typename StlContainer::const_iterator it = stl_container.begin();
3169 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003170 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00003171 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
3172
3173 if (matches != all_elements_should_match) {
3174 *listener << "whose element #" << i
3175 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003176 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00003177 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00003178 }
3179 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00003180 return all_elements_should_match;
3181 }
3182
3183 protected:
3184 const Matcher<const Element&> inner_matcher_;
3185
3186 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
3187};
3188
3189// Implements Contains(element_matcher) for the given argument type Container.
3190// Symmetric to EachMatcherImpl.
3191template <typename Container>
3192class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
3193 public:
3194 template <typename InnerMatcher>
3195 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
3196 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3197
3198 // Describes what this matcher does.
3199 virtual void DescribeTo(::std::ostream* os) const {
3200 *os << "contains at least one element that ";
3201 this->inner_matcher_.DescribeTo(os);
3202 }
3203
3204 virtual void DescribeNegationTo(::std::ostream* os) const {
3205 *os << "doesn't contain any element that ";
3206 this->inner_matcher_.DescribeTo(os);
3207 }
3208
3209 virtual bool MatchAndExplain(Container container,
3210 MatchResultListener* listener) const {
3211 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00003212 }
3213
3214 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003215 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00003216};
3217
zhanyong.wan33605ba2010-04-22 23:37:47 +00003218// Implements Each(element_matcher) for the given argument type Container.
3219// Symmetric to ContainsMatcherImpl.
3220template <typename Container>
3221class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
3222 public:
3223 template <typename InnerMatcher>
3224 explicit EachMatcherImpl(InnerMatcher inner_matcher)
3225 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3226
3227 // Describes what this matcher does.
3228 virtual void DescribeTo(::std::ostream* os) const {
3229 *os << "only contains elements that ";
3230 this->inner_matcher_.DescribeTo(os);
3231 }
3232
3233 virtual void DescribeNegationTo(::std::ostream* os) const {
3234 *os << "contains some element that ";
3235 this->inner_matcher_.DescribeNegationTo(os);
3236 }
3237
3238 virtual bool MatchAndExplain(Container container,
3239 MatchResultListener* listener) const {
3240 return this->MatchAndExplainImpl(true, container, listener);
3241 }
3242
3243 private:
3244 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
3245};
3246
zhanyong.wanb8243162009-06-04 05:48:20 +00003247// Implements polymorphic Contains(element_matcher).
3248template <typename M>
3249class ContainsMatcher {
3250 public:
3251 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
3252
3253 template <typename Container>
3254 operator Matcher<Container>() const {
3255 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
3256 }
3257
3258 private:
3259 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003260
3261 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00003262};
3263
zhanyong.wan33605ba2010-04-22 23:37:47 +00003264// Implements polymorphic Each(element_matcher).
3265template <typename M>
3266class EachMatcher {
3267 public:
3268 explicit EachMatcher(M m) : inner_matcher_(m) {}
3269
3270 template <typename Container>
3271 operator Matcher<Container>() const {
3272 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
3273 }
3274
3275 private:
3276 const M inner_matcher_;
3277
3278 GTEST_DISALLOW_ASSIGN_(EachMatcher);
3279};
3280
Gennadiy Civil466a49a2018-03-23 11:23:54 -04003281struct Rank1 {};
3282struct Rank0 : Rank1 {};
3283
3284namespace pair_getters {
3285#if GTEST_LANG_CXX11
3286using std::get;
3287template <typename T>
3288auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT
3289 return get<0>(x);
3290}
3291template <typename T>
3292auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT
3293 return x.first;
3294}
3295
3296template <typename T>
3297auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT
3298 return get<1>(x);
3299}
3300template <typename T>
3301auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT
3302 return x.second;
3303}
3304#else
3305template <typename T>
3306typename T::first_type& First(T& x, Rank0) { // NOLINT
3307 return x.first;
3308}
3309template <typename T>
3310const typename T::first_type& First(const T& x, Rank0) {
3311 return x.first;
3312}
3313
3314template <typename T>
3315typename T::second_type& Second(T& x, Rank0) { // NOLINT
3316 return x.second;
3317}
3318template <typename T>
3319const typename T::second_type& Second(const T& x, Rank0) {
3320 return x.second;
3321}
3322#endif // GTEST_LANG_CXX11
3323} // namespace pair_getters
3324
zhanyong.wanb5937da2009-07-16 20:26:41 +00003325// Implements Key(inner_matcher) for the given argument pair type.
3326// Key(inner_matcher) matches an std::pair whose 'first' field matches
3327// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3328// std::map that contains at least one element whose key is >= 5.
3329template <typename PairType>
3330class KeyMatcherImpl : public MatcherInterface<PairType> {
3331 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003332 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00003333 typedef typename RawPairType::first_type KeyType;
3334
3335 template <typename InnerMatcher>
3336 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
3337 : inner_matcher_(
3338 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
3339 }
3340
3341 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00003342 virtual bool MatchAndExplain(PairType key_value,
3343 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003344 StringMatchResultListener inner_listener;
Gennadiy Civil23187052018-03-26 10:16:59 -04003345 const bool match = inner_matcher_.MatchAndExplain(
3346 pair_getters::First(key_value, Rank0()), &inner_listener);
Nico Weber09fd5b32017-05-15 17:07:03 -04003347 const std::string explanation = inner_listener.str();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003348 if (explanation != "") {
3349 *listener << "whose first field is a value " << explanation;
3350 }
3351 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00003352 }
3353
3354 // Describes what this matcher does.
3355 virtual void DescribeTo(::std::ostream* os) const {
3356 *os << "has a key that ";
3357 inner_matcher_.DescribeTo(os);
3358 }
3359
3360 // Describes what the negation of this matcher does.
3361 virtual void DescribeNegationTo(::std::ostream* os) const {
3362 *os << "doesn't have a key that ";
3363 inner_matcher_.DescribeTo(os);
3364 }
3365
zhanyong.wanb5937da2009-07-16 20:26:41 +00003366 private:
3367 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003368
3369 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00003370};
3371
3372// Implements polymorphic Key(matcher_for_key).
3373template <typename M>
3374class KeyMatcher {
3375 public:
3376 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
3377
3378 template <typename PairType>
3379 operator Matcher<PairType>() const {
3380 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
3381 }
3382
3383 private:
3384 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003385
3386 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00003387};
3388
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003389// Implements Pair(first_matcher, second_matcher) for the given argument pair
3390// type with its two matchers. See Pair() function below.
3391template <typename PairType>
3392class PairMatcherImpl : public MatcherInterface<PairType> {
3393 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003394 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003395 typedef typename RawPairType::first_type FirstType;
3396 typedef typename RawPairType::second_type SecondType;
3397
3398 template <typename FirstMatcher, typename SecondMatcher>
3399 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
3400 : first_matcher_(
3401 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
3402 second_matcher_(
3403 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
3404 }
3405
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003406 // Describes what this matcher does.
3407 virtual void DescribeTo(::std::ostream* os) const {
3408 *os << "has a first field that ";
3409 first_matcher_.DescribeTo(os);
3410 *os << ", and has a second field that ";
3411 second_matcher_.DescribeTo(os);
3412 }
3413
3414 // Describes what the negation of this matcher does.
3415 virtual void DescribeNegationTo(::std::ostream* os) const {
3416 *os << "has a first field that ";
3417 first_matcher_.DescribeNegationTo(os);
3418 *os << ", or has a second field that ";
3419 second_matcher_.DescribeNegationTo(os);
3420 }
3421
zhanyong.wan82113312010-01-08 21:55:40 +00003422 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3423 // matches second_matcher.
3424 virtual bool MatchAndExplain(PairType a_pair,
3425 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003426 if (!listener->IsInterested()) {
3427 // If the listener is not interested, we don't need to construct the
3428 // explanation.
Gennadiy Civil6aae2062018-03-26 10:36:26 -04003429 return first_matcher_.Matches(pair_getters::First(a_pair, Rank0())) &&
3430 second_matcher_.Matches(pair_getters::Second(a_pair, Rank0()));
zhanyong.wan82113312010-01-08 21:55:40 +00003431 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003432 StringMatchResultListener first_inner_listener;
Gennadiy Civil6aae2062018-03-26 10:36:26 -04003433 if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank0()),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003434 &first_inner_listener)) {
3435 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003436 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003437 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003438 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003439 StringMatchResultListener second_inner_listener;
Gennadiy Civil6aae2062018-03-26 10:36:26 -04003440 if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank0()),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003441 &second_inner_listener)) {
3442 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003443 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003444 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003445 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003446 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3447 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00003448 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003449 }
3450
3451 private:
Nico Weber09fd5b32017-05-15 17:07:03 -04003452 void ExplainSuccess(const std::string& first_explanation,
3453 const std::string& second_explanation,
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003454 MatchResultListener* listener) const {
3455 *listener << "whose both fields match";
3456 if (first_explanation != "") {
3457 *listener << ", where the first field is a value " << first_explanation;
3458 }
3459 if (second_explanation != "") {
3460 *listener << ", ";
3461 if (first_explanation != "") {
3462 *listener << "and ";
3463 } else {
3464 *listener << "where ";
3465 }
3466 *listener << "the second field is a value " << second_explanation;
3467 }
3468 }
3469
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003470 const Matcher<const FirstType&> first_matcher_;
3471 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003472
3473 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003474};
3475
3476// Implements polymorphic Pair(first_matcher, second_matcher).
3477template <typename FirstMatcher, typename SecondMatcher>
3478class PairMatcher {
3479 public:
3480 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3481 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3482
3483 template <typename PairType>
3484 operator Matcher<PairType> () const {
3485 return MakeMatcher(
3486 new PairMatcherImpl<PairType>(
3487 first_matcher_, second_matcher_));
3488 }
3489
3490 private:
3491 const FirstMatcher first_matcher_;
3492 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003493
3494 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003495};
3496
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003497// Implements ElementsAre() and ElementsAreArray().
3498template <typename Container>
3499class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3500 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003501 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003502 typedef internal::StlContainerView<RawContainer> View;
3503 typedef typename View::type StlContainer;
3504 typedef typename View::const_reference StlContainerReference;
3505 typedef typename StlContainer::value_type Element;
3506
3507 // Constructs the matcher from a sequence of element values or
3508 // element matchers.
3509 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00003510 ElementsAreMatcherImpl(InputIter first, InputIter last) {
3511 while (first != last) {
3512 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003513 }
3514 }
3515
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003516 // Describes what this matcher does.
3517 virtual void DescribeTo(::std::ostream* os) const {
3518 if (count() == 0) {
3519 *os << "is empty";
3520 } else if (count() == 1) {
3521 *os << "has 1 element that ";
3522 matchers_[0].DescribeTo(os);
3523 } else {
3524 *os << "has " << Elements(count()) << " where\n";
3525 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003526 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003527 matchers_[i].DescribeTo(os);
3528 if (i + 1 < count()) {
3529 *os << ",\n";
3530 }
3531 }
3532 }
3533 }
3534
3535 // Describes what the negation of this matcher does.
3536 virtual void DescribeNegationTo(::std::ostream* os) const {
3537 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003538 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003539 return;
3540 }
3541
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003542 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003543 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003544 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003545 matchers_[i].DescribeNegationTo(os);
3546 if (i + 1 < count()) {
3547 *os << ", or\n";
3548 }
3549 }
3550 }
3551
zhanyong.wan82113312010-01-08 21:55:40 +00003552 virtual bool MatchAndExplain(Container container,
3553 MatchResultListener* listener) const {
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003554 // To work with stream-like "containers", we must only walk
3555 // through the elements in one pass.
3556
3557 const bool listener_interested = listener->IsInterested();
3558
3559 // explanations[i] is the explanation of the element at index i.
Nico Weber09fd5b32017-05-15 17:07:03 -04003560 ::std::vector<std::string> explanations(count());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003561 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003562 typename StlContainer::const_iterator it = stl_container.begin();
3563 size_t exam_pos = 0;
3564 bool mismatch_found = false; // Have we found a mismatched element yet?
3565
3566 // Go through the elements and matchers in pairs, until we reach
3567 // the end of either the elements or the matchers, or until we find a
3568 // mismatch.
3569 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3570 bool match; // Does the current element match the current matcher?
3571 if (listener_interested) {
3572 StringMatchResultListener s;
3573 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3574 explanations[exam_pos] = s.str();
3575 } else {
3576 match = matchers_[exam_pos].Matches(*it);
3577 }
3578
3579 if (!match) {
3580 mismatch_found = true;
3581 break;
3582 }
3583 }
3584 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3585
3586 // Find how many elements the actual container has. We avoid
3587 // calling size() s.t. this code works for stream-like "containers"
3588 // that don't define size().
3589 size_t actual_count = exam_pos;
3590 for (; it != stl_container.end(); ++it) {
3591 ++actual_count;
3592 }
3593
zhanyong.wan82113312010-01-08 21:55:40 +00003594 if (actual_count != count()) {
3595 // The element count doesn't match. If the container is empty,
3596 // there's no need to explain anything as Google Mock already
3597 // prints the empty container. Otherwise we just need to show
3598 // how many elements there actually are.
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003599 if (listener_interested && (actual_count != 0)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003600 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003601 }
zhanyong.wan82113312010-01-08 21:55:40 +00003602 return false;
3603 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003604
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003605 if (mismatch_found) {
3606 // The element count matches, but the exam_pos-th element doesn't match.
3607 if (listener_interested) {
3608 *listener << "whose element #" << exam_pos << " doesn't match";
3609 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003610 }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003611 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003612 }
zhanyong.wan82113312010-01-08 21:55:40 +00003613
3614 // Every element matches its expectation. We need to explain why
3615 // (the obvious ones can be skipped).
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003616 if (listener_interested) {
3617 bool reason_printed = false;
3618 for (size_t i = 0; i != count(); ++i) {
Nico Weber09fd5b32017-05-15 17:07:03 -04003619 const std::string& s = explanations[i];
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003620 if (!s.empty()) {
3621 if (reason_printed) {
3622 *listener << ",\nand ";
3623 }
3624 *listener << "whose element #" << i << " matches, " << s;
3625 reason_printed = true;
zhanyong.wan82113312010-01-08 21:55:40 +00003626 }
zhanyong.wan82113312010-01-08 21:55:40 +00003627 }
3628 }
zhanyong.wan82113312010-01-08 21:55:40 +00003629 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003630 }
3631
3632 private:
3633 static Message Elements(size_t count) {
3634 return Message() << count << (count == 1 ? " element" : " elements");
3635 }
3636
3637 size_t count() const { return matchers_.size(); }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003638
3639 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003640
3641 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003642};
3643
zhanyong.wanfb25d532013-07-28 08:24:00 +00003644// Connectivity matrix of (elements X matchers), in element-major order.
3645// Initially, there are no edges.
3646// Use NextGraph() to iterate over all possible edge configurations.
3647// Use Randomize() to generate a random edge configuration.
3648class GTEST_API_ MatchMatrix {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003649 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003650 MatchMatrix(size_t num_elements, size_t num_matchers)
3651 : num_elements_(num_elements),
3652 num_matchers_(num_matchers),
3653 matched_(num_elements_* num_matchers_, 0) {
3654 }
3655
3656 size_t LhsSize() const { return num_elements_; }
3657 size_t RhsSize() const { return num_matchers_; }
3658 bool HasEdge(size_t ilhs, size_t irhs) const {
3659 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3660 }
3661 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3662 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3663 }
3664
3665 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3666 // adds 1 to that number; returns false if incrementing the graph left it
3667 // empty.
3668 bool NextGraph();
3669
3670 void Randomize();
3671
Nico Weber09fd5b32017-05-15 17:07:03 -04003672 std::string DebugString() const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003673
3674 private:
3675 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3676 return ilhs * num_matchers_ + irhs;
3677 }
3678
3679 size_t num_elements_;
3680 size_t num_matchers_;
3681
3682 // Each element is a char interpreted as bool. They are stored as a
3683 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3684 // a (ilhs, irhs) matrix coordinate into an offset.
3685 ::std::vector<char> matched_;
3686};
3687
3688typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3689typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3690
3691// Returns a maximum bipartite matching for the specified graph 'g'.
3692// The matching is represented as a vector of {element, matcher} pairs.
3693GTEST_API_ ElementMatcherPairs
3694FindMaxBipartiteMatching(const MatchMatrix& g);
3695
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003696struct UnorderedMatcherRequire {
3697 enum Flags {
3698 Superset = 1 << 0,
3699 Subset = 1 << 1,
3700 ExactMatch = Superset | Subset,
3701 };
3702};
zhanyong.wanfb25d532013-07-28 08:24:00 +00003703
3704// Untyped base class for implementing UnorderedElementsAre. By
3705// putting logic that's not specific to the element type here, we
3706// reduce binary bloat and increase compilation speed.
3707class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3708 protected:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003709 explicit UnorderedElementsAreMatcherImplBase(
3710 UnorderedMatcherRequire::Flags matcher_flags)
3711 : match_flags_(matcher_flags) {}
3712
zhanyong.wanfb25d532013-07-28 08:24:00 +00003713 // A vector of matcher describers, one for each element matcher.
3714 // Does not own the describers (and thus can be used only when the
3715 // element matchers are alive).
3716 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3717
3718 // Describes this UnorderedElementsAre matcher.
3719 void DescribeToImpl(::std::ostream* os) const;
3720
3721 // Describes the negation of this UnorderedElementsAre matcher.
3722 void DescribeNegationToImpl(::std::ostream* os) const;
3723
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003724 bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,
3725 const MatchMatrix& matrix,
3726 MatchResultListener* listener) const;
3727
3728 bool FindPairing(const MatchMatrix& matrix,
3729 MatchResultListener* listener) const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003730
3731 MatcherDescriberVec& matcher_describers() {
3732 return matcher_describers_;
3733 }
3734
3735 static Message Elements(size_t n) {
3736 return Message() << n << " element" << (n == 1 ? "" : "s");
3737 }
3738
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003739 UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }
3740
zhanyong.wanfb25d532013-07-28 08:24:00 +00003741 private:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003742 UnorderedMatcherRequire::Flags match_flags_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003743 MatcherDescriberVec matcher_describers_;
3744
3745 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3746};
3747
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003748// Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
3749// IsSupersetOf.
zhanyong.wanfb25d532013-07-28 08:24:00 +00003750template <typename Container>
3751class UnorderedElementsAreMatcherImpl
3752 : public MatcherInterface<Container>,
3753 public UnorderedElementsAreMatcherImplBase {
3754 public:
3755 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3756 typedef internal::StlContainerView<RawContainer> View;
3757 typedef typename View::type StlContainer;
3758 typedef typename View::const_reference StlContainerReference;
3759 typedef typename StlContainer::const_iterator StlContainerConstIterator;
3760 typedef typename StlContainer::value_type Element;
3761
zhanyong.wanfb25d532013-07-28 08:24:00 +00003762 template <typename InputIter>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003763 UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,
3764 InputIter first, InputIter last)
3765 : UnorderedElementsAreMatcherImplBase(matcher_flags) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00003766 for (; first != last; ++first) {
3767 matchers_.push_back(MatcherCast<const Element&>(*first));
3768 matcher_describers().push_back(matchers_.back().GetDescriber());
3769 }
3770 }
3771
3772 // Describes what this matcher does.
3773 virtual void DescribeTo(::std::ostream* os) const {
3774 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3775 }
3776
3777 // Describes what the negation of this matcher does.
3778 virtual void DescribeNegationTo(::std::ostream* os) const {
3779 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3780 }
3781
3782 virtual bool MatchAndExplain(Container container,
3783 MatchResultListener* listener) const {
3784 StlContainerReference stl_container = View::ConstReference(container);
Nico Weber09fd5b32017-05-15 17:07:03 -04003785 ::std::vector<std::string> element_printouts;
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003786 MatchMatrix matrix =
3787 AnalyzeElements(stl_container.begin(), stl_container.end(),
3788 &element_printouts, listener);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003789
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003790 if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00003791 return true;
3792 }
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003793
3794 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
3795 if (matrix.LhsSize() != matrix.RhsSize()) {
3796 // The element count doesn't match. If the container is empty,
3797 // there's no need to explain anything as Google Mock already
3798 // prints the empty container. Otherwise we just need to show
3799 // how many elements there actually are.
3800 if (matrix.LhsSize() != 0 && listener->IsInterested()) {
3801 *listener << "which has " << Elements(matrix.LhsSize());
3802 }
3803 return false;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003804 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003805 }
3806
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003807 return VerifyMatchMatrix(element_printouts, matrix, listener) &&
zhanyong.wanfb25d532013-07-28 08:24:00 +00003808 FindPairing(matrix, listener);
3809 }
3810
3811 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003812 template <typename ElementIter>
3813 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
Nico Weber09fd5b32017-05-15 17:07:03 -04003814 ::std::vector<std::string>* element_printouts,
zhanyong.wanfb25d532013-07-28 08:24:00 +00003815 MatchResultListener* listener) const {
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003816 element_printouts->clear();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003817 ::std::vector<char> did_match;
3818 size_t num_elements = 0;
3819 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3820 if (listener->IsInterested()) {
3821 element_printouts->push_back(PrintToString(*elem_first));
3822 }
3823 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3824 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3825 }
3826 }
3827
3828 MatchMatrix matrix(num_elements, matchers_.size());
3829 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3830 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3831 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3832 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3833 }
3834 }
3835 return matrix;
3836 }
3837
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003838 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003839
3840 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3841};
3842
3843// Functor for use in TransformTuple.
3844// Performs MatcherCast<Target> on an input argument of any type.
3845template <typename Target>
3846struct CastAndAppendTransform {
3847 template <typename Arg>
3848 Matcher<Target> operator()(const Arg& a) const {
3849 return MatcherCast<Target>(a);
3850 }
3851};
3852
3853// Implements UnorderedElementsAre.
3854template <typename MatcherTuple>
3855class UnorderedElementsAreMatcher {
3856 public:
3857 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3858 : matchers_(args) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003859
3860 template <typename Container>
3861 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003862 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003863 typedef typename internal::StlContainerView<RawContainer>::type View;
3864 typedef typename View::value_type Element;
3865 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3866 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003867 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003868 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3869 ::std::back_inserter(matchers));
3870 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003871 UnorderedMatcherRequire::ExactMatch, matchers.begin(), matchers.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003872 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003873
3874 private:
3875 const MatcherTuple matchers_;
3876 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3877};
3878
3879// Implements ElementsAre.
3880template <typename MatcherTuple>
3881class ElementsAreMatcher {
3882 public:
3883 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3884
3885 template <typename Container>
3886 operator Matcher<Container>() const {
Gennadiy Civil23187052018-03-26 10:16:59 -04003887 GTEST_COMPILE_ASSERT_(
3888 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value ||
3889 ::testing::tuple_size<MatcherTuple>::value < 2,
3890 use_UnorderedElementsAre_with_hash_tables);
3891
zhanyong.wanfb25d532013-07-28 08:24:00 +00003892 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3893 typedef typename internal::StlContainerView<RawContainer>::type View;
3894 typedef typename View::value_type Element;
3895 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3896 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003897 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003898 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3899 ::std::back_inserter(matchers));
3900 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3901 matchers.begin(), matchers.end()));
3902 }
3903
3904 private:
3905 const MatcherTuple matchers_;
3906 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3907};
3908
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003909// Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
zhanyong.wanfb25d532013-07-28 08:24:00 +00003910template <typename T>
3911class UnorderedElementsAreArrayMatcher {
3912 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003913 template <typename Iter>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003914 UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,
3915 Iter first, Iter last)
3916 : match_flags_(match_flags), matchers_(first, last) {}
zhanyong.wanfb25d532013-07-28 08:24:00 +00003917
3918 template <typename Container>
3919 operator Matcher<Container>() const {
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003920 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3921 match_flags_, matchers_.begin(), matchers_.end()));
zhanyong.wanfb25d532013-07-28 08:24:00 +00003922 }
3923
3924 private:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003925 UnorderedMatcherRequire::Flags match_flags_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003926 ::std::vector<T> matchers_;
3927
3928 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003929};
3930
3931// Implements ElementsAreArray().
3932template <typename T>
3933class ElementsAreArrayMatcher {
3934 public:
jgm38513a82012-11-15 15:50:36 +00003935 template <typename Iter>
3936 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003937
3938 template <typename Container>
3939 operator Matcher<Container>() const {
Gennadiy Civil23187052018-03-26 10:16:59 -04003940 GTEST_COMPILE_ASSERT_(
3941 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value,
3942 use_UnorderedElementsAreArray_with_hash_tables);
3943
jgm38513a82012-11-15 15:50:36 +00003944 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3945 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003946 }
3947
3948 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003949 const ::std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003950
3951 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003952};
3953
kosak2336e9c2014-07-28 22:57:30 +00003954// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3955// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3956// second) is a polymorphic matcher that matches a value x iff tm
3957// matches tuple (x, second). Useful for implementing
3958// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3959//
3960// BoundSecondMatcher is copyable and assignable, as we need to put
3961// instances of this class in a vector when implementing
3962// UnorderedPointwise().
3963template <typename Tuple2Matcher, typename Second>
3964class BoundSecondMatcher {
3965 public:
3966 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3967 : tuple2_matcher_(tm), second_value_(second) {}
3968
3969 template <typename T>
3970 operator Matcher<T>() const {
3971 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3972 }
3973
3974 // We have to define this for UnorderedPointwise() to compile in
3975 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3976 // which requires the elements to be assignable in C++98. The
3977 // compiler cannot generate the operator= for us, as Tuple2Matcher
3978 // and Second may not be assignable.
3979 //
3980 // However, this should never be called, so the implementation just
3981 // need to assert.
3982 void operator=(const BoundSecondMatcher& /*rhs*/) {
3983 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3984 }
3985
3986 private:
3987 template <typename T>
3988 class Impl : public MatcherInterface<T> {
3989 public:
3990 typedef ::testing::tuple<T, Second> ArgTuple;
3991
3992 Impl(const Tuple2Matcher& tm, const Second& second)
3993 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3994 second_value_(second) {}
3995
3996 virtual void DescribeTo(::std::ostream* os) const {
3997 *os << "and ";
3998 UniversalPrint(second_value_, os);
3999 *os << " ";
4000 mono_tuple2_matcher_.DescribeTo(os);
4001 }
4002
4003 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
4004 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
4005 listener);
4006 }
4007
4008 private:
4009 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
4010 const Second second_value_;
4011
4012 GTEST_DISALLOW_ASSIGN_(Impl);
4013 };
4014
4015 const Tuple2Matcher tuple2_matcher_;
4016 const Second second_value_;
4017};
4018
4019// Given a 2-tuple matcher tm and a value second,
4020// MatcherBindSecond(tm, second) returns a matcher that matches a
4021// value x iff tm matches tuple (x, second). Useful for implementing
4022// UnorderedPointwise() in terms of UnorderedElementsAreArray().
4023template <typename Tuple2Matcher, typename Second>
4024BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
4025 const Tuple2Matcher& tm, const Second& second) {
4026 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
4027}
4028
zhanyong.wanb4140802010-06-08 22:53:57 +00004029// Returns the description for a matcher defined using the MATCHER*()
4030// macro where the user-supplied description string is "", if
4031// 'negation' is false; otherwise returns the description of the
4032// negation of the matcher. 'param_values' contains a list of strings
4033// that are the print-out of the matcher's parameters.
Nico Weber09fd5b32017-05-15 17:07:03 -04004034GTEST_API_ std::string FormatMatcherDescription(bool negation,
4035 const char* matcher_name,
4036 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00004037
Gennadiy Civilb907c262018-03-23 11:42:41 -04004038// Implements a matcher that checks the value of a optional<> type variable.
4039template <typename ValueMatcher>
4040class OptionalMatcher {
4041 public:
4042 explicit OptionalMatcher(const ValueMatcher& value_matcher)
4043 : value_matcher_(value_matcher) {}
4044
4045 template <typename Optional>
4046 operator Matcher<Optional>() const {
4047 return MakeMatcher(new Impl<Optional>(value_matcher_));
4048 }
4049
4050 template <typename Optional>
4051 class Impl : public MatcherInterface<Optional> {
4052 public:
4053 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView;
4054 typedef typename OptionalView::value_type ValueType;
4055 explicit Impl(const ValueMatcher& value_matcher)
4056 : value_matcher_(MatcherCast<ValueType>(value_matcher)) {}
4057
4058 virtual void DescribeTo(::std::ostream* os) const {
4059 *os << "value ";
4060 value_matcher_.DescribeTo(os);
4061 }
4062
4063 virtual void DescribeNegationTo(::std::ostream* os) const {
4064 *os << "value ";
4065 value_matcher_.DescribeNegationTo(os);
4066 }
4067
4068 virtual bool MatchAndExplain(Optional optional,
4069 MatchResultListener* listener) const {
4070 if (!optional) {
4071 *listener << "which is not engaged";
4072 return false;
4073 }
4074 const ValueType& value = *optional;
4075 StringMatchResultListener value_listener;
4076 const bool match = value_matcher_.MatchAndExplain(value, &value_listener);
4077 *listener << "whose value " << PrintToString(value)
4078 << (match ? " matches" : " doesn't match");
4079 PrintIfNotEmpty(value_listener.str(), listener->stream());
4080 return match;
4081 }
4082
4083 private:
4084 const Matcher<ValueType> value_matcher_;
4085 GTEST_DISALLOW_ASSIGN_(Impl);
4086 };
4087
4088 private:
4089 const ValueMatcher value_matcher_;
4090 GTEST_DISALLOW_ASSIGN_(OptionalMatcher);
4091};
4092
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05004093namespace variant_matcher {
4094// Overloads to allow VariantMatcher to do proper ADL lookup.
4095template <typename T>
4096void holds_alternative() {}
4097template <typename T>
4098void get() {}
4099
4100// Implements a matcher that checks the value of a variant<> type variable.
4101template <typename T>
4102class VariantMatcher {
4103 public:
4104 explicit VariantMatcher(::testing::Matcher<const T&> matcher)
4105 : matcher_(internal::move(matcher)) {}
4106
4107 template <typename Variant>
4108 bool MatchAndExplain(const Variant& value,
4109 ::testing::MatchResultListener* listener) const {
4110 if (!listener->IsInterested()) {
4111 return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));
4112 }
4113
4114 if (!holds_alternative<T>(value)) {
4115 *listener << "whose value is not of type '" << GetTypeName() << "'";
4116 return false;
4117 }
4118
4119 const T& elem = get<T>(value);
4120 StringMatchResultListener elem_listener;
4121 const bool match = matcher_.MatchAndExplain(elem, &elem_listener);
4122 *listener << "whose value " << PrintToString(elem)
4123 << (match ? " matches" : " doesn't match");
4124 PrintIfNotEmpty(elem_listener.str(), listener->stream());
4125 return match;
4126 }
4127
4128 void DescribeTo(std::ostream* os) const {
4129 *os << "is a variant<> with value of type '" << GetTypeName()
4130 << "' and the value ";
4131 matcher_.DescribeTo(os);
4132 }
4133
4134 void DescribeNegationTo(std::ostream* os) const {
4135 *os << "is a variant<> with value of type other than '" << GetTypeName()
4136 << "' or the value ";
4137 matcher_.DescribeNegationTo(os);
4138 }
4139
4140 private:
Gennadiy Civil23187052018-03-26 10:16:59 -04004141 static std::string GetTypeName() {
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05004142#if GTEST_HAS_RTTI
Gennadiy Civilab84d142018-04-11 15:24:04 -04004143 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
4144 return internal::GetTypeName<T>());
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05004145#endif
4146 return "the element type";
4147 }
4148
4149 const ::testing::Matcher<const T&> matcher_;
4150};
4151
4152} // namespace variant_matcher
4153
Gennadiy Civil466a49a2018-03-23 11:23:54 -04004154namespace any_cast_matcher {
4155
4156// Overloads to allow AnyCastMatcher to do proper ADL lookup.
4157template <typename T>
4158void any_cast() {}
4159
4160// Implements a matcher that any_casts the value.
4161template <typename T>
4162class AnyCastMatcher {
4163 public:
4164 explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher)
4165 : matcher_(matcher) {}
4166
4167 template <typename AnyType>
4168 bool MatchAndExplain(const AnyType& value,
4169 ::testing::MatchResultListener* listener) const {
4170 if (!listener->IsInterested()) {
4171 const T* ptr = any_cast<T>(&value);
4172 return ptr != NULL && matcher_.Matches(*ptr);
4173 }
4174
4175 const T* elem = any_cast<T>(&value);
4176 if (elem == NULL) {
4177 *listener << "whose value is not of type '" << GetTypeName() << "'";
4178 return false;
4179 }
4180
4181 StringMatchResultListener elem_listener;
4182 const bool match = matcher_.MatchAndExplain(*elem, &elem_listener);
4183 *listener << "whose value " << PrintToString(*elem)
4184 << (match ? " matches" : " doesn't match");
4185 PrintIfNotEmpty(elem_listener.str(), listener->stream());
4186 return match;
4187 }
4188
4189 void DescribeTo(std::ostream* os) const {
4190 *os << "is an 'any' type with value of type '" << GetTypeName()
4191 << "' and the value ";
4192 matcher_.DescribeTo(os);
4193 }
4194
4195 void DescribeNegationTo(std::ostream* os) const {
4196 *os << "is an 'any' type with value of type other than '" << GetTypeName()
4197 << "' or the value ";
4198 matcher_.DescribeNegationTo(os);
4199 }
4200
4201 private:
4202 static std::string GetTypeName() {
4203#if GTEST_HAS_RTTI
Gennadiy Civilab84d142018-04-11 15:24:04 -04004204 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
4205 return internal::GetTypeName<T>());
Gennadiy Civil466a49a2018-03-23 11:23:54 -04004206#endif
4207 return "the element type";
4208 }
4209
4210 const ::testing::Matcher<const T&> matcher_;
4211};
4212
4213} // namespace any_cast_matcher
shiqiane35fdd92008-12-10 05:08:54 +00004214} // namespace internal
4215
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004216// ElementsAreArray(iterator_first, iterator_last)
zhanyong.wanfb25d532013-07-28 08:24:00 +00004217// ElementsAreArray(pointer, count)
4218// ElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00004219// ElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004220// ElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00004221//
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004222// The ElementsAreArray() functions are like ElementsAre(...), except
4223// that they are given a homogeneous sequence rather than taking each
4224// element as a function argument. The sequence can be specified as an
4225// array, a pointer and count, a vector, an initializer list, or an
4226// STL iterator range. In each of these cases, the underlying sequence
4227// can be either a sequence of values or a sequence of matchers.
zhanyong.wanfb25d532013-07-28 08:24:00 +00004228//
4229// All forms of ElementsAreArray() make a copy of the input matcher sequence.
4230
4231template <typename Iter>
4232inline internal::ElementsAreArrayMatcher<
4233 typename ::std::iterator_traits<Iter>::value_type>
4234ElementsAreArray(Iter first, Iter last) {
4235 typedef typename ::std::iterator_traits<Iter>::value_type T;
4236 return internal::ElementsAreArrayMatcher<T>(first, last);
4237}
4238
4239template <typename T>
4240inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
4241 const T* pointer, size_t count) {
4242 return ElementsAreArray(pointer, pointer + count);
4243}
4244
4245template <typename T, size_t N>
4246inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
4247 const T (&array)[N]) {
4248 return ElementsAreArray(array, N);
4249}
4250
kosak06678922014-07-28 20:01:28 +00004251template <typename Container>
4252inline internal::ElementsAreArrayMatcher<typename Container::value_type>
4253ElementsAreArray(const Container& container) {
4254 return ElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00004255}
4256
kosak18489fa2013-12-04 23:49:07 +00004257#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004258template <typename T>
4259inline internal::ElementsAreArrayMatcher<T>
4260ElementsAreArray(::std::initializer_list<T> xs) {
4261 return ElementsAreArray(xs.begin(), xs.end());
4262}
4263#endif
4264
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004265// UnorderedElementsAreArray(iterator_first, iterator_last)
zhanyong.wanfb25d532013-07-28 08:24:00 +00004266// UnorderedElementsAreArray(pointer, count)
4267// UnorderedElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00004268// UnorderedElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004269// UnorderedElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00004270//
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004271// UnorderedElementsAreArray() verifies that a bijective mapping onto a
4272// collection of matchers exists.
4273//
4274// The matchers can be specified as an array, a pointer and count, a container,
4275// an initializer list, or an STL iterator range. In each of these cases, the
4276// underlying matchers can be either values or matchers.
4277
zhanyong.wanfb25d532013-07-28 08:24:00 +00004278template <typename Iter>
4279inline internal::UnorderedElementsAreArrayMatcher<
4280 typename ::std::iterator_traits<Iter>::value_type>
4281UnorderedElementsAreArray(Iter first, Iter last) {
4282 typedef typename ::std::iterator_traits<Iter>::value_type T;
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004283 return internal::UnorderedElementsAreArrayMatcher<T>(
4284 internal::UnorderedMatcherRequire::ExactMatch, first, last);
zhanyong.wanfb25d532013-07-28 08:24:00 +00004285}
4286
4287template <typename T>
4288inline internal::UnorderedElementsAreArrayMatcher<T>
4289UnorderedElementsAreArray(const T* pointer, size_t count) {
4290 return UnorderedElementsAreArray(pointer, pointer + count);
4291}
4292
4293template <typename T, size_t N>
4294inline internal::UnorderedElementsAreArrayMatcher<T>
4295UnorderedElementsAreArray(const T (&array)[N]) {
4296 return UnorderedElementsAreArray(array, N);
4297}
4298
kosak06678922014-07-28 20:01:28 +00004299template <typename Container>
4300inline internal::UnorderedElementsAreArrayMatcher<
4301 typename Container::value_type>
4302UnorderedElementsAreArray(const Container& container) {
4303 return UnorderedElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00004304}
4305
kosak18489fa2013-12-04 23:49:07 +00004306#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004307template <typename T>
4308inline internal::UnorderedElementsAreArrayMatcher<T>
4309UnorderedElementsAreArray(::std::initializer_list<T> xs) {
4310 return UnorderedElementsAreArray(xs.begin(), xs.end());
4311}
4312#endif
zhanyong.wanfb25d532013-07-28 08:24:00 +00004313
shiqiane35fdd92008-12-10 05:08:54 +00004314// _ is a matcher that matches anything of any type.
4315//
4316// This definition is fine as:
4317//
4318// 1. The C++ standard permits using the name _ in a namespace that
4319// is not the global namespace or ::std.
4320// 2. The AnythingMatcher class has no data member or constructor,
4321// so it's OK to create global variables of this type.
4322// 3. c-style has approved of using _ in this case.
4323const internal::AnythingMatcher _ = {};
4324// Creates a matcher that matches any value of the given type T.
4325template <typename T>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004326inline Matcher<T> A() {
4327 return Matcher<T>(new internal::AnyMatcherImpl<T>());
4328}
shiqiane35fdd92008-12-10 05:08:54 +00004329
4330// Creates a matcher that matches any value of the given type T.
4331template <typename T>
4332inline Matcher<T> An() { return A<T>(); }
4333
4334// Creates a polymorphic matcher that matches anything equal to x.
4335// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
4336// wouldn't compile.
4337template <typename T>
4338inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
4339
4340// Constructs a Matcher<T> from a 'value' of type T. The constructed
4341// matcher matches any value that's equal to 'value'.
4342template <typename T>
4343Matcher<T>::Matcher(T value) { *this = Eq(value); }
4344
Gennadiy Civil466a49a2018-03-23 11:23:54 -04004345template <typename T, typename M>
4346Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(
4347 const M& value,
4348 internal::BooleanConstant<false> /* convertible_to_matcher */,
4349 internal::BooleanConstant<false> /* convertible_to_T */) {
4350 return Eq(value);
4351}
4352
shiqiane35fdd92008-12-10 05:08:54 +00004353// Creates a monomorphic matcher that matches anything with type Lhs
4354// and equal to rhs. A user may need to use this instead of Eq(...)
4355// in order to resolve an overloading ambiguity.
4356//
4357// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
4358// or Matcher<T>(x), but more readable than the latter.
4359//
4360// We could define similar monomorphic matchers for other comparison
4361// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
4362// it yet as those are used much less than Eq() in practice. A user
4363// can always write Matcher<T>(Lt(5)) to be explicit about the type,
4364// for example.
4365template <typename Lhs, typename Rhs>
4366inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
4367
4368// Creates a polymorphic matcher that matches anything >= x.
4369template <typename Rhs>
4370inline internal::GeMatcher<Rhs> Ge(Rhs x) {
4371 return internal::GeMatcher<Rhs>(x);
4372}
4373
4374// Creates a polymorphic matcher that matches anything > x.
4375template <typename Rhs>
4376inline internal::GtMatcher<Rhs> Gt(Rhs x) {
4377 return internal::GtMatcher<Rhs>(x);
4378}
4379
4380// Creates a polymorphic matcher that matches anything <= x.
4381template <typename Rhs>
4382inline internal::LeMatcher<Rhs> Le(Rhs x) {
4383 return internal::LeMatcher<Rhs>(x);
4384}
4385
4386// Creates a polymorphic matcher that matches anything < x.
4387template <typename Rhs>
4388inline internal::LtMatcher<Rhs> Lt(Rhs x) {
4389 return internal::LtMatcher<Rhs>(x);
4390}
4391
4392// Creates a polymorphic matcher that matches anything != x.
4393template <typename Rhs>
4394inline internal::NeMatcher<Rhs> Ne(Rhs x) {
4395 return internal::NeMatcher<Rhs>(x);
4396}
4397
zhanyong.wan2d970ee2009-09-24 21:41:36 +00004398// Creates a polymorphic matcher that matches any NULL pointer.
4399inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
4400 return MakePolymorphicMatcher(internal::IsNullMatcher());
4401}
4402
shiqiane35fdd92008-12-10 05:08:54 +00004403// Creates a polymorphic matcher that matches any non-NULL pointer.
4404// This is convenient as Not(NULL) doesn't compile (the compiler
4405// thinks that that expression is comparing a pointer with an integer).
4406inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
4407 return MakePolymorphicMatcher(internal::NotNullMatcher());
4408}
4409
4410// Creates a polymorphic matcher that matches any argument that
4411// references variable x.
4412template <typename T>
4413inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
4414 return internal::RefMatcher<T&>(x);
4415}
4416
4417// Creates a matcher that matches any double argument approximately
4418// equal to rhs, where two NANs are considered unequal.
4419inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
4420 return internal::FloatingEqMatcher<double>(rhs, false);
4421}
4422
4423// Creates a matcher that matches any double argument approximately
4424// equal to rhs, including NaN values when rhs is NaN.
4425inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
4426 return internal::FloatingEqMatcher<double>(rhs, true);
4427}
4428
zhanyong.wan616180e2013-06-18 18:49:51 +00004429// Creates a matcher that matches any double argument approximately equal to
4430// rhs, up to the specified max absolute error bound, where two NANs are
4431// considered unequal. The max absolute error bound must be non-negative.
4432inline internal::FloatingEqMatcher<double> DoubleNear(
4433 double rhs, double max_abs_error) {
4434 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
4435}
4436
4437// Creates a matcher that matches any double argument approximately equal to
4438// rhs, up to the specified max absolute error bound, including NaN values when
4439// rhs is NaN. The max absolute error bound must be non-negative.
4440inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
4441 double rhs, double max_abs_error) {
4442 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
4443}
4444
shiqiane35fdd92008-12-10 05:08:54 +00004445// Creates a matcher that matches any float argument approximately
4446// equal to rhs, where two NANs are considered unequal.
4447inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
4448 return internal::FloatingEqMatcher<float>(rhs, false);
4449}
4450
zhanyong.wan616180e2013-06-18 18:49:51 +00004451// Creates a matcher that matches any float argument approximately
shiqiane35fdd92008-12-10 05:08:54 +00004452// equal to rhs, including NaN values when rhs is NaN.
4453inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
4454 return internal::FloatingEqMatcher<float>(rhs, true);
4455}
4456
zhanyong.wan616180e2013-06-18 18:49:51 +00004457// Creates a matcher that matches any float argument approximately equal to
4458// rhs, up to the specified max absolute error bound, where two NANs are
4459// considered unequal. The max absolute error bound must be non-negative.
4460inline internal::FloatingEqMatcher<float> FloatNear(
4461 float rhs, float max_abs_error) {
4462 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
4463}
4464
4465// Creates a matcher that matches any float argument approximately equal to
4466// rhs, up to the specified max absolute error bound, including NaN values when
4467// rhs is NaN. The max absolute error bound must be non-negative.
4468inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
4469 float rhs, float max_abs_error) {
4470 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
4471}
4472
shiqiane35fdd92008-12-10 05:08:54 +00004473// Creates a matcher that matches a pointer (raw or smart) that points
4474// to a value that matches inner_matcher.
4475template <typename InnerMatcher>
4476inline internal::PointeeMatcher<InnerMatcher> Pointee(
4477 const InnerMatcher& inner_matcher) {
4478 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
4479}
4480
billydonahue1f5fdea2014-05-19 17:54:51 +00004481// Creates a matcher that matches a pointer or reference that matches
4482// inner_matcher when dynamic_cast<To> is applied.
4483// The result of dynamic_cast<To> is forwarded to the inner matcher.
4484// If To is a pointer and the cast fails, the inner matcher will receive NULL.
4485// If To is a reference and the cast fails, this matcher returns false
4486// immediately.
4487template <typename To>
4488inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
4489WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
4490 return MakePolymorphicMatcher(
4491 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
4492}
4493
shiqiane35fdd92008-12-10 05:08:54 +00004494// Creates a matcher that matches an object whose given field matches
4495// 'matcher'. For example,
4496// Field(&Foo::number, Ge(5))
4497// matches a Foo object x iff x.number >= 5.
4498template <typename Class, typename FieldType, typename FieldMatcher>
4499inline PolymorphicMatcher<
4500 internal::FieldMatcher<Class, FieldType> > Field(
4501 FieldType Class::*field, const FieldMatcher& matcher) {
4502 return MakePolymorphicMatcher(
4503 internal::FieldMatcher<Class, FieldType>(
4504 field, MatcherCast<const FieldType&>(matcher)));
4505 // The call to MatcherCast() is required for supporting inner
4506 // matchers of compatible types. For example, it allows
4507 // Field(&Foo::bar, m)
4508 // to compile where bar is an int32 and m is a matcher for int64.
4509}
4510
Gennadiy Civilb907c262018-03-23 11:42:41 -04004511// Same as Field() but also takes the name of the field to provide better error
4512// messages.
4513template <typename Class, typename FieldType, typename FieldMatcher>
4514inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType> > Field(
4515 const std::string& field_name, FieldType Class::*field,
4516 const FieldMatcher& matcher) {
4517 return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(
4518 field_name, field, MatcherCast<const FieldType&>(matcher)));
4519}
4520
shiqiane35fdd92008-12-10 05:08:54 +00004521// Creates a matcher that matches an object whose given property
4522// matches 'matcher'. For example,
4523// Property(&Foo::str, StartsWith("hi"))
4524// matches a Foo object x iff x.str() starts with "hi".
4525template <typename Class, typename PropertyType, typename PropertyMatcher>
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004526inline PolymorphicMatcher<internal::PropertyMatcher<
4527 Class, PropertyType, PropertyType (Class::*)() const> >
4528Property(PropertyType (Class::*property)() const,
4529 const PropertyMatcher& matcher) {
shiqiane35fdd92008-12-10 05:08:54 +00004530 return MakePolymorphicMatcher(
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004531 internal::PropertyMatcher<Class, PropertyType,
4532 PropertyType (Class::*)() const>(
shiqiane35fdd92008-12-10 05:08:54 +00004533 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00004534 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00004535 // The call to MatcherCast() is required for supporting inner
4536 // matchers of compatible types. For example, it allows
4537 // Property(&Foo::bar, m)
4538 // to compile where bar() returns an int32 and m is a matcher for int64.
4539}
4540
Gennadiy Civil23187052018-03-26 10:16:59 -04004541// Same as Property() above, but also takes the name of the property to provide
4542// better error messages.
4543template <typename Class, typename PropertyType, typename PropertyMatcher>
4544inline PolymorphicMatcher<internal::PropertyMatcher<
4545 Class, PropertyType, PropertyType (Class::*)() const> >
4546Property(const std::string& property_name,
4547 PropertyType (Class::*property)() const,
4548 const PropertyMatcher& matcher) {
4549 return MakePolymorphicMatcher(
4550 internal::PropertyMatcher<Class, PropertyType,
4551 PropertyType (Class::*)() const>(
4552 property_name, property,
4553 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4554}
4555
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004556#if GTEST_LANG_CXX11
4557// The same as above but for reference-qualified member functions.
4558template <typename Class, typename PropertyType, typename PropertyMatcher>
4559inline PolymorphicMatcher<internal::PropertyMatcher<
4560 Class, PropertyType, PropertyType (Class::*)() const &> >
4561Property(PropertyType (Class::*property)() const &,
4562 const PropertyMatcher& matcher) {
4563 return MakePolymorphicMatcher(
4564 internal::PropertyMatcher<Class, PropertyType,
4565 PropertyType (Class::*)() const &>(
4566 property,
4567 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4568}
4569#endif
4570
shiqiane35fdd92008-12-10 05:08:54 +00004571// Creates a matcher that matches an object iff the result of applying
4572// a callable to x matches 'matcher'.
4573// For example,
4574// ResultOf(f, StartsWith("hi"))
4575// matches a Foo object x iff f(x) starts with "hi".
4576// callable parameter can be a function, function pointer, or a functor.
4577// Callable has to satisfy the following conditions:
4578// * It is required to keep no state affecting the results of
4579// the calls on it and make no assumptions about how many calls
4580// will be made. Any state it keeps must be protected from the
4581// concurrent access.
4582// * If it is a function object, it has to define type result_type.
4583// We recommend deriving your functor classes from std::unary_function.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004584//
shiqiane35fdd92008-12-10 05:08:54 +00004585template <typename Callable, typename ResultOfMatcher>
4586internal::ResultOfMatcher<Callable> ResultOf(
4587 Callable callable, const ResultOfMatcher& matcher) {
4588 return internal::ResultOfMatcher<Callable>(
4589 callable,
4590 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
4591 matcher));
4592 // The call to MatcherCast() is required for supporting inner
4593 // matchers of compatible types. For example, it allows
4594 // ResultOf(Function, m)
4595 // to compile where Function() returns an int32 and m is a matcher for int64.
4596}
4597
4598// String matchers.
4599
4600// Matches a string equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04004601inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
4602 const std::string& str) {
4603 return MakePolymorphicMatcher(
4604 internal::StrEqualityMatcher<std::string>(str, true, true));
shiqiane35fdd92008-12-10 05:08:54 +00004605}
4606
4607// Matches a string not equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04004608inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
4609 const std::string& str) {
4610 return MakePolymorphicMatcher(
4611 internal::StrEqualityMatcher<std::string>(str, false, true));
shiqiane35fdd92008-12-10 05:08:54 +00004612}
4613
4614// Matches a string equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04004615inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
4616 const std::string& str) {
4617 return MakePolymorphicMatcher(
4618 internal::StrEqualityMatcher<std::string>(str, true, false));
shiqiane35fdd92008-12-10 05:08:54 +00004619}
4620
4621// Matches a string not equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04004622inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
4623 const std::string& str) {
4624 return MakePolymorphicMatcher(
4625 internal::StrEqualityMatcher<std::string>(str, false, false));
shiqiane35fdd92008-12-10 05:08:54 +00004626}
4627
4628// Creates a matcher that matches any string, std::string, or C string
4629// that contains the given substring.
Nico Weber09fd5b32017-05-15 17:07:03 -04004630inline PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
4631 const std::string& substring) {
4632 return MakePolymorphicMatcher(
4633 internal::HasSubstrMatcher<std::string>(substring));
shiqiane35fdd92008-12-10 05:08:54 +00004634}
4635
4636// Matches a string that starts with 'prefix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004637inline PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
4638 const std::string& prefix) {
4639 return MakePolymorphicMatcher(
4640 internal::StartsWithMatcher<std::string>(prefix));
shiqiane35fdd92008-12-10 05:08:54 +00004641}
4642
4643// Matches a string that ends with 'suffix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004644inline PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
4645 const std::string& suffix) {
4646 return MakePolymorphicMatcher(internal::EndsWithMatcher<std::string>(suffix));
shiqiane35fdd92008-12-10 05:08:54 +00004647}
4648
shiqiane35fdd92008-12-10 05:08:54 +00004649// Matches a string that fully matches regular expression 'regex'.
4650// The matcher takes ownership of 'regex'.
4651inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4652 const internal::RE* regex) {
4653 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
4654}
4655inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004656 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004657 return MatchesRegex(new internal::RE(regex));
4658}
4659
4660// Matches a string that contains regular expression 'regex'.
4661// The matcher takes ownership of 'regex'.
4662inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4663 const internal::RE* regex) {
4664 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4665}
4666inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004667 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004668 return ContainsRegex(new internal::RE(regex));
4669}
4670
shiqiane35fdd92008-12-10 05:08:54 +00004671#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4672// Wide string matchers.
4673
4674// Matches a string equal to str.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004675inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrEq(
4676 const std::wstring& str) {
4677 return MakePolymorphicMatcher(
4678 internal::StrEqualityMatcher<std::wstring>(str, true, true));
shiqiane35fdd92008-12-10 05:08:54 +00004679}
4680
4681// Matches a string not equal to str.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004682inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrNe(
4683 const std::wstring& str) {
4684 return MakePolymorphicMatcher(
4685 internal::StrEqualityMatcher<std::wstring>(str, false, true));
shiqiane35fdd92008-12-10 05:08:54 +00004686}
4687
4688// Matches a string equal to str, ignoring case.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004689inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
4690StrCaseEq(const std::wstring& str) {
4691 return MakePolymorphicMatcher(
4692 internal::StrEqualityMatcher<std::wstring>(str, true, false));
shiqiane35fdd92008-12-10 05:08:54 +00004693}
4694
4695// Matches a string not equal to str, ignoring case.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004696inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
4697StrCaseNe(const std::wstring& str) {
4698 return MakePolymorphicMatcher(
4699 internal::StrEqualityMatcher<std::wstring>(str, false, false));
shiqiane35fdd92008-12-10 05:08:54 +00004700}
4701
Gennadiy Civilb907c262018-03-23 11:42:41 -04004702// Creates a matcher that matches any ::wstring, std::wstring, or C wide string
shiqiane35fdd92008-12-10 05:08:54 +00004703// that contains the given substring.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004704inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring> > HasSubstr(
4705 const std::wstring& substring) {
4706 return MakePolymorphicMatcher(
4707 internal::HasSubstrMatcher<std::wstring>(substring));
shiqiane35fdd92008-12-10 05:08:54 +00004708}
4709
4710// Matches a string that starts with 'prefix' (case-sensitive).
Gennadiy Civilb907c262018-03-23 11:42:41 -04004711inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring> >
4712StartsWith(const std::wstring& prefix) {
4713 return MakePolymorphicMatcher(
4714 internal::StartsWithMatcher<std::wstring>(prefix));
shiqiane35fdd92008-12-10 05:08:54 +00004715}
4716
4717// Matches a string that ends with 'suffix' (case-sensitive).
Gennadiy Civilb907c262018-03-23 11:42:41 -04004718inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring> > EndsWith(
4719 const std::wstring& suffix) {
4720 return MakePolymorphicMatcher(
4721 internal::EndsWithMatcher<std::wstring>(suffix));
shiqiane35fdd92008-12-10 05:08:54 +00004722}
4723
4724#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4725
4726// Creates a polymorphic matcher that matches a 2-tuple where the
4727// first field == the second field.
4728inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4729
4730// Creates a polymorphic matcher that matches a 2-tuple where the
4731// first field >= the second field.
4732inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4733
4734// Creates a polymorphic matcher that matches a 2-tuple where the
4735// first field > the second field.
4736inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4737
4738// Creates a polymorphic matcher that matches a 2-tuple where the
4739// first field <= the second field.
4740inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4741
4742// Creates a polymorphic matcher that matches a 2-tuple where the
4743// first field < the second field.
4744inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4745
4746// Creates a polymorphic matcher that matches a 2-tuple where the
4747// first field != the second field.
4748inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4749
Gennadiy Civilb907c262018-03-23 11:42:41 -04004750// Creates a polymorphic matcher that matches a 2-tuple where
4751// FloatEq(first field) matches the second field.
4752inline internal::FloatingEq2Matcher<float> FloatEq() {
4753 return internal::FloatingEq2Matcher<float>();
4754}
4755
4756// Creates a polymorphic matcher that matches a 2-tuple where
4757// DoubleEq(first field) matches the second field.
4758inline internal::FloatingEq2Matcher<double> DoubleEq() {
4759 return internal::FloatingEq2Matcher<double>();
4760}
4761
4762// Creates a polymorphic matcher that matches a 2-tuple where
4763// FloatEq(first field) matches the second field with NaN equality.
4764inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() {
4765 return internal::FloatingEq2Matcher<float>(true);
4766}
4767
4768// Creates a polymorphic matcher that matches a 2-tuple where
4769// DoubleEq(first field) matches the second field with NaN equality.
4770inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() {
4771 return internal::FloatingEq2Matcher<double>(true);
4772}
4773
4774// Creates a polymorphic matcher that matches a 2-tuple where
4775// FloatNear(first field, max_abs_error) matches the second field.
4776inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) {
4777 return internal::FloatingEq2Matcher<float>(max_abs_error);
4778}
4779
4780// Creates a polymorphic matcher that matches a 2-tuple where
4781// DoubleNear(first field, max_abs_error) matches the second field.
4782inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) {
4783 return internal::FloatingEq2Matcher<double>(max_abs_error);
4784}
4785
4786// Creates a polymorphic matcher that matches a 2-tuple where
4787// FloatNear(first field, max_abs_error) matches the second field with NaN
4788// equality.
4789inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear(
4790 float max_abs_error) {
4791 return internal::FloatingEq2Matcher<float>(max_abs_error, true);
4792}
4793
4794// Creates a polymorphic matcher that matches a 2-tuple where
4795// DoubleNear(first field, max_abs_error) matches the second field with NaN
4796// equality.
4797inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear(
4798 double max_abs_error) {
4799 return internal::FloatingEq2Matcher<double>(max_abs_error, true);
4800}
4801
shiqiane35fdd92008-12-10 05:08:54 +00004802// Creates a matcher that matches any value of type T that m doesn't
4803// match.
4804template <typename InnerMatcher>
4805inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4806 return internal::NotMatcher<InnerMatcher>(m);
4807}
4808
shiqiane35fdd92008-12-10 05:08:54 +00004809// Returns a matcher that matches anything that satisfies the given
4810// predicate. The predicate can be any unary function or functor
4811// whose return type can be implicitly converted to bool.
4812template <typename Predicate>
4813inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4814Truly(Predicate pred) {
4815 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4816}
4817
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004818// Returns a matcher that matches the container size. The container must
4819// support both size() and size_type which all STL-like containers provide.
4820// Note that the parameter 'size' can be a value of type size_type as well as
4821// matcher. For instance:
4822// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
4823// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
4824template <typename SizeMatcher>
4825inline internal::SizeIsMatcher<SizeMatcher>
4826SizeIs(const SizeMatcher& size_matcher) {
4827 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4828}
4829
kosakb6a34882014-03-12 21:06:46 +00004830// Returns a matcher that matches the distance between the container's begin()
4831// iterator and its end() iterator, i.e. the size of the container. This matcher
4832// can be used instead of SizeIs with containers such as std::forward_list which
4833// do not implement size(). The container must provide const_iterator (with
4834// valid iterator_traits), begin() and end().
4835template <typename DistanceMatcher>
4836inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4837BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4838 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4839}
4840
zhanyong.wan6a896b52009-01-16 01:13:50 +00004841// Returns a matcher that matches an equal container.
4842// This matcher behaves like Eq(), but in the event of mismatch lists the
4843// values that are included in one container but not the other. (Duplicate
4844// values and order differences are not explained.)
4845template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00004846inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00004847 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004848 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00004849 // This following line is for working around a bug in MSVC 8.0,
4850 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00004851 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00004852 return MakePolymorphicMatcher(
4853 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00004854}
4855
zhanyong.wan898725c2011-09-16 16:45:39 +00004856// Returns a matcher that matches a container that, when sorted using
4857// the given comparator, matches container_matcher.
4858template <typename Comparator, typename ContainerMatcher>
4859inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4860WhenSortedBy(const Comparator& comparator,
4861 const ContainerMatcher& container_matcher) {
4862 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4863 comparator, container_matcher);
4864}
4865
4866// Returns a matcher that matches a container that, when sorted using
4867// the < operator, matches container_matcher.
4868template <typename ContainerMatcher>
4869inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4870WhenSorted(const ContainerMatcher& container_matcher) {
4871 return
4872 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4873 internal::LessComparator(), container_matcher);
4874}
4875
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004876// Matches an STL-style container or a native array that contains the
4877// same number of elements as in rhs, where its i-th element and rhs's
4878// i-th element (as a pair) satisfy the given pair matcher, for all i.
4879// TupleMatcher must be able to be safely cast to Matcher<tuple<const
4880// T1&, const T2&> >, where T1 and T2 are the types of elements in the
4881// LHS container and the RHS container respectively.
4882template <typename TupleMatcher, typename Container>
4883inline internal::PointwiseMatcher<TupleMatcher,
4884 GTEST_REMOVE_CONST_(Container)>
4885Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4886 // This following line is for working around a bug in MSVC 8.0,
kosak2336e9c2014-07-28 22:57:30 +00004887 // which causes Container to be a const type sometimes (e.g. when
4888 // rhs is a const int[])..
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004889 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4890 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4891 tuple_matcher, rhs);
4892}
4893
kosak2336e9c2014-07-28 22:57:30 +00004894#if GTEST_HAS_STD_INITIALIZER_LIST_
4895
4896// Supports the Pointwise(m, {a, b, c}) syntax.
4897template <typename TupleMatcher, typename T>
4898inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4899 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4900 return Pointwise(tuple_matcher, std::vector<T>(rhs));
4901}
4902
4903#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4904
4905// UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4906// container or a native array that contains the same number of
4907// elements as in rhs, where in some permutation of the container, its
4908// i-th element and rhs's i-th element (as a pair) satisfy the given
4909// pair matcher, for all i. Tuple2Matcher must be able to be safely
4910// cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4911// the types of elements in the LHS container and the RHS container
4912// respectively.
4913//
4914// This is like Pointwise(pair_matcher, rhs), except that the element
4915// order doesn't matter.
4916template <typename Tuple2Matcher, typename RhsContainer>
4917inline internal::UnorderedElementsAreArrayMatcher<
4918 typename internal::BoundSecondMatcher<
4919 Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4920 RhsContainer)>::type::value_type> >
4921UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4922 const RhsContainer& rhs_container) {
4923 // This following line is for working around a bug in MSVC 8.0,
4924 // which causes RhsContainer to be a const type sometimes (e.g. when
4925 // rhs_container is a const int[]).
4926 typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4927
4928 // RhsView allows the same code to handle RhsContainer being a
4929 // STL-style container and it being a native C-style array.
4930 typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4931 typedef typename RhsView::type RhsStlContainer;
4932 typedef typename RhsStlContainer::value_type Second;
4933 const RhsStlContainer& rhs_stl_container =
4934 RhsView::ConstReference(rhs_container);
4935
4936 // Create a matcher for each element in rhs_container.
4937 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4938 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4939 it != rhs_stl_container.end(); ++it) {
4940 matchers.push_back(
4941 internal::MatcherBindSecond(tuple2_matcher, *it));
4942 }
4943
4944 // Delegate the work to UnorderedElementsAreArray().
4945 return UnorderedElementsAreArray(matchers);
4946}
4947
4948#if GTEST_HAS_STD_INITIALIZER_LIST_
4949
4950// Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4951template <typename Tuple2Matcher, typename T>
4952inline internal::UnorderedElementsAreArrayMatcher<
4953 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4954UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4955 std::initializer_list<T> rhs) {
4956 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4957}
4958
4959#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4960
zhanyong.wanb8243162009-06-04 05:48:20 +00004961// Matches an STL-style container or a native array that contains at
4962// least one element matching the given value or matcher.
4963//
4964// Examples:
4965// ::std::set<int> page_ids;
4966// page_ids.insert(3);
4967// page_ids.insert(1);
4968// EXPECT_THAT(page_ids, Contains(1));
4969// EXPECT_THAT(page_ids, Contains(Gt(2)));
4970// EXPECT_THAT(page_ids, Not(Contains(4)));
4971//
4972// ::std::map<int, size_t> page_lengths;
4973// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00004974// EXPECT_THAT(page_lengths,
4975// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004976//
4977// const char* user_ids[] = { "joe", "mike", "tom" };
4978// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4979template <typename M>
4980inline internal::ContainsMatcher<M> Contains(M matcher) {
4981 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004982}
4983
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004984// IsSupersetOf(iterator_first, iterator_last)
4985// IsSupersetOf(pointer, count)
4986// IsSupersetOf(array)
4987// IsSupersetOf(container)
4988// IsSupersetOf({e1, e2, ..., en})
4989//
4990// IsSupersetOf() verifies that a surjective partial mapping onto a collection
4991// of matchers exists. In other words, a container matches
4992// IsSupersetOf({e1, ..., en}) if and only if there is a permutation
4993// {y1, ..., yn} of some of the container's elements where y1 matches e1,
4994// ..., and yn matches en. Obviously, the size of the container must be >= n
4995// in order to have a match. Examples:
4996//
4997// - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and
4998// 1 matches Ne(0).
4999// - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches
5000// both Eq(1) and Lt(2). The reason is that different matchers must be used
5001// for elements in different slots of the container.
5002// - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches
5003// Eq(1) and (the second) 1 matches Lt(2).
5004// - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)
5005// Gt(1) and 3 matches (the second) Gt(1).
5006//
5007// The matchers can be specified as an array, a pointer and count, a container,
5008// an initializer list, or an STL iterator range. In each of these cases, the
5009// underlying matchers can be either values or matchers.
5010
5011template <typename Iter>
5012inline internal::UnorderedElementsAreArrayMatcher<
5013 typename ::std::iterator_traits<Iter>::value_type>
5014IsSupersetOf(Iter first, Iter last) {
5015 typedef typename ::std::iterator_traits<Iter>::value_type T;
5016 return internal::UnorderedElementsAreArrayMatcher<T>(
5017 internal::UnorderedMatcherRequire::Superset, first, last);
5018}
5019
5020template <typename T>
5021inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
5022 const T* pointer, size_t count) {
5023 return IsSupersetOf(pointer, pointer + count);
5024}
5025
5026template <typename T, size_t N>
5027inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
5028 const T (&array)[N]) {
5029 return IsSupersetOf(array, N);
5030}
5031
5032template <typename Container>
5033inline internal::UnorderedElementsAreArrayMatcher<
5034 typename Container::value_type>
5035IsSupersetOf(const Container& container) {
5036 return IsSupersetOf(container.begin(), container.end());
5037}
5038
5039#if GTEST_HAS_STD_INITIALIZER_LIST_
5040template <typename T>
5041inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
5042 ::std::initializer_list<T> xs) {
5043 return IsSupersetOf(xs.begin(), xs.end());
5044}
5045#endif
5046
5047// IsSubsetOf(iterator_first, iterator_last)
5048// IsSubsetOf(pointer, count)
5049// IsSubsetOf(array)
5050// IsSubsetOf(container)
5051// IsSubsetOf({e1, e2, ..., en})
5052//
5053// IsSubsetOf() verifies that an injective mapping onto a collection of matchers
5054// exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and
5055// only if there is a subset of matchers {m1, ..., mk} which would match the
5056// container using UnorderedElementsAre. Obviously, the size of the container
5057// must be <= n in order to have a match. Examples:
5058//
5059// - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).
5060// - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1
5061// matches Lt(0).
5062// - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both
5063// match Gt(0). The reason is that different matchers must be used for
5064// elements in different slots of the container.
5065//
5066// The matchers can be specified as an array, a pointer and count, a container,
5067// an initializer list, or an STL iterator range. In each of these cases, the
5068// underlying matchers can be either values or matchers.
5069
5070template <typename Iter>
5071inline internal::UnorderedElementsAreArrayMatcher<
5072 typename ::std::iterator_traits<Iter>::value_type>
5073IsSubsetOf(Iter first, Iter last) {
5074 typedef typename ::std::iterator_traits<Iter>::value_type T;
5075 return internal::UnorderedElementsAreArrayMatcher<T>(
5076 internal::UnorderedMatcherRequire::Subset, first, last);
5077}
5078
5079template <typename T>
5080inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
5081 const T* pointer, size_t count) {
5082 return IsSubsetOf(pointer, pointer + count);
5083}
5084
5085template <typename T, size_t N>
5086inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
5087 const T (&array)[N]) {
5088 return IsSubsetOf(array, N);
5089}
5090
5091template <typename Container>
5092inline internal::UnorderedElementsAreArrayMatcher<
5093 typename Container::value_type>
5094IsSubsetOf(const Container& container) {
5095 return IsSubsetOf(container.begin(), container.end());
5096}
5097
5098#if GTEST_HAS_STD_INITIALIZER_LIST_
5099template <typename T>
5100inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
5101 ::std::initializer_list<T> xs) {
5102 return IsSubsetOf(xs.begin(), xs.end());
5103}
5104#endif
5105
zhanyong.wan33605ba2010-04-22 23:37:47 +00005106// Matches an STL-style container or a native array that contains only
5107// elements matching the given value or matcher.
5108//
5109// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
5110// the messages are different.
5111//
5112// Examples:
5113// ::std::set<int> page_ids;
5114// // Each(m) matches an empty container, regardless of what m is.
5115// EXPECT_THAT(page_ids, Each(Eq(1)));
5116// EXPECT_THAT(page_ids, Each(Eq(77)));
5117//
5118// page_ids.insert(3);
5119// EXPECT_THAT(page_ids, Each(Gt(0)));
5120// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
5121// page_ids.insert(1);
5122// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
5123//
5124// ::std::map<int, size_t> page_lengths;
5125// page_lengths[1] = 100;
5126// page_lengths[2] = 200;
5127// page_lengths[3] = 300;
5128// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
5129// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
5130//
5131// const char* user_ids[] = { "joe", "mike", "tom" };
5132// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
5133template <typename M>
5134inline internal::EachMatcher<M> Each(M matcher) {
5135 return internal::EachMatcher<M>(matcher);
5136}
5137
zhanyong.wanb5937da2009-07-16 20:26:41 +00005138// Key(inner_matcher) matches an std::pair whose 'first' field matches
5139// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
5140// std::map that contains at least one element whose key is >= 5.
5141template <typename M>
5142inline internal::KeyMatcher<M> Key(M inner_matcher) {
5143 return internal::KeyMatcher<M>(inner_matcher);
5144}
5145
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00005146// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
5147// matches first_matcher and whose 'second' field matches second_matcher. For
5148// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
5149// to match a std::map<int, string> that contains exactly one element whose key
5150// is >= 5 and whose value equals "foo".
5151template <typename FirstMatcher, typename SecondMatcher>
5152inline internal::PairMatcher<FirstMatcher, SecondMatcher>
5153Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
5154 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
5155 first_matcher, second_matcher);
5156}
5157
shiqiane35fdd92008-12-10 05:08:54 +00005158// Returns a predicate that is satisfied by anything that matches the
5159// given matcher.
5160template <typename M>
5161inline internal::MatcherAsPredicate<M> Matches(M matcher) {
5162 return internal::MatcherAsPredicate<M>(matcher);
5163}
5164
zhanyong.wanb8243162009-06-04 05:48:20 +00005165// Returns true iff the value matches the matcher.
5166template <typename T, typename M>
5167inline bool Value(const T& value, M matcher) {
5168 return testing::Matches(matcher)(value);
5169}
5170
zhanyong.wan34b034c2010-03-05 21:23:23 +00005171// Matches the value against the given matcher and explains the match
5172// result to listener.
5173template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00005174inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00005175 M matcher, const T& value, MatchResultListener* listener) {
5176 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
5177}
5178
Gennadiy Civilb907c262018-03-23 11:42:41 -04005179// Returns a string representation of the given matcher. Useful for description
5180// strings of matchers defined using MATCHER_P* macros that accept matchers as
5181// their arguments. For example:
5182//
5183// MATCHER_P(XAndYThat, matcher,
5184// "X that " + DescribeMatcher<int>(matcher, negation) +
5185// " and Y that " + DescribeMatcher<double>(matcher, negation)) {
5186// return ExplainMatchResult(matcher, arg.x(), result_listener) &&
5187// ExplainMatchResult(matcher, arg.y(), result_listener);
5188// }
5189template <typename T, typename M>
5190std::string DescribeMatcher(const M& matcher, bool negation = false) {
5191 ::std::stringstream ss;
5192 Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher);
5193 if (negation) {
5194 monomorphic_matcher.DescribeNegationTo(&ss);
5195 } else {
5196 monomorphic_matcher.DescribeTo(&ss);
5197 }
5198 return ss.str();
5199}
5200
zhanyong.wan616180e2013-06-18 18:49:51 +00005201#if GTEST_LANG_CXX11
5202// Define variadic matcher versions. They are overloaded in
5203// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
5204template <typename... Args>
5205inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
5206 return internal::AllOfMatcher<Args...>(matchers...);
5207}
5208
5209template <typename... Args>
5210inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
5211 return internal::AnyOfMatcher<Args...>(matchers...);
5212}
5213
Gennadiy Civil3f88bb12018-04-16 15:52:47 -04005214template <typename... Args>
5215inline internal::UnorderedElementsAreMatcher<Args...>
5216UnorderedElementsAreMatcher(const Args&... matchers) {
5217 return internal::UnorderedElementsAreMatcher<Args...>(matchers...);
5218}
5219
zhanyong.wan616180e2013-06-18 18:49:51 +00005220#endif // GTEST_LANG_CXX11
5221
zhanyong.wanbf550852009-06-09 06:09:53 +00005222// AllArgs(m) is a synonym of m. This is useful in
5223//
5224// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
5225//
5226// which is easier to read than
5227//
5228// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
5229template <typename InnerMatcher>
5230inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
5231
Gennadiy Civilb907c262018-03-23 11:42:41 -04005232// Returns a matcher that matches the value of an optional<> type variable.
5233// The matcher implementation only uses '!arg' and requires that the optional<>
5234// type has a 'value_type' member type and that '*arg' is of type 'value_type'
5235// and is printable using 'PrintToString'. It is compatible with
5236// std::optional/std::experimental::optional.
5237// Note that to compare an optional type variable against nullopt you should
5238// use Eq(nullopt) and not Optional(Eq(nullopt)). The latter implies that the
5239// optional value contains an optional itself.
5240template <typename ValueMatcher>
5241inline internal::OptionalMatcher<ValueMatcher> Optional(
5242 const ValueMatcher& value_matcher) {
5243 return internal::OptionalMatcher<ValueMatcher>(value_matcher);
5244}
5245
5246// Returns a matcher that matches the value of a absl::any type variable.
5247template <typename T>
5248PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T> > AnyWith(
5249 const Matcher<const T&>& matcher) {
5250 return MakePolymorphicMatcher(
5251 internal::any_cast_matcher::AnyCastMatcher<T>(matcher));
5252}
5253
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05005254// Returns a matcher that matches the value of a variant<> type variable.
5255// The matcher implementation uses ADL to find the holds_alternative and get
5256// functions.
5257// It is compatible with std::variant.
5258template <typename T>
5259PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
5260 const Matcher<const T&>& matcher) {
5261 return MakePolymorphicMatcher(
5262 internal::variant_matcher::VariantMatcher<T>(matcher));
5263}
5264
shiqiane35fdd92008-12-10 05:08:54 +00005265// These macros allow using matchers to check values in Google Test
5266// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
5267// succeed iff the value matches the matcher. If the assertion fails,
5268// the value and the description of the matcher will be printed.
5269#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
5270 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
5271#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
5272 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
5273
5274} // namespace testing
5275
kosak6702b972015-07-27 23:05:57 +00005276// Include any custom callback matchers added by the local installation.
5277// We must include this header at the end to make sure it can use the
5278// declarations from this file.
5279#include "gmock/internal/custom/gmock-matchers.h"
Gennadiy Civilb907c262018-03-23 11:42:41 -04005280
shiqiane35fdd92008-12-10 05:08:54 +00005281#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_