blob: 000908a1a9d99b0fb02b88570fc4af58ab99713c [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.
zhanyong.wan82113312010-01-08 21:55:40 +0000290 bool Matches(T x) const {
291 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.
304 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000305 StreamMatchResultListener listener(os);
306 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000307 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000308
zhanyong.wanfb25d532013-07-28 08:24:00 +0000309 // Returns the describer for this matcher object; retains ownership
310 // of the describer, which is only guaranteed to be alive when
311 // this matcher object is alive.
312 const MatcherDescriberInterface* GetDescriber() const {
313 return impl_.get();
314 }
315
shiqiane35fdd92008-12-10 05:08:54 +0000316 protected:
317 MatcherBase() {}
318
319 // Constructs a matcher from its implementation.
320 explicit MatcherBase(const MatcherInterface<T>* impl)
321 : impl_(impl) {}
322
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400323 template <typename U>
324 explicit MatcherBase(
325 const MatcherInterface<U>* impl,
326 typename internal::EnableIf<
327 !internal::IsSame<U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* =
328 NULL)
329 : impl_(new internal::MatcherInterfaceAdapter<U>(impl)) {}
330
shiqiane35fdd92008-12-10 05:08:54 +0000331 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000332
shiqiane35fdd92008-12-10 05:08:54 +0000333 private:
334 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
335 // interfaces. The former dynamically allocates a chunk of memory
336 // to hold the reference count, while the latter tracks all
337 // references using a circular linked list without allocating
338 // memory. It has been observed that linked_ptr performs better in
339 // typical scenarios. However, shared_ptr can out-perform
340 // linked_ptr when there are many more uses of the copy constructor
341 // than the default constructor.
342 //
343 // If performance becomes a problem, we should see if using
344 // shared_ptr helps.
345 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
346};
347
shiqiane35fdd92008-12-10 05:08:54 +0000348} // namespace internal
349
350// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
351// object that can check whether a value of type T matches. The
352// implementation of Matcher<T> is just a linked_ptr to const
353// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
354// from Matcher!
355template <typename T>
356class Matcher : public internal::MatcherBase<T> {
357 public:
vladlosev88032d82010-11-17 23:29:21 +0000358 // Constructs a null matcher. Needed for storing Matcher objects in STL
359 // containers. A default-constructed matcher is not yet initialized. You
360 // cannot use it until a valid value has been assigned to it.
kosakd86a7232015-07-13 21:19:43 +0000361 explicit Matcher() {} // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000362
363 // Constructs a matcher from its implementation.
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400364 explicit Matcher(const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)>* impl)
365 : internal::MatcherBase<T>(impl) {}
366
367 template <typename U>
368 explicit Matcher(const MatcherInterface<U>* impl,
369 typename internal::EnableIf<!internal::IsSame<
370 U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* = NULL)
shiqiane35fdd92008-12-10 05:08:54 +0000371 : internal::MatcherBase<T>(impl) {}
372
zhanyong.wan18490652009-05-11 18:54:08 +0000373 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000374 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
375 Matcher(T value); // NOLINT
376};
377
378// The following two specializations allow the user to write str
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400379// instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
shiqiane35fdd92008-12-10 05:08:54 +0000380// matcher is expected.
381template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400382class GTEST_API_ Matcher<const std::string&>
383 : public internal::MatcherBase<const std::string&> {
shiqiane35fdd92008-12-10 05:08:54 +0000384 public:
385 Matcher() {}
386
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400387 explicit Matcher(const MatcherInterface<const std::string&>* impl)
388 : internal::MatcherBase<const std::string&>(impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000389
390 // Allows the user to write str instead of Eq(str) sometimes, where
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400391 // str is a std::string object.
392 Matcher(const std::string& s); // NOLINT
393
394#if GTEST_HAS_GLOBAL_STRING
395 // Allows the user to write str instead of Eq(str) sometimes, where
396 // str is a ::string object.
397 Matcher(const ::string& s); // NOLINT
398#endif // GTEST_HAS_GLOBAL_STRING
shiqiane35fdd92008-12-10 05:08:54 +0000399
400 // Allows the user to write "foo" instead of Eq("foo") sometimes.
401 Matcher(const char* s); // NOLINT
402};
403
404template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400405class GTEST_API_ Matcher<std::string>
406 : public internal::MatcherBase<std::string> {
shiqiane35fdd92008-12-10 05:08:54 +0000407 public:
408 Matcher() {}
409
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400410 explicit Matcher(const MatcherInterface<std::string>* impl)
411 : internal::MatcherBase<std::string>(impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000412
413 // Allows the user to write str instead of Eq(str) sometimes, where
414 // str is a string object.
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400415 Matcher(const std::string& s); // NOLINT
416
417#if GTEST_HAS_GLOBAL_STRING
418 // Allows the user to write str instead of Eq(str) sometimes, where
419 // str is a ::string object.
420 Matcher(const ::string& s); // NOLINT
421#endif // GTEST_HAS_GLOBAL_STRING
shiqiane35fdd92008-12-10 05:08:54 +0000422
423 // Allows the user to write "foo" instead of Eq("foo") sometimes.
424 Matcher(const char* s); // NOLINT
425};
426
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400427#if GTEST_HAS_GLOBAL_STRING
zhanyong.wan1f122a02013-03-25 16:27:03 +0000428// The following two specializations allow the user to write str
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400429// instead of Eq(str) and "foo" instead of Eq("foo") when a ::string
zhanyong.wan1f122a02013-03-25 16:27:03 +0000430// matcher is expected.
431template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400432class GTEST_API_ Matcher<const ::string&>
433 : public internal::MatcherBase<const ::string&> {
zhanyong.wan1f122a02013-03-25 16:27:03 +0000434 public:
435 Matcher() {}
436
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400437 explicit Matcher(const MatcherInterface<const ::string&>* impl)
438 : internal::MatcherBase<const ::string&>(impl) {}
zhanyong.wan1f122a02013-03-25 16:27:03 +0000439
440 // Allows the user to write str instead of Eq(str) sometimes, where
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400441 // str is a std::string object.
442 Matcher(const std::string& s); // NOLINT
443
444 // Allows the user to write str instead of Eq(str) sometimes, where
445 // str is a ::string object.
446 Matcher(const ::string& s); // NOLINT
zhanyong.wan1f122a02013-03-25 16:27:03 +0000447
448 // Allows the user to write "foo" instead of Eq("foo") sometimes.
449 Matcher(const char* s); // NOLINT
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400450};
zhanyong.wan1f122a02013-03-25 16:27:03 +0000451
zhanyong.wan1f122a02013-03-25 16:27:03 +0000452};
453
454template <>
455class GTEST_API_ Matcher<StringPiece>
456 : public internal::MatcherBase<StringPiece> {
457 public:
458 Matcher() {}
459
460 explicit Matcher(const MatcherInterface<StringPiece>* impl)
461 : internal::MatcherBase<StringPiece>(impl) {}
462
463 // Allows the user to write str instead of Eq(str) sometimes, where
464 // str is a string object.
465 Matcher(const internal::string& s); // NOLINT
466
467 // Allows the user to write "foo" instead of Eq("foo") sometimes.
468 Matcher(const char* s); // NOLINT
469
470 // Allows the user to pass StringPieces directly.
471 Matcher(StringPiece s); // NOLINT
472};
473#endif // GTEST_HAS_STRING_PIECE_
474
shiqiane35fdd92008-12-10 05:08:54 +0000475// The PolymorphicMatcher class template makes it easy to implement a
476// polymorphic matcher (i.e. a matcher that can match values of more
477// than one type, e.g. Eq(n) and NotNull()).
478//
zhanyong.wandb22c222010-01-28 21:52:29 +0000479// To define a polymorphic matcher, a user should provide an Impl
480// class that has a DescribeTo() method and a DescribeNegationTo()
481// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000482//
zhanyong.wandb22c222010-01-28 21:52:29 +0000483// bool MatchAndExplain(const Value& value,
484// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000485//
486// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000487template <class Impl>
488class PolymorphicMatcher {
489 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000490 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000491
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000492 // Returns a mutable reference to the underlying matcher
493 // implementation object.
494 Impl& mutable_impl() { return impl_; }
495
496 // Returns an immutable reference to the underlying matcher
497 // implementation object.
498 const Impl& impl() const { return impl_; }
499
shiqiane35fdd92008-12-10 05:08:54 +0000500 template <typename T>
501 operator Matcher<T>() const {
502 return Matcher<T>(new MonomorphicImpl<T>(impl_));
503 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000504
shiqiane35fdd92008-12-10 05:08:54 +0000505 private:
506 template <typename T>
507 class MonomorphicImpl : public MatcherInterface<T> {
508 public:
509 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
510
shiqiane35fdd92008-12-10 05:08:54 +0000511 virtual void DescribeTo(::std::ostream* os) const {
512 impl_.DescribeTo(os);
513 }
514
515 virtual void DescribeNegationTo(::std::ostream* os) const {
516 impl_.DescribeNegationTo(os);
517 }
518
zhanyong.wan82113312010-01-08 21:55:40 +0000519 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000520 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000521 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000522
shiqiane35fdd92008-12-10 05:08:54 +0000523 private:
524 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000525
526 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000527 };
528
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000529 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000530
531 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000532};
533
534// Creates a matcher from its implementation. This is easier to use
535// than the Matcher<T> constructor as it doesn't require you to
536// explicitly write the template argument, e.g.
537//
538// MakeMatcher(foo);
539// vs
540// Matcher<const string&>(foo);
541template <typename T>
542inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
543 return Matcher<T>(impl);
zhanyong.wan2eab17b2013-03-08 17:53:24 +0000544}
shiqiane35fdd92008-12-10 05:08:54 +0000545
546// Creates a polymorphic matcher from its implementation. This is
547// easier to use than the PolymorphicMatcher<Impl> constructor as it
548// doesn't require you to explicitly write the template argument, e.g.
549//
550// MakePolymorphicMatcher(foo);
551// vs
552// PolymorphicMatcher<TypeOfFoo>(foo);
553template <class Impl>
554inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
555 return PolymorphicMatcher<Impl>(impl);
556}
557
jgm79a367e2012-04-10 16:02:11 +0000558// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
559// and MUST NOT BE USED IN USER CODE!!!
560namespace internal {
561
562// The MatcherCastImpl class template is a helper for implementing
563// MatcherCast(). We need this helper in order to partially
564// specialize the implementation of MatcherCast() (C++ allows
565// class/struct templates to be partially specialized, but not
566// function templates.).
567
568// This general version is used when MatcherCast()'s argument is a
569// polymorphic matcher (i.e. something that can be converted to a
570// Matcher but is not one yet; for example, Eq(value)) or a value (for
571// example, "hello").
572template <typename T, typename M>
573class MatcherCastImpl {
574 public:
kosak5f2a6ca2013-12-03 01:43:07 +0000575 static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
Gennadiy Civil2bd17502018-02-27 13:51:09 -0500576 // M can be a polymorphic matcher, in which case we want to use
jgm79a367e2012-04-10 16:02:11 +0000577 // its conversion operator to create Matcher<T>. Or it can be a value
578 // that should be passed to the Matcher<T>'s constructor.
579 //
580 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
581 // polymorphic matcher because it'll be ambiguous if T has an implicit
582 // constructor from M (this usually happens when T has an implicit
583 // constructor from any type).
584 //
585 // It won't work to unconditionally implict_cast
586 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
587 // a user-defined conversion from M to T if one exists (assuming M is
588 // a value).
589 return CastImpl(
590 polymorphic_matcher_or_value,
591 BooleanConstant<
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400592 internal::ImplicitlyConvertible<M, Matcher<T> >::value>(),
593 BooleanConstant<
594 internal::ImplicitlyConvertible<M, T>::value>());
jgm79a367e2012-04-10 16:02:11 +0000595 }
596
597 private:
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400598 template <bool Ignore>
kosak5f2a6ca2013-12-03 01:43:07 +0000599 static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400600 BooleanConstant<true> /* convertible_to_matcher */,
601 BooleanConstant<Ignore>) {
jgm79a367e2012-04-10 16:02:11 +0000602 // M is implicitly convertible to Matcher<T>, which means that either
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400603 // M is a polymorphic matcher or Matcher<T> has an implicit constructor
jgm79a367e2012-04-10 16:02:11 +0000604 // from M. In both cases using the implicit conversion will produce a
605 // matcher.
606 //
607 // Even if T has an implicit constructor from M, it won't be called because
608 // creating Matcher<T> would require a chain of two user-defined conversions
609 // (first to create T from M and then to create Matcher<T> from T).
610 return polymorphic_matcher_or_value;
611 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400612
613 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
614 // matcher. It's a value of a type implicitly convertible to T. Use direct
615 // initialization to create a matcher.
616 static Matcher<T> CastImpl(
617 const M& value, BooleanConstant<false> /* convertible_to_matcher */,
618 BooleanConstant<true> /* convertible_to_T */) {
619 return Matcher<T>(ImplicitCast_<T>(value));
620 }
621
622 // M can't be implicitly converted to either Matcher<T> or T. Attempt to use
623 // polymorphic matcher Eq(value) in this case.
624 //
625 // Note that we first attempt to perform an implicit cast on the value and
626 // only fall back to the polymorphic Eq() matcher afterwards because the
627 // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end
628 // which might be undefined even when Rhs is implicitly convertible to Lhs
629 // (e.g. std::pair<const int, int> vs. std::pair<int, int>).
630 //
631 // We don't define this method inline as we need the declaration of Eq().
632 static Matcher<T> CastImpl(
633 const M& value, BooleanConstant<false> /* convertible_to_matcher */,
634 BooleanConstant<false> /* convertible_to_T */);
jgm79a367e2012-04-10 16:02:11 +0000635};
636
637// This more specialized version is used when MatcherCast()'s argument
638// is already a Matcher. This only compiles when type T can be
639// statically converted to type U.
640template <typename T, typename U>
641class MatcherCastImpl<T, Matcher<U> > {
642 public:
643 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
644 return Matcher<T>(new Impl(source_matcher));
645 }
646
647 private:
648 class Impl : public MatcherInterface<T> {
649 public:
650 explicit Impl(const Matcher<U>& source_matcher)
651 : source_matcher_(source_matcher) {}
652
653 // We delegate the matching logic to the source matcher.
654 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
Gennadiy Civilb907c262018-03-23 11:42:41 -0400655#if GTEST_LANG_CXX11
656 using FromType = typename std::remove_cv<typename std::remove_pointer<
657 typename std::remove_reference<T>::type>::type>::type;
658 using ToType = typename std::remove_cv<typename std::remove_pointer<
659 typename std::remove_reference<U>::type>::type>::type;
660 // Do not allow implicitly converting base*/& to derived*/&.
661 static_assert(
662 // Do not trigger if only one of them is a pointer. That implies a
663 // regular conversion and not a down_cast.
664 (std::is_pointer<typename std::remove_reference<T>::type>::value !=
665 std::is_pointer<typename std::remove_reference<U>::type>::value) ||
666 std::is_same<FromType, ToType>::value ||
667 !std::is_base_of<FromType, ToType>::value,
668 "Can't implicitly convert from <base> to <derived>");
669#endif // GTEST_LANG_CXX11
670
jgm79a367e2012-04-10 16:02:11 +0000671 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
672 }
673
674 virtual void DescribeTo(::std::ostream* os) const {
675 source_matcher_.DescribeTo(os);
676 }
677
678 virtual void DescribeNegationTo(::std::ostream* os) const {
679 source_matcher_.DescribeNegationTo(os);
680 }
681
682 private:
683 const Matcher<U> source_matcher_;
684
685 GTEST_DISALLOW_ASSIGN_(Impl);
686 };
687};
688
689// This even more specialized version is used for efficiently casting
690// a matcher to its own type.
691template <typename T>
692class MatcherCastImpl<T, Matcher<T> > {
693 public:
694 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
695};
696
697} // namespace internal
698
shiqiane35fdd92008-12-10 05:08:54 +0000699// In order to be safe and clear, casting between different matcher
700// types is done explicitly via MatcherCast<T>(m), which takes a
701// matcher m and returns a Matcher<T>. It compiles only when T can be
702// statically converted to the argument type of m.
703template <typename T, typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000704inline Matcher<T> MatcherCast(const M& matcher) {
jgm79a367e2012-04-10 16:02:11 +0000705 return internal::MatcherCastImpl<T, M>::Cast(matcher);
706}
shiqiane35fdd92008-12-10 05:08:54 +0000707
zhanyong.wan18490652009-05-11 18:54:08 +0000708// Implements SafeMatcherCast().
709//
zhanyong.wan95b12332009-09-25 18:55:50 +0000710// We use an intermediate class to do the actual safe casting as Nokia's
711// Symbian compiler cannot decide between
712// template <T, M> ... (M) and
713// template <T, U> ... (const Matcher<U>&)
714// for function templates but can for member function templates.
715template <typename T>
716class SafeMatcherCastImpl {
717 public:
jgm79a367e2012-04-10 16:02:11 +0000718 // This overload handles polymorphic matchers and values only since
719 // monomorphic matchers are handled by the next one.
zhanyong.wan95b12332009-09-25 18:55:50 +0000720 template <typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000721 static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
jgm79a367e2012-04-10 16:02:11 +0000722 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
zhanyong.wan95b12332009-09-25 18:55:50 +0000723 }
zhanyong.wan18490652009-05-11 18:54:08 +0000724
zhanyong.wan95b12332009-09-25 18:55:50 +0000725 // This overload handles monomorphic matchers.
726 //
727 // In general, if type T can be implicitly converted to type U, we can
728 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
729 // contravariant): just keep a copy of the original Matcher<U>, convert the
730 // argument from type T to U, and then pass it to the underlying Matcher<U>.
731 // The only exception is when U is a reference and T is not, as the
732 // underlying Matcher<U> may be interested in the argument's address, which
733 // is not preserved in the conversion from T to U.
734 template <typename U>
735 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
736 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000737 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000738 T_must_be_implicitly_convertible_to_U);
739 // Enforce that we are not converting a non-reference type T to a reference
740 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000741 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000742 internal::is_reference<T>::value || !internal::is_reference<U>::value,
Hector Dearman24054ff2017-06-19 18:27:33 +0100743 cannot_convert_non_reference_arg_to_reference);
zhanyong.wan95b12332009-09-25 18:55:50 +0000744 // In case both T and U are arithmetic types, enforce that the
745 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000746 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
747 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000748 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
749 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000750 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000751 kTIsOther || kUIsOther ||
752 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
753 conversion_of_arithmetic_types_must_be_lossless);
754 return MatcherCast<T>(matcher);
755 }
756};
757
758template <typename T, typename M>
759inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
760 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000761}
762
shiqiane35fdd92008-12-10 05:08:54 +0000763// A<T>() returns a matcher that matches any value of type T.
764template <typename T>
765Matcher<T> A();
766
767// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
768// and MUST NOT BE USED IN USER CODE!!!
769namespace internal {
770
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000771// If the explanation is not empty, prints it to the ostream.
Nico Weber09fd5b32017-05-15 17:07:03 -0400772inline void PrintIfNotEmpty(const std::string& explanation,
zhanyong.wanfb25d532013-07-28 08:24:00 +0000773 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000774 if (explanation != "" && os != NULL) {
775 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000776 }
777}
778
zhanyong.wan736baa82010-09-27 17:44:16 +0000779// Returns true if the given type name is easy to read by a human.
780// This is used to decide whether printing the type of a value might
781// be helpful.
Nico Weber09fd5b32017-05-15 17:07:03 -0400782inline bool IsReadableTypeName(const std::string& type_name) {
zhanyong.wan736baa82010-09-27 17:44:16 +0000783 // We consider a type name readable if it's short or doesn't contain
784 // a template or function type.
785 return (type_name.length() <= 20 ||
Nico Weber09fd5b32017-05-15 17:07:03 -0400786 type_name.find_first_of("<(") == std::string::npos);
zhanyong.wan736baa82010-09-27 17:44:16 +0000787}
788
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000789// Matches the value against the given matcher, prints the value and explains
790// the match result to the listener. Returns the match result.
791// 'listener' must not be NULL.
792// Value cannot be passed by const reference, because some matchers take a
793// non-const argument.
794template <typename Value, typename T>
795bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
796 MatchResultListener* listener) {
797 if (!listener->IsInterested()) {
798 // If the listener is not interested, we do not need to construct the
799 // inner explanation.
800 return matcher.Matches(value);
801 }
802
803 StringMatchResultListener inner_listener;
804 const bool match = matcher.MatchAndExplain(value, &inner_listener);
805
806 UniversalPrint(value, listener->stream());
zhanyong.wan736baa82010-09-27 17:44:16 +0000807#if GTEST_HAS_RTTI
Nico Weber09fd5b32017-05-15 17:07:03 -0400808 const std::string& type_name = GetTypeName<Value>();
zhanyong.wan736baa82010-09-27 17:44:16 +0000809 if (IsReadableTypeName(type_name))
810 *listener->stream() << " (of type " << type_name << ")";
811#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000812 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000813
814 return match;
815}
816
shiqiane35fdd92008-12-10 05:08:54 +0000817// An internal helper class for doing compile-time loop on a tuple's
818// fields.
819template <size_t N>
820class TuplePrefix {
821 public:
822 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
823 // iff the first N fields of matcher_tuple matches the first N
824 // fields of value_tuple, respectively.
825 template <typename MatcherTuple, typename ValueTuple>
826 static bool Matches(const MatcherTuple& matcher_tuple,
827 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000828 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
829 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
830 }
831
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000832 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000833 // describes failures in matching the first N fields of matchers
834 // against the first N fields of values. If there is no failure,
835 // nothing will be streamed to os.
836 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000837 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
838 const ValueTuple& values,
839 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000840 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000841 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000842
843 // Then describes the failure (if any) in the (N - 1)-th (0-based)
844 // field.
845 typename tuple_element<N - 1, MatcherTuple>::type matcher =
846 get<N - 1>(matchers);
847 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
848 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000849 StringMatchResultListener listener;
850 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000851 // TODO(wan): include in the message the name of the parameter
852 // as used in MOCK_METHOD*() when possible.
853 *os << " Expected arg #" << N - 1 << ": ";
854 get<N - 1>(matchers).DescribeTo(os);
855 *os << "\n Actual: ";
856 // We remove the reference in type Value to prevent the
857 // universal printer from printing the address of value, which
858 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000859 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000860 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000861 internal::UniversalPrint(value, os);
862 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000863 *os << "\n";
864 }
865 }
866};
867
868// The base case.
869template <>
870class TuplePrefix<0> {
871 public:
872 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000873 static bool Matches(const MatcherTuple& /* matcher_tuple */,
874 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000875 return true;
876 }
877
878 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000879 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
880 const ValueTuple& /* values */,
881 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000882};
883
884// TupleMatches(matcher_tuple, value_tuple) returns true iff all
885// matchers in matcher_tuple match the corresponding fields in
886// value_tuple. It is a compiler error if matcher_tuple and
887// value_tuple have different number of fields or incompatible field
888// types.
889template <typename MatcherTuple, typename ValueTuple>
890bool TupleMatches(const MatcherTuple& matcher_tuple,
891 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000892 // Makes sure that matcher_tuple and value_tuple have the same
893 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000894 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000895 tuple_size<ValueTuple>::value,
896 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000897 return TuplePrefix<tuple_size<ValueTuple>::value>::
898 Matches(matcher_tuple, value_tuple);
899}
900
901// Describes failures in matching matchers against values. If there
902// is no failure, nothing will be streamed to os.
903template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000904void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
905 const ValueTuple& values,
906 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000907 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000908 matchers, values, os);
909}
910
zhanyong.wanfb25d532013-07-28 08:24:00 +0000911// TransformTupleValues and its helper.
912//
913// TransformTupleValuesHelper hides the internal machinery that
914// TransformTupleValues uses to implement a tuple traversal.
915template <typename Tuple, typename Func, typename OutIter>
916class TransformTupleValuesHelper {
917 private:
kosakbd018832014-04-02 20:30:00 +0000918 typedef ::testing::tuple_size<Tuple> TupleSize;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000919
920 public:
921 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
922 // Returns the final value of 'out' in case the caller needs it.
923 static OutIter Run(Func f, const Tuple& t, OutIter out) {
924 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
925 }
926
927 private:
928 template <typename Tup, size_t kRemainingSize>
929 struct IterateOverTuple {
930 OutIter operator() (Func f, const Tup& t, OutIter out) const {
kosakbd018832014-04-02 20:30:00 +0000931 *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
zhanyong.wanfb25d532013-07-28 08:24:00 +0000932 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
933 }
934 };
935 template <typename Tup>
936 struct IterateOverTuple<Tup, 0> {
937 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
938 return out;
939 }
940 };
941};
942
943// Successively invokes 'f(element)' on each element of the tuple 't',
944// appending each result to the 'out' iterator. Returns the final value
945// of 'out'.
946template <typename Tuple, typename Func, typename OutIter>
947OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
948 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
949}
950
shiqiane35fdd92008-12-10 05:08:54 +0000951// Implements A<T>().
952template <typename T>
953class AnyMatcherImpl : public MatcherInterface<T> {
954 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000955 virtual bool MatchAndExplain(
956 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000957 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
958 virtual void DescribeNegationTo(::std::ostream* os) const {
959 // This is mostly for completeness' safe, as it's not very useful
960 // to write Not(A<bool>()). However we cannot completely rule out
961 // such a possibility, and it doesn't hurt to be prepared.
962 *os << "never matches";
963 }
964};
965
966// Implements _, a matcher that matches any value of any
967// type. This is a polymorphic matcher, so we need a template type
968// conversion operator to make it appearing as a Matcher<T> for any
969// type T.
970class AnythingMatcher {
971 public:
972 template <typename T>
973 operator Matcher<T>() const { return A<T>(); }
974};
975
976// Implements a matcher that compares a given value with a
977// pre-supplied value using one of the ==, <=, <, etc, operators. The
978// two values being compared don't have to have the same type.
979//
980// The matcher defined here is polymorphic (for example, Eq(5) can be
981// used to match an int, a short, a double, etc). Therefore we use
982// a template type conversion operator in the implementation.
983//
shiqiane35fdd92008-12-10 05:08:54 +0000984// The following template definition assumes that the Rhs parameter is
985// a "bare" type (i.e. neither 'const T' nor 'T&').
kosak506340a2014-11-17 01:47:54 +0000986template <typename D, typename Rhs, typename Op>
987class ComparisonBase {
988 public:
989 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
990 template <typename Lhs>
991 operator Matcher<Lhs>() const {
992 return MakeMatcher(new Impl<Lhs>(rhs_));
shiqiane35fdd92008-12-10 05:08:54 +0000993 }
994
kosak506340a2014-11-17 01:47:54 +0000995 private:
996 template <typename Lhs>
997 class Impl : public MatcherInterface<Lhs> {
998 public:
999 explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
1000 virtual bool MatchAndExplain(
1001 Lhs lhs, MatchResultListener* /* listener */) const {
1002 return Op()(lhs, rhs_);
1003 }
1004 virtual void DescribeTo(::std::ostream* os) const {
1005 *os << D::Desc() << " ";
1006 UniversalPrint(rhs_, os);
1007 }
1008 virtual void DescribeNegationTo(::std::ostream* os) const {
1009 *os << D::NegatedDesc() << " ";
1010 UniversalPrint(rhs_, os);
1011 }
1012 private:
1013 Rhs rhs_;
1014 GTEST_DISALLOW_ASSIGN_(Impl);
1015 };
1016 Rhs rhs_;
1017 GTEST_DISALLOW_ASSIGN_(ComparisonBase);
1018};
shiqiane35fdd92008-12-10 05:08:54 +00001019
kosak506340a2014-11-17 01:47:54 +00001020template <typename Rhs>
1021class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
1022 public:
1023 explicit EqMatcher(const Rhs& rhs)
1024 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
1025 static const char* Desc() { return "is equal to"; }
1026 static const char* NegatedDesc() { return "isn't equal to"; }
1027};
1028template <typename Rhs>
1029class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
1030 public:
1031 explicit NeMatcher(const Rhs& rhs)
1032 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
1033 static const char* Desc() { return "isn't equal to"; }
1034 static const char* NegatedDesc() { return "is equal to"; }
1035};
1036template <typename Rhs>
1037class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
1038 public:
1039 explicit LtMatcher(const Rhs& rhs)
1040 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
1041 static const char* Desc() { return "is <"; }
1042 static const char* NegatedDesc() { return "isn't <"; }
1043};
1044template <typename Rhs>
1045class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
1046 public:
1047 explicit GtMatcher(const Rhs& rhs)
1048 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
1049 static const char* Desc() { return "is >"; }
1050 static const char* NegatedDesc() { return "isn't >"; }
1051};
1052template <typename Rhs>
1053class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
1054 public:
1055 explicit LeMatcher(const Rhs& rhs)
1056 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
1057 static const char* Desc() { return "is <="; }
1058 static const char* NegatedDesc() { return "isn't <="; }
1059};
1060template <typename Rhs>
1061class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
1062 public:
1063 explicit GeMatcher(const Rhs& rhs)
1064 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
1065 static const char* Desc() { return "is >="; }
1066 static const char* NegatedDesc() { return "isn't >="; }
1067};
shiqiane35fdd92008-12-10 05:08:54 +00001068
vladlosev79b83502009-11-18 00:43:37 +00001069// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001070// pointer that is NULL.
1071class IsNullMatcher {
1072 public:
vladlosev79b83502009-11-18 00:43:37 +00001073 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +00001074 bool MatchAndExplain(const Pointer& p,
1075 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001076#if GTEST_LANG_CXX11
1077 return p == nullptr;
1078#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001079 return GetRawPointer(p) == NULL;
kosak6305ff52015-04-28 22:36:31 +00001080#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001081 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001082
1083 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
1084 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001085 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001086 }
1087};
1088
vladlosev79b83502009-11-18 00:43:37 +00001089// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +00001090// pointer that is not NULL.
1091class NotNullMatcher {
1092 public:
vladlosev79b83502009-11-18 00:43:37 +00001093 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +00001094 bool MatchAndExplain(const Pointer& p,
1095 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001096#if GTEST_LANG_CXX11
1097 return p != nullptr;
1098#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001099 return GetRawPointer(p) != NULL;
kosak6305ff52015-04-28 22:36:31 +00001100#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001101 }
shiqiane35fdd92008-12-10 05:08:54 +00001102
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001103 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +00001104 void DescribeNegationTo(::std::ostream* os) const {
1105 *os << "is NULL";
1106 }
1107};
1108
1109// Ref(variable) matches any argument that is a reference to
1110// 'variable'. This matcher is polymorphic as it can match any
1111// super type of the type of 'variable'.
1112//
1113// The RefMatcher template class implements Ref(variable). It can
1114// only be instantiated with a reference type. This prevents a user
1115// from mistakenly using Ref(x) to match a non-reference function
1116// argument. For example, the following will righteously cause a
1117// compiler error:
1118//
1119// int n;
1120// Matcher<int> m1 = Ref(n); // This won't compile.
1121// Matcher<int&> m2 = Ref(n); // This will compile.
1122template <typename T>
1123class RefMatcher;
1124
1125template <typename T>
1126class RefMatcher<T&> {
1127 // Google Mock is a generic framework and thus needs to support
1128 // mocking any function types, including those that take non-const
1129 // reference arguments. Therefore the template parameter T (and
1130 // Super below) can be instantiated to either a const type or a
1131 // non-const type.
1132 public:
1133 // RefMatcher() takes a T& instead of const T&, as we want the
1134 // compiler to catch using Ref(const_value) as a matcher for a
1135 // non-const reference.
1136 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
1137
1138 template <typename Super>
1139 operator Matcher<Super&>() const {
1140 // By passing object_ (type T&) to Impl(), which expects a Super&,
1141 // we make sure that Super is a super type of T. In particular,
1142 // this catches using Ref(const_value) as a matcher for a
1143 // non-const reference, as you cannot implicitly convert a const
1144 // reference to a non-const reference.
1145 return MakeMatcher(new Impl<Super>(object_));
1146 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001147
shiqiane35fdd92008-12-10 05:08:54 +00001148 private:
1149 template <typename Super>
1150 class Impl : public MatcherInterface<Super&> {
1151 public:
1152 explicit Impl(Super& x) : object_(x) {} // NOLINT
1153
zhanyong.wandb22c222010-01-28 21:52:29 +00001154 // MatchAndExplain() takes a Super& (as opposed to const Super&)
1155 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +00001156 virtual bool MatchAndExplain(
1157 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001158 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +00001159 return &x == &object_;
1160 }
shiqiane35fdd92008-12-10 05:08:54 +00001161
1162 virtual void DescribeTo(::std::ostream* os) const {
1163 *os << "references the variable ";
1164 UniversalPrinter<Super&>::Print(object_, os);
1165 }
1166
1167 virtual void DescribeNegationTo(::std::ostream* os) const {
1168 *os << "does not reference the variable ";
1169 UniversalPrinter<Super&>::Print(object_, os);
1170 }
1171
shiqiane35fdd92008-12-10 05:08:54 +00001172 private:
1173 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001174
1175 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001176 };
1177
1178 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001179
1180 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001181};
1182
1183// Polymorphic helper functions for narrow and wide string matchers.
1184inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1185 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1186}
1187
1188inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1189 const wchar_t* rhs) {
1190 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1191}
1192
1193// String comparison for narrow or wide strings that can have embedded NUL
1194// characters.
1195template <typename StringType>
1196bool CaseInsensitiveStringEquals(const StringType& s1,
1197 const StringType& s2) {
1198 // Are the heads equal?
1199 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1200 return false;
1201 }
1202
1203 // Skip the equal heads.
1204 const typename StringType::value_type nul = 0;
1205 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1206
1207 // Are we at the end of either s1 or s2?
1208 if (i1 == StringType::npos || i2 == StringType::npos) {
1209 return i1 == i2;
1210 }
1211
1212 // Are the tails equal?
1213 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1214}
1215
1216// String matchers.
1217
1218// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1219template <typename StringType>
1220class StrEqualityMatcher {
1221 public:
shiqiane35fdd92008-12-10 05:08:54 +00001222 StrEqualityMatcher(const StringType& str, bool expect_eq,
1223 bool case_sensitive)
1224 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1225
jgm38513a82012-11-15 15:50:36 +00001226 // Accepts pointer types, particularly:
1227 // const char*
1228 // char*
1229 // const wchar_t*
1230 // wchar_t*
1231 template <typename CharType>
1232 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001233 if (s == NULL) {
1234 return !expect_eq_;
1235 }
zhanyong.wandb22c222010-01-28 21:52:29 +00001236 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001237 }
1238
jgm38513a82012-11-15 15:50:36 +00001239 // Matches anything that can convert to StringType.
1240 //
1241 // This is a template, not just a plain function with const StringType&,
1242 // because StringPiece has some interfering non-explicit constructors.
1243 template <typename MatcheeStringType>
1244 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001245 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001246 const StringType& s2(s);
1247 const bool eq = case_sensitive_ ? s2 == string_ :
1248 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +00001249 return expect_eq_ == eq;
1250 }
1251
1252 void DescribeTo(::std::ostream* os) const {
1253 DescribeToHelper(expect_eq_, os);
1254 }
1255
1256 void DescribeNegationTo(::std::ostream* os) const {
1257 DescribeToHelper(!expect_eq_, os);
1258 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001259
shiqiane35fdd92008-12-10 05:08:54 +00001260 private:
1261 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001262 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +00001263 *os << "equal to ";
1264 if (!case_sensitive_) {
1265 *os << "(ignoring case) ";
1266 }
vladloseve2e8ba42010-05-13 18:16:03 +00001267 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001268 }
1269
1270 const StringType string_;
1271 const bool expect_eq_;
1272 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001273
1274 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001275};
1276
1277// Implements the polymorphic HasSubstr(substring) matcher, which
1278// can be used as a Matcher<T> as long as T can be converted to a
1279// string.
1280template <typename StringType>
1281class HasSubstrMatcher {
1282 public:
shiqiane35fdd92008-12-10 05:08:54 +00001283 explicit HasSubstrMatcher(const StringType& substring)
1284 : substring_(substring) {}
1285
jgm38513a82012-11-15 15:50:36 +00001286 // Accepts pointer types, particularly:
1287 // const char*
1288 // char*
1289 // const wchar_t*
1290 // wchar_t*
1291 template <typename CharType>
1292 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001293 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001294 }
1295
jgm38513a82012-11-15 15:50:36 +00001296 // Matches anything that can convert to StringType.
1297 //
1298 // This is a template, not just a plain function with const StringType&,
1299 // because StringPiece has some interfering non-explicit constructors.
1300 template <typename MatcheeStringType>
1301 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001302 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001303 const StringType& s2(s);
1304 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001305 }
1306
1307 // Describes what this matcher matches.
1308 void DescribeTo(::std::ostream* os) const {
1309 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001310 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001311 }
1312
1313 void DescribeNegationTo(::std::ostream* os) const {
1314 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001315 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001316 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001317
shiqiane35fdd92008-12-10 05:08:54 +00001318 private:
1319 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001320
1321 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001322};
1323
1324// Implements the polymorphic StartsWith(substring) matcher, which
1325// can be used as a Matcher<T> as long as T can be converted to a
1326// string.
1327template <typename StringType>
1328class StartsWithMatcher {
1329 public:
shiqiane35fdd92008-12-10 05:08:54 +00001330 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1331 }
1332
jgm38513a82012-11-15 15:50:36 +00001333 // Accepts pointer types, particularly:
1334 // const char*
1335 // char*
1336 // const wchar_t*
1337 // wchar_t*
1338 template <typename CharType>
1339 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001340 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001341 }
1342
jgm38513a82012-11-15 15:50:36 +00001343 // Matches anything that can convert to StringType.
1344 //
1345 // This is a template, not just a plain function with const StringType&,
1346 // because StringPiece has some interfering non-explicit constructors.
1347 template <typename MatcheeStringType>
1348 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001349 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001350 const StringType& s2(s);
1351 return s2.length() >= prefix_.length() &&
1352 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001353 }
1354
1355 void DescribeTo(::std::ostream* os) const {
1356 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001357 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001358 }
1359
1360 void DescribeNegationTo(::std::ostream* os) const {
1361 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001362 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001363 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001364
shiqiane35fdd92008-12-10 05:08:54 +00001365 private:
1366 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001367
1368 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001369};
1370
1371// Implements the polymorphic EndsWith(substring) matcher, which
1372// can be used as a Matcher<T> as long as T can be converted to a
1373// string.
1374template <typename StringType>
1375class EndsWithMatcher {
1376 public:
shiqiane35fdd92008-12-10 05:08:54 +00001377 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1378
jgm38513a82012-11-15 15:50:36 +00001379 // Accepts pointer types, particularly:
1380 // const char*
1381 // char*
1382 // const wchar_t*
1383 // wchar_t*
1384 template <typename CharType>
1385 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001386 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001387 }
1388
jgm38513a82012-11-15 15:50:36 +00001389 // Matches anything that can convert to StringType.
1390 //
1391 // This is a template, not just a plain function with const StringType&,
1392 // because StringPiece has some interfering non-explicit constructors.
1393 template <typename MatcheeStringType>
1394 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001395 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001396 const StringType& s2(s);
1397 return s2.length() >= suffix_.length() &&
1398 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001399 }
1400
1401 void DescribeTo(::std::ostream* os) const {
1402 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001403 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001404 }
1405
1406 void DescribeNegationTo(::std::ostream* os) const {
1407 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001408 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001409 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001410
shiqiane35fdd92008-12-10 05:08:54 +00001411 private:
1412 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001413
1414 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001415};
1416
shiqiane35fdd92008-12-10 05:08:54 +00001417// Implements polymorphic matchers MatchesRegex(regex) and
1418// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1419// T can be converted to a string.
1420class MatchesRegexMatcher {
1421 public:
1422 MatchesRegexMatcher(const RE* regex, bool full_match)
1423 : regex_(regex), full_match_(full_match) {}
1424
jgm38513a82012-11-15 15:50:36 +00001425 // Accepts pointer types, particularly:
1426 // const char*
1427 // char*
1428 // const wchar_t*
1429 // wchar_t*
1430 template <typename CharType>
1431 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001432 return s != NULL && MatchAndExplain(std::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001433 }
1434
Nico Weber09fd5b32017-05-15 17:07:03 -04001435 // Matches anything that can convert to std::string.
jgm38513a82012-11-15 15:50:36 +00001436 //
Nico Weber09fd5b32017-05-15 17:07:03 -04001437 // This is a template, not just a plain function with const std::string&,
Gennadiy Civilb7c56832018-03-22 15:35:37 -04001438 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001439 template <class MatcheeStringType>
1440 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001441 MatchResultListener* /* listener */) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001442 const std::string& s2(s);
jgm38513a82012-11-15 15:50:36 +00001443 return full_match_ ? RE::FullMatch(s2, *regex_) :
1444 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001445 }
1446
1447 void DescribeTo(::std::ostream* os) const {
1448 *os << (full_match_ ? "matches" : "contains")
1449 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001450 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001451 }
1452
1453 void DescribeNegationTo(::std::ostream* os) const {
1454 *os << "doesn't " << (full_match_ ? "match" : "contain")
1455 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001456 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001457 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001458
shiqiane35fdd92008-12-10 05:08:54 +00001459 private:
1460 const internal::linked_ptr<const RE> regex_;
1461 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001462
1463 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001464};
1465
shiqiane35fdd92008-12-10 05:08:54 +00001466// Implements a matcher that compares the two fields of a 2-tuple
1467// using one of the ==, <=, <, etc, operators. The two fields being
1468// compared don't have to have the same type.
1469//
1470// The matcher defined here is polymorphic (for example, Eq() can be
1471// used to match a tuple<int, short>, a tuple<const long&, double>,
1472// etc). Therefore we use a template type conversion operator in the
1473// implementation.
kosak506340a2014-11-17 01:47:54 +00001474template <typename D, typename Op>
1475class PairMatchBase {
1476 public:
1477 template <typename T1, typename T2>
1478 operator Matcher< ::testing::tuple<T1, T2> >() const {
1479 return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >);
1480 }
1481 template <typename T1, typename T2>
1482 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
1483 return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>);
shiqiane35fdd92008-12-10 05:08:54 +00001484 }
1485
kosak506340a2014-11-17 01:47:54 +00001486 private:
1487 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
1488 return os << D::Desc();
1489 }
shiqiane35fdd92008-12-10 05:08:54 +00001490
kosak506340a2014-11-17 01:47:54 +00001491 template <typename Tuple>
1492 class Impl : public MatcherInterface<Tuple> {
1493 public:
1494 virtual bool MatchAndExplain(
1495 Tuple args,
1496 MatchResultListener* /* listener */) const {
1497 return Op()(::testing::get<0>(args), ::testing::get<1>(args));
1498 }
1499 virtual void DescribeTo(::std::ostream* os) const {
1500 *os << "are " << GetDesc;
1501 }
1502 virtual void DescribeNegationTo(::std::ostream* os) const {
1503 *os << "aren't " << GetDesc;
1504 }
1505 };
1506};
1507
1508class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
1509 public:
1510 static const char* Desc() { return "an equal pair"; }
1511};
1512class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
1513 public:
1514 static const char* Desc() { return "an unequal pair"; }
1515};
1516class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
1517 public:
1518 static const char* Desc() { return "a pair where the first < the second"; }
1519};
1520class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
1521 public:
1522 static const char* Desc() { return "a pair where the first > the second"; }
1523};
1524class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
1525 public:
1526 static const char* Desc() { return "a pair where the first <= the second"; }
1527};
1528class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
1529 public:
1530 static const char* Desc() { return "a pair where the first >= the second"; }
1531};
shiqiane35fdd92008-12-10 05:08:54 +00001532
zhanyong.wanc6a41232009-05-13 23:38:40 +00001533// Implements the Not(...) matcher for a particular argument type T.
1534// We do not nest it inside the NotMatcher class template, as that
1535// will prevent different instantiations of NotMatcher from sharing
1536// the same NotMatcherImpl<T> class.
1537template <typename T>
1538class NotMatcherImpl : public MatcherInterface<T> {
1539 public:
1540 explicit NotMatcherImpl(const Matcher<T>& matcher)
1541 : matcher_(matcher) {}
1542
zhanyong.wan82113312010-01-08 21:55:40 +00001543 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1544 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001545 }
1546
1547 virtual void DescribeTo(::std::ostream* os) const {
1548 matcher_.DescribeNegationTo(os);
1549 }
1550
1551 virtual void DescribeNegationTo(::std::ostream* os) const {
1552 matcher_.DescribeTo(os);
1553 }
1554
zhanyong.wanc6a41232009-05-13 23:38:40 +00001555 private:
1556 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001557
1558 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001559};
1560
shiqiane35fdd92008-12-10 05:08:54 +00001561// Implements the Not(m) matcher, which matches a value that doesn't
1562// match matcher m.
1563template <typename InnerMatcher>
1564class NotMatcher {
1565 public:
1566 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1567
1568 // This template type conversion operator allows Not(m) to be used
1569 // to match any type m can match.
1570 template <typename T>
1571 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001572 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001573 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001574
shiqiane35fdd92008-12-10 05:08:54 +00001575 private:
shiqiane35fdd92008-12-10 05:08:54 +00001576 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001577
1578 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001579};
1580
zhanyong.wanc6a41232009-05-13 23:38:40 +00001581// Implements the AllOf(m1, m2) matcher for a particular argument type
1582// T. We do not nest it inside the BothOfMatcher class template, as
1583// that will prevent different instantiations of BothOfMatcher from
1584// sharing the same BothOfMatcherImpl<T> class.
1585template <typename T>
1586class BothOfMatcherImpl : public MatcherInterface<T> {
1587 public:
1588 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1589 : matcher1_(matcher1), matcher2_(matcher2) {}
1590
zhanyong.wanc6a41232009-05-13 23:38:40 +00001591 virtual void DescribeTo(::std::ostream* os) const {
1592 *os << "(";
1593 matcher1_.DescribeTo(os);
1594 *os << ") and (";
1595 matcher2_.DescribeTo(os);
1596 *os << ")";
1597 }
1598
1599 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001600 *os << "(";
1601 matcher1_.DescribeNegationTo(os);
1602 *os << ") or (";
1603 matcher2_.DescribeNegationTo(os);
1604 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001605 }
1606
zhanyong.wan82113312010-01-08 21:55:40 +00001607 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1608 // If either matcher1_ or matcher2_ doesn't match x, we only need
1609 // to explain why one of them fails.
1610 StringMatchResultListener listener1;
1611 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1612 *listener << listener1.str();
1613 return false;
1614 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001615
zhanyong.wan82113312010-01-08 21:55:40 +00001616 StringMatchResultListener listener2;
1617 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1618 *listener << listener2.str();
1619 return false;
1620 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001621
zhanyong.wan82113312010-01-08 21:55:40 +00001622 // Otherwise we need to explain why *both* of them match.
Nico Weber09fd5b32017-05-15 17:07:03 -04001623 const std::string s1 = listener1.str();
1624 const std::string s2 = listener2.str();
zhanyong.wan82113312010-01-08 21:55:40 +00001625
1626 if (s1 == "") {
1627 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001628 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001629 *listener << s1;
1630 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001631 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001632 }
1633 }
zhanyong.wan82113312010-01-08 21:55:40 +00001634 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001635 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001636
zhanyong.wanc6a41232009-05-13 23:38:40 +00001637 private:
1638 const Matcher<T> matcher1_;
1639 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001640
1641 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001642};
1643
zhanyong.wan616180e2013-06-18 18:49:51 +00001644#if GTEST_LANG_CXX11
1645// MatcherList provides mechanisms for storing a variable number of matchers in
1646// a list structure (ListType) and creating a combining matcher from such a
1647// list.
Troy Holsapplec8510502018-02-07 22:06:00 -08001648// The template is defined recursively using the following template parameters:
zhanyong.wan616180e2013-06-18 18:49:51 +00001649// * kSize is the length of the MatcherList.
1650// * Head is the type of the first matcher of the list.
1651// * Tail denotes the types of the remaining matchers of the list.
1652template <int kSize, typename Head, typename... Tail>
1653struct MatcherList {
1654 typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
zhanyong.wan29897032013-06-20 18:59:15 +00001655 typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001656
1657 // BuildList stores variadic type values in a nested pair structure.
1658 // Example:
1659 // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
1660 // the corresponding result of type pair<int, pair<string, float>>.
1661 static ListType BuildList(const Head& matcher, const Tail&... tail) {
1662 return ListType(matcher, MatcherListTail::BuildList(tail...));
1663 }
1664
1665 // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
1666 // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
1667 // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
1668 // constructor taking two Matcher<T>s as input.
1669 template <typename T, template <typename /* T */> class CombiningMatcher>
1670 static Matcher<T> CreateMatcher(const ListType& matchers) {
1671 return Matcher<T>(new CombiningMatcher<T>(
1672 SafeMatcherCast<T>(matchers.first),
1673 MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
1674 matchers.second)));
1675 }
1676};
1677
1678// The following defines the base case for the recursive definition of
1679// MatcherList.
1680template <typename Matcher1, typename Matcher2>
1681struct MatcherList<2, Matcher1, Matcher2> {
zhanyong.wan29897032013-06-20 18:59:15 +00001682 typedef ::std::pair<Matcher1, Matcher2> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001683
1684 static ListType BuildList(const Matcher1& matcher1,
1685 const Matcher2& matcher2) {
zhanyong.wan29897032013-06-20 18:59:15 +00001686 return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
zhanyong.wan616180e2013-06-18 18:49:51 +00001687 }
1688
1689 template <typename T, template <typename /* T */> class CombiningMatcher>
1690 static Matcher<T> CreateMatcher(const ListType& matchers) {
1691 return Matcher<T>(new CombiningMatcher<T>(
1692 SafeMatcherCast<T>(matchers.first),
1693 SafeMatcherCast<T>(matchers.second)));
1694 }
1695};
1696
1697// VariadicMatcher is used for the variadic implementation of
1698// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1699// CombiningMatcher<T> is used to recursively combine the provided matchers
1700// (of type Args...).
1701template <template <typename T> class CombiningMatcher, typename... Args>
1702class VariadicMatcher {
1703 public:
1704 VariadicMatcher(const Args&... matchers) // NOLINT
1705 : matchers_(MatcherListType::BuildList(matchers...)) {}
1706
1707 // This template type conversion operator allows an
1708 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1709 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1710 template <typename T>
1711 operator Matcher<T>() const {
1712 return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
1713 matchers_);
1714 }
1715
1716 private:
1717 typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
1718
1719 const typename MatcherListType::ListType matchers_;
1720
1721 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1722};
1723
1724template <typename... Args>
1725using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
1726
1727#endif // GTEST_LANG_CXX11
1728
shiqiane35fdd92008-12-10 05:08:54 +00001729// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1730// matches a value that matches all of the matchers m_1, ..., and m_n.
1731template <typename Matcher1, typename Matcher2>
1732class BothOfMatcher {
1733 public:
1734 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1735 : matcher1_(matcher1), matcher2_(matcher2) {}
1736
1737 // This template type conversion operator allows a
1738 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1739 // both Matcher1 and Matcher2 can match.
1740 template <typename T>
1741 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001742 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1743 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001744 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001745
shiqiane35fdd92008-12-10 05:08:54 +00001746 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001747 Matcher1 matcher1_;
1748 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001749
1750 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001751};
shiqiane35fdd92008-12-10 05:08:54 +00001752
zhanyong.wanc6a41232009-05-13 23:38:40 +00001753// Implements the AnyOf(m1, m2) matcher for a particular argument type
1754// T. We do not nest it inside the AnyOfMatcher class template, as
1755// that will prevent different instantiations of AnyOfMatcher from
1756// sharing the same EitherOfMatcherImpl<T> class.
1757template <typename T>
1758class EitherOfMatcherImpl : public MatcherInterface<T> {
1759 public:
1760 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1761 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001762
zhanyong.wanc6a41232009-05-13 23:38:40 +00001763 virtual void DescribeTo(::std::ostream* os) const {
1764 *os << "(";
1765 matcher1_.DescribeTo(os);
1766 *os << ") or (";
1767 matcher2_.DescribeTo(os);
1768 *os << ")";
1769 }
shiqiane35fdd92008-12-10 05:08:54 +00001770
zhanyong.wanc6a41232009-05-13 23:38:40 +00001771 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001772 *os << "(";
1773 matcher1_.DescribeNegationTo(os);
1774 *os << ") and (";
1775 matcher2_.DescribeNegationTo(os);
1776 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001777 }
shiqiane35fdd92008-12-10 05:08:54 +00001778
zhanyong.wan82113312010-01-08 21:55:40 +00001779 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1780 // If either matcher1_ or matcher2_ matches x, we just need to
1781 // explain why *one* of them matches.
1782 StringMatchResultListener listener1;
1783 if (matcher1_.MatchAndExplain(x, &listener1)) {
1784 *listener << listener1.str();
1785 return true;
1786 }
1787
1788 StringMatchResultListener listener2;
1789 if (matcher2_.MatchAndExplain(x, &listener2)) {
1790 *listener << listener2.str();
1791 return true;
1792 }
1793
1794 // Otherwise we need to explain why *both* of them fail.
Nico Weber09fd5b32017-05-15 17:07:03 -04001795 const std::string s1 = listener1.str();
1796 const std::string s2 = listener2.str();
zhanyong.wan82113312010-01-08 21:55:40 +00001797
1798 if (s1 == "") {
1799 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001800 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001801 *listener << s1;
1802 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001803 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001804 }
1805 }
zhanyong.wan82113312010-01-08 21:55:40 +00001806 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001807 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001808
zhanyong.wanc6a41232009-05-13 23:38:40 +00001809 private:
1810 const Matcher<T> matcher1_;
1811 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001812
1813 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001814};
1815
zhanyong.wan616180e2013-06-18 18:49:51 +00001816#if GTEST_LANG_CXX11
1817// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1818template <typename... Args>
1819using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
1820
1821#endif // GTEST_LANG_CXX11
1822
shiqiane35fdd92008-12-10 05:08:54 +00001823// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1824// matches a value that matches at least one of the matchers m_1, ...,
1825// and m_n.
1826template <typename Matcher1, typename Matcher2>
1827class EitherOfMatcher {
1828 public:
1829 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1830 : matcher1_(matcher1), matcher2_(matcher2) {}
1831
1832 // This template type conversion operator allows a
1833 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1834 // both Matcher1 and Matcher2 can match.
1835 template <typename T>
1836 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001837 return Matcher<T>(new EitherOfMatcherImpl<T>(
1838 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001839 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001840
shiqiane35fdd92008-12-10 05:08:54 +00001841 private:
shiqiane35fdd92008-12-10 05:08:54 +00001842 Matcher1 matcher1_;
1843 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001844
1845 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001846};
1847
1848// Used for implementing Truly(pred), which turns a predicate into a
1849// matcher.
1850template <typename Predicate>
1851class TrulyMatcher {
1852 public:
1853 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1854
1855 // This method template allows Truly(pred) to be used as a matcher
1856 // for type T where T is the argument type of predicate 'pred'. The
1857 // argument is passed by reference as the predicate may be
1858 // interested in the address of the argument.
1859 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001860 bool MatchAndExplain(T& x, // NOLINT
1861 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001862 // Without the if-statement, MSVC sometimes warns about converting
1863 // a value to bool (warning 4800).
1864 //
1865 // We cannot write 'return !!predicate_(x);' as that doesn't work
1866 // when predicate_(x) returns a class convertible to bool but
1867 // having no operator!().
1868 if (predicate_(x))
1869 return true;
1870 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001871 }
1872
1873 void DescribeTo(::std::ostream* os) const {
1874 *os << "satisfies the given predicate";
1875 }
1876
1877 void DescribeNegationTo(::std::ostream* os) const {
1878 *os << "doesn't satisfy the given predicate";
1879 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001880
shiqiane35fdd92008-12-10 05:08:54 +00001881 private:
1882 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001883
1884 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001885};
1886
1887// Used for implementing Matches(matcher), which turns a matcher into
1888// a predicate.
1889template <typename M>
1890class MatcherAsPredicate {
1891 public:
1892 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1893
1894 // This template operator() allows Matches(m) to be used as a
1895 // predicate on type T where m is a matcher on type T.
1896 //
1897 // The argument x is passed by reference instead of by value, as
1898 // some matcher may be interested in its address (e.g. as in
1899 // Matches(Ref(n))(x)).
1900 template <typename T>
1901 bool operator()(const T& x) const {
1902 // We let matcher_ commit to a particular type here instead of
1903 // when the MatcherAsPredicate object was constructed. This
1904 // allows us to write Matches(m) where m is a polymorphic matcher
1905 // (e.g. Eq(5)).
1906 //
1907 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1908 // compile when matcher_ has type Matcher<const T&>; if we write
1909 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1910 // when matcher_ has type Matcher<T>; if we just write
1911 // matcher_.Matches(x), it won't compile when matcher_ is
1912 // polymorphic, e.g. Eq(5).
1913 //
1914 // MatcherCast<const T&>() is necessary for making the code work
1915 // in all of the above situations.
1916 return MatcherCast<const T&>(matcher_).Matches(x);
1917 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001918
shiqiane35fdd92008-12-10 05:08:54 +00001919 private:
1920 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001921
1922 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001923};
1924
1925// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1926// argument M must be a type that can be converted to a matcher.
1927template <typename M>
1928class PredicateFormatterFromMatcher {
1929 public:
kosak9b1a9442015-04-28 23:06:58 +00001930 explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {}
shiqiane35fdd92008-12-10 05:08:54 +00001931
1932 // This template () operator allows a PredicateFormatterFromMatcher
1933 // object to act as a predicate-formatter suitable for using with
1934 // Google Test's EXPECT_PRED_FORMAT1() macro.
1935 template <typename T>
1936 AssertionResult operator()(const char* value_text, const T& x) const {
1937 // We convert matcher_ to a Matcher<const T&> *now* instead of
1938 // when the PredicateFormatterFromMatcher object was constructed,
1939 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1940 // know which type to instantiate it to until we actually see the
1941 // type of x here.
1942 //
zhanyong.wanf4274522013-04-24 02:49:43 +00001943 // We write SafeMatcherCast<const T&>(matcher_) instead of
shiqiane35fdd92008-12-10 05:08:54 +00001944 // Matcher<const T&>(matcher_), as the latter won't compile when
1945 // matcher_ has type Matcher<T> (e.g. An<int>()).
zhanyong.wanf4274522013-04-24 02:49:43 +00001946 // We don't write MatcherCast<const T&> either, as that allows
1947 // potentially unsafe downcasting of the matcher argument.
1948 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001949 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001950 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001951 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001952
1953 ::std::stringstream ss;
1954 ss << "Value of: " << value_text << "\n"
1955 << "Expected: ";
1956 matcher.DescribeTo(&ss);
1957 ss << "\n Actual: " << listener.str();
1958 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001959 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001960
shiqiane35fdd92008-12-10 05:08:54 +00001961 private:
1962 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001963
1964 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001965};
1966
1967// A helper function for converting a matcher to a predicate-formatter
1968// without the user needing to explicitly write the type. This is
1969// used for implementing ASSERT_THAT() and EXPECT_THAT().
kosak9b1a9442015-04-28 23:06:58 +00001970// Implementation detail: 'matcher' is received by-value to force decaying.
shiqiane35fdd92008-12-10 05:08:54 +00001971template <typename M>
1972inline PredicateFormatterFromMatcher<M>
kosak9b1a9442015-04-28 23:06:58 +00001973MakePredicateFormatterFromMatcher(M matcher) {
1974 return PredicateFormatterFromMatcher<M>(internal::move(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00001975}
1976
zhanyong.wan616180e2013-06-18 18:49:51 +00001977// Implements the polymorphic floating point equality matcher, which matches
1978// two float values using ULP-based approximation or, optionally, a
1979// user-specified epsilon. The template is meant to be instantiated with
1980// FloatType being either float or double.
shiqiane35fdd92008-12-10 05:08:54 +00001981template <typename FloatType>
1982class FloatingEqMatcher {
1983 public:
1984 // Constructor for FloatingEqMatcher.
kosak6b817802015-01-08 02:38:14 +00001985 // The matcher's input will be compared with expected. The matcher treats two
shiqiane35fdd92008-12-10 05:08:54 +00001986 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
zhanyong.wan616180e2013-06-18 18:49:51 +00001987 // equality comparisons between NANs will always return false. We specify a
1988 // negative max_abs_error_ term to indicate that ULP-based approximation will
1989 // be used for comparison.
kosak6b817802015-01-08 02:38:14 +00001990 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
1991 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001992 }
1993
1994 // Constructor that supports a user-specified max_abs_error that will be used
1995 // for comparison instead of ULP-based approximation. The max absolute
1996 // should be non-negative.
kosak6b817802015-01-08 02:38:14 +00001997 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
1998 FloatType max_abs_error)
1999 : expected_(expected),
2000 nan_eq_nan_(nan_eq_nan),
2001 max_abs_error_(max_abs_error) {
zhanyong.wan616180e2013-06-18 18:49:51 +00002002 GTEST_CHECK_(max_abs_error >= 0)
2003 << ", where max_abs_error is" << max_abs_error;
2004 }
shiqiane35fdd92008-12-10 05:08:54 +00002005
2006 // Implements floating point equality matcher as a Matcher<T>.
2007 template <typename T>
2008 class Impl : public MatcherInterface<T> {
2009 public:
kosak6b817802015-01-08 02:38:14 +00002010 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
2011 : expected_(expected),
2012 nan_eq_nan_(nan_eq_nan),
2013 max_abs_error_(max_abs_error) {}
shiqiane35fdd92008-12-10 05:08:54 +00002014
zhanyong.wan82113312010-01-08 21:55:40 +00002015 virtual bool MatchAndExplain(T value,
kosak6b817802015-01-08 02:38:14 +00002016 MatchResultListener* listener) const {
2017 const FloatingPoint<FloatType> actual(value), expected(expected_);
shiqiane35fdd92008-12-10 05:08:54 +00002018
2019 // Compares NaNs first, if nan_eq_nan_ is true.
kosak6b817802015-01-08 02:38:14 +00002020 if (actual.is_nan() || expected.is_nan()) {
2021 if (actual.is_nan() && expected.is_nan()) {
zhanyong.wan616180e2013-06-18 18:49:51 +00002022 return nan_eq_nan_;
2023 }
2024 // One is nan; the other is not nan.
2025 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002026 }
zhanyong.wan616180e2013-06-18 18:49:51 +00002027 if (HasMaxAbsError()) {
2028 // We perform an equality check so that inf will match inf, regardless
kosak6b817802015-01-08 02:38:14 +00002029 // of error bounds. If the result of value - expected_ would result in
zhanyong.wan616180e2013-06-18 18:49:51 +00002030 // overflow or if either value is inf, the default result is infinity,
2031 // which should only match if max_abs_error_ is also infinity.
kosak6b817802015-01-08 02:38:14 +00002032 if (value == expected_) {
2033 return true;
2034 }
2035
2036 const FloatType diff = value - expected_;
2037 if (fabs(diff) <= max_abs_error_) {
2038 return true;
2039 }
2040
2041 if (listener->IsInterested()) {
2042 *listener << "which is " << diff << " from " << expected_;
2043 }
2044 return false;
zhanyong.wan616180e2013-06-18 18:49:51 +00002045 } else {
kosak6b817802015-01-08 02:38:14 +00002046 return actual.AlmostEquals(expected);
zhanyong.wan616180e2013-06-18 18:49:51 +00002047 }
shiqiane35fdd92008-12-10 05:08:54 +00002048 }
2049
2050 virtual void DescribeTo(::std::ostream* os) const {
2051 // os->precision() returns the previously set precision, which we
2052 // store to restore the ostream to its original configuration
2053 // after outputting.
2054 const ::std::streamsize old_precision = os->precision(
2055 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00002056 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00002057 if (nan_eq_nan_) {
2058 *os << "is NaN";
2059 } else {
2060 *os << "never matches";
2061 }
2062 } else {
kosak6b817802015-01-08 02:38:14 +00002063 *os << "is approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002064 if (HasMaxAbsError()) {
2065 *os << " (absolute error <= " << max_abs_error_ << ")";
2066 }
shiqiane35fdd92008-12-10 05:08:54 +00002067 }
2068 os->precision(old_precision);
2069 }
2070
2071 virtual void DescribeNegationTo(::std::ostream* os) const {
2072 // As before, get original precision.
2073 const ::std::streamsize old_precision = os->precision(
2074 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00002075 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00002076 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002077 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00002078 } else {
2079 *os << "is anything";
2080 }
2081 } else {
kosak6b817802015-01-08 02:38:14 +00002082 *os << "isn't approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002083 if (HasMaxAbsError()) {
2084 *os << " (absolute error > " << max_abs_error_ << ")";
2085 }
shiqiane35fdd92008-12-10 05:08:54 +00002086 }
2087 // Restore original precision.
2088 os->precision(old_precision);
2089 }
2090
2091 private:
zhanyong.wan616180e2013-06-18 18:49:51 +00002092 bool HasMaxAbsError() const {
2093 return max_abs_error_ >= 0;
2094 }
2095
kosak6b817802015-01-08 02:38:14 +00002096 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002097 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002098 // max_abs_error will be used for value comparison when >= 0.
2099 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002100
2101 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002102 };
2103
kosak6b817802015-01-08 02:38:14 +00002104 // The following 3 type conversion operators allow FloatEq(expected) and
2105 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
shiqiane35fdd92008-12-10 05:08:54 +00002106 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
2107 // (While Google's C++ coding style doesn't allow arguments passed
2108 // by non-const reference, we may see them in code not conforming to
2109 // the style. Therefore Google Mock needs to support them.)
2110 operator Matcher<FloatType>() const {
kosak6b817802015-01-08 02:38:14 +00002111 return MakeMatcher(
2112 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002113 }
2114
2115 operator Matcher<const FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00002116 return MakeMatcher(
kosak6b817802015-01-08 02:38:14 +00002117 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002118 }
2119
2120 operator Matcher<FloatType&>() const {
kosak6b817802015-01-08 02:38:14 +00002121 return MakeMatcher(
2122 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002123 }
jgm79a367e2012-04-10 16:02:11 +00002124
shiqiane35fdd92008-12-10 05:08:54 +00002125 private:
kosak6b817802015-01-08 02:38:14 +00002126 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002127 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002128 // max_abs_error will be used for value comparison when >= 0.
2129 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002130
2131 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002132};
2133
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002134// A 2-tuple ("binary") wrapper around FloatingEqMatcher:
2135// FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false)
2136// against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e)
2137// against y. The former implements "Eq", the latter "Near". At present, there
2138// is no version that compares NaNs as equal.
2139template <typename FloatType>
2140class FloatingEq2Matcher {
2141 public:
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002142 FloatingEq2Matcher() { Init(-1, false); }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002143
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002144 explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002145
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002146 explicit FloatingEq2Matcher(FloatType max_abs_error) {
2147 Init(max_abs_error, false);
2148 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002149
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002150 FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) {
2151 Init(max_abs_error, nan_eq_nan);
2152 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002153
2154 template <typename T1, typename T2>
2155 operator Matcher< ::testing::tuple<T1, T2> >() const {
2156 return MakeMatcher(
2157 new Impl< ::testing::tuple<T1, T2> >(max_abs_error_, nan_eq_nan_));
2158 }
2159 template <typename T1, typename T2>
2160 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
2161 return MakeMatcher(
2162 new Impl<const ::testing::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_));
2163 }
2164
2165 private:
2166 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
2167 return os << "an almost-equal pair";
2168 }
2169
2170 template <typename Tuple>
2171 class Impl : public MatcherInterface<Tuple> {
2172 public:
2173 Impl(FloatType max_abs_error, bool nan_eq_nan) :
2174 max_abs_error_(max_abs_error),
2175 nan_eq_nan_(nan_eq_nan) {}
2176
2177 virtual bool MatchAndExplain(Tuple args,
2178 MatchResultListener* listener) const {
2179 if (max_abs_error_ == -1) {
2180 FloatingEqMatcher<FloatType> fm(::testing::get<0>(args), nan_eq_nan_);
2181 return static_cast<Matcher<FloatType> >(fm).MatchAndExplain(
2182 ::testing::get<1>(args), listener);
2183 } else {
2184 FloatingEqMatcher<FloatType> fm(::testing::get<0>(args), nan_eq_nan_,
2185 max_abs_error_);
2186 return static_cast<Matcher<FloatType> >(fm).MatchAndExplain(
2187 ::testing::get<1>(args), listener);
2188 }
2189 }
2190 virtual void DescribeTo(::std::ostream* os) const {
2191 *os << "are " << GetDesc;
2192 }
2193 virtual void DescribeNegationTo(::std::ostream* os) const {
2194 *os << "aren't " << GetDesc;
2195 }
2196
2197 private:
2198 FloatType max_abs_error_;
2199 const bool nan_eq_nan_;
2200 };
2201
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002202 void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) {
2203 max_abs_error_ = max_abs_error_val;
2204 nan_eq_nan_ = nan_eq_nan_val;
2205 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002206 FloatType max_abs_error_;
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002207 bool nan_eq_nan_;
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002208};
2209
shiqiane35fdd92008-12-10 05:08:54 +00002210// Implements the Pointee(m) matcher for matching a pointer whose
2211// pointee matches matcher m. The pointer can be either raw or smart.
2212template <typename InnerMatcher>
2213class PointeeMatcher {
2214 public:
2215 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
2216
2217 // This type conversion operator template allows Pointee(m) to be
2218 // used as a matcher for any pointer type whose pointee type is
2219 // compatible with the inner matcher, where type Pointer can be
2220 // either a raw pointer or a smart pointer.
2221 //
2222 // The reason we do this instead of relying on
2223 // MakePolymorphicMatcher() is that the latter is not flexible
2224 // enough for implementing the DescribeTo() method of Pointee().
2225 template <typename Pointer>
2226 operator Matcher<Pointer>() const {
2227 return MakeMatcher(new Impl<Pointer>(matcher_));
2228 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002229
shiqiane35fdd92008-12-10 05:08:54 +00002230 private:
2231 // The monomorphic implementation that works for a particular pointer type.
2232 template <typename Pointer>
2233 class Impl : public MatcherInterface<Pointer> {
2234 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00002235 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
2236 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00002237
2238 explicit Impl(const InnerMatcher& matcher)
2239 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
2240
shiqiane35fdd92008-12-10 05:08:54 +00002241 virtual void DescribeTo(::std::ostream* os) const {
2242 *os << "points to a value that ";
2243 matcher_.DescribeTo(os);
2244 }
2245
2246 virtual void DescribeNegationTo(::std::ostream* os) const {
2247 *os << "does not point to a value that ";
2248 matcher_.DescribeTo(os);
2249 }
2250
zhanyong.wan82113312010-01-08 21:55:40 +00002251 virtual bool MatchAndExplain(Pointer pointer,
2252 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00002253 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00002254 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002255
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002256 *listener << "which points to ";
2257 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002258 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002259
shiqiane35fdd92008-12-10 05:08:54 +00002260 private:
2261 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002262
2263 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002264 };
2265
2266 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002267
2268 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002269};
2270
billydonahue1f5fdea2014-05-19 17:54:51 +00002271// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2272// reference that matches inner_matcher when dynamic_cast<T> is applied.
2273// The result of dynamic_cast<To> is forwarded to the inner matcher.
2274// If To is a pointer and the cast fails, the inner matcher will receive NULL.
2275// If To is a reference and the cast fails, this matcher returns false
2276// immediately.
2277template <typename To>
2278class WhenDynamicCastToMatcherBase {
2279 public:
2280 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2281 : matcher_(matcher) {}
2282
2283 void DescribeTo(::std::ostream* os) const {
2284 GetCastTypeDescription(os);
2285 matcher_.DescribeTo(os);
2286 }
2287
2288 void DescribeNegationTo(::std::ostream* os) const {
2289 GetCastTypeDescription(os);
2290 matcher_.DescribeNegationTo(os);
2291 }
2292
2293 protected:
2294 const Matcher<To> matcher_;
2295
Nico Weber09fd5b32017-05-15 17:07:03 -04002296 static std::string GetToName() {
billydonahue1f5fdea2014-05-19 17:54:51 +00002297#if GTEST_HAS_RTTI
2298 return GetTypeName<To>();
2299#else // GTEST_HAS_RTTI
2300 return "the target type";
2301#endif // GTEST_HAS_RTTI
2302 }
2303
2304 private:
2305 static void GetCastTypeDescription(::std::ostream* os) {
2306 *os << "when dynamic_cast to " << GetToName() << ", ";
2307 }
2308
2309 GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2310};
2311
2312// Primary template.
2313// To is a pointer. Cast and forward the result.
2314template <typename To>
2315class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2316 public:
2317 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2318 : WhenDynamicCastToMatcherBase<To>(matcher) {}
2319
2320 template <typename From>
2321 bool MatchAndExplain(From from, MatchResultListener* listener) const {
2322 // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail?
2323 To to = dynamic_cast<To>(from);
2324 return MatchPrintAndExplain(to, this->matcher_, listener);
2325 }
2326};
2327
2328// Specialize for references.
2329// In this case we return false if the dynamic_cast fails.
2330template <typename To>
2331class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2332 public:
2333 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2334 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2335
2336 template <typename From>
2337 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2338 // We don't want an std::bad_cast here, so do the cast with pointers.
2339 To* to = dynamic_cast<To*>(&from);
2340 if (to == NULL) {
2341 *listener << "which cannot be dynamic_cast to " << this->GetToName();
2342 return false;
2343 }
2344 return MatchPrintAndExplain(*to, this->matcher_, listener);
2345 }
2346};
2347
shiqiane35fdd92008-12-10 05:08:54 +00002348// Implements the Field() matcher for matching a field (i.e. member
2349// variable) of an object.
2350template <typename Class, typename FieldType>
2351class FieldMatcher {
2352 public:
2353 FieldMatcher(FieldType Class::*field,
2354 const Matcher<const FieldType&>& matcher)
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002355 : field_(field), matcher_(matcher), whose_field_("whose given field ") {}
2356
2357 FieldMatcher(const std::string& field_name, FieldType Class::*field,
2358 const Matcher<const FieldType&>& matcher)
2359 : field_(field),
2360 matcher_(matcher),
2361 whose_field_("whose field `" + field_name + "` ") {}
shiqiane35fdd92008-12-10 05:08:54 +00002362
shiqiane35fdd92008-12-10 05:08:54 +00002363 void DescribeTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002364 *os << "is an object " << whose_field_;
shiqiane35fdd92008-12-10 05:08:54 +00002365 matcher_.DescribeTo(os);
2366 }
2367
2368 void DescribeNegationTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002369 *os << "is an object " << whose_field_;
shiqiane35fdd92008-12-10 05:08:54 +00002370 matcher_.DescribeNegationTo(os);
2371 }
2372
zhanyong.wandb22c222010-01-28 21:52:29 +00002373 template <typename T>
2374 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2375 return MatchAndExplainImpl(
2376 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002377 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002378 value, listener);
2379 }
2380
2381 private:
2382 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002383 // Symbian's C++ compiler choose which overload to use. Its type is
2384 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002385 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2386 MatchResultListener* listener) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002387 *listener << whose_field_ << "is ";
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002388 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002389 }
2390
zhanyong.wandb22c222010-01-28 21:52:29 +00002391 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2392 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002393 if (p == NULL)
2394 return false;
2395
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002396 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002397 // Since *p has a field, it must be a class/struct/union type and
2398 // thus cannot be a pointer. Therefore we pass false_type() as
2399 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002400 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002401 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002402
shiqiane35fdd92008-12-10 05:08:54 +00002403 const FieldType Class::*field_;
2404 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002405
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002406 // Contains either "whose given field " if the name of the field is unknown
2407 // or "whose field `name_of_field` " if the name is known.
2408 const std::string whose_field_;
2409
zhanyong.wan32de5f52009-12-23 00:13:23 +00002410 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002411};
2412
shiqiane35fdd92008-12-10 05:08:54 +00002413// Implements the Property() matcher for matching a property
2414// (i.e. return value of a getter method) of an object.
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002415//
2416// Property is a const-qualified member function of Class returning
2417// PropertyType.
2418template <typename Class, typename PropertyType, typename Property>
shiqiane35fdd92008-12-10 05:08:54 +00002419class PropertyMatcher {
2420 public:
2421 // The property may have a reference type, so 'const PropertyType&'
2422 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00002423 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00002424 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00002425 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00002426
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002427 PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002428 : property_(property),
2429 matcher_(matcher),
2430 whose_property_("whose given property ") {}
2431
2432 PropertyMatcher(const std::string& property_name, Property property,
2433 const Matcher<RefToConstProperty>& matcher)
2434 : property_(property),
2435 matcher_(matcher),
2436 whose_property_("whose property `" + property_name + "` ") {}
shiqiane35fdd92008-12-10 05:08:54 +00002437
shiqiane35fdd92008-12-10 05:08:54 +00002438 void DescribeTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002439 *os << "is an object " << whose_property_;
shiqiane35fdd92008-12-10 05:08:54 +00002440 matcher_.DescribeTo(os);
2441 }
2442
2443 void DescribeNegationTo(::std::ostream* os) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002444 *os << "is an object " << whose_property_;
shiqiane35fdd92008-12-10 05:08:54 +00002445 matcher_.DescribeNegationTo(os);
2446 }
2447
zhanyong.wandb22c222010-01-28 21:52:29 +00002448 template <typename T>
2449 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2450 return MatchAndExplainImpl(
2451 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002452 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002453 value, listener);
2454 }
2455
2456 private:
2457 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002458 // Symbian's C++ compiler choose which overload to use. Its type is
2459 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002460 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2461 MatchResultListener* listener) const {
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002462 *listener << whose_property_ << "is ";
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002463 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2464 // which takes a non-const reference as argument.
kosak02d64792015-02-14 02:22:21 +00002465#if defined(_PREFAST_ ) && _MSC_VER == 1800
2466 // Workaround bug in VC++ 2013's /analyze parser.
2467 // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move
2468 posix::Abort(); // To make sure it is never run.
2469 return false;
2470#else
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002471 RefToConstProperty result = (obj.*property_)();
2472 return MatchPrintAndExplain(result, matcher_, listener);
kosak02d64792015-02-14 02:22:21 +00002473#endif
shiqiane35fdd92008-12-10 05:08:54 +00002474 }
2475
zhanyong.wandb22c222010-01-28 21:52:29 +00002476 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2477 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002478 if (p == NULL)
2479 return false;
2480
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002481 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002482 // Since *p has a property method, it must be a class/struct/union
2483 // type and thus cannot be a pointer. Therefore we pass
2484 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002485 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002486 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002487
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002488 Property property_;
shiqiane35fdd92008-12-10 05:08:54 +00002489 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002490
Gennadiy Civil6aae2062018-03-26 10:36:26 -04002491 // Contains either "whose given property " if the name of the property is
2492 // unknown or "whose property `name_of_property` " if the name is known.
2493 const std::string whose_property_;
2494
zhanyong.wan32de5f52009-12-23 00:13:23 +00002495 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002496};
2497
shiqiane35fdd92008-12-10 05:08:54 +00002498// Type traits specifying various features of different functors for ResultOf.
2499// The default template specifies features for functor objects.
2500// Functor classes have to typedef argument_type and result_type
2501// to be compatible with ResultOf.
2502template <typename Functor>
2503struct CallableTraits {
2504 typedef typename Functor::result_type ResultType;
2505 typedef Functor StorageType;
2506
zhanyong.wan32de5f52009-12-23 00:13:23 +00002507 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00002508 template <typename T>
2509 static ResultType Invoke(Functor f, T arg) { return f(arg); }
2510};
2511
2512// Specialization for function pointers.
2513template <typename ArgType, typename ResType>
2514struct CallableTraits<ResType(*)(ArgType)> {
2515 typedef ResType ResultType;
2516 typedef ResType(*StorageType)(ArgType);
2517
2518 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002519 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00002520 << "NULL function pointer is passed into ResultOf().";
2521 }
2522 template <typename T>
2523 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2524 return (*f)(arg);
2525 }
2526};
2527
2528// Implements the ResultOf() matcher for matching a return value of a
2529// unary function of an object.
2530template <typename Callable>
2531class ResultOfMatcher {
2532 public:
2533 typedef typename CallableTraits<Callable>::ResultType ResultType;
2534
2535 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
2536 : callable_(callable), matcher_(matcher) {
2537 CallableTraits<Callable>::CheckIsValid(callable_);
2538 }
2539
2540 template <typename T>
2541 operator Matcher<T>() const {
2542 return Matcher<T>(new Impl<T>(callable_, matcher_));
2543 }
2544
2545 private:
2546 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2547
2548 template <typename T>
2549 class Impl : public MatcherInterface<T> {
2550 public:
2551 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
2552 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00002553
2554 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002555 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002556 matcher_.DescribeTo(os);
2557 }
2558
2559 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002560 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002561 matcher_.DescribeNegationTo(os);
2562 }
2563
zhanyong.wan82113312010-01-08 21:55:40 +00002564 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002565 *listener << "which is mapped by the given callable to ";
2566 // Cannot pass the return value (for example, int) to
2567 // MatchPrintAndExplain, which takes a non-const reference as argument.
2568 ResultType result =
2569 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2570 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002571 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002572
shiqiane35fdd92008-12-10 05:08:54 +00002573 private:
2574 // Functors often define operator() as non-const method even though
Troy Holsapplec8510502018-02-07 22:06:00 -08002575 // they are actually stateless. But we need to use them even when
shiqiane35fdd92008-12-10 05:08:54 +00002576 // 'this' is a const pointer. It's the user's responsibility not to
2577 // use stateful callables with ResultOf(), which does't guarantee
2578 // how many times the callable will be invoked.
2579 mutable CallableStorageType callable_;
2580 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002581
2582 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002583 }; // class Impl
2584
2585 const CallableStorageType callable_;
2586 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002587
2588 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002589};
2590
zhanyong.wana31d9ce2013-03-01 01:50:17 +00002591// Implements a matcher that checks the size of an STL-style container.
2592template <typename SizeMatcher>
2593class SizeIsMatcher {
2594 public:
2595 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2596 : size_matcher_(size_matcher) {
2597 }
2598
2599 template <typename Container>
2600 operator Matcher<Container>() const {
2601 return MakeMatcher(new Impl<Container>(size_matcher_));
2602 }
2603
2604 template <typename Container>
2605 class Impl : public MatcherInterface<Container> {
2606 public:
2607 typedef internal::StlContainerView<
2608 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2609 typedef typename ContainerView::type::size_type SizeType;
2610 explicit Impl(const SizeMatcher& size_matcher)
2611 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2612
2613 virtual void DescribeTo(::std::ostream* os) const {
2614 *os << "size ";
2615 size_matcher_.DescribeTo(os);
2616 }
2617 virtual void DescribeNegationTo(::std::ostream* os) const {
2618 *os << "size ";
2619 size_matcher_.DescribeNegationTo(os);
2620 }
2621
2622 virtual bool MatchAndExplain(Container container,
2623 MatchResultListener* listener) const {
2624 SizeType size = container.size();
2625 StringMatchResultListener size_listener;
2626 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2627 *listener
2628 << "whose size " << size << (result ? " matches" : " doesn't match");
2629 PrintIfNotEmpty(size_listener.str(), listener->stream());
2630 return result;
2631 }
2632
2633 private:
2634 const Matcher<SizeType> size_matcher_;
2635 GTEST_DISALLOW_ASSIGN_(Impl);
2636 };
2637
2638 private:
2639 const SizeMatcher size_matcher_;
2640 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2641};
2642
kosakb6a34882014-03-12 21:06:46 +00002643// Implements a matcher that checks the begin()..end() distance of an STL-style
2644// container.
2645template <typename DistanceMatcher>
2646class BeginEndDistanceIsMatcher {
2647 public:
2648 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2649 : distance_matcher_(distance_matcher) {}
2650
2651 template <typename Container>
2652 operator Matcher<Container>() const {
2653 return MakeMatcher(new Impl<Container>(distance_matcher_));
2654 }
2655
2656 template <typename Container>
2657 class Impl : public MatcherInterface<Container> {
2658 public:
2659 typedef internal::StlContainerView<
2660 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2661 typedef typename std::iterator_traits<
2662 typename ContainerView::type::const_iterator>::difference_type
2663 DistanceType;
2664 explicit Impl(const DistanceMatcher& distance_matcher)
2665 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2666
2667 virtual void DescribeTo(::std::ostream* os) const {
2668 *os << "distance between begin() and end() ";
2669 distance_matcher_.DescribeTo(os);
2670 }
2671 virtual void DescribeNegationTo(::std::ostream* os) const {
2672 *os << "distance between begin() and end() ";
2673 distance_matcher_.DescribeNegationTo(os);
2674 }
2675
2676 virtual bool MatchAndExplain(Container container,
2677 MatchResultListener* listener) const {
kosak5b9cbbb2014-11-17 00:28:55 +00002678#if GTEST_HAS_STD_BEGIN_AND_END_
kosakb6a34882014-03-12 21:06:46 +00002679 using std::begin;
2680 using std::end;
2681 DistanceType distance = std::distance(begin(container), end(container));
2682#else
2683 DistanceType distance = std::distance(container.begin(), container.end());
2684#endif
2685 StringMatchResultListener distance_listener;
2686 const bool result =
2687 distance_matcher_.MatchAndExplain(distance, &distance_listener);
2688 *listener << "whose distance between begin() and end() " << distance
2689 << (result ? " matches" : " doesn't match");
2690 PrintIfNotEmpty(distance_listener.str(), listener->stream());
2691 return result;
2692 }
2693
2694 private:
2695 const Matcher<DistanceType> distance_matcher_;
2696 GTEST_DISALLOW_ASSIGN_(Impl);
2697 };
2698
2699 private:
2700 const DistanceMatcher distance_matcher_;
2701 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2702};
2703
zhanyong.wan6a896b52009-01-16 01:13:50 +00002704// Implements an equality matcher for any STL-style container whose elements
2705// support ==. This matcher is like Eq(), but its failure explanations provide
2706// more detailed information that is useful when the container is used as a set.
2707// The failure message reports elements that are in one of the operands but not
2708// the other. The failure messages do not report duplicate or out-of-order
2709// elements in the containers (which don't properly matter to sets, but can
2710// occur if the containers are vectors or lists, for example).
2711//
2712// Uses the container's const_iterator, value_type, operator ==,
2713// begin(), and end().
2714template <typename Container>
2715class ContainerEqMatcher {
2716 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002717 typedef internal::StlContainerView<Container> View;
2718 typedef typename View::type StlContainer;
2719 typedef typename View::const_reference StlContainerReference;
2720
kosak6b817802015-01-08 02:38:14 +00002721 // We make a copy of expected in case the elements in it are modified
zhanyong.wanb8243162009-06-04 05:48:20 +00002722 // after this matcher is created.
kosak6b817802015-01-08 02:38:14 +00002723 explicit ContainerEqMatcher(const Container& expected)
2724 : expected_(View::Copy(expected)) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002725 // Makes sure the user doesn't instantiate this class template
2726 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002727 (void)testing::StaticAssertTypeEq<Container,
2728 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002729 }
2730
zhanyong.wan6a896b52009-01-16 01:13:50 +00002731 void DescribeTo(::std::ostream* os) const {
2732 *os << "equals ";
kosak6b817802015-01-08 02:38:14 +00002733 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002734 }
2735 void DescribeNegationTo(::std::ostream* os) const {
2736 *os << "does not equal ";
kosak6b817802015-01-08 02:38:14 +00002737 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002738 }
2739
zhanyong.wanb8243162009-06-04 05:48:20 +00002740 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002741 bool MatchAndExplain(const LhsContainer& lhs,
2742 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002743 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002744 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002745 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002746 LhsView;
2747 typedef typename LhsView::type LhsStlContainer;
2748 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
kosak6b817802015-01-08 02:38:14 +00002749 if (lhs_stl_container == expected_)
zhanyong.wane122e452010-01-12 09:03:52 +00002750 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002751
zhanyong.wane122e452010-01-12 09:03:52 +00002752 ::std::ostream* const os = listener->stream();
2753 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002754 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002755 bool printed_header = false;
2756 for (typename LhsStlContainer::const_iterator it =
2757 lhs_stl_container.begin();
2758 it != lhs_stl_container.end(); ++it) {
kosak6b817802015-01-08 02:38:14 +00002759 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
2760 expected_.end()) {
zhanyong.wane122e452010-01-12 09:03:52 +00002761 if (printed_header) {
2762 *os << ", ";
2763 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002764 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002765 printed_header = true;
2766 }
vladloseve2e8ba42010-05-13 18:16:03 +00002767 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002768 }
zhanyong.wane122e452010-01-12 09:03:52 +00002769 }
2770
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002771 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002772 bool printed_header2 = false;
kosak6b817802015-01-08 02:38:14 +00002773 for (typename StlContainer::const_iterator it = expected_.begin();
2774 it != expected_.end(); ++it) {
zhanyong.wane122e452010-01-12 09:03:52 +00002775 if (internal::ArrayAwareFind(
2776 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2777 lhs_stl_container.end()) {
2778 if (printed_header2) {
2779 *os << ", ";
2780 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002781 *os << (printed_header ? ",\nand" : "which")
2782 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002783 printed_header2 = true;
2784 }
vladloseve2e8ba42010-05-13 18:16:03 +00002785 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002786 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002787 }
2788 }
2789
zhanyong.wane122e452010-01-12 09:03:52 +00002790 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002791 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002792
zhanyong.wan6a896b52009-01-16 01:13:50 +00002793 private:
kosak6b817802015-01-08 02:38:14 +00002794 const StlContainer expected_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002795
2796 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002797};
2798
zhanyong.wan898725c2011-09-16 16:45:39 +00002799// A comparator functor that uses the < operator to compare two values.
2800struct LessComparator {
2801 template <typename T, typename U>
2802 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2803};
2804
2805// Implements WhenSortedBy(comparator, container_matcher).
2806template <typename Comparator, typename ContainerMatcher>
2807class WhenSortedByMatcher {
2808 public:
2809 WhenSortedByMatcher(const Comparator& comparator,
2810 const ContainerMatcher& matcher)
2811 : comparator_(comparator), matcher_(matcher) {}
2812
2813 template <typename LhsContainer>
2814 operator Matcher<LhsContainer>() const {
2815 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2816 }
2817
2818 template <typename LhsContainer>
2819 class Impl : public MatcherInterface<LhsContainer> {
2820 public:
2821 typedef internal::StlContainerView<
2822 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2823 typedef typename LhsView::type LhsStlContainer;
2824 typedef typename LhsView::const_reference LhsStlContainerReference;
zhanyong.wana9a59e02013-03-27 16:14:55 +00002825 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2826 // so that we can match associative containers.
2827 typedef typename RemoveConstFromKey<
2828 typename LhsStlContainer::value_type>::type LhsValue;
zhanyong.wan898725c2011-09-16 16:45:39 +00002829
2830 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2831 : comparator_(comparator), matcher_(matcher) {}
2832
2833 virtual void DescribeTo(::std::ostream* os) const {
2834 *os << "(when sorted) ";
2835 matcher_.DescribeTo(os);
2836 }
2837
2838 virtual void DescribeNegationTo(::std::ostream* os) const {
2839 *os << "(when sorted) ";
2840 matcher_.DescribeNegationTo(os);
2841 }
2842
2843 virtual bool MatchAndExplain(LhsContainer lhs,
2844 MatchResultListener* listener) const {
2845 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wanfb25d532013-07-28 08:24:00 +00002846 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2847 lhs_stl_container.end());
2848 ::std::sort(
2849 sorted_container.begin(), sorted_container.end(), comparator_);
zhanyong.wan898725c2011-09-16 16:45:39 +00002850
2851 if (!listener->IsInterested()) {
2852 // If the listener is not interested, we do not need to
2853 // construct the inner explanation.
2854 return matcher_.Matches(sorted_container);
2855 }
2856
2857 *listener << "which is ";
2858 UniversalPrint(sorted_container, listener->stream());
2859 *listener << " when sorted";
2860
2861 StringMatchResultListener inner_listener;
2862 const bool match = matcher_.MatchAndExplain(sorted_container,
2863 &inner_listener);
2864 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2865 return match;
2866 }
2867
2868 private:
2869 const Comparator comparator_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00002870 const Matcher<const ::std::vector<LhsValue>&> matcher_;
zhanyong.wan898725c2011-09-16 16:45:39 +00002871
2872 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2873 };
2874
2875 private:
2876 const Comparator comparator_;
2877 const ContainerMatcher matcher_;
2878
2879 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2880};
2881
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002882// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2883// must be able to be safely cast to Matcher<tuple<const T1&, const
2884// T2&> >, where T1 and T2 are the types of elements in the LHS
2885// container and the RHS container respectively.
2886template <typename TupleMatcher, typename RhsContainer>
2887class PointwiseMatcher {
Gennadiy Civil23187052018-03-26 10:16:59 -04002888 GTEST_COMPILE_ASSERT_(
2889 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value,
2890 use_UnorderedPointwise_with_hash_tables);
2891
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002892 public:
2893 typedef internal::StlContainerView<RhsContainer> RhsView;
2894 typedef typename RhsView::type RhsStlContainer;
2895 typedef typename RhsStlContainer::value_type RhsValue;
2896
2897 // Like ContainerEq, we make a copy of rhs in case the elements in
2898 // it are modified after this matcher is created.
2899 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2900 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2901 // Makes sure the user doesn't instantiate this class template
2902 // with a const or reference type.
2903 (void)testing::StaticAssertTypeEq<RhsContainer,
2904 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2905 }
2906
2907 template <typename LhsContainer>
2908 operator Matcher<LhsContainer>() const {
Gennadiy Civil23187052018-03-26 10:16:59 -04002909 GTEST_COMPILE_ASSERT_(
2910 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value,
2911 use_UnorderedPointwise_with_hash_tables);
2912
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002913 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2914 }
2915
2916 template <typename LhsContainer>
2917 class Impl : public MatcherInterface<LhsContainer> {
2918 public:
2919 typedef internal::StlContainerView<
2920 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2921 typedef typename LhsView::type LhsStlContainer;
2922 typedef typename LhsView::const_reference LhsStlContainerReference;
2923 typedef typename LhsStlContainer::value_type LhsValue;
2924 // We pass the LHS value and the RHS value to the inner matcher by
2925 // reference, as they may be expensive to copy. We must use tuple
2926 // instead of pair here, as a pair cannot hold references (C++ 98,
2927 // 20.2.2 [lib.pairs]).
kosakbd018832014-04-02 20:30:00 +00002928 typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002929
2930 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2931 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2932 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2933 rhs_(rhs) {}
2934
2935 virtual void DescribeTo(::std::ostream* os) const {
2936 *os << "contains " << rhs_.size()
2937 << " values, where each value and its corresponding value in ";
2938 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2939 *os << " ";
2940 mono_tuple_matcher_.DescribeTo(os);
2941 }
2942 virtual void DescribeNegationTo(::std::ostream* os) const {
2943 *os << "doesn't contain exactly " << rhs_.size()
2944 << " values, or contains a value x at some index i"
2945 << " where x and the i-th value of ";
2946 UniversalPrint(rhs_, os);
2947 *os << " ";
2948 mono_tuple_matcher_.DescribeNegationTo(os);
2949 }
2950
2951 virtual bool MatchAndExplain(LhsContainer lhs,
2952 MatchResultListener* listener) const {
2953 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2954 const size_t actual_size = lhs_stl_container.size();
2955 if (actual_size != rhs_.size()) {
2956 *listener << "which contains " << actual_size << " values";
2957 return false;
2958 }
2959
2960 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2961 typename RhsStlContainer::const_iterator right = rhs_.begin();
2962 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002963 if (listener->IsInterested()) {
2964 StringMatchResultListener inner_listener;
Gennadiy Civil23187052018-03-26 10:16:59 -04002965 // Create InnerMatcherArg as a temporarily object to avoid it outlives
2966 // *left and *right. Dereference or the conversion to `const T&` may
2967 // return temp objects, e.g for vector<bool>.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002968 if (!mono_tuple_matcher_.MatchAndExplain(
Gennadiy Civil23187052018-03-26 10:16:59 -04002969 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
2970 ImplicitCast_<const RhsValue&>(*right)),
2971 &inner_listener)) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002972 *listener << "where the value pair (";
2973 UniversalPrint(*left, listener->stream());
2974 *listener << ", ";
2975 UniversalPrint(*right, listener->stream());
2976 *listener << ") at index #" << i << " don't match";
2977 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2978 return false;
2979 }
2980 } else {
Gennadiy Civil23187052018-03-26 10:16:59 -04002981 if (!mono_tuple_matcher_.Matches(
2982 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
2983 ImplicitCast_<const RhsValue&>(*right))))
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002984 return false;
2985 }
2986 }
2987
2988 return true;
2989 }
2990
2991 private:
2992 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2993 const RhsStlContainer rhs_;
2994
2995 GTEST_DISALLOW_ASSIGN_(Impl);
2996 };
2997
2998 private:
2999 const TupleMatcher tuple_matcher_;
3000 const RhsStlContainer rhs_;
3001
3002 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
3003};
3004
zhanyong.wan33605ba2010-04-22 23:37:47 +00003005// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00003006template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00003007class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00003008 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003009 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00003010 typedef StlContainerView<RawContainer> View;
3011 typedef typename View::type StlContainer;
3012 typedef typename View::const_reference StlContainerReference;
3013 typedef typename StlContainer::value_type Element;
3014
3015 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00003016 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00003017 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00003018 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00003019
zhanyong.wan33605ba2010-04-22 23:37:47 +00003020 // Checks whether:
3021 // * All elements in the container match, if all_elements_should_match.
3022 // * Any element in the container matches, if !all_elements_should_match.
3023 bool MatchAndExplainImpl(bool all_elements_should_match,
3024 Container container,
3025 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00003026 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00003027 size_t i = 0;
3028 for (typename StlContainer::const_iterator it = stl_container.begin();
3029 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003030 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00003031 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
3032
3033 if (matches != all_elements_should_match) {
3034 *listener << "whose element #" << i
3035 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003036 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00003037 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00003038 }
3039 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00003040 return all_elements_should_match;
3041 }
3042
3043 protected:
3044 const Matcher<const Element&> inner_matcher_;
3045
3046 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
3047};
3048
3049// Implements Contains(element_matcher) for the given argument type Container.
3050// Symmetric to EachMatcherImpl.
3051template <typename Container>
3052class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
3053 public:
3054 template <typename InnerMatcher>
3055 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
3056 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3057
3058 // Describes what this matcher does.
3059 virtual void DescribeTo(::std::ostream* os) const {
3060 *os << "contains at least one element that ";
3061 this->inner_matcher_.DescribeTo(os);
3062 }
3063
3064 virtual void DescribeNegationTo(::std::ostream* os) const {
3065 *os << "doesn't contain any element that ";
3066 this->inner_matcher_.DescribeTo(os);
3067 }
3068
3069 virtual bool MatchAndExplain(Container container,
3070 MatchResultListener* listener) const {
3071 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00003072 }
3073
3074 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003075 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00003076};
3077
zhanyong.wan33605ba2010-04-22 23:37:47 +00003078// Implements Each(element_matcher) for the given argument type Container.
3079// Symmetric to ContainsMatcherImpl.
3080template <typename Container>
3081class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
3082 public:
3083 template <typename InnerMatcher>
3084 explicit EachMatcherImpl(InnerMatcher inner_matcher)
3085 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3086
3087 // Describes what this matcher does.
3088 virtual void DescribeTo(::std::ostream* os) const {
3089 *os << "only contains elements that ";
3090 this->inner_matcher_.DescribeTo(os);
3091 }
3092
3093 virtual void DescribeNegationTo(::std::ostream* os) const {
3094 *os << "contains some element that ";
3095 this->inner_matcher_.DescribeNegationTo(os);
3096 }
3097
3098 virtual bool MatchAndExplain(Container container,
3099 MatchResultListener* listener) const {
3100 return this->MatchAndExplainImpl(true, container, listener);
3101 }
3102
3103 private:
3104 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
3105};
3106
zhanyong.wanb8243162009-06-04 05:48:20 +00003107// Implements polymorphic Contains(element_matcher).
3108template <typename M>
3109class ContainsMatcher {
3110 public:
3111 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
3112
3113 template <typename Container>
3114 operator Matcher<Container>() const {
3115 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
3116 }
3117
3118 private:
3119 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003120
3121 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00003122};
3123
zhanyong.wan33605ba2010-04-22 23:37:47 +00003124// Implements polymorphic Each(element_matcher).
3125template <typename M>
3126class EachMatcher {
3127 public:
3128 explicit EachMatcher(M m) : inner_matcher_(m) {}
3129
3130 template <typename Container>
3131 operator Matcher<Container>() const {
3132 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
3133 }
3134
3135 private:
3136 const M inner_matcher_;
3137
3138 GTEST_DISALLOW_ASSIGN_(EachMatcher);
3139};
3140
Gennadiy Civil466a49a2018-03-23 11:23:54 -04003141struct Rank1 {};
3142struct Rank0 : Rank1 {};
3143
3144namespace pair_getters {
3145#if GTEST_LANG_CXX11
3146using std::get;
3147template <typename T>
3148auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT
3149 return get<0>(x);
3150}
3151template <typename T>
3152auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT
3153 return x.first;
3154}
3155
3156template <typename T>
3157auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT
3158 return get<1>(x);
3159}
3160template <typename T>
3161auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT
3162 return x.second;
3163}
3164#else
3165template <typename T>
3166typename T::first_type& First(T& x, Rank0) { // NOLINT
3167 return x.first;
3168}
3169template <typename T>
3170const typename T::first_type& First(const T& x, Rank0) {
3171 return x.first;
3172}
3173
3174template <typename T>
3175typename T::second_type& Second(T& x, Rank0) { // NOLINT
3176 return x.second;
3177}
3178template <typename T>
3179const typename T::second_type& Second(const T& x, Rank0) {
3180 return x.second;
3181}
3182#endif // GTEST_LANG_CXX11
3183} // namespace pair_getters
3184
zhanyong.wanb5937da2009-07-16 20:26:41 +00003185// Implements Key(inner_matcher) for the given argument pair type.
3186// Key(inner_matcher) matches an std::pair whose 'first' field matches
3187// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3188// std::map that contains at least one element whose key is >= 5.
3189template <typename PairType>
3190class KeyMatcherImpl : public MatcherInterface<PairType> {
3191 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003192 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00003193 typedef typename RawPairType::first_type KeyType;
3194
3195 template <typename InnerMatcher>
3196 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
3197 : inner_matcher_(
3198 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
3199 }
3200
3201 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00003202 virtual bool MatchAndExplain(PairType key_value,
3203 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003204 StringMatchResultListener inner_listener;
Gennadiy Civil23187052018-03-26 10:16:59 -04003205 const bool match = inner_matcher_.MatchAndExplain(
3206 pair_getters::First(key_value, Rank0()), &inner_listener);
Nico Weber09fd5b32017-05-15 17:07:03 -04003207 const std::string explanation = inner_listener.str();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003208 if (explanation != "") {
3209 *listener << "whose first field is a value " << explanation;
3210 }
3211 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00003212 }
3213
3214 // Describes what this matcher does.
3215 virtual void DescribeTo(::std::ostream* os) const {
3216 *os << "has a key that ";
3217 inner_matcher_.DescribeTo(os);
3218 }
3219
3220 // Describes what the negation of this matcher does.
3221 virtual void DescribeNegationTo(::std::ostream* os) const {
3222 *os << "doesn't have a key that ";
3223 inner_matcher_.DescribeTo(os);
3224 }
3225
zhanyong.wanb5937da2009-07-16 20:26:41 +00003226 private:
3227 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003228
3229 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00003230};
3231
3232// Implements polymorphic Key(matcher_for_key).
3233template <typename M>
3234class KeyMatcher {
3235 public:
3236 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
3237
3238 template <typename PairType>
3239 operator Matcher<PairType>() const {
3240 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
3241 }
3242
3243 private:
3244 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003245
3246 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00003247};
3248
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003249// Implements Pair(first_matcher, second_matcher) for the given argument pair
3250// type with its two matchers. See Pair() function below.
3251template <typename PairType>
3252class PairMatcherImpl : public MatcherInterface<PairType> {
3253 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003254 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003255 typedef typename RawPairType::first_type FirstType;
3256 typedef typename RawPairType::second_type SecondType;
3257
3258 template <typename FirstMatcher, typename SecondMatcher>
3259 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
3260 : first_matcher_(
3261 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
3262 second_matcher_(
3263 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
3264 }
3265
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003266 // Describes what this matcher does.
3267 virtual void DescribeTo(::std::ostream* os) const {
3268 *os << "has a first field that ";
3269 first_matcher_.DescribeTo(os);
3270 *os << ", and has a second field that ";
3271 second_matcher_.DescribeTo(os);
3272 }
3273
3274 // Describes what the negation of this matcher does.
3275 virtual void DescribeNegationTo(::std::ostream* os) const {
3276 *os << "has a first field that ";
3277 first_matcher_.DescribeNegationTo(os);
3278 *os << ", or has a second field that ";
3279 second_matcher_.DescribeNegationTo(os);
3280 }
3281
zhanyong.wan82113312010-01-08 21:55:40 +00003282 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3283 // matches second_matcher.
3284 virtual bool MatchAndExplain(PairType a_pair,
3285 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003286 if (!listener->IsInterested()) {
3287 // If the listener is not interested, we don't need to construct the
3288 // explanation.
Gennadiy Civil6aae2062018-03-26 10:36:26 -04003289 return first_matcher_.Matches(pair_getters::First(a_pair, Rank0())) &&
3290 second_matcher_.Matches(pair_getters::Second(a_pair, Rank0()));
zhanyong.wan82113312010-01-08 21:55:40 +00003291 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003292 StringMatchResultListener first_inner_listener;
Gennadiy Civil6aae2062018-03-26 10:36:26 -04003293 if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank0()),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003294 &first_inner_listener)) {
3295 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003296 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003297 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003298 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003299 StringMatchResultListener second_inner_listener;
Gennadiy Civil6aae2062018-03-26 10:36:26 -04003300 if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank0()),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003301 &second_inner_listener)) {
3302 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003303 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003304 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003305 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003306 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3307 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00003308 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003309 }
3310
3311 private:
Nico Weber09fd5b32017-05-15 17:07:03 -04003312 void ExplainSuccess(const std::string& first_explanation,
3313 const std::string& second_explanation,
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003314 MatchResultListener* listener) const {
3315 *listener << "whose both fields match";
3316 if (first_explanation != "") {
3317 *listener << ", where the first field is a value " << first_explanation;
3318 }
3319 if (second_explanation != "") {
3320 *listener << ", ";
3321 if (first_explanation != "") {
3322 *listener << "and ";
3323 } else {
3324 *listener << "where ";
3325 }
3326 *listener << "the second field is a value " << second_explanation;
3327 }
3328 }
3329
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003330 const Matcher<const FirstType&> first_matcher_;
3331 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003332
3333 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003334};
3335
3336// Implements polymorphic Pair(first_matcher, second_matcher).
3337template <typename FirstMatcher, typename SecondMatcher>
3338class PairMatcher {
3339 public:
3340 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3341 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3342
3343 template <typename PairType>
3344 operator Matcher<PairType> () const {
3345 return MakeMatcher(
3346 new PairMatcherImpl<PairType>(
3347 first_matcher_, second_matcher_));
3348 }
3349
3350 private:
3351 const FirstMatcher first_matcher_;
3352 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003353
3354 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003355};
3356
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003357// Implements ElementsAre() and ElementsAreArray().
3358template <typename Container>
3359class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3360 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003361 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003362 typedef internal::StlContainerView<RawContainer> View;
3363 typedef typename View::type StlContainer;
3364 typedef typename View::const_reference StlContainerReference;
3365 typedef typename StlContainer::value_type Element;
3366
3367 // Constructs the matcher from a sequence of element values or
3368 // element matchers.
3369 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00003370 ElementsAreMatcherImpl(InputIter first, InputIter last) {
3371 while (first != last) {
3372 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003373 }
3374 }
3375
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003376 // Describes what this matcher does.
3377 virtual void DescribeTo(::std::ostream* os) const {
3378 if (count() == 0) {
3379 *os << "is empty";
3380 } else if (count() == 1) {
3381 *os << "has 1 element that ";
3382 matchers_[0].DescribeTo(os);
3383 } else {
3384 *os << "has " << Elements(count()) << " where\n";
3385 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003386 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003387 matchers_[i].DescribeTo(os);
3388 if (i + 1 < count()) {
3389 *os << ",\n";
3390 }
3391 }
3392 }
3393 }
3394
3395 // Describes what the negation of this matcher does.
3396 virtual void DescribeNegationTo(::std::ostream* os) const {
3397 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003398 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003399 return;
3400 }
3401
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003402 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003403 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003404 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003405 matchers_[i].DescribeNegationTo(os);
3406 if (i + 1 < count()) {
3407 *os << ", or\n";
3408 }
3409 }
3410 }
3411
zhanyong.wan82113312010-01-08 21:55:40 +00003412 virtual bool MatchAndExplain(Container container,
3413 MatchResultListener* listener) const {
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003414 // To work with stream-like "containers", we must only walk
3415 // through the elements in one pass.
3416
3417 const bool listener_interested = listener->IsInterested();
3418
3419 // explanations[i] is the explanation of the element at index i.
Nico Weber09fd5b32017-05-15 17:07:03 -04003420 ::std::vector<std::string> explanations(count());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003421 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003422 typename StlContainer::const_iterator it = stl_container.begin();
3423 size_t exam_pos = 0;
3424 bool mismatch_found = false; // Have we found a mismatched element yet?
3425
3426 // Go through the elements and matchers in pairs, until we reach
3427 // the end of either the elements or the matchers, or until we find a
3428 // mismatch.
3429 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3430 bool match; // Does the current element match the current matcher?
3431 if (listener_interested) {
3432 StringMatchResultListener s;
3433 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3434 explanations[exam_pos] = s.str();
3435 } else {
3436 match = matchers_[exam_pos].Matches(*it);
3437 }
3438
3439 if (!match) {
3440 mismatch_found = true;
3441 break;
3442 }
3443 }
3444 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3445
3446 // Find how many elements the actual container has. We avoid
3447 // calling size() s.t. this code works for stream-like "containers"
3448 // that don't define size().
3449 size_t actual_count = exam_pos;
3450 for (; it != stl_container.end(); ++it) {
3451 ++actual_count;
3452 }
3453
zhanyong.wan82113312010-01-08 21:55:40 +00003454 if (actual_count != count()) {
3455 // The element count doesn't match. If the container is empty,
3456 // there's no need to explain anything as Google Mock already
3457 // prints the empty container. Otherwise we just need to show
3458 // how many elements there actually are.
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003459 if (listener_interested && (actual_count != 0)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003460 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003461 }
zhanyong.wan82113312010-01-08 21:55:40 +00003462 return false;
3463 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003464
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003465 if (mismatch_found) {
3466 // The element count matches, but the exam_pos-th element doesn't match.
3467 if (listener_interested) {
3468 *listener << "whose element #" << exam_pos << " doesn't match";
3469 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003470 }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003471 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003472 }
zhanyong.wan82113312010-01-08 21:55:40 +00003473
3474 // Every element matches its expectation. We need to explain why
3475 // (the obvious ones can be skipped).
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003476 if (listener_interested) {
3477 bool reason_printed = false;
3478 for (size_t i = 0; i != count(); ++i) {
Nico Weber09fd5b32017-05-15 17:07:03 -04003479 const std::string& s = explanations[i];
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003480 if (!s.empty()) {
3481 if (reason_printed) {
3482 *listener << ",\nand ";
3483 }
3484 *listener << "whose element #" << i << " matches, " << s;
3485 reason_printed = true;
zhanyong.wan82113312010-01-08 21:55:40 +00003486 }
zhanyong.wan82113312010-01-08 21:55:40 +00003487 }
3488 }
zhanyong.wan82113312010-01-08 21:55:40 +00003489 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003490 }
3491
3492 private:
3493 static Message Elements(size_t count) {
3494 return Message() << count << (count == 1 ? " element" : " elements");
3495 }
3496
3497 size_t count() const { return matchers_.size(); }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003498
3499 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003500
3501 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003502};
3503
zhanyong.wanfb25d532013-07-28 08:24:00 +00003504// Connectivity matrix of (elements X matchers), in element-major order.
3505// Initially, there are no edges.
3506// Use NextGraph() to iterate over all possible edge configurations.
3507// Use Randomize() to generate a random edge configuration.
3508class GTEST_API_ MatchMatrix {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003509 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003510 MatchMatrix(size_t num_elements, size_t num_matchers)
3511 : num_elements_(num_elements),
3512 num_matchers_(num_matchers),
3513 matched_(num_elements_* num_matchers_, 0) {
3514 }
3515
3516 size_t LhsSize() const { return num_elements_; }
3517 size_t RhsSize() const { return num_matchers_; }
3518 bool HasEdge(size_t ilhs, size_t irhs) const {
3519 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3520 }
3521 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3522 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3523 }
3524
3525 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3526 // adds 1 to that number; returns false if incrementing the graph left it
3527 // empty.
3528 bool NextGraph();
3529
3530 void Randomize();
3531
Nico Weber09fd5b32017-05-15 17:07:03 -04003532 std::string DebugString() const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003533
3534 private:
3535 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3536 return ilhs * num_matchers_ + irhs;
3537 }
3538
3539 size_t num_elements_;
3540 size_t num_matchers_;
3541
3542 // Each element is a char interpreted as bool. They are stored as a
3543 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3544 // a (ilhs, irhs) matrix coordinate into an offset.
3545 ::std::vector<char> matched_;
3546};
3547
3548typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3549typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3550
3551// Returns a maximum bipartite matching for the specified graph 'g'.
3552// The matching is represented as a vector of {element, matcher} pairs.
3553GTEST_API_ ElementMatcherPairs
3554FindMaxBipartiteMatching(const MatchMatrix& g);
3555
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003556struct UnorderedMatcherRequire {
3557 enum Flags {
3558 Superset = 1 << 0,
3559 Subset = 1 << 1,
3560 ExactMatch = Superset | Subset,
3561 };
3562};
zhanyong.wanfb25d532013-07-28 08:24:00 +00003563
3564// Untyped base class for implementing UnorderedElementsAre. By
3565// putting logic that's not specific to the element type here, we
3566// reduce binary bloat and increase compilation speed.
3567class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3568 protected:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003569 explicit UnorderedElementsAreMatcherImplBase(
3570 UnorderedMatcherRequire::Flags matcher_flags)
3571 : match_flags_(matcher_flags) {}
3572
zhanyong.wanfb25d532013-07-28 08:24:00 +00003573 // A vector of matcher describers, one for each element matcher.
3574 // Does not own the describers (and thus can be used only when the
3575 // element matchers are alive).
3576 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3577
3578 // Describes this UnorderedElementsAre matcher.
3579 void DescribeToImpl(::std::ostream* os) const;
3580
3581 // Describes the negation of this UnorderedElementsAre matcher.
3582 void DescribeNegationToImpl(::std::ostream* os) const;
3583
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003584 bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,
3585 const MatchMatrix& matrix,
3586 MatchResultListener* listener) const;
3587
3588 bool FindPairing(const MatchMatrix& matrix,
3589 MatchResultListener* listener) const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003590
3591 MatcherDescriberVec& matcher_describers() {
3592 return matcher_describers_;
3593 }
3594
3595 static Message Elements(size_t n) {
3596 return Message() << n << " element" << (n == 1 ? "" : "s");
3597 }
3598
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003599 UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }
3600
zhanyong.wanfb25d532013-07-28 08:24:00 +00003601 private:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003602 UnorderedMatcherRequire::Flags match_flags_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003603 MatcherDescriberVec matcher_describers_;
3604
3605 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3606};
3607
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003608// Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
3609// IsSupersetOf.
zhanyong.wanfb25d532013-07-28 08:24:00 +00003610template <typename Container>
3611class UnorderedElementsAreMatcherImpl
3612 : public MatcherInterface<Container>,
3613 public UnorderedElementsAreMatcherImplBase {
3614 public:
3615 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3616 typedef internal::StlContainerView<RawContainer> View;
3617 typedef typename View::type StlContainer;
3618 typedef typename View::const_reference StlContainerReference;
3619 typedef typename StlContainer::const_iterator StlContainerConstIterator;
3620 typedef typename StlContainer::value_type Element;
3621
zhanyong.wanfb25d532013-07-28 08:24:00 +00003622 template <typename InputIter>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003623 UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,
3624 InputIter first, InputIter last)
3625 : UnorderedElementsAreMatcherImplBase(matcher_flags) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00003626 for (; first != last; ++first) {
3627 matchers_.push_back(MatcherCast<const Element&>(*first));
3628 matcher_describers().push_back(matchers_.back().GetDescriber());
3629 }
3630 }
3631
3632 // Describes what this matcher does.
3633 virtual void DescribeTo(::std::ostream* os) const {
3634 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3635 }
3636
3637 // Describes what the negation of this matcher does.
3638 virtual void DescribeNegationTo(::std::ostream* os) const {
3639 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3640 }
3641
3642 virtual bool MatchAndExplain(Container container,
3643 MatchResultListener* listener) const {
3644 StlContainerReference stl_container = View::ConstReference(container);
Nico Weber09fd5b32017-05-15 17:07:03 -04003645 ::std::vector<std::string> element_printouts;
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003646 MatchMatrix matrix =
3647 AnalyzeElements(stl_container.begin(), stl_container.end(),
3648 &element_printouts, listener);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003649
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003650 if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00003651 return true;
3652 }
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003653
3654 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
3655 if (matrix.LhsSize() != matrix.RhsSize()) {
3656 // The element count doesn't match. If the container is empty,
3657 // there's no need to explain anything as Google Mock already
3658 // prints the empty container. Otherwise we just need to show
3659 // how many elements there actually are.
3660 if (matrix.LhsSize() != 0 && listener->IsInterested()) {
3661 *listener << "which has " << Elements(matrix.LhsSize());
3662 }
3663 return false;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003664 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003665 }
3666
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003667 return VerifyMatchMatrix(element_printouts, matrix, listener) &&
zhanyong.wanfb25d532013-07-28 08:24:00 +00003668 FindPairing(matrix, listener);
3669 }
3670
3671 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003672 template <typename ElementIter>
3673 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
Nico Weber09fd5b32017-05-15 17:07:03 -04003674 ::std::vector<std::string>* element_printouts,
zhanyong.wanfb25d532013-07-28 08:24:00 +00003675 MatchResultListener* listener) const {
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003676 element_printouts->clear();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003677 ::std::vector<char> did_match;
3678 size_t num_elements = 0;
3679 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3680 if (listener->IsInterested()) {
3681 element_printouts->push_back(PrintToString(*elem_first));
3682 }
3683 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3684 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3685 }
3686 }
3687
3688 MatchMatrix matrix(num_elements, matchers_.size());
3689 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3690 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3691 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3692 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3693 }
3694 }
3695 return matrix;
3696 }
3697
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003698 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003699
3700 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3701};
3702
3703// Functor for use in TransformTuple.
3704// Performs MatcherCast<Target> on an input argument of any type.
3705template <typename Target>
3706struct CastAndAppendTransform {
3707 template <typename Arg>
3708 Matcher<Target> operator()(const Arg& a) const {
3709 return MatcherCast<Target>(a);
3710 }
3711};
3712
3713// Implements UnorderedElementsAre.
3714template <typename MatcherTuple>
3715class UnorderedElementsAreMatcher {
3716 public:
3717 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3718 : matchers_(args) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003719
3720 template <typename Container>
3721 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003722 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003723 typedef typename internal::StlContainerView<RawContainer>::type View;
3724 typedef typename View::value_type Element;
3725 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3726 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003727 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003728 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3729 ::std::back_inserter(matchers));
3730 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003731 UnorderedMatcherRequire::ExactMatch, matchers.begin(), matchers.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003732 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003733
3734 private:
3735 const MatcherTuple matchers_;
3736 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3737};
3738
3739// Implements ElementsAre.
3740template <typename MatcherTuple>
3741class ElementsAreMatcher {
3742 public:
3743 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3744
3745 template <typename Container>
3746 operator Matcher<Container>() const {
Gennadiy Civil23187052018-03-26 10:16:59 -04003747 GTEST_COMPILE_ASSERT_(
3748 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value ||
3749 ::testing::tuple_size<MatcherTuple>::value < 2,
3750 use_UnorderedElementsAre_with_hash_tables);
3751
zhanyong.wanfb25d532013-07-28 08:24:00 +00003752 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3753 typedef typename internal::StlContainerView<RawContainer>::type View;
3754 typedef typename View::value_type Element;
3755 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3756 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003757 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003758 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3759 ::std::back_inserter(matchers));
3760 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3761 matchers.begin(), matchers.end()));
3762 }
3763
3764 private:
3765 const MatcherTuple matchers_;
3766 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3767};
3768
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003769// Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
zhanyong.wanfb25d532013-07-28 08:24:00 +00003770template <typename T>
3771class UnorderedElementsAreArrayMatcher {
3772 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003773 template <typename Iter>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003774 UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,
3775 Iter first, Iter last)
3776 : match_flags_(match_flags), matchers_(first, last) {}
zhanyong.wanfb25d532013-07-28 08:24:00 +00003777
3778 template <typename Container>
3779 operator Matcher<Container>() const {
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003780 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3781 match_flags_, matchers_.begin(), matchers_.end()));
zhanyong.wanfb25d532013-07-28 08:24:00 +00003782 }
3783
3784 private:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003785 UnorderedMatcherRequire::Flags match_flags_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003786 ::std::vector<T> matchers_;
3787
3788 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003789};
3790
3791// Implements ElementsAreArray().
3792template <typename T>
3793class ElementsAreArrayMatcher {
3794 public:
jgm38513a82012-11-15 15:50:36 +00003795 template <typename Iter>
3796 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003797
3798 template <typename Container>
3799 operator Matcher<Container>() const {
Gennadiy Civil23187052018-03-26 10:16:59 -04003800 GTEST_COMPILE_ASSERT_(
3801 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value,
3802 use_UnorderedElementsAreArray_with_hash_tables);
3803
jgm38513a82012-11-15 15:50:36 +00003804 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3805 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003806 }
3807
3808 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003809 const ::std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003810
3811 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003812};
3813
kosak2336e9c2014-07-28 22:57:30 +00003814// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3815// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3816// second) is a polymorphic matcher that matches a value x iff tm
3817// matches tuple (x, second). Useful for implementing
3818// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3819//
3820// BoundSecondMatcher is copyable and assignable, as we need to put
3821// instances of this class in a vector when implementing
3822// UnorderedPointwise().
3823template <typename Tuple2Matcher, typename Second>
3824class BoundSecondMatcher {
3825 public:
3826 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3827 : tuple2_matcher_(tm), second_value_(second) {}
3828
3829 template <typename T>
3830 operator Matcher<T>() const {
3831 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3832 }
3833
3834 // We have to define this for UnorderedPointwise() to compile in
3835 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3836 // which requires the elements to be assignable in C++98. The
3837 // compiler cannot generate the operator= for us, as Tuple2Matcher
3838 // and Second may not be assignable.
3839 //
3840 // However, this should never be called, so the implementation just
3841 // need to assert.
3842 void operator=(const BoundSecondMatcher& /*rhs*/) {
3843 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3844 }
3845
3846 private:
3847 template <typename T>
3848 class Impl : public MatcherInterface<T> {
3849 public:
3850 typedef ::testing::tuple<T, Second> ArgTuple;
3851
3852 Impl(const Tuple2Matcher& tm, const Second& second)
3853 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3854 second_value_(second) {}
3855
3856 virtual void DescribeTo(::std::ostream* os) const {
3857 *os << "and ";
3858 UniversalPrint(second_value_, os);
3859 *os << " ";
3860 mono_tuple2_matcher_.DescribeTo(os);
3861 }
3862
3863 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3864 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3865 listener);
3866 }
3867
3868 private:
3869 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3870 const Second second_value_;
3871
3872 GTEST_DISALLOW_ASSIGN_(Impl);
3873 };
3874
3875 const Tuple2Matcher tuple2_matcher_;
3876 const Second second_value_;
3877};
3878
3879// Given a 2-tuple matcher tm and a value second,
3880// MatcherBindSecond(tm, second) returns a matcher that matches a
3881// value x iff tm matches tuple (x, second). Useful for implementing
3882// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3883template <typename Tuple2Matcher, typename Second>
3884BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
3885 const Tuple2Matcher& tm, const Second& second) {
3886 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
3887}
3888
zhanyong.wanb4140802010-06-08 22:53:57 +00003889// Returns the description for a matcher defined using the MATCHER*()
3890// macro where the user-supplied description string is "", if
3891// 'negation' is false; otherwise returns the description of the
3892// negation of the matcher. 'param_values' contains a list of strings
3893// that are the print-out of the matcher's parameters.
Nico Weber09fd5b32017-05-15 17:07:03 -04003894GTEST_API_ std::string FormatMatcherDescription(bool negation,
3895 const char* matcher_name,
3896 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003897
Gennadiy Civilb907c262018-03-23 11:42:41 -04003898// Implements a matcher that checks the value of a optional<> type variable.
3899template <typename ValueMatcher>
3900class OptionalMatcher {
3901 public:
3902 explicit OptionalMatcher(const ValueMatcher& value_matcher)
3903 : value_matcher_(value_matcher) {}
3904
3905 template <typename Optional>
3906 operator Matcher<Optional>() const {
3907 return MakeMatcher(new Impl<Optional>(value_matcher_));
3908 }
3909
3910 template <typename Optional>
3911 class Impl : public MatcherInterface<Optional> {
3912 public:
3913 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView;
3914 typedef typename OptionalView::value_type ValueType;
3915 explicit Impl(const ValueMatcher& value_matcher)
3916 : value_matcher_(MatcherCast<ValueType>(value_matcher)) {}
3917
3918 virtual void DescribeTo(::std::ostream* os) const {
3919 *os << "value ";
3920 value_matcher_.DescribeTo(os);
3921 }
3922
3923 virtual void DescribeNegationTo(::std::ostream* os) const {
3924 *os << "value ";
3925 value_matcher_.DescribeNegationTo(os);
3926 }
3927
3928 virtual bool MatchAndExplain(Optional optional,
3929 MatchResultListener* listener) const {
3930 if (!optional) {
3931 *listener << "which is not engaged";
3932 return false;
3933 }
3934 const ValueType& value = *optional;
3935 StringMatchResultListener value_listener;
3936 const bool match = value_matcher_.MatchAndExplain(value, &value_listener);
3937 *listener << "whose value " << PrintToString(value)
3938 << (match ? " matches" : " doesn't match");
3939 PrintIfNotEmpty(value_listener.str(), listener->stream());
3940 return match;
3941 }
3942
3943 private:
3944 const Matcher<ValueType> value_matcher_;
3945 GTEST_DISALLOW_ASSIGN_(Impl);
3946 };
3947
3948 private:
3949 const ValueMatcher value_matcher_;
3950 GTEST_DISALLOW_ASSIGN_(OptionalMatcher);
3951};
3952
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05003953namespace variant_matcher {
3954// Overloads to allow VariantMatcher to do proper ADL lookup.
3955template <typename T>
3956void holds_alternative() {}
3957template <typename T>
3958void get() {}
3959
3960// Implements a matcher that checks the value of a variant<> type variable.
3961template <typename T>
3962class VariantMatcher {
3963 public:
3964 explicit VariantMatcher(::testing::Matcher<const T&> matcher)
3965 : matcher_(internal::move(matcher)) {}
3966
3967 template <typename Variant>
3968 bool MatchAndExplain(const Variant& value,
3969 ::testing::MatchResultListener* listener) const {
3970 if (!listener->IsInterested()) {
3971 return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));
3972 }
3973
3974 if (!holds_alternative<T>(value)) {
3975 *listener << "whose value is not of type '" << GetTypeName() << "'";
3976 return false;
3977 }
3978
3979 const T& elem = get<T>(value);
3980 StringMatchResultListener elem_listener;
3981 const bool match = matcher_.MatchAndExplain(elem, &elem_listener);
3982 *listener << "whose value " << PrintToString(elem)
3983 << (match ? " matches" : " doesn't match");
3984 PrintIfNotEmpty(elem_listener.str(), listener->stream());
3985 return match;
3986 }
3987
3988 void DescribeTo(std::ostream* os) const {
3989 *os << "is a variant<> with value of type '" << GetTypeName()
3990 << "' and the value ";
3991 matcher_.DescribeTo(os);
3992 }
3993
3994 void DescribeNegationTo(std::ostream* os) const {
3995 *os << "is a variant<> with value of type other than '" << GetTypeName()
3996 << "' or the value ";
3997 matcher_.DescribeNegationTo(os);
3998 }
3999
4000 private:
Gennadiy Civil23187052018-03-26 10:16:59 -04004001 static std::string GetTypeName() {
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05004002#if GTEST_HAS_RTTI
4003 return internal::GetTypeName<T>();
4004#endif
4005 return "the element type";
4006 }
4007
4008 const ::testing::Matcher<const T&> matcher_;
4009};
4010
4011} // namespace variant_matcher
4012
Gennadiy Civil466a49a2018-03-23 11:23:54 -04004013namespace any_cast_matcher {
4014
4015// Overloads to allow AnyCastMatcher to do proper ADL lookup.
4016template <typename T>
4017void any_cast() {}
4018
4019// Implements a matcher that any_casts the value.
4020template <typename T>
4021class AnyCastMatcher {
4022 public:
4023 explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher)
4024 : matcher_(matcher) {}
4025
4026 template <typename AnyType>
4027 bool MatchAndExplain(const AnyType& value,
4028 ::testing::MatchResultListener* listener) const {
4029 if (!listener->IsInterested()) {
4030 const T* ptr = any_cast<T>(&value);
4031 return ptr != NULL && matcher_.Matches(*ptr);
4032 }
4033
4034 const T* elem = any_cast<T>(&value);
4035 if (elem == NULL) {
4036 *listener << "whose value is not of type '" << GetTypeName() << "'";
4037 return false;
4038 }
4039
4040 StringMatchResultListener elem_listener;
4041 const bool match = matcher_.MatchAndExplain(*elem, &elem_listener);
4042 *listener << "whose value " << PrintToString(*elem)
4043 << (match ? " matches" : " doesn't match");
4044 PrintIfNotEmpty(elem_listener.str(), listener->stream());
4045 return match;
4046 }
4047
4048 void DescribeTo(std::ostream* os) const {
4049 *os << "is an 'any' type with value of type '" << GetTypeName()
4050 << "' and the value ";
4051 matcher_.DescribeTo(os);
4052 }
4053
4054 void DescribeNegationTo(std::ostream* os) const {
4055 *os << "is an 'any' type with value of type other than '" << GetTypeName()
4056 << "' or the value ";
4057 matcher_.DescribeNegationTo(os);
4058 }
4059
4060 private:
4061 static std::string GetTypeName() {
4062#if GTEST_HAS_RTTI
4063 return internal::GetTypeName<T>();
4064#endif
4065 return "the element type";
4066 }
4067
4068 const ::testing::Matcher<const T&> matcher_;
4069};
4070
4071} // namespace any_cast_matcher
shiqiane35fdd92008-12-10 05:08:54 +00004072} // namespace internal
4073
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004074// ElementsAreArray(iterator_first, iterator_last)
zhanyong.wanfb25d532013-07-28 08:24:00 +00004075// ElementsAreArray(pointer, count)
4076// ElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00004077// ElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004078// ElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00004079//
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004080// The ElementsAreArray() functions are like ElementsAre(...), except
4081// that they are given a homogeneous sequence rather than taking each
4082// element as a function argument. The sequence can be specified as an
4083// array, a pointer and count, a vector, an initializer list, or an
4084// STL iterator range. In each of these cases, the underlying sequence
4085// can be either a sequence of values or a sequence of matchers.
zhanyong.wanfb25d532013-07-28 08:24:00 +00004086//
4087// All forms of ElementsAreArray() make a copy of the input matcher sequence.
4088
4089template <typename Iter>
4090inline internal::ElementsAreArrayMatcher<
4091 typename ::std::iterator_traits<Iter>::value_type>
4092ElementsAreArray(Iter first, Iter last) {
4093 typedef typename ::std::iterator_traits<Iter>::value_type T;
4094 return internal::ElementsAreArrayMatcher<T>(first, last);
4095}
4096
4097template <typename T>
4098inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
4099 const T* pointer, size_t count) {
4100 return ElementsAreArray(pointer, pointer + count);
4101}
4102
4103template <typename T, size_t N>
4104inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
4105 const T (&array)[N]) {
4106 return ElementsAreArray(array, N);
4107}
4108
kosak06678922014-07-28 20:01:28 +00004109template <typename Container>
4110inline internal::ElementsAreArrayMatcher<typename Container::value_type>
4111ElementsAreArray(const Container& container) {
4112 return ElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00004113}
4114
kosak18489fa2013-12-04 23:49:07 +00004115#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004116template <typename T>
4117inline internal::ElementsAreArrayMatcher<T>
4118ElementsAreArray(::std::initializer_list<T> xs) {
4119 return ElementsAreArray(xs.begin(), xs.end());
4120}
4121#endif
4122
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004123// UnorderedElementsAreArray(iterator_first, iterator_last)
zhanyong.wanfb25d532013-07-28 08:24:00 +00004124// UnorderedElementsAreArray(pointer, count)
4125// UnorderedElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00004126// UnorderedElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004127// UnorderedElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00004128//
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004129// UnorderedElementsAreArray() verifies that a bijective mapping onto a
4130// collection of matchers exists.
4131//
4132// The matchers can be specified as an array, a pointer and count, a container,
4133// an initializer list, or an STL iterator range. In each of these cases, the
4134// underlying matchers can be either values or matchers.
4135
zhanyong.wanfb25d532013-07-28 08:24:00 +00004136template <typename Iter>
4137inline internal::UnorderedElementsAreArrayMatcher<
4138 typename ::std::iterator_traits<Iter>::value_type>
4139UnorderedElementsAreArray(Iter first, Iter last) {
4140 typedef typename ::std::iterator_traits<Iter>::value_type T;
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004141 return internal::UnorderedElementsAreArrayMatcher<T>(
4142 internal::UnorderedMatcherRequire::ExactMatch, first, last);
zhanyong.wanfb25d532013-07-28 08:24:00 +00004143}
4144
4145template <typename T>
4146inline internal::UnorderedElementsAreArrayMatcher<T>
4147UnorderedElementsAreArray(const T* pointer, size_t count) {
4148 return UnorderedElementsAreArray(pointer, pointer + count);
4149}
4150
4151template <typename T, size_t N>
4152inline internal::UnorderedElementsAreArrayMatcher<T>
4153UnorderedElementsAreArray(const T (&array)[N]) {
4154 return UnorderedElementsAreArray(array, N);
4155}
4156
kosak06678922014-07-28 20:01:28 +00004157template <typename Container>
4158inline internal::UnorderedElementsAreArrayMatcher<
4159 typename Container::value_type>
4160UnorderedElementsAreArray(const Container& container) {
4161 return UnorderedElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00004162}
4163
kosak18489fa2013-12-04 23:49:07 +00004164#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004165template <typename T>
4166inline internal::UnorderedElementsAreArrayMatcher<T>
4167UnorderedElementsAreArray(::std::initializer_list<T> xs) {
4168 return UnorderedElementsAreArray(xs.begin(), xs.end());
4169}
4170#endif
zhanyong.wanfb25d532013-07-28 08:24:00 +00004171
shiqiane35fdd92008-12-10 05:08:54 +00004172// _ is a matcher that matches anything of any type.
4173//
4174// This definition is fine as:
4175//
4176// 1. The C++ standard permits using the name _ in a namespace that
4177// is not the global namespace or ::std.
4178// 2. The AnythingMatcher class has no data member or constructor,
4179// so it's OK to create global variables of this type.
4180// 3. c-style has approved of using _ in this case.
4181const internal::AnythingMatcher _ = {};
4182// Creates a matcher that matches any value of the given type T.
4183template <typename T>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004184inline Matcher<T> A() {
4185 return Matcher<T>(new internal::AnyMatcherImpl<T>());
4186}
shiqiane35fdd92008-12-10 05:08:54 +00004187
4188// Creates a matcher that matches any value of the given type T.
4189template <typename T>
4190inline Matcher<T> An() { return A<T>(); }
4191
4192// Creates a polymorphic matcher that matches anything equal to x.
4193// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
4194// wouldn't compile.
4195template <typename T>
4196inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
4197
4198// Constructs a Matcher<T> from a 'value' of type T. The constructed
4199// matcher matches any value that's equal to 'value'.
4200template <typename T>
4201Matcher<T>::Matcher(T value) { *this = Eq(value); }
4202
Gennadiy Civil466a49a2018-03-23 11:23:54 -04004203template <typename T, typename M>
4204Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(
4205 const M& value,
4206 internal::BooleanConstant<false> /* convertible_to_matcher */,
4207 internal::BooleanConstant<false> /* convertible_to_T */) {
4208 return Eq(value);
4209}
4210
shiqiane35fdd92008-12-10 05:08:54 +00004211// Creates a monomorphic matcher that matches anything with type Lhs
4212// and equal to rhs. A user may need to use this instead of Eq(...)
4213// in order to resolve an overloading ambiguity.
4214//
4215// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
4216// or Matcher<T>(x), but more readable than the latter.
4217//
4218// We could define similar monomorphic matchers for other comparison
4219// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
4220// it yet as those are used much less than Eq() in practice. A user
4221// can always write Matcher<T>(Lt(5)) to be explicit about the type,
4222// for example.
4223template <typename Lhs, typename Rhs>
4224inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
4225
4226// Creates a polymorphic matcher that matches anything >= x.
4227template <typename Rhs>
4228inline internal::GeMatcher<Rhs> Ge(Rhs x) {
4229 return internal::GeMatcher<Rhs>(x);
4230}
4231
4232// Creates a polymorphic matcher that matches anything > x.
4233template <typename Rhs>
4234inline internal::GtMatcher<Rhs> Gt(Rhs x) {
4235 return internal::GtMatcher<Rhs>(x);
4236}
4237
4238// Creates a polymorphic matcher that matches anything <= x.
4239template <typename Rhs>
4240inline internal::LeMatcher<Rhs> Le(Rhs x) {
4241 return internal::LeMatcher<Rhs>(x);
4242}
4243
4244// Creates a polymorphic matcher that matches anything < x.
4245template <typename Rhs>
4246inline internal::LtMatcher<Rhs> Lt(Rhs x) {
4247 return internal::LtMatcher<Rhs>(x);
4248}
4249
4250// Creates a polymorphic matcher that matches anything != x.
4251template <typename Rhs>
4252inline internal::NeMatcher<Rhs> Ne(Rhs x) {
4253 return internal::NeMatcher<Rhs>(x);
4254}
4255
zhanyong.wan2d970ee2009-09-24 21:41:36 +00004256// Creates a polymorphic matcher that matches any NULL pointer.
4257inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
4258 return MakePolymorphicMatcher(internal::IsNullMatcher());
4259}
4260
shiqiane35fdd92008-12-10 05:08:54 +00004261// Creates a polymorphic matcher that matches any non-NULL pointer.
4262// This is convenient as Not(NULL) doesn't compile (the compiler
4263// thinks that that expression is comparing a pointer with an integer).
4264inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
4265 return MakePolymorphicMatcher(internal::NotNullMatcher());
4266}
4267
4268// Creates a polymorphic matcher that matches any argument that
4269// references variable x.
4270template <typename T>
4271inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
4272 return internal::RefMatcher<T&>(x);
4273}
4274
4275// Creates a matcher that matches any double argument approximately
4276// equal to rhs, where two NANs are considered unequal.
4277inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
4278 return internal::FloatingEqMatcher<double>(rhs, false);
4279}
4280
4281// Creates a matcher that matches any double argument approximately
4282// equal to rhs, including NaN values when rhs is NaN.
4283inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
4284 return internal::FloatingEqMatcher<double>(rhs, true);
4285}
4286
zhanyong.wan616180e2013-06-18 18:49:51 +00004287// Creates a matcher that matches any double argument approximately equal to
4288// rhs, up to the specified max absolute error bound, where two NANs are
4289// considered unequal. The max absolute error bound must be non-negative.
4290inline internal::FloatingEqMatcher<double> DoubleNear(
4291 double rhs, double max_abs_error) {
4292 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
4293}
4294
4295// Creates a matcher that matches any double argument approximately equal to
4296// rhs, up to the specified max absolute error bound, including NaN values when
4297// rhs is NaN. The max absolute error bound must be non-negative.
4298inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
4299 double rhs, double max_abs_error) {
4300 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
4301}
4302
shiqiane35fdd92008-12-10 05:08:54 +00004303// Creates a matcher that matches any float argument approximately
4304// equal to rhs, where two NANs are considered unequal.
4305inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
4306 return internal::FloatingEqMatcher<float>(rhs, false);
4307}
4308
zhanyong.wan616180e2013-06-18 18:49:51 +00004309// Creates a matcher that matches any float argument approximately
shiqiane35fdd92008-12-10 05:08:54 +00004310// equal to rhs, including NaN values when rhs is NaN.
4311inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
4312 return internal::FloatingEqMatcher<float>(rhs, true);
4313}
4314
zhanyong.wan616180e2013-06-18 18:49:51 +00004315// Creates a matcher that matches any float argument approximately equal to
4316// rhs, up to the specified max absolute error bound, where two NANs are
4317// considered unequal. The max absolute error bound must be non-negative.
4318inline internal::FloatingEqMatcher<float> FloatNear(
4319 float rhs, float max_abs_error) {
4320 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
4321}
4322
4323// Creates a matcher that matches any float argument approximately equal to
4324// rhs, up to the specified max absolute error bound, including NaN values when
4325// rhs is NaN. The max absolute error bound must be non-negative.
4326inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
4327 float rhs, float max_abs_error) {
4328 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
4329}
4330
shiqiane35fdd92008-12-10 05:08:54 +00004331// Creates a matcher that matches a pointer (raw or smart) that points
4332// to a value that matches inner_matcher.
4333template <typename InnerMatcher>
4334inline internal::PointeeMatcher<InnerMatcher> Pointee(
4335 const InnerMatcher& inner_matcher) {
4336 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
4337}
4338
billydonahue1f5fdea2014-05-19 17:54:51 +00004339// Creates a matcher that matches a pointer or reference that matches
4340// inner_matcher when dynamic_cast<To> is applied.
4341// The result of dynamic_cast<To> is forwarded to the inner matcher.
4342// If To is a pointer and the cast fails, the inner matcher will receive NULL.
4343// If To is a reference and the cast fails, this matcher returns false
4344// immediately.
4345template <typename To>
4346inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
4347WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
4348 return MakePolymorphicMatcher(
4349 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
4350}
4351
shiqiane35fdd92008-12-10 05:08:54 +00004352// Creates a matcher that matches an object whose given field matches
4353// 'matcher'. For example,
4354// Field(&Foo::number, Ge(5))
4355// matches a Foo object x iff x.number >= 5.
4356template <typename Class, typename FieldType, typename FieldMatcher>
4357inline PolymorphicMatcher<
4358 internal::FieldMatcher<Class, FieldType> > Field(
4359 FieldType Class::*field, const FieldMatcher& matcher) {
4360 return MakePolymorphicMatcher(
4361 internal::FieldMatcher<Class, FieldType>(
4362 field, MatcherCast<const FieldType&>(matcher)));
4363 // The call to MatcherCast() is required for supporting inner
4364 // matchers of compatible types. For example, it allows
4365 // Field(&Foo::bar, m)
4366 // to compile where bar is an int32 and m is a matcher for int64.
4367}
4368
Gennadiy Civilb907c262018-03-23 11:42:41 -04004369// Same as Field() but also takes the name of the field to provide better error
4370// messages.
4371template <typename Class, typename FieldType, typename FieldMatcher>
4372inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType> > Field(
4373 const std::string& field_name, FieldType Class::*field,
4374 const FieldMatcher& matcher) {
4375 return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(
4376 field_name, field, MatcherCast<const FieldType&>(matcher)));
4377}
4378
shiqiane35fdd92008-12-10 05:08:54 +00004379// Creates a matcher that matches an object whose given property
4380// matches 'matcher'. For example,
4381// Property(&Foo::str, StartsWith("hi"))
4382// matches a Foo object x iff x.str() starts with "hi".
4383template <typename Class, typename PropertyType, typename PropertyMatcher>
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004384inline PolymorphicMatcher<internal::PropertyMatcher<
4385 Class, PropertyType, PropertyType (Class::*)() const> >
4386Property(PropertyType (Class::*property)() const,
4387 const PropertyMatcher& matcher) {
shiqiane35fdd92008-12-10 05:08:54 +00004388 return MakePolymorphicMatcher(
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004389 internal::PropertyMatcher<Class, PropertyType,
4390 PropertyType (Class::*)() const>(
shiqiane35fdd92008-12-10 05:08:54 +00004391 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00004392 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00004393 // The call to MatcherCast() is required for supporting inner
4394 // matchers of compatible types. For example, it allows
4395 // Property(&Foo::bar, m)
4396 // to compile where bar() returns an int32 and m is a matcher for int64.
4397}
4398
Gennadiy Civil23187052018-03-26 10:16:59 -04004399// Same as Property() above, but also takes the name of the property to provide
4400// better error messages.
4401template <typename Class, typename PropertyType, typename PropertyMatcher>
4402inline PolymorphicMatcher<internal::PropertyMatcher<
4403 Class, PropertyType, PropertyType (Class::*)() const> >
4404Property(const std::string& property_name,
4405 PropertyType (Class::*property)() const,
4406 const PropertyMatcher& matcher) {
4407 return MakePolymorphicMatcher(
4408 internal::PropertyMatcher<Class, PropertyType,
4409 PropertyType (Class::*)() const>(
4410 property_name, property,
4411 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4412}
4413
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004414#if GTEST_LANG_CXX11
4415// The same as above but for reference-qualified member functions.
4416template <typename Class, typename PropertyType, typename PropertyMatcher>
4417inline PolymorphicMatcher<internal::PropertyMatcher<
4418 Class, PropertyType, PropertyType (Class::*)() const &> >
4419Property(PropertyType (Class::*property)() const &,
4420 const PropertyMatcher& matcher) {
4421 return MakePolymorphicMatcher(
4422 internal::PropertyMatcher<Class, PropertyType,
4423 PropertyType (Class::*)() const &>(
4424 property,
4425 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4426}
4427#endif
4428
shiqiane35fdd92008-12-10 05:08:54 +00004429// Creates a matcher that matches an object iff the result of applying
4430// a callable to x matches 'matcher'.
4431// For example,
4432// ResultOf(f, StartsWith("hi"))
4433// matches a Foo object x iff f(x) starts with "hi".
4434// callable parameter can be a function, function pointer, or a functor.
4435// Callable has to satisfy the following conditions:
4436// * It is required to keep no state affecting the results of
4437// the calls on it and make no assumptions about how many calls
4438// will be made. Any state it keeps must be protected from the
4439// concurrent access.
4440// * If it is a function object, it has to define type result_type.
4441// We recommend deriving your functor classes from std::unary_function.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004442//
shiqiane35fdd92008-12-10 05:08:54 +00004443template <typename Callable, typename ResultOfMatcher>
4444internal::ResultOfMatcher<Callable> ResultOf(
4445 Callable callable, const ResultOfMatcher& matcher) {
4446 return internal::ResultOfMatcher<Callable>(
4447 callable,
4448 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
4449 matcher));
4450 // The call to MatcherCast() is required for supporting inner
4451 // matchers of compatible types. For example, it allows
4452 // ResultOf(Function, m)
4453 // to compile where Function() returns an int32 and m is a matcher for int64.
4454}
4455
4456// String matchers.
4457
4458// Matches a string equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04004459inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
4460 const std::string& str) {
4461 return MakePolymorphicMatcher(
4462 internal::StrEqualityMatcher<std::string>(str, true, true));
shiqiane35fdd92008-12-10 05:08:54 +00004463}
4464
4465// Matches a string not equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04004466inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
4467 const std::string& str) {
4468 return MakePolymorphicMatcher(
4469 internal::StrEqualityMatcher<std::string>(str, false, true));
shiqiane35fdd92008-12-10 05:08:54 +00004470}
4471
4472// Matches a string equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04004473inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
4474 const std::string& str) {
4475 return MakePolymorphicMatcher(
4476 internal::StrEqualityMatcher<std::string>(str, true, false));
shiqiane35fdd92008-12-10 05:08:54 +00004477}
4478
4479// Matches a string not equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04004480inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
4481 const std::string& str) {
4482 return MakePolymorphicMatcher(
4483 internal::StrEqualityMatcher<std::string>(str, false, false));
shiqiane35fdd92008-12-10 05:08:54 +00004484}
4485
4486// Creates a matcher that matches any string, std::string, or C string
4487// that contains the given substring.
Nico Weber09fd5b32017-05-15 17:07:03 -04004488inline PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
4489 const std::string& substring) {
4490 return MakePolymorphicMatcher(
4491 internal::HasSubstrMatcher<std::string>(substring));
shiqiane35fdd92008-12-10 05:08:54 +00004492}
4493
4494// Matches a string that starts with 'prefix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004495inline PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
4496 const std::string& prefix) {
4497 return MakePolymorphicMatcher(
4498 internal::StartsWithMatcher<std::string>(prefix));
shiqiane35fdd92008-12-10 05:08:54 +00004499}
4500
4501// Matches a string that ends with 'suffix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004502inline PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
4503 const std::string& suffix) {
4504 return MakePolymorphicMatcher(internal::EndsWithMatcher<std::string>(suffix));
shiqiane35fdd92008-12-10 05:08:54 +00004505}
4506
shiqiane35fdd92008-12-10 05:08:54 +00004507// Matches a string that fully matches regular expression 'regex'.
4508// The matcher takes ownership of 'regex'.
4509inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4510 const internal::RE* regex) {
4511 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
4512}
4513inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004514 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004515 return MatchesRegex(new internal::RE(regex));
4516}
4517
4518// Matches a string that contains regular expression 'regex'.
4519// The matcher takes ownership of 'regex'.
4520inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4521 const internal::RE* regex) {
4522 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4523}
4524inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004525 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004526 return ContainsRegex(new internal::RE(regex));
4527}
4528
shiqiane35fdd92008-12-10 05:08:54 +00004529#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4530// Wide string matchers.
4531
4532// Matches a string equal to str.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004533inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrEq(
4534 const std::wstring& str) {
4535 return MakePolymorphicMatcher(
4536 internal::StrEqualityMatcher<std::wstring>(str, true, true));
shiqiane35fdd92008-12-10 05:08:54 +00004537}
4538
4539// Matches a string not equal to str.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004540inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrNe(
4541 const std::wstring& str) {
4542 return MakePolymorphicMatcher(
4543 internal::StrEqualityMatcher<std::wstring>(str, false, true));
shiqiane35fdd92008-12-10 05:08:54 +00004544}
4545
4546// Matches a string equal to str, ignoring case.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004547inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
4548StrCaseEq(const std::wstring& str) {
4549 return MakePolymorphicMatcher(
4550 internal::StrEqualityMatcher<std::wstring>(str, true, false));
shiqiane35fdd92008-12-10 05:08:54 +00004551}
4552
4553// Matches a string not equal to str, ignoring case.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004554inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
4555StrCaseNe(const std::wstring& str) {
4556 return MakePolymorphicMatcher(
4557 internal::StrEqualityMatcher<std::wstring>(str, false, false));
shiqiane35fdd92008-12-10 05:08:54 +00004558}
4559
Gennadiy Civilb907c262018-03-23 11:42:41 -04004560// Creates a matcher that matches any ::wstring, std::wstring, or C wide string
shiqiane35fdd92008-12-10 05:08:54 +00004561// that contains the given substring.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004562inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring> > HasSubstr(
4563 const std::wstring& substring) {
4564 return MakePolymorphicMatcher(
4565 internal::HasSubstrMatcher<std::wstring>(substring));
shiqiane35fdd92008-12-10 05:08:54 +00004566}
4567
4568// Matches a string that starts with 'prefix' (case-sensitive).
Gennadiy Civilb907c262018-03-23 11:42:41 -04004569inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring> >
4570StartsWith(const std::wstring& prefix) {
4571 return MakePolymorphicMatcher(
4572 internal::StartsWithMatcher<std::wstring>(prefix));
shiqiane35fdd92008-12-10 05:08:54 +00004573}
4574
4575// Matches a string that ends with 'suffix' (case-sensitive).
Gennadiy Civilb907c262018-03-23 11:42:41 -04004576inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring> > EndsWith(
4577 const std::wstring& suffix) {
4578 return MakePolymorphicMatcher(
4579 internal::EndsWithMatcher<std::wstring>(suffix));
shiqiane35fdd92008-12-10 05:08:54 +00004580}
4581
4582#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4583
4584// Creates a polymorphic matcher that matches a 2-tuple where the
4585// first field == the second field.
4586inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4587
4588// Creates a polymorphic matcher that matches a 2-tuple where the
4589// first field >= the second field.
4590inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4591
4592// Creates a polymorphic matcher that matches a 2-tuple where the
4593// first field > the second field.
4594inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4595
4596// Creates a polymorphic matcher that matches a 2-tuple where the
4597// first field <= the second field.
4598inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4599
4600// Creates a polymorphic matcher that matches a 2-tuple where the
4601// first field < the second field.
4602inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4603
4604// Creates a polymorphic matcher that matches a 2-tuple where the
4605// first field != the second field.
4606inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4607
Gennadiy Civilb907c262018-03-23 11:42:41 -04004608// Creates a polymorphic matcher that matches a 2-tuple where
4609// FloatEq(first field) matches the second field.
4610inline internal::FloatingEq2Matcher<float> FloatEq() {
4611 return internal::FloatingEq2Matcher<float>();
4612}
4613
4614// Creates a polymorphic matcher that matches a 2-tuple where
4615// DoubleEq(first field) matches the second field.
4616inline internal::FloatingEq2Matcher<double> DoubleEq() {
4617 return internal::FloatingEq2Matcher<double>();
4618}
4619
4620// Creates a polymorphic matcher that matches a 2-tuple where
4621// FloatEq(first field) matches the second field with NaN equality.
4622inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() {
4623 return internal::FloatingEq2Matcher<float>(true);
4624}
4625
4626// Creates a polymorphic matcher that matches a 2-tuple where
4627// DoubleEq(first field) matches the second field with NaN equality.
4628inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() {
4629 return internal::FloatingEq2Matcher<double>(true);
4630}
4631
4632// Creates a polymorphic matcher that matches a 2-tuple where
4633// FloatNear(first field, max_abs_error) matches the second field.
4634inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) {
4635 return internal::FloatingEq2Matcher<float>(max_abs_error);
4636}
4637
4638// Creates a polymorphic matcher that matches a 2-tuple where
4639// DoubleNear(first field, max_abs_error) matches the second field.
4640inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) {
4641 return internal::FloatingEq2Matcher<double>(max_abs_error);
4642}
4643
4644// Creates a polymorphic matcher that matches a 2-tuple where
4645// FloatNear(first field, max_abs_error) matches the second field with NaN
4646// equality.
4647inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear(
4648 float max_abs_error) {
4649 return internal::FloatingEq2Matcher<float>(max_abs_error, true);
4650}
4651
4652// Creates a polymorphic matcher that matches a 2-tuple where
4653// DoubleNear(first field, max_abs_error) matches the second field with NaN
4654// equality.
4655inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear(
4656 double max_abs_error) {
4657 return internal::FloatingEq2Matcher<double>(max_abs_error, true);
4658}
4659
shiqiane35fdd92008-12-10 05:08:54 +00004660// Creates a matcher that matches any value of type T that m doesn't
4661// match.
4662template <typename InnerMatcher>
4663inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4664 return internal::NotMatcher<InnerMatcher>(m);
4665}
4666
shiqiane35fdd92008-12-10 05:08:54 +00004667// Returns a matcher that matches anything that satisfies the given
4668// predicate. The predicate can be any unary function or functor
4669// whose return type can be implicitly converted to bool.
4670template <typename Predicate>
4671inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4672Truly(Predicate pred) {
4673 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4674}
4675
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004676// Returns a matcher that matches the container size. The container must
4677// support both size() and size_type which all STL-like containers provide.
4678// Note that the parameter 'size' can be a value of type size_type as well as
4679// matcher. For instance:
4680// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
4681// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
4682template <typename SizeMatcher>
4683inline internal::SizeIsMatcher<SizeMatcher>
4684SizeIs(const SizeMatcher& size_matcher) {
4685 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4686}
4687
kosakb6a34882014-03-12 21:06:46 +00004688// Returns a matcher that matches the distance between the container's begin()
4689// iterator and its end() iterator, i.e. the size of the container. This matcher
4690// can be used instead of SizeIs with containers such as std::forward_list which
4691// do not implement size(). The container must provide const_iterator (with
4692// valid iterator_traits), begin() and end().
4693template <typename DistanceMatcher>
4694inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4695BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4696 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4697}
4698
zhanyong.wan6a896b52009-01-16 01:13:50 +00004699// Returns a matcher that matches an equal container.
4700// This matcher behaves like Eq(), but in the event of mismatch lists the
4701// values that are included in one container but not the other. (Duplicate
4702// values and order differences are not explained.)
4703template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00004704inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00004705 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004706 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00004707 // This following line is for working around a bug in MSVC 8.0,
4708 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00004709 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00004710 return MakePolymorphicMatcher(
4711 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00004712}
4713
zhanyong.wan898725c2011-09-16 16:45:39 +00004714// Returns a matcher that matches a container that, when sorted using
4715// the given comparator, matches container_matcher.
4716template <typename Comparator, typename ContainerMatcher>
4717inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4718WhenSortedBy(const Comparator& comparator,
4719 const ContainerMatcher& container_matcher) {
4720 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4721 comparator, container_matcher);
4722}
4723
4724// Returns a matcher that matches a container that, when sorted using
4725// the < operator, matches container_matcher.
4726template <typename ContainerMatcher>
4727inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4728WhenSorted(const ContainerMatcher& container_matcher) {
4729 return
4730 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4731 internal::LessComparator(), container_matcher);
4732}
4733
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004734// Matches an STL-style container or a native array that contains the
4735// same number of elements as in rhs, where its i-th element and rhs's
4736// i-th element (as a pair) satisfy the given pair matcher, for all i.
4737// TupleMatcher must be able to be safely cast to Matcher<tuple<const
4738// T1&, const T2&> >, where T1 and T2 are the types of elements in the
4739// LHS container and the RHS container respectively.
4740template <typename TupleMatcher, typename Container>
4741inline internal::PointwiseMatcher<TupleMatcher,
4742 GTEST_REMOVE_CONST_(Container)>
4743Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4744 // This following line is for working around a bug in MSVC 8.0,
kosak2336e9c2014-07-28 22:57:30 +00004745 // which causes Container to be a const type sometimes (e.g. when
4746 // rhs is a const int[])..
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004747 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4748 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4749 tuple_matcher, rhs);
4750}
4751
kosak2336e9c2014-07-28 22:57:30 +00004752#if GTEST_HAS_STD_INITIALIZER_LIST_
4753
4754// Supports the Pointwise(m, {a, b, c}) syntax.
4755template <typename TupleMatcher, typename T>
4756inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4757 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4758 return Pointwise(tuple_matcher, std::vector<T>(rhs));
4759}
4760
4761#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4762
4763// UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4764// container or a native array that contains the same number of
4765// elements as in rhs, where in some permutation of the container, its
4766// i-th element and rhs's i-th element (as a pair) satisfy the given
4767// pair matcher, for all i. Tuple2Matcher must be able to be safely
4768// cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4769// the types of elements in the LHS container and the RHS container
4770// respectively.
4771//
4772// This is like Pointwise(pair_matcher, rhs), except that the element
4773// order doesn't matter.
4774template <typename Tuple2Matcher, typename RhsContainer>
4775inline internal::UnorderedElementsAreArrayMatcher<
4776 typename internal::BoundSecondMatcher<
4777 Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4778 RhsContainer)>::type::value_type> >
4779UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4780 const RhsContainer& rhs_container) {
4781 // This following line is for working around a bug in MSVC 8.0,
4782 // which causes RhsContainer to be a const type sometimes (e.g. when
4783 // rhs_container is a const int[]).
4784 typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4785
4786 // RhsView allows the same code to handle RhsContainer being a
4787 // STL-style container and it being a native C-style array.
4788 typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4789 typedef typename RhsView::type RhsStlContainer;
4790 typedef typename RhsStlContainer::value_type Second;
4791 const RhsStlContainer& rhs_stl_container =
4792 RhsView::ConstReference(rhs_container);
4793
4794 // Create a matcher for each element in rhs_container.
4795 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4796 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4797 it != rhs_stl_container.end(); ++it) {
4798 matchers.push_back(
4799 internal::MatcherBindSecond(tuple2_matcher, *it));
4800 }
4801
4802 // Delegate the work to UnorderedElementsAreArray().
4803 return UnorderedElementsAreArray(matchers);
4804}
4805
4806#if GTEST_HAS_STD_INITIALIZER_LIST_
4807
4808// Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4809template <typename Tuple2Matcher, typename T>
4810inline internal::UnorderedElementsAreArrayMatcher<
4811 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4812UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4813 std::initializer_list<T> rhs) {
4814 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4815}
4816
4817#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4818
zhanyong.wanb8243162009-06-04 05:48:20 +00004819// Matches an STL-style container or a native array that contains at
4820// least one element matching the given value or matcher.
4821//
4822// Examples:
4823// ::std::set<int> page_ids;
4824// page_ids.insert(3);
4825// page_ids.insert(1);
4826// EXPECT_THAT(page_ids, Contains(1));
4827// EXPECT_THAT(page_ids, Contains(Gt(2)));
4828// EXPECT_THAT(page_ids, Not(Contains(4)));
4829//
4830// ::std::map<int, size_t> page_lengths;
4831// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00004832// EXPECT_THAT(page_lengths,
4833// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004834//
4835// const char* user_ids[] = { "joe", "mike", "tom" };
4836// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4837template <typename M>
4838inline internal::ContainsMatcher<M> Contains(M matcher) {
4839 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004840}
4841
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004842// IsSupersetOf(iterator_first, iterator_last)
4843// IsSupersetOf(pointer, count)
4844// IsSupersetOf(array)
4845// IsSupersetOf(container)
4846// IsSupersetOf({e1, e2, ..., en})
4847//
4848// IsSupersetOf() verifies that a surjective partial mapping onto a collection
4849// of matchers exists. In other words, a container matches
4850// IsSupersetOf({e1, ..., en}) if and only if there is a permutation
4851// {y1, ..., yn} of some of the container's elements where y1 matches e1,
4852// ..., and yn matches en. Obviously, the size of the container must be >= n
4853// in order to have a match. Examples:
4854//
4855// - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and
4856// 1 matches Ne(0).
4857// - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches
4858// both Eq(1) and Lt(2). The reason is that different matchers must be used
4859// for elements in different slots of the container.
4860// - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches
4861// Eq(1) and (the second) 1 matches Lt(2).
4862// - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)
4863// Gt(1) and 3 matches (the second) Gt(1).
4864//
4865// The matchers can be specified as an array, a pointer and count, a container,
4866// an initializer list, or an STL iterator range. In each of these cases, the
4867// underlying matchers can be either values or matchers.
4868
4869template <typename Iter>
4870inline internal::UnorderedElementsAreArrayMatcher<
4871 typename ::std::iterator_traits<Iter>::value_type>
4872IsSupersetOf(Iter first, Iter last) {
4873 typedef typename ::std::iterator_traits<Iter>::value_type T;
4874 return internal::UnorderedElementsAreArrayMatcher<T>(
4875 internal::UnorderedMatcherRequire::Superset, first, last);
4876}
4877
4878template <typename T>
4879inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
4880 const T* pointer, size_t count) {
4881 return IsSupersetOf(pointer, pointer + count);
4882}
4883
4884template <typename T, size_t N>
4885inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
4886 const T (&array)[N]) {
4887 return IsSupersetOf(array, N);
4888}
4889
4890template <typename Container>
4891inline internal::UnorderedElementsAreArrayMatcher<
4892 typename Container::value_type>
4893IsSupersetOf(const Container& container) {
4894 return IsSupersetOf(container.begin(), container.end());
4895}
4896
4897#if GTEST_HAS_STD_INITIALIZER_LIST_
4898template <typename T>
4899inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
4900 ::std::initializer_list<T> xs) {
4901 return IsSupersetOf(xs.begin(), xs.end());
4902}
4903#endif
4904
4905// IsSubsetOf(iterator_first, iterator_last)
4906// IsSubsetOf(pointer, count)
4907// IsSubsetOf(array)
4908// IsSubsetOf(container)
4909// IsSubsetOf({e1, e2, ..., en})
4910//
4911// IsSubsetOf() verifies that an injective mapping onto a collection of matchers
4912// exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and
4913// only if there is a subset of matchers {m1, ..., mk} which would match the
4914// container using UnorderedElementsAre. Obviously, the size of the container
4915// must be <= n in order to have a match. Examples:
4916//
4917// - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).
4918// - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1
4919// matches Lt(0).
4920// - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both
4921// match Gt(0). The reason is that different matchers must be used for
4922// elements in different slots of the container.
4923//
4924// The matchers can be specified as an array, a pointer and count, a container,
4925// an initializer list, or an STL iterator range. In each of these cases, the
4926// underlying matchers can be either values or matchers.
4927
4928template <typename Iter>
4929inline internal::UnorderedElementsAreArrayMatcher<
4930 typename ::std::iterator_traits<Iter>::value_type>
4931IsSubsetOf(Iter first, Iter last) {
4932 typedef typename ::std::iterator_traits<Iter>::value_type T;
4933 return internal::UnorderedElementsAreArrayMatcher<T>(
4934 internal::UnorderedMatcherRequire::Subset, first, last);
4935}
4936
4937template <typename T>
4938inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
4939 const T* pointer, size_t count) {
4940 return IsSubsetOf(pointer, pointer + count);
4941}
4942
4943template <typename T, size_t N>
4944inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
4945 const T (&array)[N]) {
4946 return IsSubsetOf(array, N);
4947}
4948
4949template <typename Container>
4950inline internal::UnorderedElementsAreArrayMatcher<
4951 typename Container::value_type>
4952IsSubsetOf(const Container& container) {
4953 return IsSubsetOf(container.begin(), container.end());
4954}
4955
4956#if GTEST_HAS_STD_INITIALIZER_LIST_
4957template <typename T>
4958inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
4959 ::std::initializer_list<T> xs) {
4960 return IsSubsetOf(xs.begin(), xs.end());
4961}
4962#endif
4963
zhanyong.wan33605ba2010-04-22 23:37:47 +00004964// Matches an STL-style container or a native array that contains only
4965// elements matching the given value or matcher.
4966//
4967// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
4968// the messages are different.
4969//
4970// Examples:
4971// ::std::set<int> page_ids;
4972// // Each(m) matches an empty container, regardless of what m is.
4973// EXPECT_THAT(page_ids, Each(Eq(1)));
4974// EXPECT_THAT(page_ids, Each(Eq(77)));
4975//
4976// page_ids.insert(3);
4977// EXPECT_THAT(page_ids, Each(Gt(0)));
4978// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
4979// page_ids.insert(1);
4980// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
4981//
4982// ::std::map<int, size_t> page_lengths;
4983// page_lengths[1] = 100;
4984// page_lengths[2] = 200;
4985// page_lengths[3] = 300;
4986// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
4987// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
4988//
4989// const char* user_ids[] = { "joe", "mike", "tom" };
4990// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
4991template <typename M>
4992inline internal::EachMatcher<M> Each(M matcher) {
4993 return internal::EachMatcher<M>(matcher);
4994}
4995
zhanyong.wanb5937da2009-07-16 20:26:41 +00004996// Key(inner_matcher) matches an std::pair whose 'first' field matches
4997// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
4998// std::map that contains at least one element whose key is >= 5.
4999template <typename M>
5000inline internal::KeyMatcher<M> Key(M inner_matcher) {
5001 return internal::KeyMatcher<M>(inner_matcher);
5002}
5003
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00005004// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
5005// matches first_matcher and whose 'second' field matches second_matcher. For
5006// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
5007// to match a std::map<int, string> that contains exactly one element whose key
5008// is >= 5 and whose value equals "foo".
5009template <typename FirstMatcher, typename SecondMatcher>
5010inline internal::PairMatcher<FirstMatcher, SecondMatcher>
5011Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
5012 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
5013 first_matcher, second_matcher);
5014}
5015
shiqiane35fdd92008-12-10 05:08:54 +00005016// Returns a predicate that is satisfied by anything that matches the
5017// given matcher.
5018template <typename M>
5019inline internal::MatcherAsPredicate<M> Matches(M matcher) {
5020 return internal::MatcherAsPredicate<M>(matcher);
5021}
5022
zhanyong.wanb8243162009-06-04 05:48:20 +00005023// Returns true iff the value matches the matcher.
5024template <typename T, typename M>
5025inline bool Value(const T& value, M matcher) {
5026 return testing::Matches(matcher)(value);
5027}
5028
zhanyong.wan34b034c2010-03-05 21:23:23 +00005029// Matches the value against the given matcher and explains the match
5030// result to listener.
5031template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00005032inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00005033 M matcher, const T& value, MatchResultListener* listener) {
5034 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
5035}
5036
Gennadiy Civilb907c262018-03-23 11:42:41 -04005037// Returns a string representation of the given matcher. Useful for description
5038// strings of matchers defined using MATCHER_P* macros that accept matchers as
5039// their arguments. For example:
5040//
5041// MATCHER_P(XAndYThat, matcher,
5042// "X that " + DescribeMatcher<int>(matcher, negation) +
5043// " and Y that " + DescribeMatcher<double>(matcher, negation)) {
5044// return ExplainMatchResult(matcher, arg.x(), result_listener) &&
5045// ExplainMatchResult(matcher, arg.y(), result_listener);
5046// }
5047template <typename T, typename M>
5048std::string DescribeMatcher(const M& matcher, bool negation = false) {
5049 ::std::stringstream ss;
5050 Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher);
5051 if (negation) {
5052 monomorphic_matcher.DescribeNegationTo(&ss);
5053 } else {
5054 monomorphic_matcher.DescribeTo(&ss);
5055 }
5056 return ss.str();
5057}
5058
zhanyong.wan616180e2013-06-18 18:49:51 +00005059#if GTEST_LANG_CXX11
5060// Define variadic matcher versions. They are overloaded in
5061// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
5062template <typename... Args>
5063inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
5064 return internal::AllOfMatcher<Args...>(matchers...);
5065}
5066
5067template <typename... Args>
5068inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
5069 return internal::AnyOfMatcher<Args...>(matchers...);
5070}
5071
5072#endif // GTEST_LANG_CXX11
5073
zhanyong.wanbf550852009-06-09 06:09:53 +00005074// AllArgs(m) is a synonym of m. This is useful in
5075//
5076// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
5077//
5078// which is easier to read than
5079//
5080// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
5081template <typename InnerMatcher>
5082inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
5083
Gennadiy Civilb907c262018-03-23 11:42:41 -04005084// Returns a matcher that matches the value of an optional<> type variable.
5085// The matcher implementation only uses '!arg' and requires that the optional<>
5086// type has a 'value_type' member type and that '*arg' is of type 'value_type'
5087// and is printable using 'PrintToString'. It is compatible with
5088// std::optional/std::experimental::optional.
5089// Note that to compare an optional type variable against nullopt you should
5090// use Eq(nullopt) and not Optional(Eq(nullopt)). The latter implies that the
5091// optional value contains an optional itself.
5092template <typename ValueMatcher>
5093inline internal::OptionalMatcher<ValueMatcher> Optional(
5094 const ValueMatcher& value_matcher) {
5095 return internal::OptionalMatcher<ValueMatcher>(value_matcher);
5096}
5097
5098// Returns a matcher that matches the value of a absl::any type variable.
5099template <typename T>
5100PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T> > AnyWith(
5101 const Matcher<const T&>& matcher) {
5102 return MakePolymorphicMatcher(
5103 internal::any_cast_matcher::AnyCastMatcher<T>(matcher));
5104}
5105
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05005106// Returns a matcher that matches the value of a variant<> type variable.
5107// The matcher implementation uses ADL to find the holds_alternative and get
5108// functions.
5109// It is compatible with std::variant.
5110template <typename T>
5111PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
5112 const Matcher<const T&>& matcher) {
5113 return MakePolymorphicMatcher(
5114 internal::variant_matcher::VariantMatcher<T>(matcher));
5115}
5116
shiqiane35fdd92008-12-10 05:08:54 +00005117// These macros allow using matchers to check values in Google Test
5118// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
5119// succeed iff the value matches the matcher. If the assertion fails,
5120// the value and the description of the matcher will be printed.
5121#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
5122 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
5123#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
5124 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
5125
5126} // namespace testing
5127
kosak6702b972015-07-27 23:05:57 +00005128// Include any custom callback matchers added by the local installation.
5129// We must include this header at the end to make sure it can use the
5130// declarations from this file.
5131#include "gmock/internal/custom/gmock-matchers.h"
Gennadiy Civilb907c262018-03-23 11:42:41 -04005132
shiqiane35fdd92008-12-10 05:08:54 +00005133#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_