blob: dea1070c465e07b313932c9ddf09117858ce148c [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'.
284 bool MatchAndExplain(T x, MatchResultListener* listener) const {
285 return impl_->MatchAndExplain(x, listener);
286 }
287
shiqiane35fdd92008-12-10 05:08:54 +0000288 // Returns true iff this matcher matches x.
zhanyong.wan82113312010-01-08 21:55:40 +0000289 bool Matches(T x) const {
290 DummyMatchResultListener dummy;
291 return MatchAndExplain(x, &dummy);
292 }
shiqiane35fdd92008-12-10 05:08:54 +0000293
294 // Describes this matcher to an ostream.
295 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
296
297 // Describes the negation of this matcher to an ostream.
298 void DescribeNegationTo(::std::ostream* os) const {
299 impl_->DescribeNegationTo(os);
300 }
301
302 // Explains why x matches, or doesn't match, the matcher.
303 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000304 StreamMatchResultListener listener(os);
305 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000306 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000307
zhanyong.wanfb25d532013-07-28 08:24:00 +0000308 // Returns the describer for this matcher object; retains ownership
309 // of the describer, which is only guaranteed to be alive when
310 // this matcher object is alive.
311 const MatcherDescriberInterface* GetDescriber() const {
312 return impl_.get();
313 }
314
shiqiane35fdd92008-12-10 05:08:54 +0000315 protected:
316 MatcherBase() {}
317
318 // Constructs a matcher from its implementation.
319 explicit MatcherBase(const MatcherInterface<T>* impl)
320 : impl_(impl) {}
321
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400322 template <typename U>
323 explicit MatcherBase(
324 const MatcherInterface<U>* impl,
325 typename internal::EnableIf<
326 !internal::IsSame<U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* =
327 NULL)
328 : impl_(new internal::MatcherInterfaceAdapter<U>(impl)) {}
329
shiqiane35fdd92008-12-10 05:08:54 +0000330 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000331
shiqiane35fdd92008-12-10 05:08:54 +0000332 private:
333 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
334 // interfaces. The former dynamically allocates a chunk of memory
335 // to hold the reference count, while the latter tracks all
336 // references using a circular linked list without allocating
337 // memory. It has been observed that linked_ptr performs better in
338 // typical scenarios. However, shared_ptr can out-perform
339 // linked_ptr when there are many more uses of the copy constructor
340 // than the default constructor.
341 //
342 // If performance becomes a problem, we should see if using
343 // shared_ptr helps.
344 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
345};
346
shiqiane35fdd92008-12-10 05:08:54 +0000347} // namespace internal
348
349// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
350// object that can check whether a value of type T matches. The
351// implementation of Matcher<T> is just a linked_ptr to const
352// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
353// from Matcher!
354template <typename T>
355class Matcher : public internal::MatcherBase<T> {
356 public:
vladlosev88032d82010-11-17 23:29:21 +0000357 // Constructs a null matcher. Needed for storing Matcher objects in STL
358 // containers. A default-constructed matcher is not yet initialized. You
359 // cannot use it until a valid value has been assigned to it.
kosakd86a7232015-07-13 21:19:43 +0000360 explicit Matcher() {} // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000361
362 // Constructs a matcher from its implementation.
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400363 explicit Matcher(const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)>* impl)
364 : internal::MatcherBase<T>(impl) {}
365
366 template <typename U>
367 explicit Matcher(const MatcherInterface<U>* impl,
368 typename internal::EnableIf<!internal::IsSame<
369 U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* = NULL)
shiqiane35fdd92008-12-10 05:08:54 +0000370 : internal::MatcherBase<T>(impl) {}
371
zhanyong.wan18490652009-05-11 18:54:08 +0000372 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000373 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
374 Matcher(T value); // NOLINT
375};
376
377// The following two specializations allow the user to write str
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400378// instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
shiqiane35fdd92008-12-10 05:08:54 +0000379// matcher is expected.
380template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400381class GTEST_API_ Matcher<const std::string&>
382 : public internal::MatcherBase<const std::string&> {
shiqiane35fdd92008-12-10 05:08:54 +0000383 public:
384 Matcher() {}
385
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400386 explicit Matcher(const MatcherInterface<const std::string&>* impl)
387 : internal::MatcherBase<const std::string&>(impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000388
389 // Allows the user to write str instead of Eq(str) sometimes, where
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400390 // str is a std::string object.
391 Matcher(const std::string& s); // NOLINT
392
393#if GTEST_HAS_GLOBAL_STRING
394 // Allows the user to write str instead of Eq(str) sometimes, where
395 // str is a ::string object.
396 Matcher(const ::string& s); // NOLINT
397#endif // GTEST_HAS_GLOBAL_STRING
shiqiane35fdd92008-12-10 05:08:54 +0000398
399 // Allows the user to write "foo" instead of Eq("foo") sometimes.
400 Matcher(const char* s); // NOLINT
401};
402
403template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400404class GTEST_API_ Matcher<std::string>
405 : public internal::MatcherBase<std::string> {
shiqiane35fdd92008-12-10 05:08:54 +0000406 public:
407 Matcher() {}
408
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400409 explicit Matcher(const MatcherInterface<std::string>* impl)
410 : internal::MatcherBase<std::string>(impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000411
412 // Allows the user to write str instead of Eq(str) sometimes, where
413 // str is a string object.
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400414 Matcher(const std::string& s); // NOLINT
415
416#if GTEST_HAS_GLOBAL_STRING
417 // Allows the user to write str instead of Eq(str) sometimes, where
418 // str is a ::string object.
419 Matcher(const ::string& s); // NOLINT
420#endif // GTEST_HAS_GLOBAL_STRING
shiqiane35fdd92008-12-10 05:08:54 +0000421
422 // Allows the user to write "foo" instead of Eq("foo") sometimes.
423 Matcher(const char* s); // NOLINT
424};
425
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400426#if GTEST_HAS_GLOBAL_STRING
zhanyong.wan1f122a02013-03-25 16:27:03 +0000427// The following two specializations allow the user to write str
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400428// instead of Eq(str) and "foo" instead of Eq("foo") when a ::string
zhanyong.wan1f122a02013-03-25 16:27:03 +0000429// matcher is expected.
430template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400431class GTEST_API_ Matcher<const ::string&>
432 : public internal::MatcherBase<const ::string&> {
zhanyong.wan1f122a02013-03-25 16:27:03 +0000433 public:
434 Matcher() {}
435
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400436 explicit Matcher(const MatcherInterface<const ::string&>* impl)
437 : internal::MatcherBase<const ::string&>(impl) {}
zhanyong.wan1f122a02013-03-25 16:27:03 +0000438
439 // Allows the user to write str instead of Eq(str) sometimes, where
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400440 // str is a std::string object.
441 Matcher(const std::string& s); // NOLINT
442
443 // Allows the user to write str instead of Eq(str) sometimes, where
444 // str is a ::string object.
445 Matcher(const ::string& s); // NOLINT
zhanyong.wan1f122a02013-03-25 16:27:03 +0000446
447 // Allows the user to write "foo" instead of Eq("foo") sometimes.
448 Matcher(const char* s); // NOLINT
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400449};
zhanyong.wan1f122a02013-03-25 16:27:03 +0000450
zhanyong.wan1f122a02013-03-25 16:27:03 +0000451};
452
453template <>
454class GTEST_API_ Matcher<StringPiece>
455 : public internal::MatcherBase<StringPiece> {
456 public:
457 Matcher() {}
458
459 explicit Matcher(const MatcherInterface<StringPiece>* impl)
460 : internal::MatcherBase<StringPiece>(impl) {}
461
462 // Allows the user to write str instead of Eq(str) sometimes, where
463 // str is a string object.
464 Matcher(const internal::string& s); // NOLINT
465
466 // Allows the user to write "foo" instead of Eq("foo") sometimes.
467 Matcher(const char* s); // NOLINT
468
469 // Allows the user to pass StringPieces directly.
470 Matcher(StringPiece s); // NOLINT
471};
472#endif // GTEST_HAS_STRING_PIECE_
473
shiqiane35fdd92008-12-10 05:08:54 +0000474// The PolymorphicMatcher class template makes it easy to implement a
475// polymorphic matcher (i.e. a matcher that can match values of more
476// than one type, e.g. Eq(n) and NotNull()).
477//
zhanyong.wandb22c222010-01-28 21:52:29 +0000478// To define a polymorphic matcher, a user should provide an Impl
479// class that has a DescribeTo() method and a DescribeNegationTo()
480// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000481//
zhanyong.wandb22c222010-01-28 21:52:29 +0000482// bool MatchAndExplain(const Value& value,
483// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000484//
485// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000486template <class Impl>
487class PolymorphicMatcher {
488 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000489 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000490
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000491 // Returns a mutable reference to the underlying matcher
492 // implementation object.
493 Impl& mutable_impl() { return impl_; }
494
495 // Returns an immutable reference to the underlying matcher
496 // implementation object.
497 const Impl& impl() const { return impl_; }
498
shiqiane35fdd92008-12-10 05:08:54 +0000499 template <typename T>
500 operator Matcher<T>() const {
501 return Matcher<T>(new MonomorphicImpl<T>(impl_));
502 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000503
shiqiane35fdd92008-12-10 05:08:54 +0000504 private:
505 template <typename T>
506 class MonomorphicImpl : public MatcherInterface<T> {
507 public:
508 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
509
shiqiane35fdd92008-12-10 05:08:54 +0000510 virtual void DescribeTo(::std::ostream* os) const {
511 impl_.DescribeTo(os);
512 }
513
514 virtual void DescribeNegationTo(::std::ostream* os) const {
515 impl_.DescribeNegationTo(os);
516 }
517
zhanyong.wan82113312010-01-08 21:55:40 +0000518 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000519 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000520 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000521
shiqiane35fdd92008-12-10 05:08:54 +0000522 private:
523 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000524
525 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000526 };
527
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000528 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000529
530 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000531};
532
533// Creates a matcher from its implementation. This is easier to use
534// than the Matcher<T> constructor as it doesn't require you to
535// explicitly write the template argument, e.g.
536//
537// MakeMatcher(foo);
538// vs
539// Matcher<const string&>(foo);
540template <typename T>
541inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
542 return Matcher<T>(impl);
zhanyong.wan2eab17b2013-03-08 17:53:24 +0000543}
shiqiane35fdd92008-12-10 05:08:54 +0000544
545// Creates a polymorphic matcher from its implementation. This is
546// easier to use than the PolymorphicMatcher<Impl> constructor as it
547// doesn't require you to explicitly write the template argument, e.g.
548//
549// MakePolymorphicMatcher(foo);
550// vs
551// PolymorphicMatcher<TypeOfFoo>(foo);
552template <class Impl>
553inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
554 return PolymorphicMatcher<Impl>(impl);
555}
556
jgm79a367e2012-04-10 16:02:11 +0000557// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
558// and MUST NOT BE USED IN USER CODE!!!
559namespace internal {
560
561// The MatcherCastImpl class template is a helper for implementing
562// MatcherCast(). We need this helper in order to partially
563// specialize the implementation of MatcherCast() (C++ allows
564// class/struct templates to be partially specialized, but not
565// function templates.).
566
567// This general version is used when MatcherCast()'s argument is a
568// polymorphic matcher (i.e. something that can be converted to a
569// Matcher but is not one yet; for example, Eq(value)) or a value (for
570// example, "hello").
571template <typename T, typename M>
572class MatcherCastImpl {
573 public:
kosak5f2a6ca2013-12-03 01:43:07 +0000574 static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
Gennadiy Civil2bd17502018-02-27 13:51:09 -0500575 // M can be a polymorphic matcher, in which case we want to use
jgm79a367e2012-04-10 16:02:11 +0000576 // its conversion operator to create Matcher<T>. Or it can be a value
577 // that should be passed to the Matcher<T>'s constructor.
578 //
579 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
580 // polymorphic matcher because it'll be ambiguous if T has an implicit
581 // constructor from M (this usually happens when T has an implicit
582 // constructor from any type).
583 //
584 // It won't work to unconditionally implict_cast
585 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
586 // a user-defined conversion from M to T if one exists (assuming M is
587 // a value).
588 return CastImpl(
589 polymorphic_matcher_or_value,
590 BooleanConstant<
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400591 internal::ImplicitlyConvertible<M, Matcher<T> >::value>(),
592 BooleanConstant<
593 internal::ImplicitlyConvertible<M, T>::value>());
jgm79a367e2012-04-10 16:02:11 +0000594 }
595
596 private:
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400597 template <bool Ignore>
kosak5f2a6ca2013-12-03 01:43:07 +0000598 static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400599 BooleanConstant<true> /* convertible_to_matcher */,
600 BooleanConstant<Ignore>) {
jgm79a367e2012-04-10 16:02:11 +0000601 // M is implicitly convertible to Matcher<T>, which means that either
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400602 // M is a polymorphic matcher or Matcher<T> has an implicit constructor
jgm79a367e2012-04-10 16:02:11 +0000603 // from M. In both cases using the implicit conversion will produce a
604 // matcher.
605 //
606 // Even if T has an implicit constructor from M, it won't be called because
607 // creating Matcher<T> would require a chain of two user-defined conversions
608 // (first to create T from M and then to create Matcher<T> from T).
609 return polymorphic_matcher_or_value;
610 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -0400611
612 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
613 // matcher. It's a value of a type implicitly convertible to T. Use direct
614 // initialization to create a matcher.
615 static Matcher<T> CastImpl(
616 const M& value, BooleanConstant<false> /* convertible_to_matcher */,
617 BooleanConstant<true> /* convertible_to_T */) {
618 return Matcher<T>(ImplicitCast_<T>(value));
619 }
620
621 // M can't be implicitly converted to either Matcher<T> or T. Attempt to use
622 // polymorphic matcher Eq(value) in this case.
623 //
624 // Note that we first attempt to perform an implicit cast on the value and
625 // only fall back to the polymorphic Eq() matcher afterwards because the
626 // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end
627 // which might be undefined even when Rhs is implicitly convertible to Lhs
628 // (e.g. std::pair<const int, int> vs. std::pair<int, int>).
629 //
630 // We don't define this method inline as we need the declaration of Eq().
631 static Matcher<T> CastImpl(
632 const M& value, BooleanConstant<false> /* convertible_to_matcher */,
633 BooleanConstant<false> /* convertible_to_T */);
jgm79a367e2012-04-10 16:02:11 +0000634};
635
636// This more specialized version is used when MatcherCast()'s argument
637// is already a Matcher. This only compiles when type T can be
638// statically converted to type U.
639template <typename T, typename U>
640class MatcherCastImpl<T, Matcher<U> > {
641 public:
642 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
643 return Matcher<T>(new Impl(source_matcher));
644 }
645
646 private:
647 class Impl : public MatcherInterface<T> {
648 public:
649 explicit Impl(const Matcher<U>& source_matcher)
650 : source_matcher_(source_matcher) {}
651
652 // We delegate the matching logic to the source matcher.
653 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
654 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
655 }
656
657 virtual void DescribeTo(::std::ostream* os) const {
658 source_matcher_.DescribeTo(os);
659 }
660
661 virtual void DescribeNegationTo(::std::ostream* os) const {
662 source_matcher_.DescribeNegationTo(os);
663 }
664
665 private:
666 const Matcher<U> source_matcher_;
667
668 GTEST_DISALLOW_ASSIGN_(Impl);
669 };
670};
671
672// This even more specialized version is used for efficiently casting
673// a matcher to its own type.
674template <typename T>
675class MatcherCastImpl<T, Matcher<T> > {
676 public:
677 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
678};
679
680} // namespace internal
681
shiqiane35fdd92008-12-10 05:08:54 +0000682// In order to be safe and clear, casting between different matcher
683// types is done explicitly via MatcherCast<T>(m), which takes a
684// matcher m and returns a Matcher<T>. It compiles only when T can be
685// statically converted to the argument type of m.
686template <typename T, typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000687inline Matcher<T> MatcherCast(const M& matcher) {
jgm79a367e2012-04-10 16:02:11 +0000688 return internal::MatcherCastImpl<T, M>::Cast(matcher);
689}
shiqiane35fdd92008-12-10 05:08:54 +0000690
zhanyong.wan18490652009-05-11 18:54:08 +0000691// Implements SafeMatcherCast().
692//
zhanyong.wan95b12332009-09-25 18:55:50 +0000693// We use an intermediate class to do the actual safe casting as Nokia's
694// Symbian compiler cannot decide between
695// template <T, M> ... (M) and
696// template <T, U> ... (const Matcher<U>&)
697// for function templates but can for member function templates.
698template <typename T>
699class SafeMatcherCastImpl {
700 public:
jgm79a367e2012-04-10 16:02:11 +0000701 // This overload handles polymorphic matchers and values only since
702 // monomorphic matchers are handled by the next one.
zhanyong.wan95b12332009-09-25 18:55:50 +0000703 template <typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000704 static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
jgm79a367e2012-04-10 16:02:11 +0000705 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
zhanyong.wan95b12332009-09-25 18:55:50 +0000706 }
zhanyong.wan18490652009-05-11 18:54:08 +0000707
zhanyong.wan95b12332009-09-25 18:55:50 +0000708 // This overload handles monomorphic matchers.
709 //
710 // In general, if type T can be implicitly converted to type U, we can
711 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
712 // contravariant): just keep a copy of the original Matcher<U>, convert the
713 // argument from type T to U, and then pass it to the underlying Matcher<U>.
714 // The only exception is when U is a reference and T is not, as the
715 // underlying Matcher<U> may be interested in the argument's address, which
716 // is not preserved in the conversion from T to U.
717 template <typename U>
718 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
719 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000720 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000721 T_must_be_implicitly_convertible_to_U);
722 // Enforce that we are not converting a non-reference type T to a reference
723 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000724 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000725 internal::is_reference<T>::value || !internal::is_reference<U>::value,
Hector Dearman24054ff2017-06-19 18:27:33 +0100726 cannot_convert_non_reference_arg_to_reference);
zhanyong.wan95b12332009-09-25 18:55:50 +0000727 // In case both T and U are arithmetic types, enforce that the
728 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000729 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
730 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000731 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
732 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000733 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000734 kTIsOther || kUIsOther ||
735 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
736 conversion_of_arithmetic_types_must_be_lossless);
737 return MatcherCast<T>(matcher);
738 }
739};
740
741template <typename T, typename M>
742inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
743 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000744}
745
shiqiane35fdd92008-12-10 05:08:54 +0000746// A<T>() returns a matcher that matches any value of type T.
747template <typename T>
748Matcher<T> A();
749
750// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
751// and MUST NOT BE USED IN USER CODE!!!
752namespace internal {
753
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000754// If the explanation is not empty, prints it to the ostream.
Nico Weber09fd5b32017-05-15 17:07:03 -0400755inline void PrintIfNotEmpty(const std::string& explanation,
zhanyong.wanfb25d532013-07-28 08:24:00 +0000756 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000757 if (explanation != "" && os != NULL) {
758 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000759 }
760}
761
zhanyong.wan736baa82010-09-27 17:44:16 +0000762// Returns true if the given type name is easy to read by a human.
763// This is used to decide whether printing the type of a value might
764// be helpful.
Nico Weber09fd5b32017-05-15 17:07:03 -0400765inline bool IsReadableTypeName(const std::string& type_name) {
zhanyong.wan736baa82010-09-27 17:44:16 +0000766 // We consider a type name readable if it's short or doesn't contain
767 // a template or function type.
768 return (type_name.length() <= 20 ||
Nico Weber09fd5b32017-05-15 17:07:03 -0400769 type_name.find_first_of("<(") == std::string::npos);
zhanyong.wan736baa82010-09-27 17:44:16 +0000770}
771
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000772// Matches the value against the given matcher, prints the value and explains
773// the match result to the listener. Returns the match result.
774// 'listener' must not be NULL.
775// Value cannot be passed by const reference, because some matchers take a
776// non-const argument.
777template <typename Value, typename T>
778bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
779 MatchResultListener* listener) {
780 if (!listener->IsInterested()) {
781 // If the listener is not interested, we do not need to construct the
782 // inner explanation.
783 return matcher.Matches(value);
784 }
785
786 StringMatchResultListener inner_listener;
787 const bool match = matcher.MatchAndExplain(value, &inner_listener);
788
789 UniversalPrint(value, listener->stream());
zhanyong.wan736baa82010-09-27 17:44:16 +0000790#if GTEST_HAS_RTTI
Nico Weber09fd5b32017-05-15 17:07:03 -0400791 const std::string& type_name = GetTypeName<Value>();
zhanyong.wan736baa82010-09-27 17:44:16 +0000792 if (IsReadableTypeName(type_name))
793 *listener->stream() << " (of type " << type_name << ")";
794#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000795 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000796
797 return match;
798}
799
shiqiane35fdd92008-12-10 05:08:54 +0000800// An internal helper class for doing compile-time loop on a tuple's
801// fields.
802template <size_t N>
803class TuplePrefix {
804 public:
805 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
806 // iff the first N fields of matcher_tuple matches the first N
807 // fields of value_tuple, respectively.
808 template <typename MatcherTuple, typename ValueTuple>
809 static bool Matches(const MatcherTuple& matcher_tuple,
810 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000811 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
812 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
813 }
814
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000815 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000816 // describes failures in matching the first N fields of matchers
817 // against the first N fields of values. If there is no failure,
818 // nothing will be streamed to os.
819 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000820 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
821 const ValueTuple& values,
822 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000823 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000824 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000825
826 // Then describes the failure (if any) in the (N - 1)-th (0-based)
827 // field.
828 typename tuple_element<N - 1, MatcherTuple>::type matcher =
829 get<N - 1>(matchers);
830 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
831 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000832 StringMatchResultListener listener;
833 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000834 // TODO(wan): include in the message the name of the parameter
835 // as used in MOCK_METHOD*() when possible.
836 *os << " Expected arg #" << N - 1 << ": ";
837 get<N - 1>(matchers).DescribeTo(os);
838 *os << "\n Actual: ";
839 // We remove the reference in type Value to prevent the
840 // universal printer from printing the address of value, which
841 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000842 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000843 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000844 internal::UniversalPrint(value, os);
845 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000846 *os << "\n";
847 }
848 }
849};
850
851// The base case.
852template <>
853class TuplePrefix<0> {
854 public:
855 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000856 static bool Matches(const MatcherTuple& /* matcher_tuple */,
857 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000858 return true;
859 }
860
861 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000862 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
863 const ValueTuple& /* values */,
864 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000865};
866
867// TupleMatches(matcher_tuple, value_tuple) returns true iff all
868// matchers in matcher_tuple match the corresponding fields in
869// value_tuple. It is a compiler error if matcher_tuple and
870// value_tuple have different number of fields or incompatible field
871// types.
872template <typename MatcherTuple, typename ValueTuple>
873bool TupleMatches(const MatcherTuple& matcher_tuple,
874 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000875 // Makes sure that matcher_tuple and value_tuple have the same
876 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000877 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000878 tuple_size<ValueTuple>::value,
879 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000880 return TuplePrefix<tuple_size<ValueTuple>::value>::
881 Matches(matcher_tuple, value_tuple);
882}
883
884// Describes failures in matching matchers against values. If there
885// is no failure, nothing will be streamed to os.
886template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000887void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
888 const ValueTuple& values,
889 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000890 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000891 matchers, values, os);
892}
893
zhanyong.wanfb25d532013-07-28 08:24:00 +0000894// TransformTupleValues and its helper.
895//
896// TransformTupleValuesHelper hides the internal machinery that
897// TransformTupleValues uses to implement a tuple traversal.
898template <typename Tuple, typename Func, typename OutIter>
899class TransformTupleValuesHelper {
900 private:
kosakbd018832014-04-02 20:30:00 +0000901 typedef ::testing::tuple_size<Tuple> TupleSize;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000902
903 public:
904 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
905 // Returns the final value of 'out' in case the caller needs it.
906 static OutIter Run(Func f, const Tuple& t, OutIter out) {
907 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
908 }
909
910 private:
911 template <typename Tup, size_t kRemainingSize>
912 struct IterateOverTuple {
913 OutIter operator() (Func f, const Tup& t, OutIter out) const {
kosakbd018832014-04-02 20:30:00 +0000914 *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
zhanyong.wanfb25d532013-07-28 08:24:00 +0000915 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
916 }
917 };
918 template <typename Tup>
919 struct IterateOverTuple<Tup, 0> {
920 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
921 return out;
922 }
923 };
924};
925
926// Successively invokes 'f(element)' on each element of the tuple 't',
927// appending each result to the 'out' iterator. Returns the final value
928// of 'out'.
929template <typename Tuple, typename Func, typename OutIter>
930OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
931 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
932}
933
shiqiane35fdd92008-12-10 05:08:54 +0000934// Implements A<T>().
935template <typename T>
936class AnyMatcherImpl : public MatcherInterface<T> {
937 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000938 virtual bool MatchAndExplain(
939 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000940 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
941 virtual void DescribeNegationTo(::std::ostream* os) const {
942 // This is mostly for completeness' safe, as it's not very useful
943 // to write Not(A<bool>()). However we cannot completely rule out
944 // such a possibility, and it doesn't hurt to be prepared.
945 *os << "never matches";
946 }
947};
948
949// Implements _, a matcher that matches any value of any
950// type. This is a polymorphic matcher, so we need a template type
951// conversion operator to make it appearing as a Matcher<T> for any
952// type T.
953class AnythingMatcher {
954 public:
955 template <typename T>
956 operator Matcher<T>() const { return A<T>(); }
957};
958
959// Implements a matcher that compares a given value with a
960// pre-supplied value using one of the ==, <=, <, etc, operators. The
961// two values being compared don't have to have the same type.
962//
963// The matcher defined here is polymorphic (for example, Eq(5) can be
964// used to match an int, a short, a double, etc). Therefore we use
965// a template type conversion operator in the implementation.
966//
shiqiane35fdd92008-12-10 05:08:54 +0000967// The following template definition assumes that the Rhs parameter is
968// a "bare" type (i.e. neither 'const T' nor 'T&').
kosak506340a2014-11-17 01:47:54 +0000969template <typename D, typename Rhs, typename Op>
970class ComparisonBase {
971 public:
972 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
973 template <typename Lhs>
974 operator Matcher<Lhs>() const {
975 return MakeMatcher(new Impl<Lhs>(rhs_));
shiqiane35fdd92008-12-10 05:08:54 +0000976 }
977
kosak506340a2014-11-17 01:47:54 +0000978 private:
979 template <typename Lhs>
980 class Impl : public MatcherInterface<Lhs> {
981 public:
982 explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
983 virtual bool MatchAndExplain(
984 Lhs lhs, MatchResultListener* /* listener */) const {
985 return Op()(lhs, rhs_);
986 }
987 virtual void DescribeTo(::std::ostream* os) const {
988 *os << D::Desc() << " ";
989 UniversalPrint(rhs_, os);
990 }
991 virtual void DescribeNegationTo(::std::ostream* os) const {
992 *os << D::NegatedDesc() << " ";
993 UniversalPrint(rhs_, os);
994 }
995 private:
996 Rhs rhs_;
997 GTEST_DISALLOW_ASSIGN_(Impl);
998 };
999 Rhs rhs_;
1000 GTEST_DISALLOW_ASSIGN_(ComparisonBase);
1001};
shiqiane35fdd92008-12-10 05:08:54 +00001002
kosak506340a2014-11-17 01:47:54 +00001003template <typename Rhs>
1004class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
1005 public:
1006 explicit EqMatcher(const Rhs& rhs)
1007 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
1008 static const char* Desc() { return "is equal to"; }
1009 static const char* NegatedDesc() { return "isn't equal to"; }
1010};
1011template <typename Rhs>
1012class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
1013 public:
1014 explicit NeMatcher(const Rhs& rhs)
1015 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
1016 static const char* Desc() { return "isn't equal to"; }
1017 static const char* NegatedDesc() { return "is equal to"; }
1018};
1019template <typename Rhs>
1020class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
1021 public:
1022 explicit LtMatcher(const Rhs& rhs)
1023 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
1024 static const char* Desc() { return "is <"; }
1025 static const char* NegatedDesc() { return "isn't <"; }
1026};
1027template <typename Rhs>
1028class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
1029 public:
1030 explicit GtMatcher(const Rhs& rhs)
1031 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
1032 static const char* Desc() { return "is >"; }
1033 static const char* NegatedDesc() { return "isn't >"; }
1034};
1035template <typename Rhs>
1036class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
1037 public:
1038 explicit LeMatcher(const Rhs& rhs)
1039 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
1040 static const char* Desc() { return "is <="; }
1041 static const char* NegatedDesc() { return "isn't <="; }
1042};
1043template <typename Rhs>
1044class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
1045 public:
1046 explicit GeMatcher(const Rhs& rhs)
1047 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
1048 static const char* Desc() { return "is >="; }
1049 static const char* NegatedDesc() { return "isn't >="; }
1050};
shiqiane35fdd92008-12-10 05:08:54 +00001051
vladlosev79b83502009-11-18 00:43:37 +00001052// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001053// pointer that is NULL.
1054class IsNullMatcher {
1055 public:
vladlosev79b83502009-11-18 00:43:37 +00001056 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +00001057 bool MatchAndExplain(const Pointer& p,
1058 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001059#if GTEST_LANG_CXX11
1060 return p == nullptr;
1061#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001062 return GetRawPointer(p) == NULL;
kosak6305ff52015-04-28 22:36:31 +00001063#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001064 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001065
1066 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
1067 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001068 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001069 }
1070};
1071
vladlosev79b83502009-11-18 00:43:37 +00001072// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +00001073// pointer that is not NULL.
1074class NotNullMatcher {
1075 public:
vladlosev79b83502009-11-18 00:43:37 +00001076 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +00001077 bool MatchAndExplain(const Pointer& p,
1078 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001079#if GTEST_LANG_CXX11
1080 return p != nullptr;
1081#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001082 return GetRawPointer(p) != NULL;
kosak6305ff52015-04-28 22:36:31 +00001083#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001084 }
shiqiane35fdd92008-12-10 05:08:54 +00001085
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001086 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +00001087 void DescribeNegationTo(::std::ostream* os) const {
1088 *os << "is NULL";
1089 }
1090};
1091
1092// Ref(variable) matches any argument that is a reference to
1093// 'variable'. This matcher is polymorphic as it can match any
1094// super type of the type of 'variable'.
1095//
1096// The RefMatcher template class implements Ref(variable). It can
1097// only be instantiated with a reference type. This prevents a user
1098// from mistakenly using Ref(x) to match a non-reference function
1099// argument. For example, the following will righteously cause a
1100// compiler error:
1101//
1102// int n;
1103// Matcher<int> m1 = Ref(n); // This won't compile.
1104// Matcher<int&> m2 = Ref(n); // This will compile.
1105template <typename T>
1106class RefMatcher;
1107
1108template <typename T>
1109class RefMatcher<T&> {
1110 // Google Mock is a generic framework and thus needs to support
1111 // mocking any function types, including those that take non-const
1112 // reference arguments. Therefore the template parameter T (and
1113 // Super below) can be instantiated to either a const type or a
1114 // non-const type.
1115 public:
1116 // RefMatcher() takes a T& instead of const T&, as we want the
1117 // compiler to catch using Ref(const_value) as a matcher for a
1118 // non-const reference.
1119 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
1120
1121 template <typename Super>
1122 operator Matcher<Super&>() const {
1123 // By passing object_ (type T&) to Impl(), which expects a Super&,
1124 // we make sure that Super is a super type of T. In particular,
1125 // this catches using Ref(const_value) as a matcher for a
1126 // non-const reference, as you cannot implicitly convert a const
1127 // reference to a non-const reference.
1128 return MakeMatcher(new Impl<Super>(object_));
1129 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001130
shiqiane35fdd92008-12-10 05:08:54 +00001131 private:
1132 template <typename Super>
1133 class Impl : public MatcherInterface<Super&> {
1134 public:
1135 explicit Impl(Super& x) : object_(x) {} // NOLINT
1136
zhanyong.wandb22c222010-01-28 21:52:29 +00001137 // MatchAndExplain() takes a Super& (as opposed to const Super&)
1138 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +00001139 virtual bool MatchAndExplain(
1140 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001141 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +00001142 return &x == &object_;
1143 }
shiqiane35fdd92008-12-10 05:08:54 +00001144
1145 virtual void DescribeTo(::std::ostream* os) const {
1146 *os << "references the variable ";
1147 UniversalPrinter<Super&>::Print(object_, os);
1148 }
1149
1150 virtual void DescribeNegationTo(::std::ostream* os) const {
1151 *os << "does not reference the variable ";
1152 UniversalPrinter<Super&>::Print(object_, os);
1153 }
1154
shiqiane35fdd92008-12-10 05:08:54 +00001155 private:
1156 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001157
1158 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001159 };
1160
1161 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001162
1163 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001164};
1165
1166// Polymorphic helper functions for narrow and wide string matchers.
1167inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1168 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1169}
1170
1171inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1172 const wchar_t* rhs) {
1173 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1174}
1175
1176// String comparison for narrow or wide strings that can have embedded NUL
1177// characters.
1178template <typename StringType>
1179bool CaseInsensitiveStringEquals(const StringType& s1,
1180 const StringType& s2) {
1181 // Are the heads equal?
1182 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1183 return false;
1184 }
1185
1186 // Skip the equal heads.
1187 const typename StringType::value_type nul = 0;
1188 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1189
1190 // Are we at the end of either s1 or s2?
1191 if (i1 == StringType::npos || i2 == StringType::npos) {
1192 return i1 == i2;
1193 }
1194
1195 // Are the tails equal?
1196 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1197}
1198
1199// String matchers.
1200
1201// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1202template <typename StringType>
1203class StrEqualityMatcher {
1204 public:
shiqiane35fdd92008-12-10 05:08:54 +00001205 StrEqualityMatcher(const StringType& str, bool expect_eq,
1206 bool case_sensitive)
1207 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1208
jgm38513a82012-11-15 15:50:36 +00001209 // Accepts pointer types, particularly:
1210 // const char*
1211 // char*
1212 // const wchar_t*
1213 // wchar_t*
1214 template <typename CharType>
1215 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001216 if (s == NULL) {
1217 return !expect_eq_;
1218 }
zhanyong.wandb22c222010-01-28 21:52:29 +00001219 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001220 }
1221
jgm38513a82012-11-15 15:50:36 +00001222 // Matches anything that can convert to StringType.
1223 //
1224 // This is a template, not just a plain function with const StringType&,
1225 // because StringPiece has some interfering non-explicit constructors.
1226 template <typename MatcheeStringType>
1227 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001228 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001229 const StringType& s2(s);
1230 const bool eq = case_sensitive_ ? s2 == string_ :
1231 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +00001232 return expect_eq_ == eq;
1233 }
1234
1235 void DescribeTo(::std::ostream* os) const {
1236 DescribeToHelper(expect_eq_, os);
1237 }
1238
1239 void DescribeNegationTo(::std::ostream* os) const {
1240 DescribeToHelper(!expect_eq_, os);
1241 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001242
shiqiane35fdd92008-12-10 05:08:54 +00001243 private:
1244 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001245 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +00001246 *os << "equal to ";
1247 if (!case_sensitive_) {
1248 *os << "(ignoring case) ";
1249 }
vladloseve2e8ba42010-05-13 18:16:03 +00001250 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001251 }
1252
1253 const StringType string_;
1254 const bool expect_eq_;
1255 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001256
1257 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001258};
1259
1260// Implements the polymorphic HasSubstr(substring) matcher, which
1261// can be used as a Matcher<T> as long as T can be converted to a
1262// string.
1263template <typename StringType>
1264class HasSubstrMatcher {
1265 public:
shiqiane35fdd92008-12-10 05:08:54 +00001266 explicit HasSubstrMatcher(const StringType& substring)
1267 : substring_(substring) {}
1268
jgm38513a82012-11-15 15:50:36 +00001269 // Accepts pointer types, particularly:
1270 // const char*
1271 // char*
1272 // const wchar_t*
1273 // wchar_t*
1274 template <typename CharType>
1275 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001276 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001277 }
1278
jgm38513a82012-11-15 15:50:36 +00001279 // Matches anything that can convert to StringType.
1280 //
1281 // This is a template, not just a plain function with const StringType&,
1282 // because StringPiece has some interfering non-explicit constructors.
1283 template <typename MatcheeStringType>
1284 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001285 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001286 const StringType& s2(s);
1287 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001288 }
1289
1290 // Describes what this matcher matches.
1291 void DescribeTo(::std::ostream* os) const {
1292 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001293 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001294 }
1295
1296 void DescribeNegationTo(::std::ostream* os) const {
1297 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001298 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001299 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001300
shiqiane35fdd92008-12-10 05:08:54 +00001301 private:
1302 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001303
1304 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001305};
1306
1307// Implements the polymorphic StartsWith(substring) matcher, which
1308// can be used as a Matcher<T> as long as T can be converted to a
1309// string.
1310template <typename StringType>
1311class StartsWithMatcher {
1312 public:
shiqiane35fdd92008-12-10 05:08:54 +00001313 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1314 }
1315
jgm38513a82012-11-15 15:50:36 +00001316 // Accepts pointer types, particularly:
1317 // const char*
1318 // char*
1319 // const wchar_t*
1320 // wchar_t*
1321 template <typename CharType>
1322 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001323 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001324 }
1325
jgm38513a82012-11-15 15:50:36 +00001326 // Matches anything that can convert to StringType.
1327 //
1328 // This is a template, not just a plain function with const StringType&,
1329 // because StringPiece has some interfering non-explicit constructors.
1330 template <typename MatcheeStringType>
1331 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001332 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001333 const StringType& s2(s);
1334 return s2.length() >= prefix_.length() &&
1335 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001336 }
1337
1338 void DescribeTo(::std::ostream* os) const {
1339 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001340 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001341 }
1342
1343 void DescribeNegationTo(::std::ostream* os) const {
1344 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001345 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001346 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001347
shiqiane35fdd92008-12-10 05:08:54 +00001348 private:
1349 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001350
1351 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001352};
1353
1354// Implements the polymorphic EndsWith(substring) matcher, which
1355// can be used as a Matcher<T> as long as T can be converted to a
1356// string.
1357template <typename StringType>
1358class EndsWithMatcher {
1359 public:
shiqiane35fdd92008-12-10 05:08:54 +00001360 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1361
jgm38513a82012-11-15 15:50:36 +00001362 // Accepts pointer types, particularly:
1363 // const char*
1364 // char*
1365 // const wchar_t*
1366 // wchar_t*
1367 template <typename CharType>
1368 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001369 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001370 }
1371
jgm38513a82012-11-15 15:50:36 +00001372 // Matches anything that can convert to StringType.
1373 //
1374 // This is a template, not just a plain function with const StringType&,
1375 // because StringPiece has some interfering non-explicit constructors.
1376 template <typename MatcheeStringType>
1377 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001378 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001379 const StringType& s2(s);
1380 return s2.length() >= suffix_.length() &&
1381 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001382 }
1383
1384 void DescribeTo(::std::ostream* os) const {
1385 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001386 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001387 }
1388
1389 void DescribeNegationTo(::std::ostream* os) const {
1390 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001391 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001392 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001393
shiqiane35fdd92008-12-10 05:08:54 +00001394 private:
1395 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001396
1397 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001398};
1399
shiqiane35fdd92008-12-10 05:08:54 +00001400// Implements polymorphic matchers MatchesRegex(regex) and
1401// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1402// T can be converted to a string.
1403class MatchesRegexMatcher {
1404 public:
1405 MatchesRegexMatcher(const RE* regex, bool full_match)
1406 : regex_(regex), full_match_(full_match) {}
1407
jgm38513a82012-11-15 15:50:36 +00001408 // Accepts pointer types, particularly:
1409 // const char*
1410 // char*
1411 // const wchar_t*
1412 // wchar_t*
1413 template <typename CharType>
1414 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001415 return s != NULL && MatchAndExplain(std::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001416 }
1417
Nico Weber09fd5b32017-05-15 17:07:03 -04001418 // Matches anything that can convert to std::string.
jgm38513a82012-11-15 15:50:36 +00001419 //
Nico Weber09fd5b32017-05-15 17:07:03 -04001420 // This is a template, not just a plain function with const std::string&,
Gennadiy Civilb7c56832018-03-22 15:35:37 -04001421 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001422 template <class MatcheeStringType>
1423 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001424 MatchResultListener* /* listener */) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001425 const std::string& s2(s);
jgm38513a82012-11-15 15:50:36 +00001426 return full_match_ ? RE::FullMatch(s2, *regex_) :
1427 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001428 }
1429
1430 void DescribeTo(::std::ostream* os) const {
1431 *os << (full_match_ ? "matches" : "contains")
1432 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001433 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001434 }
1435
1436 void DescribeNegationTo(::std::ostream* os) const {
1437 *os << "doesn't " << (full_match_ ? "match" : "contain")
1438 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001439 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001440 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001441
shiqiane35fdd92008-12-10 05:08:54 +00001442 private:
1443 const internal::linked_ptr<const RE> regex_;
1444 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001445
1446 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001447};
1448
shiqiane35fdd92008-12-10 05:08:54 +00001449// Implements a matcher that compares the two fields of a 2-tuple
1450// using one of the ==, <=, <, etc, operators. The two fields being
1451// compared don't have to have the same type.
1452//
1453// The matcher defined here is polymorphic (for example, Eq() can be
1454// used to match a tuple<int, short>, a tuple<const long&, double>,
1455// etc). Therefore we use a template type conversion operator in the
1456// implementation.
kosak506340a2014-11-17 01:47:54 +00001457template <typename D, typename Op>
1458class PairMatchBase {
1459 public:
1460 template <typename T1, typename T2>
1461 operator Matcher< ::testing::tuple<T1, T2> >() const {
1462 return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >);
1463 }
1464 template <typename T1, typename T2>
1465 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
1466 return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>);
shiqiane35fdd92008-12-10 05:08:54 +00001467 }
1468
kosak506340a2014-11-17 01:47:54 +00001469 private:
1470 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
1471 return os << D::Desc();
1472 }
shiqiane35fdd92008-12-10 05:08:54 +00001473
kosak506340a2014-11-17 01:47:54 +00001474 template <typename Tuple>
1475 class Impl : public MatcherInterface<Tuple> {
1476 public:
1477 virtual bool MatchAndExplain(
1478 Tuple args,
1479 MatchResultListener* /* listener */) const {
1480 return Op()(::testing::get<0>(args), ::testing::get<1>(args));
1481 }
1482 virtual void DescribeTo(::std::ostream* os) const {
1483 *os << "are " << GetDesc;
1484 }
1485 virtual void DescribeNegationTo(::std::ostream* os) const {
1486 *os << "aren't " << GetDesc;
1487 }
1488 };
1489};
1490
1491class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
1492 public:
1493 static const char* Desc() { return "an equal pair"; }
1494};
1495class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
1496 public:
1497 static const char* Desc() { return "an unequal pair"; }
1498};
1499class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
1500 public:
1501 static const char* Desc() { return "a pair where the first < the second"; }
1502};
1503class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
1504 public:
1505 static const char* Desc() { return "a pair where the first > the second"; }
1506};
1507class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
1508 public:
1509 static const char* Desc() { return "a pair where the first <= the second"; }
1510};
1511class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
1512 public:
1513 static const char* Desc() { return "a pair where the first >= the second"; }
1514};
shiqiane35fdd92008-12-10 05:08:54 +00001515
zhanyong.wanc6a41232009-05-13 23:38:40 +00001516// Implements the Not(...) matcher for a particular argument type T.
1517// We do not nest it inside the NotMatcher class template, as that
1518// will prevent different instantiations of NotMatcher from sharing
1519// the same NotMatcherImpl<T> class.
1520template <typename T>
1521class NotMatcherImpl : public MatcherInterface<T> {
1522 public:
1523 explicit NotMatcherImpl(const Matcher<T>& matcher)
1524 : matcher_(matcher) {}
1525
zhanyong.wan82113312010-01-08 21:55:40 +00001526 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1527 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001528 }
1529
1530 virtual void DescribeTo(::std::ostream* os) const {
1531 matcher_.DescribeNegationTo(os);
1532 }
1533
1534 virtual void DescribeNegationTo(::std::ostream* os) const {
1535 matcher_.DescribeTo(os);
1536 }
1537
zhanyong.wanc6a41232009-05-13 23:38:40 +00001538 private:
1539 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001540
1541 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001542};
1543
shiqiane35fdd92008-12-10 05:08:54 +00001544// Implements the Not(m) matcher, which matches a value that doesn't
1545// match matcher m.
1546template <typename InnerMatcher>
1547class NotMatcher {
1548 public:
1549 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1550
1551 // This template type conversion operator allows Not(m) to be used
1552 // to match any type m can match.
1553 template <typename T>
1554 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001555 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001556 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001557
shiqiane35fdd92008-12-10 05:08:54 +00001558 private:
shiqiane35fdd92008-12-10 05:08:54 +00001559 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001560
1561 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001562};
1563
zhanyong.wanc6a41232009-05-13 23:38:40 +00001564// Implements the AllOf(m1, m2) matcher for a particular argument type
1565// T. We do not nest it inside the BothOfMatcher class template, as
1566// that will prevent different instantiations of BothOfMatcher from
1567// sharing the same BothOfMatcherImpl<T> class.
1568template <typename T>
1569class BothOfMatcherImpl : public MatcherInterface<T> {
1570 public:
1571 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1572 : matcher1_(matcher1), matcher2_(matcher2) {}
1573
zhanyong.wanc6a41232009-05-13 23:38:40 +00001574 virtual void DescribeTo(::std::ostream* os) const {
1575 *os << "(";
1576 matcher1_.DescribeTo(os);
1577 *os << ") and (";
1578 matcher2_.DescribeTo(os);
1579 *os << ")";
1580 }
1581
1582 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001583 *os << "(";
1584 matcher1_.DescribeNegationTo(os);
1585 *os << ") or (";
1586 matcher2_.DescribeNegationTo(os);
1587 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001588 }
1589
zhanyong.wan82113312010-01-08 21:55:40 +00001590 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1591 // If either matcher1_ or matcher2_ doesn't match x, we only need
1592 // to explain why one of them fails.
1593 StringMatchResultListener listener1;
1594 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1595 *listener << listener1.str();
1596 return false;
1597 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001598
zhanyong.wan82113312010-01-08 21:55:40 +00001599 StringMatchResultListener listener2;
1600 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1601 *listener << listener2.str();
1602 return false;
1603 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001604
zhanyong.wan82113312010-01-08 21:55:40 +00001605 // Otherwise we need to explain why *both* of them match.
Nico Weber09fd5b32017-05-15 17:07:03 -04001606 const std::string s1 = listener1.str();
1607 const std::string s2 = listener2.str();
zhanyong.wan82113312010-01-08 21:55:40 +00001608
1609 if (s1 == "") {
1610 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001611 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001612 *listener << s1;
1613 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001614 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001615 }
1616 }
zhanyong.wan82113312010-01-08 21:55:40 +00001617 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001618 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001619
zhanyong.wanc6a41232009-05-13 23:38:40 +00001620 private:
1621 const Matcher<T> matcher1_;
1622 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001623
1624 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001625};
1626
zhanyong.wan616180e2013-06-18 18:49:51 +00001627#if GTEST_LANG_CXX11
1628// MatcherList provides mechanisms for storing a variable number of matchers in
1629// a list structure (ListType) and creating a combining matcher from such a
1630// list.
Troy Holsapplec8510502018-02-07 22:06:00 -08001631// The template is defined recursively using the following template parameters:
zhanyong.wan616180e2013-06-18 18:49:51 +00001632// * kSize is the length of the MatcherList.
1633// * Head is the type of the first matcher of the list.
1634// * Tail denotes the types of the remaining matchers of the list.
1635template <int kSize, typename Head, typename... Tail>
1636struct MatcherList {
1637 typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
zhanyong.wan29897032013-06-20 18:59:15 +00001638 typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001639
1640 // BuildList stores variadic type values in a nested pair structure.
1641 // Example:
1642 // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
1643 // the corresponding result of type pair<int, pair<string, float>>.
1644 static ListType BuildList(const Head& matcher, const Tail&... tail) {
1645 return ListType(matcher, MatcherListTail::BuildList(tail...));
1646 }
1647
1648 // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
1649 // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
1650 // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
1651 // constructor taking two Matcher<T>s as input.
1652 template <typename T, template <typename /* T */> class CombiningMatcher>
1653 static Matcher<T> CreateMatcher(const ListType& matchers) {
1654 return Matcher<T>(new CombiningMatcher<T>(
1655 SafeMatcherCast<T>(matchers.first),
1656 MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
1657 matchers.second)));
1658 }
1659};
1660
1661// The following defines the base case for the recursive definition of
1662// MatcherList.
1663template <typename Matcher1, typename Matcher2>
1664struct MatcherList<2, Matcher1, Matcher2> {
zhanyong.wan29897032013-06-20 18:59:15 +00001665 typedef ::std::pair<Matcher1, Matcher2> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001666
1667 static ListType BuildList(const Matcher1& matcher1,
1668 const Matcher2& matcher2) {
zhanyong.wan29897032013-06-20 18:59:15 +00001669 return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
zhanyong.wan616180e2013-06-18 18:49:51 +00001670 }
1671
1672 template <typename T, template <typename /* T */> class CombiningMatcher>
1673 static Matcher<T> CreateMatcher(const ListType& matchers) {
1674 return Matcher<T>(new CombiningMatcher<T>(
1675 SafeMatcherCast<T>(matchers.first),
1676 SafeMatcherCast<T>(matchers.second)));
1677 }
1678};
1679
1680// VariadicMatcher is used for the variadic implementation of
1681// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1682// CombiningMatcher<T> is used to recursively combine the provided matchers
1683// (of type Args...).
1684template <template <typename T> class CombiningMatcher, typename... Args>
1685class VariadicMatcher {
1686 public:
1687 VariadicMatcher(const Args&... matchers) // NOLINT
1688 : matchers_(MatcherListType::BuildList(matchers...)) {}
1689
1690 // This template type conversion operator allows an
1691 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1692 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1693 template <typename T>
1694 operator Matcher<T>() const {
1695 return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
1696 matchers_);
1697 }
1698
1699 private:
1700 typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
1701
1702 const typename MatcherListType::ListType matchers_;
1703
1704 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1705};
1706
1707template <typename... Args>
1708using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
1709
1710#endif // GTEST_LANG_CXX11
1711
shiqiane35fdd92008-12-10 05:08:54 +00001712// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1713// matches a value that matches all of the matchers m_1, ..., and m_n.
1714template <typename Matcher1, typename Matcher2>
1715class BothOfMatcher {
1716 public:
1717 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1718 : matcher1_(matcher1), matcher2_(matcher2) {}
1719
1720 // This template type conversion operator allows a
1721 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1722 // both Matcher1 and Matcher2 can match.
1723 template <typename T>
1724 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001725 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1726 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001727 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001728
shiqiane35fdd92008-12-10 05:08:54 +00001729 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001730 Matcher1 matcher1_;
1731 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001732
1733 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001734};
shiqiane35fdd92008-12-10 05:08:54 +00001735
zhanyong.wanc6a41232009-05-13 23:38:40 +00001736// Implements the AnyOf(m1, m2) matcher for a particular argument type
1737// T. We do not nest it inside the AnyOfMatcher class template, as
1738// that will prevent different instantiations of AnyOfMatcher from
1739// sharing the same EitherOfMatcherImpl<T> class.
1740template <typename T>
1741class EitherOfMatcherImpl : public MatcherInterface<T> {
1742 public:
1743 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1744 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001745
zhanyong.wanc6a41232009-05-13 23:38:40 +00001746 virtual void DescribeTo(::std::ostream* os) const {
1747 *os << "(";
1748 matcher1_.DescribeTo(os);
1749 *os << ") or (";
1750 matcher2_.DescribeTo(os);
1751 *os << ")";
1752 }
shiqiane35fdd92008-12-10 05:08:54 +00001753
zhanyong.wanc6a41232009-05-13 23:38:40 +00001754 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001755 *os << "(";
1756 matcher1_.DescribeNegationTo(os);
1757 *os << ") and (";
1758 matcher2_.DescribeNegationTo(os);
1759 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001760 }
shiqiane35fdd92008-12-10 05:08:54 +00001761
zhanyong.wan82113312010-01-08 21:55:40 +00001762 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1763 // If either matcher1_ or matcher2_ matches x, we just need to
1764 // explain why *one* of them matches.
1765 StringMatchResultListener listener1;
1766 if (matcher1_.MatchAndExplain(x, &listener1)) {
1767 *listener << listener1.str();
1768 return true;
1769 }
1770
1771 StringMatchResultListener listener2;
1772 if (matcher2_.MatchAndExplain(x, &listener2)) {
1773 *listener << listener2.str();
1774 return true;
1775 }
1776
1777 // Otherwise we need to explain why *both* of them fail.
Nico Weber09fd5b32017-05-15 17:07:03 -04001778 const std::string s1 = listener1.str();
1779 const std::string s2 = listener2.str();
zhanyong.wan82113312010-01-08 21:55:40 +00001780
1781 if (s1 == "") {
1782 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001783 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001784 *listener << s1;
1785 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001786 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001787 }
1788 }
zhanyong.wan82113312010-01-08 21:55:40 +00001789 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001790 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001791
zhanyong.wanc6a41232009-05-13 23:38:40 +00001792 private:
1793 const Matcher<T> matcher1_;
1794 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001795
1796 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001797};
1798
zhanyong.wan616180e2013-06-18 18:49:51 +00001799#if GTEST_LANG_CXX11
1800// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1801template <typename... Args>
1802using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
1803
1804#endif // GTEST_LANG_CXX11
1805
shiqiane35fdd92008-12-10 05:08:54 +00001806// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1807// matches a value that matches at least one of the matchers m_1, ...,
1808// and m_n.
1809template <typename Matcher1, typename Matcher2>
1810class EitherOfMatcher {
1811 public:
1812 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1813 : matcher1_(matcher1), matcher2_(matcher2) {}
1814
1815 // This template type conversion operator allows a
1816 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1817 // both Matcher1 and Matcher2 can match.
1818 template <typename T>
1819 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001820 return Matcher<T>(new EitherOfMatcherImpl<T>(
1821 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001822 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001823
shiqiane35fdd92008-12-10 05:08:54 +00001824 private:
shiqiane35fdd92008-12-10 05:08:54 +00001825 Matcher1 matcher1_;
1826 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001827
1828 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001829};
1830
1831// Used for implementing Truly(pred), which turns a predicate into a
1832// matcher.
1833template <typename Predicate>
1834class TrulyMatcher {
1835 public:
1836 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1837
1838 // This method template allows Truly(pred) to be used as a matcher
1839 // for type T where T is the argument type of predicate 'pred'. The
1840 // argument is passed by reference as the predicate may be
1841 // interested in the address of the argument.
1842 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001843 bool MatchAndExplain(T& x, // NOLINT
1844 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001845 // Without the if-statement, MSVC sometimes warns about converting
1846 // a value to bool (warning 4800).
1847 //
1848 // We cannot write 'return !!predicate_(x);' as that doesn't work
1849 // when predicate_(x) returns a class convertible to bool but
1850 // having no operator!().
1851 if (predicate_(x))
1852 return true;
1853 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001854 }
1855
1856 void DescribeTo(::std::ostream* os) const {
1857 *os << "satisfies the given predicate";
1858 }
1859
1860 void DescribeNegationTo(::std::ostream* os) const {
1861 *os << "doesn't satisfy the given predicate";
1862 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001863
shiqiane35fdd92008-12-10 05:08:54 +00001864 private:
1865 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001866
1867 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001868};
1869
1870// Used for implementing Matches(matcher), which turns a matcher into
1871// a predicate.
1872template <typename M>
1873class MatcherAsPredicate {
1874 public:
1875 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1876
1877 // This template operator() allows Matches(m) to be used as a
1878 // predicate on type T where m is a matcher on type T.
1879 //
1880 // The argument x is passed by reference instead of by value, as
1881 // some matcher may be interested in its address (e.g. as in
1882 // Matches(Ref(n))(x)).
1883 template <typename T>
1884 bool operator()(const T& x) const {
1885 // We let matcher_ commit to a particular type here instead of
1886 // when the MatcherAsPredicate object was constructed. This
1887 // allows us to write Matches(m) where m is a polymorphic matcher
1888 // (e.g. Eq(5)).
1889 //
1890 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1891 // compile when matcher_ has type Matcher<const T&>; if we write
1892 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1893 // when matcher_ has type Matcher<T>; if we just write
1894 // matcher_.Matches(x), it won't compile when matcher_ is
1895 // polymorphic, e.g. Eq(5).
1896 //
1897 // MatcherCast<const T&>() is necessary for making the code work
1898 // in all of the above situations.
1899 return MatcherCast<const T&>(matcher_).Matches(x);
1900 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001901
shiqiane35fdd92008-12-10 05:08:54 +00001902 private:
1903 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001904
1905 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001906};
1907
1908// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1909// argument M must be a type that can be converted to a matcher.
1910template <typename M>
1911class PredicateFormatterFromMatcher {
1912 public:
kosak9b1a9442015-04-28 23:06:58 +00001913 explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {}
shiqiane35fdd92008-12-10 05:08:54 +00001914
1915 // This template () operator allows a PredicateFormatterFromMatcher
1916 // object to act as a predicate-formatter suitable for using with
1917 // Google Test's EXPECT_PRED_FORMAT1() macro.
1918 template <typename T>
1919 AssertionResult operator()(const char* value_text, const T& x) const {
1920 // We convert matcher_ to a Matcher<const T&> *now* instead of
1921 // when the PredicateFormatterFromMatcher object was constructed,
1922 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1923 // know which type to instantiate it to until we actually see the
1924 // type of x here.
1925 //
zhanyong.wanf4274522013-04-24 02:49:43 +00001926 // We write SafeMatcherCast<const T&>(matcher_) instead of
shiqiane35fdd92008-12-10 05:08:54 +00001927 // Matcher<const T&>(matcher_), as the latter won't compile when
1928 // matcher_ has type Matcher<T> (e.g. An<int>()).
zhanyong.wanf4274522013-04-24 02:49:43 +00001929 // We don't write MatcherCast<const T&> either, as that allows
1930 // potentially unsafe downcasting of the matcher argument.
1931 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001932 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001933 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001934 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001935
1936 ::std::stringstream ss;
1937 ss << "Value of: " << value_text << "\n"
1938 << "Expected: ";
1939 matcher.DescribeTo(&ss);
1940 ss << "\n Actual: " << listener.str();
1941 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001942 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001943
shiqiane35fdd92008-12-10 05:08:54 +00001944 private:
1945 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001946
1947 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001948};
1949
1950// A helper function for converting a matcher to a predicate-formatter
1951// without the user needing to explicitly write the type. This is
1952// used for implementing ASSERT_THAT() and EXPECT_THAT().
kosak9b1a9442015-04-28 23:06:58 +00001953// Implementation detail: 'matcher' is received by-value to force decaying.
shiqiane35fdd92008-12-10 05:08:54 +00001954template <typename M>
1955inline PredicateFormatterFromMatcher<M>
kosak9b1a9442015-04-28 23:06:58 +00001956MakePredicateFormatterFromMatcher(M matcher) {
1957 return PredicateFormatterFromMatcher<M>(internal::move(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00001958}
1959
zhanyong.wan616180e2013-06-18 18:49:51 +00001960// Implements the polymorphic floating point equality matcher, which matches
1961// two float values using ULP-based approximation or, optionally, a
1962// user-specified epsilon. The template is meant to be instantiated with
1963// FloatType being either float or double.
shiqiane35fdd92008-12-10 05:08:54 +00001964template <typename FloatType>
1965class FloatingEqMatcher {
1966 public:
1967 // Constructor for FloatingEqMatcher.
kosak6b817802015-01-08 02:38:14 +00001968 // The matcher's input will be compared with expected. The matcher treats two
shiqiane35fdd92008-12-10 05:08:54 +00001969 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
zhanyong.wan616180e2013-06-18 18:49:51 +00001970 // equality comparisons between NANs will always return false. We specify a
1971 // negative max_abs_error_ term to indicate that ULP-based approximation will
1972 // be used for comparison.
kosak6b817802015-01-08 02:38:14 +00001973 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
1974 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001975 }
1976
1977 // Constructor that supports a user-specified max_abs_error that will be used
1978 // for comparison instead of ULP-based approximation. The max absolute
1979 // should be non-negative.
kosak6b817802015-01-08 02:38:14 +00001980 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
1981 FloatType max_abs_error)
1982 : expected_(expected),
1983 nan_eq_nan_(nan_eq_nan),
1984 max_abs_error_(max_abs_error) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001985 GTEST_CHECK_(max_abs_error >= 0)
1986 << ", where max_abs_error is" << max_abs_error;
1987 }
shiqiane35fdd92008-12-10 05:08:54 +00001988
1989 // Implements floating point equality matcher as a Matcher<T>.
1990 template <typename T>
1991 class Impl : public MatcherInterface<T> {
1992 public:
kosak6b817802015-01-08 02:38:14 +00001993 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
1994 : expected_(expected),
1995 nan_eq_nan_(nan_eq_nan),
1996 max_abs_error_(max_abs_error) {}
shiqiane35fdd92008-12-10 05:08:54 +00001997
zhanyong.wan82113312010-01-08 21:55:40 +00001998 virtual bool MatchAndExplain(T value,
kosak6b817802015-01-08 02:38:14 +00001999 MatchResultListener* listener) const {
2000 const FloatingPoint<FloatType> actual(value), expected(expected_);
shiqiane35fdd92008-12-10 05:08:54 +00002001
2002 // Compares NaNs first, if nan_eq_nan_ is true.
kosak6b817802015-01-08 02:38:14 +00002003 if (actual.is_nan() || expected.is_nan()) {
2004 if (actual.is_nan() && expected.is_nan()) {
zhanyong.wan616180e2013-06-18 18:49:51 +00002005 return nan_eq_nan_;
2006 }
2007 // One is nan; the other is not nan.
2008 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002009 }
zhanyong.wan616180e2013-06-18 18:49:51 +00002010 if (HasMaxAbsError()) {
2011 // We perform an equality check so that inf will match inf, regardless
kosak6b817802015-01-08 02:38:14 +00002012 // of error bounds. If the result of value - expected_ would result in
zhanyong.wan616180e2013-06-18 18:49:51 +00002013 // overflow or if either value is inf, the default result is infinity,
2014 // which should only match if max_abs_error_ is also infinity.
kosak6b817802015-01-08 02:38:14 +00002015 if (value == expected_) {
2016 return true;
2017 }
2018
2019 const FloatType diff = value - expected_;
2020 if (fabs(diff) <= max_abs_error_) {
2021 return true;
2022 }
2023
2024 if (listener->IsInterested()) {
2025 *listener << "which is " << diff << " from " << expected_;
2026 }
2027 return false;
zhanyong.wan616180e2013-06-18 18:49:51 +00002028 } else {
kosak6b817802015-01-08 02:38:14 +00002029 return actual.AlmostEquals(expected);
zhanyong.wan616180e2013-06-18 18:49:51 +00002030 }
shiqiane35fdd92008-12-10 05:08:54 +00002031 }
2032
2033 virtual void DescribeTo(::std::ostream* os) const {
2034 // os->precision() returns the previously set precision, which we
2035 // store to restore the ostream to its original configuration
2036 // after outputting.
2037 const ::std::streamsize old_precision = os->precision(
2038 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00002039 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00002040 if (nan_eq_nan_) {
2041 *os << "is NaN";
2042 } else {
2043 *os << "never matches";
2044 }
2045 } else {
kosak6b817802015-01-08 02:38:14 +00002046 *os << "is approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002047 if (HasMaxAbsError()) {
2048 *os << " (absolute error <= " << max_abs_error_ << ")";
2049 }
shiqiane35fdd92008-12-10 05:08:54 +00002050 }
2051 os->precision(old_precision);
2052 }
2053
2054 virtual void DescribeNegationTo(::std::ostream* os) const {
2055 // As before, get original precision.
2056 const ::std::streamsize old_precision = os->precision(
2057 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00002058 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00002059 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002060 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00002061 } else {
2062 *os << "is anything";
2063 }
2064 } else {
kosak6b817802015-01-08 02:38:14 +00002065 *os << "isn't approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002066 if (HasMaxAbsError()) {
2067 *os << " (absolute error > " << max_abs_error_ << ")";
2068 }
shiqiane35fdd92008-12-10 05:08:54 +00002069 }
2070 // Restore original precision.
2071 os->precision(old_precision);
2072 }
2073
2074 private:
zhanyong.wan616180e2013-06-18 18:49:51 +00002075 bool HasMaxAbsError() const {
2076 return max_abs_error_ >= 0;
2077 }
2078
kosak6b817802015-01-08 02:38:14 +00002079 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002080 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002081 // max_abs_error will be used for value comparison when >= 0.
2082 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002083
2084 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002085 };
2086
kosak6b817802015-01-08 02:38:14 +00002087 // The following 3 type conversion operators allow FloatEq(expected) and
2088 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
shiqiane35fdd92008-12-10 05:08:54 +00002089 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
2090 // (While Google's C++ coding style doesn't allow arguments passed
2091 // by non-const reference, we may see them in code not conforming to
2092 // the style. Therefore Google Mock needs to support them.)
2093 operator Matcher<FloatType>() const {
kosak6b817802015-01-08 02:38:14 +00002094 return MakeMatcher(
2095 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002096 }
2097
2098 operator Matcher<const FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00002099 return MakeMatcher(
kosak6b817802015-01-08 02:38:14 +00002100 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002101 }
2102
2103 operator Matcher<FloatType&>() const {
kosak6b817802015-01-08 02:38:14 +00002104 return MakeMatcher(
2105 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002106 }
jgm79a367e2012-04-10 16:02:11 +00002107
shiqiane35fdd92008-12-10 05:08:54 +00002108 private:
kosak6b817802015-01-08 02:38:14 +00002109 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002110 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002111 // max_abs_error will be used for value comparison when >= 0.
2112 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002113
2114 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002115};
2116
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002117// A 2-tuple ("binary") wrapper around FloatingEqMatcher:
2118// FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false)
2119// against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e)
2120// against y. The former implements "Eq", the latter "Near". At present, there
2121// is no version that compares NaNs as equal.
2122template <typename FloatType>
2123class FloatingEq2Matcher {
2124 public:
2125 FloatingEq2Matcher() : FloatingEq2Matcher(-1, false) {}
2126
2127 explicit FloatingEq2Matcher(bool nan_eq_nan)
2128 : FloatingEq2Matcher(-1, nan_eq_nan) {}
2129
2130 explicit FloatingEq2Matcher(FloatType max_abs_error)
2131 : FloatingEq2Matcher(max_abs_error, false) {}
2132
2133 FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan)
2134 : max_abs_error_(max_abs_error),
2135 nan_eq_nan_(nan_eq_nan) {}
2136
2137 template <typename T1, typename T2>
2138 operator Matcher< ::testing::tuple<T1, T2> >() const {
2139 return MakeMatcher(
2140 new Impl< ::testing::tuple<T1, T2> >(max_abs_error_, nan_eq_nan_));
2141 }
2142 template <typename T1, typename T2>
2143 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
2144 return MakeMatcher(
2145 new Impl<const ::testing::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_));
2146 }
2147
2148 private:
2149 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
2150 return os << "an almost-equal pair";
2151 }
2152
2153 template <typename Tuple>
2154 class Impl : public MatcherInterface<Tuple> {
2155 public:
2156 Impl(FloatType max_abs_error, bool nan_eq_nan) :
2157 max_abs_error_(max_abs_error),
2158 nan_eq_nan_(nan_eq_nan) {}
2159
2160 virtual bool MatchAndExplain(Tuple args,
2161 MatchResultListener* listener) const {
2162 if (max_abs_error_ == -1) {
2163 FloatingEqMatcher<FloatType> fm(::testing::get<0>(args), nan_eq_nan_);
2164 return static_cast<Matcher<FloatType> >(fm).MatchAndExplain(
2165 ::testing::get<1>(args), listener);
2166 } else {
2167 FloatingEqMatcher<FloatType> fm(::testing::get<0>(args), nan_eq_nan_,
2168 max_abs_error_);
2169 return static_cast<Matcher<FloatType> >(fm).MatchAndExplain(
2170 ::testing::get<1>(args), listener);
2171 }
2172 }
2173 virtual void DescribeTo(::std::ostream* os) const {
2174 *os << "are " << GetDesc;
2175 }
2176 virtual void DescribeNegationTo(::std::ostream* os) const {
2177 *os << "aren't " << GetDesc;
2178 }
2179
2180 private:
2181 FloatType max_abs_error_;
2182 const bool nan_eq_nan_;
2183 };
2184
2185 FloatType max_abs_error_;
2186 const bool nan_eq_nan_;
2187};
2188
shiqiane35fdd92008-12-10 05:08:54 +00002189// Implements the Pointee(m) matcher for matching a pointer whose
2190// pointee matches matcher m. The pointer can be either raw or smart.
2191template <typename InnerMatcher>
2192class PointeeMatcher {
2193 public:
2194 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
2195
2196 // This type conversion operator template allows Pointee(m) to be
2197 // used as a matcher for any pointer type whose pointee type is
2198 // compatible with the inner matcher, where type Pointer can be
2199 // either a raw pointer or a smart pointer.
2200 //
2201 // The reason we do this instead of relying on
2202 // MakePolymorphicMatcher() is that the latter is not flexible
2203 // enough for implementing the DescribeTo() method of Pointee().
2204 template <typename Pointer>
2205 operator Matcher<Pointer>() const {
2206 return MakeMatcher(new Impl<Pointer>(matcher_));
2207 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002208
shiqiane35fdd92008-12-10 05:08:54 +00002209 private:
2210 // The monomorphic implementation that works for a particular pointer type.
2211 template <typename Pointer>
2212 class Impl : public MatcherInterface<Pointer> {
2213 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00002214 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
2215 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00002216
2217 explicit Impl(const InnerMatcher& matcher)
2218 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
2219
shiqiane35fdd92008-12-10 05:08:54 +00002220 virtual void DescribeTo(::std::ostream* os) const {
2221 *os << "points to a value that ";
2222 matcher_.DescribeTo(os);
2223 }
2224
2225 virtual void DescribeNegationTo(::std::ostream* os) const {
2226 *os << "does not point to a value that ";
2227 matcher_.DescribeTo(os);
2228 }
2229
zhanyong.wan82113312010-01-08 21:55:40 +00002230 virtual bool MatchAndExplain(Pointer pointer,
2231 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00002232 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00002233 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002234
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002235 *listener << "which points to ";
2236 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002237 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002238
shiqiane35fdd92008-12-10 05:08:54 +00002239 private:
2240 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002241
2242 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002243 };
2244
2245 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002246
2247 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002248};
2249
billydonahue1f5fdea2014-05-19 17:54:51 +00002250// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2251// reference that matches inner_matcher when dynamic_cast<T> is applied.
2252// The result of dynamic_cast<To> is forwarded to the inner matcher.
2253// If To is a pointer and the cast fails, the inner matcher will receive NULL.
2254// If To is a reference and the cast fails, this matcher returns false
2255// immediately.
2256template <typename To>
2257class WhenDynamicCastToMatcherBase {
2258 public:
2259 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2260 : matcher_(matcher) {}
2261
2262 void DescribeTo(::std::ostream* os) const {
2263 GetCastTypeDescription(os);
2264 matcher_.DescribeTo(os);
2265 }
2266
2267 void DescribeNegationTo(::std::ostream* os) const {
2268 GetCastTypeDescription(os);
2269 matcher_.DescribeNegationTo(os);
2270 }
2271
2272 protected:
2273 const Matcher<To> matcher_;
2274
Nico Weber09fd5b32017-05-15 17:07:03 -04002275 static std::string GetToName() {
billydonahue1f5fdea2014-05-19 17:54:51 +00002276#if GTEST_HAS_RTTI
2277 return GetTypeName<To>();
2278#else // GTEST_HAS_RTTI
2279 return "the target type";
2280#endif // GTEST_HAS_RTTI
2281 }
2282
2283 private:
2284 static void GetCastTypeDescription(::std::ostream* os) {
2285 *os << "when dynamic_cast to " << GetToName() << ", ";
2286 }
2287
2288 GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2289};
2290
2291// Primary template.
2292// To is a pointer. Cast and forward the result.
2293template <typename To>
2294class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2295 public:
2296 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2297 : WhenDynamicCastToMatcherBase<To>(matcher) {}
2298
2299 template <typename From>
2300 bool MatchAndExplain(From from, MatchResultListener* listener) const {
2301 // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail?
2302 To to = dynamic_cast<To>(from);
2303 return MatchPrintAndExplain(to, this->matcher_, listener);
2304 }
2305};
2306
2307// Specialize for references.
2308// In this case we return false if the dynamic_cast fails.
2309template <typename To>
2310class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2311 public:
2312 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2313 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2314
2315 template <typename From>
2316 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2317 // We don't want an std::bad_cast here, so do the cast with pointers.
2318 To* to = dynamic_cast<To*>(&from);
2319 if (to == NULL) {
2320 *listener << "which cannot be dynamic_cast to " << this->GetToName();
2321 return false;
2322 }
2323 return MatchPrintAndExplain(*to, this->matcher_, listener);
2324 }
2325};
2326
shiqiane35fdd92008-12-10 05:08:54 +00002327// Implements the Field() matcher for matching a field (i.e. member
2328// variable) of an object.
2329template <typename Class, typename FieldType>
2330class FieldMatcher {
2331 public:
2332 FieldMatcher(FieldType Class::*field,
2333 const Matcher<const FieldType&>& matcher)
2334 : field_(field), matcher_(matcher) {}
2335
shiqiane35fdd92008-12-10 05:08:54 +00002336 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002337 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002338 matcher_.DescribeTo(os);
2339 }
2340
2341 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002342 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002343 matcher_.DescribeNegationTo(os);
2344 }
2345
zhanyong.wandb22c222010-01-28 21:52:29 +00002346 template <typename T>
2347 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2348 return MatchAndExplainImpl(
2349 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002350 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002351 value, listener);
2352 }
2353
2354 private:
2355 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002356 // Symbian's C++ compiler choose which overload to use. Its type is
2357 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002358 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2359 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002360 *listener << "whose given field is ";
2361 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002362 }
2363
zhanyong.wandb22c222010-01-28 21:52:29 +00002364 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2365 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002366 if (p == NULL)
2367 return false;
2368
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002369 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002370 // Since *p has a field, it must be a class/struct/union type and
2371 // thus cannot be a pointer. Therefore we pass false_type() as
2372 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002373 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002374 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002375
shiqiane35fdd92008-12-10 05:08:54 +00002376 const FieldType Class::*field_;
2377 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002378
2379 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002380};
2381
shiqiane35fdd92008-12-10 05:08:54 +00002382// Implements the Property() matcher for matching a property
2383// (i.e. return value of a getter method) of an object.
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002384//
2385// Property is a const-qualified member function of Class returning
2386// PropertyType.
2387template <typename Class, typename PropertyType, typename Property>
shiqiane35fdd92008-12-10 05:08:54 +00002388class PropertyMatcher {
2389 public:
2390 // The property may have a reference type, so 'const PropertyType&'
2391 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00002392 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00002393 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00002394 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00002395
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002396 PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)
shiqiane35fdd92008-12-10 05:08:54 +00002397 : property_(property), matcher_(matcher) {}
2398
shiqiane35fdd92008-12-10 05:08:54 +00002399 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002400 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002401 matcher_.DescribeTo(os);
2402 }
2403
2404 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002405 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002406 matcher_.DescribeNegationTo(os);
2407 }
2408
zhanyong.wandb22c222010-01-28 21:52:29 +00002409 template <typename T>
2410 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2411 return MatchAndExplainImpl(
2412 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002413 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002414 value, listener);
2415 }
2416
2417 private:
2418 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002419 // Symbian's C++ compiler choose which overload to use. Its type is
2420 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002421 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2422 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002423 *listener << "whose given property is ";
2424 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2425 // which takes a non-const reference as argument.
kosak02d64792015-02-14 02:22:21 +00002426#if defined(_PREFAST_ ) && _MSC_VER == 1800
2427 // Workaround bug in VC++ 2013's /analyze parser.
2428 // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move
2429 posix::Abort(); // To make sure it is never run.
2430 return false;
2431#else
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002432 RefToConstProperty result = (obj.*property_)();
2433 return MatchPrintAndExplain(result, matcher_, listener);
kosak02d64792015-02-14 02:22:21 +00002434#endif
shiqiane35fdd92008-12-10 05:08:54 +00002435 }
2436
zhanyong.wandb22c222010-01-28 21:52:29 +00002437 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2438 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002439 if (p == NULL)
2440 return false;
2441
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002442 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002443 // Since *p has a property method, it must be a class/struct/union
2444 // type and thus cannot be a pointer. Therefore we pass
2445 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002446 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002447 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002448
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002449 Property property_;
shiqiane35fdd92008-12-10 05:08:54 +00002450 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002451
2452 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002453};
2454
shiqiane35fdd92008-12-10 05:08:54 +00002455// Type traits specifying various features of different functors for ResultOf.
2456// The default template specifies features for functor objects.
2457// Functor classes have to typedef argument_type and result_type
2458// to be compatible with ResultOf.
2459template <typename Functor>
2460struct CallableTraits {
2461 typedef typename Functor::result_type ResultType;
2462 typedef Functor StorageType;
2463
zhanyong.wan32de5f52009-12-23 00:13:23 +00002464 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00002465 template <typename T>
2466 static ResultType Invoke(Functor f, T arg) { return f(arg); }
2467};
2468
2469// Specialization for function pointers.
2470template <typename ArgType, typename ResType>
2471struct CallableTraits<ResType(*)(ArgType)> {
2472 typedef ResType ResultType;
2473 typedef ResType(*StorageType)(ArgType);
2474
2475 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002476 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00002477 << "NULL function pointer is passed into ResultOf().";
2478 }
2479 template <typename T>
2480 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2481 return (*f)(arg);
2482 }
2483};
2484
2485// Implements the ResultOf() matcher for matching a return value of a
2486// unary function of an object.
2487template <typename Callable>
2488class ResultOfMatcher {
2489 public:
2490 typedef typename CallableTraits<Callable>::ResultType ResultType;
2491
2492 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
2493 : callable_(callable), matcher_(matcher) {
2494 CallableTraits<Callable>::CheckIsValid(callable_);
2495 }
2496
2497 template <typename T>
2498 operator Matcher<T>() const {
2499 return Matcher<T>(new Impl<T>(callable_, matcher_));
2500 }
2501
2502 private:
2503 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2504
2505 template <typename T>
2506 class Impl : public MatcherInterface<T> {
2507 public:
2508 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
2509 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00002510
2511 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002512 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002513 matcher_.DescribeTo(os);
2514 }
2515
2516 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002517 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002518 matcher_.DescribeNegationTo(os);
2519 }
2520
zhanyong.wan82113312010-01-08 21:55:40 +00002521 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002522 *listener << "which is mapped by the given callable to ";
2523 // Cannot pass the return value (for example, int) to
2524 // MatchPrintAndExplain, which takes a non-const reference as argument.
2525 ResultType result =
2526 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2527 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002528 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002529
shiqiane35fdd92008-12-10 05:08:54 +00002530 private:
2531 // Functors often define operator() as non-const method even though
Troy Holsapplec8510502018-02-07 22:06:00 -08002532 // they are actually stateless. But we need to use them even when
shiqiane35fdd92008-12-10 05:08:54 +00002533 // 'this' is a const pointer. It's the user's responsibility not to
2534 // use stateful callables with ResultOf(), which does't guarantee
2535 // how many times the callable will be invoked.
2536 mutable CallableStorageType callable_;
2537 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002538
2539 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002540 }; // class Impl
2541
2542 const CallableStorageType callable_;
2543 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002544
2545 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002546};
2547
zhanyong.wana31d9ce2013-03-01 01:50:17 +00002548// Implements a matcher that checks the size of an STL-style container.
2549template <typename SizeMatcher>
2550class SizeIsMatcher {
2551 public:
2552 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2553 : size_matcher_(size_matcher) {
2554 }
2555
2556 template <typename Container>
2557 operator Matcher<Container>() const {
2558 return MakeMatcher(new Impl<Container>(size_matcher_));
2559 }
2560
2561 template <typename Container>
2562 class Impl : public MatcherInterface<Container> {
2563 public:
2564 typedef internal::StlContainerView<
2565 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2566 typedef typename ContainerView::type::size_type SizeType;
2567 explicit Impl(const SizeMatcher& size_matcher)
2568 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2569
2570 virtual void DescribeTo(::std::ostream* os) const {
2571 *os << "size ";
2572 size_matcher_.DescribeTo(os);
2573 }
2574 virtual void DescribeNegationTo(::std::ostream* os) const {
2575 *os << "size ";
2576 size_matcher_.DescribeNegationTo(os);
2577 }
2578
2579 virtual bool MatchAndExplain(Container container,
2580 MatchResultListener* listener) const {
2581 SizeType size = container.size();
2582 StringMatchResultListener size_listener;
2583 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2584 *listener
2585 << "whose size " << size << (result ? " matches" : " doesn't match");
2586 PrintIfNotEmpty(size_listener.str(), listener->stream());
2587 return result;
2588 }
2589
2590 private:
2591 const Matcher<SizeType> size_matcher_;
2592 GTEST_DISALLOW_ASSIGN_(Impl);
2593 };
2594
2595 private:
2596 const SizeMatcher size_matcher_;
2597 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2598};
2599
kosakb6a34882014-03-12 21:06:46 +00002600// Implements a matcher that checks the begin()..end() distance of an STL-style
2601// container.
2602template <typename DistanceMatcher>
2603class BeginEndDistanceIsMatcher {
2604 public:
2605 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2606 : distance_matcher_(distance_matcher) {}
2607
2608 template <typename Container>
2609 operator Matcher<Container>() const {
2610 return MakeMatcher(new Impl<Container>(distance_matcher_));
2611 }
2612
2613 template <typename Container>
2614 class Impl : public MatcherInterface<Container> {
2615 public:
2616 typedef internal::StlContainerView<
2617 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2618 typedef typename std::iterator_traits<
2619 typename ContainerView::type::const_iterator>::difference_type
2620 DistanceType;
2621 explicit Impl(const DistanceMatcher& distance_matcher)
2622 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2623
2624 virtual void DescribeTo(::std::ostream* os) const {
2625 *os << "distance between begin() and end() ";
2626 distance_matcher_.DescribeTo(os);
2627 }
2628 virtual void DescribeNegationTo(::std::ostream* os) const {
2629 *os << "distance between begin() and end() ";
2630 distance_matcher_.DescribeNegationTo(os);
2631 }
2632
2633 virtual bool MatchAndExplain(Container container,
2634 MatchResultListener* listener) const {
kosak5b9cbbb2014-11-17 00:28:55 +00002635#if GTEST_HAS_STD_BEGIN_AND_END_
kosakb6a34882014-03-12 21:06:46 +00002636 using std::begin;
2637 using std::end;
2638 DistanceType distance = std::distance(begin(container), end(container));
2639#else
2640 DistanceType distance = std::distance(container.begin(), container.end());
2641#endif
2642 StringMatchResultListener distance_listener;
2643 const bool result =
2644 distance_matcher_.MatchAndExplain(distance, &distance_listener);
2645 *listener << "whose distance between begin() and end() " << distance
2646 << (result ? " matches" : " doesn't match");
2647 PrintIfNotEmpty(distance_listener.str(), listener->stream());
2648 return result;
2649 }
2650
2651 private:
2652 const Matcher<DistanceType> distance_matcher_;
2653 GTEST_DISALLOW_ASSIGN_(Impl);
2654 };
2655
2656 private:
2657 const DistanceMatcher distance_matcher_;
2658 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2659};
2660
zhanyong.wan6a896b52009-01-16 01:13:50 +00002661// Implements an equality matcher for any STL-style container whose elements
2662// support ==. This matcher is like Eq(), but its failure explanations provide
2663// more detailed information that is useful when the container is used as a set.
2664// The failure message reports elements that are in one of the operands but not
2665// the other. The failure messages do not report duplicate or out-of-order
2666// elements in the containers (which don't properly matter to sets, but can
2667// occur if the containers are vectors or lists, for example).
2668//
2669// Uses the container's const_iterator, value_type, operator ==,
2670// begin(), and end().
2671template <typename Container>
2672class ContainerEqMatcher {
2673 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002674 typedef internal::StlContainerView<Container> View;
2675 typedef typename View::type StlContainer;
2676 typedef typename View::const_reference StlContainerReference;
2677
kosak6b817802015-01-08 02:38:14 +00002678 // We make a copy of expected in case the elements in it are modified
zhanyong.wanb8243162009-06-04 05:48:20 +00002679 // after this matcher is created.
kosak6b817802015-01-08 02:38:14 +00002680 explicit ContainerEqMatcher(const Container& expected)
2681 : expected_(View::Copy(expected)) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002682 // Makes sure the user doesn't instantiate this class template
2683 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002684 (void)testing::StaticAssertTypeEq<Container,
2685 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002686 }
2687
zhanyong.wan6a896b52009-01-16 01:13:50 +00002688 void DescribeTo(::std::ostream* os) const {
2689 *os << "equals ";
kosak6b817802015-01-08 02:38:14 +00002690 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002691 }
2692 void DescribeNegationTo(::std::ostream* os) const {
2693 *os << "does not equal ";
kosak6b817802015-01-08 02:38:14 +00002694 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002695 }
2696
zhanyong.wanb8243162009-06-04 05:48:20 +00002697 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002698 bool MatchAndExplain(const LhsContainer& lhs,
2699 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002700 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002701 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002702 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002703 LhsView;
2704 typedef typename LhsView::type LhsStlContainer;
2705 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
kosak6b817802015-01-08 02:38:14 +00002706 if (lhs_stl_container == expected_)
zhanyong.wane122e452010-01-12 09:03:52 +00002707 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002708
zhanyong.wane122e452010-01-12 09:03:52 +00002709 ::std::ostream* const os = listener->stream();
2710 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002711 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002712 bool printed_header = false;
2713 for (typename LhsStlContainer::const_iterator it =
2714 lhs_stl_container.begin();
2715 it != lhs_stl_container.end(); ++it) {
kosak6b817802015-01-08 02:38:14 +00002716 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
2717 expected_.end()) {
zhanyong.wane122e452010-01-12 09:03:52 +00002718 if (printed_header) {
2719 *os << ", ";
2720 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002721 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002722 printed_header = true;
2723 }
vladloseve2e8ba42010-05-13 18:16:03 +00002724 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002725 }
zhanyong.wane122e452010-01-12 09:03:52 +00002726 }
2727
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002728 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002729 bool printed_header2 = false;
kosak6b817802015-01-08 02:38:14 +00002730 for (typename StlContainer::const_iterator it = expected_.begin();
2731 it != expected_.end(); ++it) {
zhanyong.wane122e452010-01-12 09:03:52 +00002732 if (internal::ArrayAwareFind(
2733 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2734 lhs_stl_container.end()) {
2735 if (printed_header2) {
2736 *os << ", ";
2737 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002738 *os << (printed_header ? ",\nand" : "which")
2739 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002740 printed_header2 = true;
2741 }
vladloseve2e8ba42010-05-13 18:16:03 +00002742 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002743 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002744 }
2745 }
2746
zhanyong.wane122e452010-01-12 09:03:52 +00002747 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002748 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002749
zhanyong.wan6a896b52009-01-16 01:13:50 +00002750 private:
kosak6b817802015-01-08 02:38:14 +00002751 const StlContainer expected_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002752
2753 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002754};
2755
zhanyong.wan898725c2011-09-16 16:45:39 +00002756// A comparator functor that uses the < operator to compare two values.
2757struct LessComparator {
2758 template <typename T, typename U>
2759 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2760};
2761
2762// Implements WhenSortedBy(comparator, container_matcher).
2763template <typename Comparator, typename ContainerMatcher>
2764class WhenSortedByMatcher {
2765 public:
2766 WhenSortedByMatcher(const Comparator& comparator,
2767 const ContainerMatcher& matcher)
2768 : comparator_(comparator), matcher_(matcher) {}
2769
2770 template <typename LhsContainer>
2771 operator Matcher<LhsContainer>() const {
2772 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2773 }
2774
2775 template <typename LhsContainer>
2776 class Impl : public MatcherInterface<LhsContainer> {
2777 public:
2778 typedef internal::StlContainerView<
2779 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2780 typedef typename LhsView::type LhsStlContainer;
2781 typedef typename LhsView::const_reference LhsStlContainerReference;
zhanyong.wana9a59e02013-03-27 16:14:55 +00002782 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2783 // so that we can match associative containers.
2784 typedef typename RemoveConstFromKey<
2785 typename LhsStlContainer::value_type>::type LhsValue;
zhanyong.wan898725c2011-09-16 16:45:39 +00002786
2787 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2788 : comparator_(comparator), matcher_(matcher) {}
2789
2790 virtual void DescribeTo(::std::ostream* os) const {
2791 *os << "(when sorted) ";
2792 matcher_.DescribeTo(os);
2793 }
2794
2795 virtual void DescribeNegationTo(::std::ostream* os) const {
2796 *os << "(when sorted) ";
2797 matcher_.DescribeNegationTo(os);
2798 }
2799
2800 virtual bool MatchAndExplain(LhsContainer lhs,
2801 MatchResultListener* listener) const {
2802 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wanfb25d532013-07-28 08:24:00 +00002803 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2804 lhs_stl_container.end());
2805 ::std::sort(
2806 sorted_container.begin(), sorted_container.end(), comparator_);
zhanyong.wan898725c2011-09-16 16:45:39 +00002807
2808 if (!listener->IsInterested()) {
2809 // If the listener is not interested, we do not need to
2810 // construct the inner explanation.
2811 return matcher_.Matches(sorted_container);
2812 }
2813
2814 *listener << "which is ";
2815 UniversalPrint(sorted_container, listener->stream());
2816 *listener << " when sorted";
2817
2818 StringMatchResultListener inner_listener;
2819 const bool match = matcher_.MatchAndExplain(sorted_container,
2820 &inner_listener);
2821 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2822 return match;
2823 }
2824
2825 private:
2826 const Comparator comparator_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00002827 const Matcher<const ::std::vector<LhsValue>&> matcher_;
zhanyong.wan898725c2011-09-16 16:45:39 +00002828
2829 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2830 };
2831
2832 private:
2833 const Comparator comparator_;
2834 const ContainerMatcher matcher_;
2835
2836 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2837};
2838
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002839// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2840// must be able to be safely cast to Matcher<tuple<const T1&, const
2841// T2&> >, where T1 and T2 are the types of elements in the LHS
2842// container and the RHS container respectively.
2843template <typename TupleMatcher, typename RhsContainer>
2844class PointwiseMatcher {
2845 public:
2846 typedef internal::StlContainerView<RhsContainer> RhsView;
2847 typedef typename RhsView::type RhsStlContainer;
2848 typedef typename RhsStlContainer::value_type RhsValue;
2849
2850 // Like ContainerEq, we make a copy of rhs in case the elements in
2851 // it are modified after this matcher is created.
2852 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2853 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2854 // Makes sure the user doesn't instantiate this class template
2855 // with a const or reference type.
2856 (void)testing::StaticAssertTypeEq<RhsContainer,
2857 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2858 }
2859
2860 template <typename LhsContainer>
2861 operator Matcher<LhsContainer>() const {
2862 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2863 }
2864
2865 template <typename LhsContainer>
2866 class Impl : public MatcherInterface<LhsContainer> {
2867 public:
2868 typedef internal::StlContainerView<
2869 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2870 typedef typename LhsView::type LhsStlContainer;
2871 typedef typename LhsView::const_reference LhsStlContainerReference;
2872 typedef typename LhsStlContainer::value_type LhsValue;
2873 // We pass the LHS value and the RHS value to the inner matcher by
2874 // reference, as they may be expensive to copy. We must use tuple
2875 // instead of pair here, as a pair cannot hold references (C++ 98,
2876 // 20.2.2 [lib.pairs]).
kosakbd018832014-04-02 20:30:00 +00002877 typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002878
2879 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2880 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2881 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2882 rhs_(rhs) {}
2883
2884 virtual void DescribeTo(::std::ostream* os) const {
2885 *os << "contains " << rhs_.size()
2886 << " values, where each value and its corresponding value in ";
2887 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2888 *os << " ";
2889 mono_tuple_matcher_.DescribeTo(os);
2890 }
2891 virtual void DescribeNegationTo(::std::ostream* os) const {
2892 *os << "doesn't contain exactly " << rhs_.size()
2893 << " values, or contains a value x at some index i"
2894 << " where x and the i-th value of ";
2895 UniversalPrint(rhs_, os);
2896 *os << " ";
2897 mono_tuple_matcher_.DescribeNegationTo(os);
2898 }
2899
2900 virtual bool MatchAndExplain(LhsContainer lhs,
2901 MatchResultListener* listener) const {
2902 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2903 const size_t actual_size = lhs_stl_container.size();
2904 if (actual_size != rhs_.size()) {
2905 *listener << "which contains " << actual_size << " values";
2906 return false;
2907 }
2908
2909 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2910 typename RhsStlContainer::const_iterator right = rhs_.begin();
2911 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2912 const InnerMatcherArg value_pair(*left, *right);
2913
2914 if (listener->IsInterested()) {
2915 StringMatchResultListener inner_listener;
2916 if (!mono_tuple_matcher_.MatchAndExplain(
2917 value_pair, &inner_listener)) {
2918 *listener << "where the value pair (";
2919 UniversalPrint(*left, listener->stream());
2920 *listener << ", ";
2921 UniversalPrint(*right, listener->stream());
2922 *listener << ") at index #" << i << " don't match";
2923 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2924 return false;
2925 }
2926 } else {
2927 if (!mono_tuple_matcher_.Matches(value_pair))
2928 return false;
2929 }
2930 }
2931
2932 return true;
2933 }
2934
2935 private:
2936 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2937 const RhsStlContainer rhs_;
2938
2939 GTEST_DISALLOW_ASSIGN_(Impl);
2940 };
2941
2942 private:
2943 const TupleMatcher tuple_matcher_;
2944 const RhsStlContainer rhs_;
2945
2946 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2947};
2948
zhanyong.wan33605ba2010-04-22 23:37:47 +00002949// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002950template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002951class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002952 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002953 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002954 typedef StlContainerView<RawContainer> View;
2955 typedef typename View::type StlContainer;
2956 typedef typename View::const_reference StlContainerReference;
2957 typedef typename StlContainer::value_type Element;
2958
2959 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002960 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002961 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002962 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002963
zhanyong.wan33605ba2010-04-22 23:37:47 +00002964 // Checks whether:
2965 // * All elements in the container match, if all_elements_should_match.
2966 // * Any element in the container matches, if !all_elements_should_match.
2967 bool MatchAndExplainImpl(bool all_elements_should_match,
2968 Container container,
2969 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002970 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002971 size_t i = 0;
2972 for (typename StlContainer::const_iterator it = stl_container.begin();
2973 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002974 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002975 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2976
2977 if (matches != all_elements_should_match) {
2978 *listener << "whose element #" << i
2979 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002980 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002981 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002982 }
2983 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002984 return all_elements_should_match;
2985 }
2986
2987 protected:
2988 const Matcher<const Element&> inner_matcher_;
2989
2990 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2991};
2992
2993// Implements Contains(element_matcher) for the given argument type Container.
2994// Symmetric to EachMatcherImpl.
2995template <typename Container>
2996class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2997 public:
2998 template <typename InnerMatcher>
2999 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
3000 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3001
3002 // Describes what this matcher does.
3003 virtual void DescribeTo(::std::ostream* os) const {
3004 *os << "contains at least one element that ";
3005 this->inner_matcher_.DescribeTo(os);
3006 }
3007
3008 virtual void DescribeNegationTo(::std::ostream* os) const {
3009 *os << "doesn't contain any element that ";
3010 this->inner_matcher_.DescribeTo(os);
3011 }
3012
3013 virtual bool MatchAndExplain(Container container,
3014 MatchResultListener* listener) const {
3015 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00003016 }
3017
3018 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003019 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00003020};
3021
zhanyong.wan33605ba2010-04-22 23:37:47 +00003022// Implements Each(element_matcher) for the given argument type Container.
3023// Symmetric to ContainsMatcherImpl.
3024template <typename Container>
3025class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
3026 public:
3027 template <typename InnerMatcher>
3028 explicit EachMatcherImpl(InnerMatcher inner_matcher)
3029 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3030
3031 // Describes what this matcher does.
3032 virtual void DescribeTo(::std::ostream* os) const {
3033 *os << "only contains elements that ";
3034 this->inner_matcher_.DescribeTo(os);
3035 }
3036
3037 virtual void DescribeNegationTo(::std::ostream* os) const {
3038 *os << "contains some element that ";
3039 this->inner_matcher_.DescribeNegationTo(os);
3040 }
3041
3042 virtual bool MatchAndExplain(Container container,
3043 MatchResultListener* listener) const {
3044 return this->MatchAndExplainImpl(true, container, listener);
3045 }
3046
3047 private:
3048 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
3049};
3050
zhanyong.wanb8243162009-06-04 05:48:20 +00003051// Implements polymorphic Contains(element_matcher).
3052template <typename M>
3053class ContainsMatcher {
3054 public:
3055 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
3056
3057 template <typename Container>
3058 operator Matcher<Container>() const {
3059 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
3060 }
3061
3062 private:
3063 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003064
3065 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00003066};
3067
zhanyong.wan33605ba2010-04-22 23:37:47 +00003068// Implements polymorphic Each(element_matcher).
3069template <typename M>
3070class EachMatcher {
3071 public:
3072 explicit EachMatcher(M m) : inner_matcher_(m) {}
3073
3074 template <typename Container>
3075 operator Matcher<Container>() const {
3076 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
3077 }
3078
3079 private:
3080 const M inner_matcher_;
3081
3082 GTEST_DISALLOW_ASSIGN_(EachMatcher);
3083};
3084
Gennadiy Civil466a49a2018-03-23 11:23:54 -04003085struct Rank1 {};
3086struct Rank0 : Rank1 {};
3087
3088namespace pair_getters {
3089#if GTEST_LANG_CXX11
3090using std::get;
3091template <typename T>
3092auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT
3093 return get<0>(x);
3094}
3095template <typename T>
3096auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT
3097 return x.first;
3098}
3099
3100template <typename T>
3101auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT
3102 return get<1>(x);
3103}
3104template <typename T>
3105auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT
3106 return x.second;
3107}
3108#else
3109template <typename T>
3110typename T::first_type& First(T& x, Rank0) { // NOLINT
3111 return x.first;
3112}
3113template <typename T>
3114const typename T::first_type& First(const T& x, Rank0) {
3115 return x.first;
3116}
3117
3118template <typename T>
3119typename T::second_type& Second(T& x, Rank0) { // NOLINT
3120 return x.second;
3121}
3122template <typename T>
3123const typename T::second_type& Second(const T& x, Rank0) {
3124 return x.second;
3125}
3126#endif // GTEST_LANG_CXX11
3127} // namespace pair_getters
3128
zhanyong.wanb5937da2009-07-16 20:26:41 +00003129// Implements Key(inner_matcher) for the given argument pair type.
3130// Key(inner_matcher) matches an std::pair whose 'first' field matches
3131// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3132// std::map that contains at least one element whose key is >= 5.
3133template <typename PairType>
3134class KeyMatcherImpl : public MatcherInterface<PairType> {
3135 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003136 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00003137 typedef typename RawPairType::first_type KeyType;
3138
3139 template <typename InnerMatcher>
3140 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
3141 : inner_matcher_(
3142 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
3143 }
3144
3145 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00003146 virtual bool MatchAndExplain(PairType key_value,
3147 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003148 StringMatchResultListener inner_listener;
3149 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
3150 &inner_listener);
Nico Weber09fd5b32017-05-15 17:07:03 -04003151 const std::string explanation = inner_listener.str();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003152 if (explanation != "") {
3153 *listener << "whose first field is a value " << explanation;
3154 }
3155 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00003156 }
3157
3158 // Describes what this matcher does.
3159 virtual void DescribeTo(::std::ostream* os) const {
3160 *os << "has a key that ";
3161 inner_matcher_.DescribeTo(os);
3162 }
3163
3164 // Describes what the negation of this matcher does.
3165 virtual void DescribeNegationTo(::std::ostream* os) const {
3166 *os << "doesn't have a key that ";
3167 inner_matcher_.DescribeTo(os);
3168 }
3169
zhanyong.wanb5937da2009-07-16 20:26:41 +00003170 private:
3171 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003172
3173 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00003174};
3175
3176// Implements polymorphic Key(matcher_for_key).
3177template <typename M>
3178class KeyMatcher {
3179 public:
3180 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
3181
3182 template <typename PairType>
3183 operator Matcher<PairType>() const {
3184 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
3185 }
3186
3187 private:
3188 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003189
3190 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00003191};
3192
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003193// Implements Pair(first_matcher, second_matcher) for the given argument pair
3194// type with its two matchers. See Pair() function below.
3195template <typename PairType>
3196class PairMatcherImpl : public MatcherInterface<PairType> {
3197 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003198 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003199 typedef typename RawPairType::first_type FirstType;
3200 typedef typename RawPairType::second_type SecondType;
3201
3202 template <typename FirstMatcher, typename SecondMatcher>
3203 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
3204 : first_matcher_(
3205 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
3206 second_matcher_(
3207 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
3208 }
3209
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003210 // Describes what this matcher does.
3211 virtual void DescribeTo(::std::ostream* os) const {
3212 *os << "has a first field that ";
3213 first_matcher_.DescribeTo(os);
3214 *os << ", and has a second field that ";
3215 second_matcher_.DescribeTo(os);
3216 }
3217
3218 // Describes what the negation of this matcher does.
3219 virtual void DescribeNegationTo(::std::ostream* os) const {
3220 *os << "has a first field that ";
3221 first_matcher_.DescribeNegationTo(os);
3222 *os << ", or has a second field that ";
3223 second_matcher_.DescribeNegationTo(os);
3224 }
3225
zhanyong.wan82113312010-01-08 21:55:40 +00003226 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3227 // matches second_matcher.
3228 virtual bool MatchAndExplain(PairType a_pair,
3229 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003230 if (!listener->IsInterested()) {
3231 // If the listener is not interested, we don't need to construct the
3232 // explanation.
3233 return first_matcher_.Matches(a_pair.first) &&
3234 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00003235 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003236 StringMatchResultListener first_inner_listener;
3237 if (!first_matcher_.MatchAndExplain(a_pair.first,
3238 &first_inner_listener)) {
3239 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003240 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003241 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003242 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003243 StringMatchResultListener second_inner_listener;
3244 if (!second_matcher_.MatchAndExplain(a_pair.second,
3245 &second_inner_listener)) {
3246 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003247 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003248 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003249 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003250 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3251 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00003252 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003253 }
3254
3255 private:
Nico Weber09fd5b32017-05-15 17:07:03 -04003256 void ExplainSuccess(const std::string& first_explanation,
3257 const std::string& second_explanation,
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003258 MatchResultListener* listener) const {
3259 *listener << "whose both fields match";
3260 if (first_explanation != "") {
3261 *listener << ", where the first field is a value " << first_explanation;
3262 }
3263 if (second_explanation != "") {
3264 *listener << ", ";
3265 if (first_explanation != "") {
3266 *listener << "and ";
3267 } else {
3268 *listener << "where ";
3269 }
3270 *listener << "the second field is a value " << second_explanation;
3271 }
3272 }
3273
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003274 const Matcher<const FirstType&> first_matcher_;
3275 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003276
3277 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003278};
3279
3280// Implements polymorphic Pair(first_matcher, second_matcher).
3281template <typename FirstMatcher, typename SecondMatcher>
3282class PairMatcher {
3283 public:
3284 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3285 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3286
3287 template <typename PairType>
3288 operator Matcher<PairType> () const {
3289 return MakeMatcher(
3290 new PairMatcherImpl<PairType>(
3291 first_matcher_, second_matcher_));
3292 }
3293
3294 private:
3295 const FirstMatcher first_matcher_;
3296 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003297
3298 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003299};
3300
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003301// Implements ElementsAre() and ElementsAreArray().
3302template <typename Container>
3303class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3304 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003305 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003306 typedef internal::StlContainerView<RawContainer> View;
3307 typedef typename View::type StlContainer;
3308 typedef typename View::const_reference StlContainerReference;
3309 typedef typename StlContainer::value_type Element;
3310
3311 // Constructs the matcher from a sequence of element values or
3312 // element matchers.
3313 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00003314 ElementsAreMatcherImpl(InputIter first, InputIter last) {
3315 while (first != last) {
3316 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003317 }
3318 }
3319
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003320 // Describes what this matcher does.
3321 virtual void DescribeTo(::std::ostream* os) const {
3322 if (count() == 0) {
3323 *os << "is empty";
3324 } else if (count() == 1) {
3325 *os << "has 1 element that ";
3326 matchers_[0].DescribeTo(os);
3327 } else {
3328 *os << "has " << Elements(count()) << " where\n";
3329 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003330 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003331 matchers_[i].DescribeTo(os);
3332 if (i + 1 < count()) {
3333 *os << ",\n";
3334 }
3335 }
3336 }
3337 }
3338
3339 // Describes what the negation of this matcher does.
3340 virtual void DescribeNegationTo(::std::ostream* os) const {
3341 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003342 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003343 return;
3344 }
3345
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003346 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003347 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003348 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003349 matchers_[i].DescribeNegationTo(os);
3350 if (i + 1 < count()) {
3351 *os << ", or\n";
3352 }
3353 }
3354 }
3355
zhanyong.wan82113312010-01-08 21:55:40 +00003356 virtual bool MatchAndExplain(Container container,
3357 MatchResultListener* listener) const {
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003358 // To work with stream-like "containers", we must only walk
3359 // through the elements in one pass.
3360
3361 const bool listener_interested = listener->IsInterested();
3362
3363 // explanations[i] is the explanation of the element at index i.
Nico Weber09fd5b32017-05-15 17:07:03 -04003364 ::std::vector<std::string> explanations(count());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003365 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003366 typename StlContainer::const_iterator it = stl_container.begin();
3367 size_t exam_pos = 0;
3368 bool mismatch_found = false; // Have we found a mismatched element yet?
3369
3370 // Go through the elements and matchers in pairs, until we reach
3371 // the end of either the elements or the matchers, or until we find a
3372 // mismatch.
3373 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3374 bool match; // Does the current element match the current matcher?
3375 if (listener_interested) {
3376 StringMatchResultListener s;
3377 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3378 explanations[exam_pos] = s.str();
3379 } else {
3380 match = matchers_[exam_pos].Matches(*it);
3381 }
3382
3383 if (!match) {
3384 mismatch_found = true;
3385 break;
3386 }
3387 }
3388 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3389
3390 // Find how many elements the actual container has. We avoid
3391 // calling size() s.t. this code works for stream-like "containers"
3392 // that don't define size().
3393 size_t actual_count = exam_pos;
3394 for (; it != stl_container.end(); ++it) {
3395 ++actual_count;
3396 }
3397
zhanyong.wan82113312010-01-08 21:55:40 +00003398 if (actual_count != count()) {
3399 // The element count doesn't match. If the container is empty,
3400 // there's no need to explain anything as Google Mock already
3401 // prints the empty container. Otherwise we just need to show
3402 // how many elements there actually are.
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003403 if (listener_interested && (actual_count != 0)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003404 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003405 }
zhanyong.wan82113312010-01-08 21:55:40 +00003406 return false;
3407 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003408
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003409 if (mismatch_found) {
3410 // The element count matches, but the exam_pos-th element doesn't match.
3411 if (listener_interested) {
3412 *listener << "whose element #" << exam_pos << " doesn't match";
3413 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003414 }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003415 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003416 }
zhanyong.wan82113312010-01-08 21:55:40 +00003417
3418 // Every element matches its expectation. We need to explain why
3419 // (the obvious ones can be skipped).
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003420 if (listener_interested) {
3421 bool reason_printed = false;
3422 for (size_t i = 0; i != count(); ++i) {
Nico Weber09fd5b32017-05-15 17:07:03 -04003423 const std::string& s = explanations[i];
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003424 if (!s.empty()) {
3425 if (reason_printed) {
3426 *listener << ",\nand ";
3427 }
3428 *listener << "whose element #" << i << " matches, " << s;
3429 reason_printed = true;
zhanyong.wan82113312010-01-08 21:55:40 +00003430 }
zhanyong.wan82113312010-01-08 21:55:40 +00003431 }
3432 }
zhanyong.wan82113312010-01-08 21:55:40 +00003433 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003434 }
3435
3436 private:
3437 static Message Elements(size_t count) {
3438 return Message() << count << (count == 1 ? " element" : " elements");
3439 }
3440
3441 size_t count() const { return matchers_.size(); }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003442
3443 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003444
3445 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003446};
3447
zhanyong.wanfb25d532013-07-28 08:24:00 +00003448// Connectivity matrix of (elements X matchers), in element-major order.
3449// Initially, there are no edges.
3450// Use NextGraph() to iterate over all possible edge configurations.
3451// Use Randomize() to generate a random edge configuration.
3452class GTEST_API_ MatchMatrix {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003453 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003454 MatchMatrix(size_t num_elements, size_t num_matchers)
3455 : num_elements_(num_elements),
3456 num_matchers_(num_matchers),
3457 matched_(num_elements_* num_matchers_, 0) {
3458 }
3459
3460 size_t LhsSize() const { return num_elements_; }
3461 size_t RhsSize() const { return num_matchers_; }
3462 bool HasEdge(size_t ilhs, size_t irhs) const {
3463 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3464 }
3465 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3466 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3467 }
3468
3469 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3470 // adds 1 to that number; returns false if incrementing the graph left it
3471 // empty.
3472 bool NextGraph();
3473
3474 void Randomize();
3475
Nico Weber09fd5b32017-05-15 17:07:03 -04003476 std::string DebugString() const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003477
3478 private:
3479 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3480 return ilhs * num_matchers_ + irhs;
3481 }
3482
3483 size_t num_elements_;
3484 size_t num_matchers_;
3485
3486 // Each element is a char interpreted as bool. They are stored as a
3487 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3488 // a (ilhs, irhs) matrix coordinate into an offset.
3489 ::std::vector<char> matched_;
3490};
3491
3492typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3493typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3494
3495// Returns a maximum bipartite matching for the specified graph 'g'.
3496// The matching is represented as a vector of {element, matcher} pairs.
3497GTEST_API_ ElementMatcherPairs
3498FindMaxBipartiteMatching(const MatchMatrix& g);
3499
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003500struct UnorderedMatcherRequire {
3501 enum Flags {
3502 Superset = 1 << 0,
3503 Subset = 1 << 1,
3504 ExactMatch = Superset | Subset,
3505 };
3506};
zhanyong.wanfb25d532013-07-28 08:24:00 +00003507
3508// Untyped base class for implementing UnorderedElementsAre. By
3509// putting logic that's not specific to the element type here, we
3510// reduce binary bloat and increase compilation speed.
3511class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3512 protected:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003513 explicit UnorderedElementsAreMatcherImplBase(
3514 UnorderedMatcherRequire::Flags matcher_flags)
3515 : match_flags_(matcher_flags) {}
3516
zhanyong.wanfb25d532013-07-28 08:24:00 +00003517 // A vector of matcher describers, one for each element matcher.
3518 // Does not own the describers (and thus can be used only when the
3519 // element matchers are alive).
3520 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3521
3522 // Describes this UnorderedElementsAre matcher.
3523 void DescribeToImpl(::std::ostream* os) const;
3524
3525 // Describes the negation of this UnorderedElementsAre matcher.
3526 void DescribeNegationToImpl(::std::ostream* os) const;
3527
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003528 bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,
3529 const MatchMatrix& matrix,
3530 MatchResultListener* listener) const;
3531
3532 bool FindPairing(const MatchMatrix& matrix,
3533 MatchResultListener* listener) const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003534
3535 MatcherDescriberVec& matcher_describers() {
3536 return matcher_describers_;
3537 }
3538
3539 static Message Elements(size_t n) {
3540 return Message() << n << " element" << (n == 1 ? "" : "s");
3541 }
3542
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003543 UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }
3544
zhanyong.wanfb25d532013-07-28 08:24:00 +00003545 private:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003546 UnorderedMatcherRequire::Flags match_flags_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003547 MatcherDescriberVec matcher_describers_;
3548
3549 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3550};
3551
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003552// Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
3553// IsSupersetOf.
zhanyong.wanfb25d532013-07-28 08:24:00 +00003554template <typename Container>
3555class UnorderedElementsAreMatcherImpl
3556 : public MatcherInterface<Container>,
3557 public UnorderedElementsAreMatcherImplBase {
3558 public:
3559 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3560 typedef internal::StlContainerView<RawContainer> View;
3561 typedef typename View::type StlContainer;
3562 typedef typename View::const_reference StlContainerReference;
3563 typedef typename StlContainer::const_iterator StlContainerConstIterator;
3564 typedef typename StlContainer::value_type Element;
3565
zhanyong.wanfb25d532013-07-28 08:24:00 +00003566 template <typename InputIter>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003567 UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,
3568 InputIter first, InputIter last)
3569 : UnorderedElementsAreMatcherImplBase(matcher_flags) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00003570 for (; first != last; ++first) {
3571 matchers_.push_back(MatcherCast<const Element&>(*first));
3572 matcher_describers().push_back(matchers_.back().GetDescriber());
3573 }
3574 }
3575
3576 // Describes what this matcher does.
3577 virtual void DescribeTo(::std::ostream* os) const {
3578 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3579 }
3580
3581 // Describes what the negation of this matcher does.
3582 virtual void DescribeNegationTo(::std::ostream* os) const {
3583 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3584 }
3585
3586 virtual bool MatchAndExplain(Container container,
3587 MatchResultListener* listener) const {
3588 StlContainerReference stl_container = View::ConstReference(container);
Nico Weber09fd5b32017-05-15 17:07:03 -04003589 ::std::vector<std::string> element_printouts;
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003590 MatchMatrix matrix =
3591 AnalyzeElements(stl_container.begin(), stl_container.end(),
3592 &element_printouts, listener);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003593
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003594 if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00003595 return true;
3596 }
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003597
3598 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
3599 if (matrix.LhsSize() != matrix.RhsSize()) {
3600 // The element count doesn't match. If the container is empty,
3601 // there's no need to explain anything as Google Mock already
3602 // prints the empty container. Otherwise we just need to show
3603 // how many elements there actually are.
3604 if (matrix.LhsSize() != 0 && listener->IsInterested()) {
3605 *listener << "which has " << Elements(matrix.LhsSize());
3606 }
3607 return false;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003608 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003609 }
3610
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003611 return VerifyMatchMatrix(element_printouts, matrix, listener) &&
zhanyong.wanfb25d532013-07-28 08:24:00 +00003612 FindPairing(matrix, listener);
3613 }
3614
3615 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003616 template <typename ElementIter>
3617 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
Nico Weber09fd5b32017-05-15 17:07:03 -04003618 ::std::vector<std::string>* element_printouts,
zhanyong.wanfb25d532013-07-28 08:24:00 +00003619 MatchResultListener* listener) const {
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003620 element_printouts->clear();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003621 ::std::vector<char> did_match;
3622 size_t num_elements = 0;
3623 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3624 if (listener->IsInterested()) {
3625 element_printouts->push_back(PrintToString(*elem_first));
3626 }
3627 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3628 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3629 }
3630 }
3631
3632 MatchMatrix matrix(num_elements, matchers_.size());
3633 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3634 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3635 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3636 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3637 }
3638 }
3639 return matrix;
3640 }
3641
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003642 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003643
3644 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3645};
3646
3647// Functor for use in TransformTuple.
3648// Performs MatcherCast<Target> on an input argument of any type.
3649template <typename Target>
3650struct CastAndAppendTransform {
3651 template <typename Arg>
3652 Matcher<Target> operator()(const Arg& a) const {
3653 return MatcherCast<Target>(a);
3654 }
3655};
3656
3657// Implements UnorderedElementsAre.
3658template <typename MatcherTuple>
3659class UnorderedElementsAreMatcher {
3660 public:
3661 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3662 : matchers_(args) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003663
3664 template <typename Container>
3665 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003666 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003667 typedef typename internal::StlContainerView<RawContainer>::type View;
3668 typedef typename View::value_type Element;
3669 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3670 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003671 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003672 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3673 ::std::back_inserter(matchers));
3674 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003675 UnorderedMatcherRequire::ExactMatch, matchers.begin(), matchers.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003676 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003677
3678 private:
3679 const MatcherTuple matchers_;
3680 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3681};
3682
3683// Implements ElementsAre.
3684template <typename MatcherTuple>
3685class ElementsAreMatcher {
3686 public:
3687 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3688
3689 template <typename Container>
3690 operator Matcher<Container>() const {
3691 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3692 typedef typename internal::StlContainerView<RawContainer>::type View;
3693 typedef typename View::value_type Element;
3694 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3695 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003696 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003697 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3698 ::std::back_inserter(matchers));
3699 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3700 matchers.begin(), matchers.end()));
3701 }
3702
3703 private:
3704 const MatcherTuple matchers_;
3705 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3706};
3707
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003708// Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
zhanyong.wanfb25d532013-07-28 08:24:00 +00003709template <typename T>
3710class UnorderedElementsAreArrayMatcher {
3711 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003712 template <typename Iter>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003713 UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,
3714 Iter first, Iter last)
3715 : match_flags_(match_flags), matchers_(first, last) {}
zhanyong.wanfb25d532013-07-28 08:24:00 +00003716
3717 template <typename Container>
3718 operator Matcher<Container>() const {
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003719 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3720 match_flags_, matchers_.begin(), matchers_.end()));
zhanyong.wanfb25d532013-07-28 08:24:00 +00003721 }
3722
3723 private:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003724 UnorderedMatcherRequire::Flags match_flags_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003725 ::std::vector<T> matchers_;
3726
3727 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003728};
3729
3730// Implements ElementsAreArray().
3731template <typename T>
3732class ElementsAreArrayMatcher {
3733 public:
jgm38513a82012-11-15 15:50:36 +00003734 template <typename Iter>
3735 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003736
3737 template <typename Container>
3738 operator Matcher<Container>() const {
jgm38513a82012-11-15 15:50:36 +00003739 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3740 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003741 }
3742
3743 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003744 const ::std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003745
3746 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003747};
3748
kosak2336e9c2014-07-28 22:57:30 +00003749// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3750// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3751// second) is a polymorphic matcher that matches a value x iff tm
3752// matches tuple (x, second). Useful for implementing
3753// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3754//
3755// BoundSecondMatcher is copyable and assignable, as we need to put
3756// instances of this class in a vector when implementing
3757// UnorderedPointwise().
3758template <typename Tuple2Matcher, typename Second>
3759class BoundSecondMatcher {
3760 public:
3761 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3762 : tuple2_matcher_(tm), second_value_(second) {}
3763
3764 template <typename T>
3765 operator Matcher<T>() const {
3766 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3767 }
3768
3769 // We have to define this for UnorderedPointwise() to compile in
3770 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3771 // which requires the elements to be assignable in C++98. The
3772 // compiler cannot generate the operator= for us, as Tuple2Matcher
3773 // and Second may not be assignable.
3774 //
3775 // However, this should never be called, so the implementation just
3776 // need to assert.
3777 void operator=(const BoundSecondMatcher& /*rhs*/) {
3778 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3779 }
3780
3781 private:
3782 template <typename T>
3783 class Impl : public MatcherInterface<T> {
3784 public:
3785 typedef ::testing::tuple<T, Second> ArgTuple;
3786
3787 Impl(const Tuple2Matcher& tm, const Second& second)
3788 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3789 second_value_(second) {}
3790
3791 virtual void DescribeTo(::std::ostream* os) const {
3792 *os << "and ";
3793 UniversalPrint(second_value_, os);
3794 *os << " ";
3795 mono_tuple2_matcher_.DescribeTo(os);
3796 }
3797
3798 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3799 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3800 listener);
3801 }
3802
3803 private:
3804 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3805 const Second second_value_;
3806
3807 GTEST_DISALLOW_ASSIGN_(Impl);
3808 };
3809
3810 const Tuple2Matcher tuple2_matcher_;
3811 const Second second_value_;
3812};
3813
3814// Given a 2-tuple matcher tm and a value second,
3815// MatcherBindSecond(tm, second) returns a matcher that matches a
3816// value x iff tm matches tuple (x, second). Useful for implementing
3817// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3818template <typename Tuple2Matcher, typename Second>
3819BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
3820 const Tuple2Matcher& tm, const Second& second) {
3821 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
3822}
3823
zhanyong.wanb4140802010-06-08 22:53:57 +00003824// Returns the description for a matcher defined using the MATCHER*()
3825// macro where the user-supplied description string is "", if
3826// 'negation' is false; otherwise returns the description of the
3827// negation of the matcher. 'param_values' contains a list of strings
3828// that are the print-out of the matcher's parameters.
Nico Weber09fd5b32017-05-15 17:07:03 -04003829GTEST_API_ std::string FormatMatcherDescription(bool negation,
3830 const char* matcher_name,
3831 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003832
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05003833namespace variant_matcher {
3834// Overloads to allow VariantMatcher to do proper ADL lookup.
3835template <typename T>
3836void holds_alternative() {}
3837template <typename T>
3838void get() {}
3839
3840// Implements a matcher that checks the value of a variant<> type variable.
3841template <typename T>
3842class VariantMatcher {
3843 public:
3844 explicit VariantMatcher(::testing::Matcher<const T&> matcher)
3845 : matcher_(internal::move(matcher)) {}
3846
3847 template <typename Variant>
3848 bool MatchAndExplain(const Variant& value,
3849 ::testing::MatchResultListener* listener) const {
3850 if (!listener->IsInterested()) {
3851 return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));
3852 }
3853
3854 if (!holds_alternative<T>(value)) {
3855 *listener << "whose value is not of type '" << GetTypeName() << "'";
3856 return false;
3857 }
3858
3859 const T& elem = get<T>(value);
3860 StringMatchResultListener elem_listener;
3861 const bool match = matcher_.MatchAndExplain(elem, &elem_listener);
3862 *listener << "whose value " << PrintToString(elem)
3863 << (match ? " matches" : " doesn't match");
3864 PrintIfNotEmpty(elem_listener.str(), listener->stream());
3865 return match;
3866 }
3867
3868 void DescribeTo(std::ostream* os) const {
3869 *os << "is a variant<> with value of type '" << GetTypeName()
3870 << "' and the value ";
3871 matcher_.DescribeTo(os);
3872 }
3873
3874 void DescribeNegationTo(std::ostream* os) const {
3875 *os << "is a variant<> with value of type other than '" << GetTypeName()
3876 << "' or the value ";
3877 matcher_.DescribeNegationTo(os);
3878 }
3879
3880 private:
3881 static string GetTypeName() {
3882#if GTEST_HAS_RTTI
3883 return internal::GetTypeName<T>();
3884#endif
3885 return "the element type";
3886 }
3887
3888 const ::testing::Matcher<const T&> matcher_;
3889};
3890
3891} // namespace variant_matcher
3892
Gennadiy Civil466a49a2018-03-23 11:23:54 -04003893namespace any_cast_matcher {
3894
3895// Overloads to allow AnyCastMatcher to do proper ADL lookup.
3896template <typename T>
3897void any_cast() {}
3898
3899// Implements a matcher that any_casts the value.
3900template <typename T>
3901class AnyCastMatcher {
3902 public:
3903 explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher)
3904 : matcher_(matcher) {}
3905
3906 template <typename AnyType>
3907 bool MatchAndExplain(const AnyType& value,
3908 ::testing::MatchResultListener* listener) const {
3909 if (!listener->IsInterested()) {
3910 const T* ptr = any_cast<T>(&value);
3911 return ptr != NULL && matcher_.Matches(*ptr);
3912 }
3913
3914 const T* elem = any_cast<T>(&value);
3915 if (elem == NULL) {
3916 *listener << "whose value is not of type '" << GetTypeName() << "'";
3917 return false;
3918 }
3919
3920 StringMatchResultListener elem_listener;
3921 const bool match = matcher_.MatchAndExplain(*elem, &elem_listener);
3922 *listener << "whose value " << PrintToString(*elem)
3923 << (match ? " matches" : " doesn't match");
3924 PrintIfNotEmpty(elem_listener.str(), listener->stream());
3925 return match;
3926 }
3927
3928 void DescribeTo(std::ostream* os) const {
3929 *os << "is an 'any' type with value of type '" << GetTypeName()
3930 << "' and the value ";
3931 matcher_.DescribeTo(os);
3932 }
3933
3934 void DescribeNegationTo(std::ostream* os) const {
3935 *os << "is an 'any' type with value of type other than '" << GetTypeName()
3936 << "' or the value ";
3937 matcher_.DescribeNegationTo(os);
3938 }
3939
3940 private:
3941 static std::string GetTypeName() {
3942#if GTEST_HAS_RTTI
3943 return internal::GetTypeName<T>();
3944#endif
3945 return "the element type";
3946 }
3947
3948 const ::testing::Matcher<const T&> matcher_;
3949};
3950
3951} // namespace any_cast_matcher
shiqiane35fdd92008-12-10 05:08:54 +00003952} // namespace internal
3953
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003954// ElementsAreArray(iterator_first, iterator_last)
zhanyong.wanfb25d532013-07-28 08:24:00 +00003955// ElementsAreArray(pointer, count)
3956// ElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00003957// ElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003958// ElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00003959//
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003960// The ElementsAreArray() functions are like ElementsAre(...), except
3961// that they are given a homogeneous sequence rather than taking each
3962// element as a function argument. The sequence can be specified as an
3963// array, a pointer and count, a vector, an initializer list, or an
3964// STL iterator range. In each of these cases, the underlying sequence
3965// can be either a sequence of values or a sequence of matchers.
zhanyong.wanfb25d532013-07-28 08:24:00 +00003966//
3967// All forms of ElementsAreArray() make a copy of the input matcher sequence.
3968
3969template <typename Iter>
3970inline internal::ElementsAreArrayMatcher<
3971 typename ::std::iterator_traits<Iter>::value_type>
3972ElementsAreArray(Iter first, Iter last) {
3973 typedef typename ::std::iterator_traits<Iter>::value_type T;
3974 return internal::ElementsAreArrayMatcher<T>(first, last);
3975}
3976
3977template <typename T>
3978inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3979 const T* pointer, size_t count) {
3980 return ElementsAreArray(pointer, pointer + count);
3981}
3982
3983template <typename T, size_t N>
3984inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3985 const T (&array)[N]) {
3986 return ElementsAreArray(array, N);
3987}
3988
kosak06678922014-07-28 20:01:28 +00003989template <typename Container>
3990inline internal::ElementsAreArrayMatcher<typename Container::value_type>
3991ElementsAreArray(const Container& container) {
3992 return ElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00003993}
3994
kosak18489fa2013-12-04 23:49:07 +00003995#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003996template <typename T>
3997inline internal::ElementsAreArrayMatcher<T>
3998ElementsAreArray(::std::initializer_list<T> xs) {
3999 return ElementsAreArray(xs.begin(), xs.end());
4000}
4001#endif
4002
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004003// UnorderedElementsAreArray(iterator_first, iterator_last)
zhanyong.wanfb25d532013-07-28 08:24:00 +00004004// UnorderedElementsAreArray(pointer, count)
4005// UnorderedElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00004006// UnorderedElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004007// UnorderedElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00004008//
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004009// UnorderedElementsAreArray() verifies that a bijective mapping onto a
4010// collection of matchers exists.
4011//
4012// The matchers can be specified as an array, a pointer and count, a container,
4013// an initializer list, or an STL iterator range. In each of these cases, the
4014// underlying matchers can be either values or matchers.
4015
zhanyong.wanfb25d532013-07-28 08:24:00 +00004016template <typename Iter>
4017inline internal::UnorderedElementsAreArrayMatcher<
4018 typename ::std::iterator_traits<Iter>::value_type>
4019UnorderedElementsAreArray(Iter first, Iter last) {
4020 typedef typename ::std::iterator_traits<Iter>::value_type T;
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004021 return internal::UnorderedElementsAreArrayMatcher<T>(
4022 internal::UnorderedMatcherRequire::ExactMatch, first, last);
zhanyong.wanfb25d532013-07-28 08:24:00 +00004023}
4024
4025template <typename T>
4026inline internal::UnorderedElementsAreArrayMatcher<T>
4027UnorderedElementsAreArray(const T* pointer, size_t count) {
4028 return UnorderedElementsAreArray(pointer, pointer + count);
4029}
4030
4031template <typename T, size_t N>
4032inline internal::UnorderedElementsAreArrayMatcher<T>
4033UnorderedElementsAreArray(const T (&array)[N]) {
4034 return UnorderedElementsAreArray(array, N);
4035}
4036
kosak06678922014-07-28 20:01:28 +00004037template <typename Container>
4038inline internal::UnorderedElementsAreArrayMatcher<
4039 typename Container::value_type>
4040UnorderedElementsAreArray(const Container& container) {
4041 return UnorderedElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00004042}
4043
kosak18489fa2013-12-04 23:49:07 +00004044#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004045template <typename T>
4046inline internal::UnorderedElementsAreArrayMatcher<T>
4047UnorderedElementsAreArray(::std::initializer_list<T> xs) {
4048 return UnorderedElementsAreArray(xs.begin(), xs.end());
4049}
4050#endif
zhanyong.wanfb25d532013-07-28 08:24:00 +00004051
shiqiane35fdd92008-12-10 05:08:54 +00004052// _ is a matcher that matches anything of any type.
4053//
4054// This definition is fine as:
4055//
4056// 1. The C++ standard permits using the name _ in a namespace that
4057// is not the global namespace or ::std.
4058// 2. The AnythingMatcher class has no data member or constructor,
4059// so it's OK to create global variables of this type.
4060// 3. c-style has approved of using _ in this case.
4061const internal::AnythingMatcher _ = {};
4062// Creates a matcher that matches any value of the given type T.
4063template <typename T>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004064inline Matcher<T> A() {
4065 return Matcher<T>(new internal::AnyMatcherImpl<T>());
4066}
shiqiane35fdd92008-12-10 05:08:54 +00004067
4068// Creates a matcher that matches any value of the given type T.
4069template <typename T>
4070inline Matcher<T> An() { return A<T>(); }
4071
4072// Creates a polymorphic matcher that matches anything equal to x.
4073// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
4074// wouldn't compile.
4075template <typename T>
4076inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
4077
4078// Constructs a Matcher<T> from a 'value' of type T. The constructed
4079// matcher matches any value that's equal to 'value'.
4080template <typename T>
4081Matcher<T>::Matcher(T value) { *this = Eq(value); }
4082
Gennadiy Civil466a49a2018-03-23 11:23:54 -04004083template <typename T, typename M>
4084Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(
4085 const M& value,
4086 internal::BooleanConstant<false> /* convertible_to_matcher */,
4087 internal::BooleanConstant<false> /* convertible_to_T */) {
4088 return Eq(value);
4089}
4090
shiqiane35fdd92008-12-10 05:08:54 +00004091// Creates a monomorphic matcher that matches anything with type Lhs
4092// and equal to rhs. A user may need to use this instead of Eq(...)
4093// in order to resolve an overloading ambiguity.
4094//
4095// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
4096// or Matcher<T>(x), but more readable than the latter.
4097//
4098// We could define similar monomorphic matchers for other comparison
4099// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
4100// it yet as those are used much less than Eq() in practice. A user
4101// can always write Matcher<T>(Lt(5)) to be explicit about the type,
4102// for example.
4103template <typename Lhs, typename Rhs>
4104inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
4105
4106// Creates a polymorphic matcher that matches anything >= x.
4107template <typename Rhs>
4108inline internal::GeMatcher<Rhs> Ge(Rhs x) {
4109 return internal::GeMatcher<Rhs>(x);
4110}
4111
4112// Creates a polymorphic matcher that matches anything > x.
4113template <typename Rhs>
4114inline internal::GtMatcher<Rhs> Gt(Rhs x) {
4115 return internal::GtMatcher<Rhs>(x);
4116}
4117
4118// Creates a polymorphic matcher that matches anything <= x.
4119template <typename Rhs>
4120inline internal::LeMatcher<Rhs> Le(Rhs x) {
4121 return internal::LeMatcher<Rhs>(x);
4122}
4123
4124// Creates a polymorphic matcher that matches anything < x.
4125template <typename Rhs>
4126inline internal::LtMatcher<Rhs> Lt(Rhs x) {
4127 return internal::LtMatcher<Rhs>(x);
4128}
4129
4130// Creates a polymorphic matcher that matches anything != x.
4131template <typename Rhs>
4132inline internal::NeMatcher<Rhs> Ne(Rhs x) {
4133 return internal::NeMatcher<Rhs>(x);
4134}
4135
zhanyong.wan2d970ee2009-09-24 21:41:36 +00004136// Creates a polymorphic matcher that matches any NULL pointer.
4137inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
4138 return MakePolymorphicMatcher(internal::IsNullMatcher());
4139}
4140
shiqiane35fdd92008-12-10 05:08:54 +00004141// Creates a polymorphic matcher that matches any non-NULL pointer.
4142// This is convenient as Not(NULL) doesn't compile (the compiler
4143// thinks that that expression is comparing a pointer with an integer).
4144inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
4145 return MakePolymorphicMatcher(internal::NotNullMatcher());
4146}
4147
4148// Creates a polymorphic matcher that matches any argument that
4149// references variable x.
4150template <typename T>
4151inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
4152 return internal::RefMatcher<T&>(x);
4153}
4154
4155// Creates a matcher that matches any double argument approximately
4156// equal to rhs, where two NANs are considered unequal.
4157inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
4158 return internal::FloatingEqMatcher<double>(rhs, false);
4159}
4160
4161// Creates a matcher that matches any double argument approximately
4162// equal to rhs, including NaN values when rhs is NaN.
4163inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
4164 return internal::FloatingEqMatcher<double>(rhs, true);
4165}
4166
zhanyong.wan616180e2013-06-18 18:49:51 +00004167// Creates a matcher that matches any double argument approximately equal to
4168// rhs, up to the specified max absolute error bound, where two NANs are
4169// considered unequal. The max absolute error bound must be non-negative.
4170inline internal::FloatingEqMatcher<double> DoubleNear(
4171 double rhs, double max_abs_error) {
4172 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
4173}
4174
4175// Creates a matcher that matches any double argument approximately equal to
4176// rhs, up to the specified max absolute error bound, including NaN values when
4177// rhs is NaN. The max absolute error bound must be non-negative.
4178inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
4179 double rhs, double max_abs_error) {
4180 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
4181}
4182
shiqiane35fdd92008-12-10 05:08:54 +00004183// Creates a matcher that matches any float argument approximately
4184// equal to rhs, where two NANs are considered unequal.
4185inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
4186 return internal::FloatingEqMatcher<float>(rhs, false);
4187}
4188
zhanyong.wan616180e2013-06-18 18:49:51 +00004189// Creates a matcher that matches any float argument approximately
shiqiane35fdd92008-12-10 05:08:54 +00004190// equal to rhs, including NaN values when rhs is NaN.
4191inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
4192 return internal::FloatingEqMatcher<float>(rhs, true);
4193}
4194
zhanyong.wan616180e2013-06-18 18:49:51 +00004195// Creates a matcher that matches any float argument approximately equal to
4196// rhs, up to the specified max absolute error bound, where two NANs are
4197// considered unequal. The max absolute error bound must be non-negative.
4198inline internal::FloatingEqMatcher<float> FloatNear(
4199 float rhs, float max_abs_error) {
4200 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
4201}
4202
4203// Creates a matcher that matches any float argument approximately equal to
4204// rhs, up to the specified max absolute error bound, including NaN values when
4205// rhs is NaN. The max absolute error bound must be non-negative.
4206inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
4207 float rhs, float max_abs_error) {
4208 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
4209}
4210
shiqiane35fdd92008-12-10 05:08:54 +00004211// Creates a matcher that matches a pointer (raw or smart) that points
4212// to a value that matches inner_matcher.
4213template <typename InnerMatcher>
4214inline internal::PointeeMatcher<InnerMatcher> Pointee(
4215 const InnerMatcher& inner_matcher) {
4216 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
4217}
4218
billydonahue1f5fdea2014-05-19 17:54:51 +00004219// Creates a matcher that matches a pointer or reference that matches
4220// inner_matcher when dynamic_cast<To> is applied.
4221// The result of dynamic_cast<To> is forwarded to the inner matcher.
4222// If To is a pointer and the cast fails, the inner matcher will receive NULL.
4223// If To is a reference and the cast fails, this matcher returns false
4224// immediately.
4225template <typename To>
4226inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
4227WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
4228 return MakePolymorphicMatcher(
4229 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
4230}
4231
shiqiane35fdd92008-12-10 05:08:54 +00004232// Creates a matcher that matches an object whose given field matches
4233// 'matcher'. For example,
4234// Field(&Foo::number, Ge(5))
4235// matches a Foo object x iff x.number >= 5.
4236template <typename Class, typename FieldType, typename FieldMatcher>
4237inline PolymorphicMatcher<
4238 internal::FieldMatcher<Class, FieldType> > Field(
4239 FieldType Class::*field, const FieldMatcher& matcher) {
4240 return MakePolymorphicMatcher(
4241 internal::FieldMatcher<Class, FieldType>(
4242 field, MatcherCast<const FieldType&>(matcher)));
4243 // The call to MatcherCast() is required for supporting inner
4244 // matchers of compatible types. For example, it allows
4245 // Field(&Foo::bar, m)
4246 // to compile where bar is an int32 and m is a matcher for int64.
4247}
4248
4249// Creates a matcher that matches an object whose given property
4250// matches 'matcher'. For example,
4251// Property(&Foo::str, StartsWith("hi"))
4252// matches a Foo object x iff x.str() starts with "hi".
4253template <typename Class, typename PropertyType, typename PropertyMatcher>
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004254inline PolymorphicMatcher<internal::PropertyMatcher<
4255 Class, PropertyType, PropertyType (Class::*)() const> >
4256Property(PropertyType (Class::*property)() const,
4257 const PropertyMatcher& matcher) {
shiqiane35fdd92008-12-10 05:08:54 +00004258 return MakePolymorphicMatcher(
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004259 internal::PropertyMatcher<Class, PropertyType,
4260 PropertyType (Class::*)() const>(
shiqiane35fdd92008-12-10 05:08:54 +00004261 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00004262 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00004263 // The call to MatcherCast() is required for supporting inner
4264 // matchers of compatible types. For example, it allows
4265 // Property(&Foo::bar, m)
4266 // to compile where bar() returns an int32 and m is a matcher for int64.
4267}
4268
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004269#if GTEST_LANG_CXX11
4270// The same as above but for reference-qualified member functions.
4271template <typename Class, typename PropertyType, typename PropertyMatcher>
4272inline PolymorphicMatcher<internal::PropertyMatcher<
4273 Class, PropertyType, PropertyType (Class::*)() const &> >
4274Property(PropertyType (Class::*property)() const &,
4275 const PropertyMatcher& matcher) {
4276 return MakePolymorphicMatcher(
4277 internal::PropertyMatcher<Class, PropertyType,
4278 PropertyType (Class::*)() const &>(
4279 property,
4280 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4281}
4282#endif
4283
shiqiane35fdd92008-12-10 05:08:54 +00004284// Creates a matcher that matches an object iff the result of applying
4285// a callable to x matches 'matcher'.
4286// For example,
4287// ResultOf(f, StartsWith("hi"))
4288// matches a Foo object x iff f(x) starts with "hi".
4289// callable parameter can be a function, function pointer, or a functor.
4290// Callable has to satisfy the following conditions:
4291// * It is required to keep no state affecting the results of
4292// the calls on it and make no assumptions about how many calls
4293// will be made. Any state it keeps must be protected from the
4294// concurrent access.
4295// * If it is a function object, it has to define type result_type.
4296// We recommend deriving your functor classes from std::unary_function.
4297template <typename Callable, typename ResultOfMatcher>
4298internal::ResultOfMatcher<Callable> ResultOf(
4299 Callable callable, const ResultOfMatcher& matcher) {
4300 return internal::ResultOfMatcher<Callable>(
4301 callable,
4302 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
4303 matcher));
4304 // The call to MatcherCast() is required for supporting inner
4305 // matchers of compatible types. For example, it allows
4306 // ResultOf(Function, m)
4307 // to compile where Function() returns an int32 and m is a matcher for int64.
4308}
4309
4310// String matchers.
4311
4312// Matches a string equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04004313inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
4314 const std::string& str) {
4315 return MakePolymorphicMatcher(
4316 internal::StrEqualityMatcher<std::string>(str, true, true));
shiqiane35fdd92008-12-10 05:08:54 +00004317}
4318
4319// Matches a string not equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04004320inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
4321 const std::string& str) {
4322 return MakePolymorphicMatcher(
4323 internal::StrEqualityMatcher<std::string>(str, false, true));
shiqiane35fdd92008-12-10 05:08:54 +00004324}
4325
4326// Matches a string equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04004327inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
4328 const std::string& str) {
4329 return MakePolymorphicMatcher(
4330 internal::StrEqualityMatcher<std::string>(str, true, false));
shiqiane35fdd92008-12-10 05:08:54 +00004331}
4332
4333// Matches a string not equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04004334inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
4335 const std::string& str) {
4336 return MakePolymorphicMatcher(
4337 internal::StrEqualityMatcher<std::string>(str, false, false));
shiqiane35fdd92008-12-10 05:08:54 +00004338}
4339
4340// Creates a matcher that matches any string, std::string, or C string
4341// that contains the given substring.
Nico Weber09fd5b32017-05-15 17:07:03 -04004342inline PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
4343 const std::string& substring) {
4344 return MakePolymorphicMatcher(
4345 internal::HasSubstrMatcher<std::string>(substring));
shiqiane35fdd92008-12-10 05:08:54 +00004346}
4347
4348// Matches a string that starts with 'prefix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004349inline PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
4350 const std::string& prefix) {
4351 return MakePolymorphicMatcher(
4352 internal::StartsWithMatcher<std::string>(prefix));
shiqiane35fdd92008-12-10 05:08:54 +00004353}
4354
4355// Matches a string that ends with 'suffix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004356inline PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
4357 const std::string& suffix) {
4358 return MakePolymorphicMatcher(internal::EndsWithMatcher<std::string>(suffix));
shiqiane35fdd92008-12-10 05:08:54 +00004359}
4360
shiqiane35fdd92008-12-10 05:08:54 +00004361// Matches a string that fully matches regular expression 'regex'.
4362// The matcher takes ownership of 'regex'.
4363inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4364 const internal::RE* regex) {
4365 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
4366}
4367inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004368 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004369 return MatchesRegex(new internal::RE(regex));
4370}
4371
4372// Matches a string that contains regular expression 'regex'.
4373// The matcher takes ownership of 'regex'.
4374inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4375 const internal::RE* regex) {
4376 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4377}
4378inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004379 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004380 return ContainsRegex(new internal::RE(regex));
4381}
4382
shiqiane35fdd92008-12-10 05:08:54 +00004383#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4384// Wide string matchers.
4385
4386// Matches a string equal to str.
4387inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4388 StrEq(const internal::wstring& str) {
4389 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4390 str, true, true));
4391}
4392
4393// Matches a string not equal to str.
4394inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4395 StrNe(const internal::wstring& str) {
4396 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4397 str, false, true));
4398}
4399
4400// Matches a string equal to str, ignoring case.
4401inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4402 StrCaseEq(const internal::wstring& str) {
4403 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4404 str, true, false));
4405}
4406
4407// Matches a string not equal to str, ignoring case.
4408inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4409 StrCaseNe(const internal::wstring& str) {
4410 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4411 str, false, false));
4412}
4413
4414// Creates a matcher that matches any wstring, std::wstring, or C wide string
4415// that contains the given substring.
4416inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
4417 HasSubstr(const internal::wstring& substring) {
4418 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
4419 substring));
4420}
4421
4422// Matches a string that starts with 'prefix' (case-sensitive).
4423inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
4424 StartsWith(const internal::wstring& prefix) {
4425 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
4426 prefix));
4427}
4428
4429// Matches a string that ends with 'suffix' (case-sensitive).
4430inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
4431 EndsWith(const internal::wstring& suffix) {
4432 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
4433 suffix));
4434}
4435
4436#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4437
4438// Creates a polymorphic matcher that matches a 2-tuple where the
4439// first field == the second field.
4440inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4441
4442// Creates a polymorphic matcher that matches a 2-tuple where the
4443// first field >= the second field.
4444inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4445
4446// Creates a polymorphic matcher that matches a 2-tuple where the
4447// first field > the second field.
4448inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4449
4450// Creates a polymorphic matcher that matches a 2-tuple where the
4451// first field <= the second field.
4452inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4453
4454// Creates a polymorphic matcher that matches a 2-tuple where the
4455// first field < the second field.
4456inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4457
4458// Creates a polymorphic matcher that matches a 2-tuple where the
4459// first field != the second field.
4460inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4461
4462// Creates a matcher that matches any value of type T that m doesn't
4463// match.
4464template <typename InnerMatcher>
4465inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4466 return internal::NotMatcher<InnerMatcher>(m);
4467}
4468
shiqiane35fdd92008-12-10 05:08:54 +00004469// Returns a matcher that matches anything that satisfies the given
4470// predicate. The predicate can be any unary function or functor
4471// whose return type can be implicitly converted to bool.
4472template <typename Predicate>
4473inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4474Truly(Predicate pred) {
4475 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4476}
4477
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004478// Returns a matcher that matches the container size. The container must
4479// support both size() and size_type which all STL-like containers provide.
4480// Note that the parameter 'size' can be a value of type size_type as well as
4481// matcher. For instance:
4482// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
4483// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
4484template <typename SizeMatcher>
4485inline internal::SizeIsMatcher<SizeMatcher>
4486SizeIs(const SizeMatcher& size_matcher) {
4487 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4488}
4489
kosakb6a34882014-03-12 21:06:46 +00004490// Returns a matcher that matches the distance between the container's begin()
4491// iterator and its end() iterator, i.e. the size of the container. This matcher
4492// can be used instead of SizeIs with containers such as std::forward_list which
4493// do not implement size(). The container must provide const_iterator (with
4494// valid iterator_traits), begin() and end().
4495template <typename DistanceMatcher>
4496inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4497BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4498 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4499}
4500
zhanyong.wan6a896b52009-01-16 01:13:50 +00004501// Returns a matcher that matches an equal container.
4502// This matcher behaves like Eq(), but in the event of mismatch lists the
4503// values that are included in one container but not the other. (Duplicate
4504// values and order differences are not explained.)
4505template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00004506inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00004507 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004508 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00004509 // This following line is for working around a bug in MSVC 8.0,
4510 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00004511 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00004512 return MakePolymorphicMatcher(
4513 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00004514}
4515
zhanyong.wan898725c2011-09-16 16:45:39 +00004516// Returns a matcher that matches a container that, when sorted using
4517// the given comparator, matches container_matcher.
4518template <typename Comparator, typename ContainerMatcher>
4519inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4520WhenSortedBy(const Comparator& comparator,
4521 const ContainerMatcher& container_matcher) {
4522 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4523 comparator, container_matcher);
4524}
4525
4526// Returns a matcher that matches a container that, when sorted using
4527// the < operator, matches container_matcher.
4528template <typename ContainerMatcher>
4529inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4530WhenSorted(const ContainerMatcher& container_matcher) {
4531 return
4532 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4533 internal::LessComparator(), container_matcher);
4534}
4535
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004536// Matches an STL-style container or a native array that contains the
4537// same number of elements as in rhs, where its i-th element and rhs's
4538// i-th element (as a pair) satisfy the given pair matcher, for all i.
4539// TupleMatcher must be able to be safely cast to Matcher<tuple<const
4540// T1&, const T2&> >, where T1 and T2 are the types of elements in the
4541// LHS container and the RHS container respectively.
4542template <typename TupleMatcher, typename Container>
4543inline internal::PointwiseMatcher<TupleMatcher,
4544 GTEST_REMOVE_CONST_(Container)>
4545Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4546 // This following line is for working around a bug in MSVC 8.0,
kosak2336e9c2014-07-28 22:57:30 +00004547 // which causes Container to be a const type sometimes (e.g. when
4548 // rhs is a const int[])..
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004549 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4550 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4551 tuple_matcher, rhs);
4552}
4553
kosak2336e9c2014-07-28 22:57:30 +00004554#if GTEST_HAS_STD_INITIALIZER_LIST_
4555
4556// Supports the Pointwise(m, {a, b, c}) syntax.
4557template <typename TupleMatcher, typename T>
4558inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4559 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4560 return Pointwise(tuple_matcher, std::vector<T>(rhs));
4561}
4562
4563#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4564
4565// UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4566// container or a native array that contains the same number of
4567// elements as in rhs, where in some permutation of the container, its
4568// i-th element and rhs's i-th element (as a pair) satisfy the given
4569// pair matcher, for all i. Tuple2Matcher must be able to be safely
4570// cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4571// the types of elements in the LHS container and the RHS container
4572// respectively.
4573//
4574// This is like Pointwise(pair_matcher, rhs), except that the element
4575// order doesn't matter.
4576template <typename Tuple2Matcher, typename RhsContainer>
4577inline internal::UnorderedElementsAreArrayMatcher<
4578 typename internal::BoundSecondMatcher<
4579 Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4580 RhsContainer)>::type::value_type> >
4581UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4582 const RhsContainer& rhs_container) {
4583 // This following line is for working around a bug in MSVC 8.0,
4584 // which causes RhsContainer to be a const type sometimes (e.g. when
4585 // rhs_container is a const int[]).
4586 typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4587
4588 // RhsView allows the same code to handle RhsContainer being a
4589 // STL-style container and it being a native C-style array.
4590 typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4591 typedef typename RhsView::type RhsStlContainer;
4592 typedef typename RhsStlContainer::value_type Second;
4593 const RhsStlContainer& rhs_stl_container =
4594 RhsView::ConstReference(rhs_container);
4595
4596 // Create a matcher for each element in rhs_container.
4597 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4598 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4599 it != rhs_stl_container.end(); ++it) {
4600 matchers.push_back(
4601 internal::MatcherBindSecond(tuple2_matcher, *it));
4602 }
4603
4604 // Delegate the work to UnorderedElementsAreArray().
4605 return UnorderedElementsAreArray(matchers);
4606}
4607
4608#if GTEST_HAS_STD_INITIALIZER_LIST_
4609
4610// Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4611template <typename Tuple2Matcher, typename T>
4612inline internal::UnorderedElementsAreArrayMatcher<
4613 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4614UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4615 std::initializer_list<T> rhs) {
4616 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4617}
4618
4619#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4620
zhanyong.wanb8243162009-06-04 05:48:20 +00004621// Matches an STL-style container or a native array that contains at
4622// least one element matching the given value or matcher.
4623//
4624// Examples:
4625// ::std::set<int> page_ids;
4626// page_ids.insert(3);
4627// page_ids.insert(1);
4628// EXPECT_THAT(page_ids, Contains(1));
4629// EXPECT_THAT(page_ids, Contains(Gt(2)));
4630// EXPECT_THAT(page_ids, Not(Contains(4)));
4631//
4632// ::std::map<int, size_t> page_lengths;
4633// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00004634// EXPECT_THAT(page_lengths,
4635// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004636//
4637// const char* user_ids[] = { "joe", "mike", "tom" };
4638// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4639template <typename M>
4640inline internal::ContainsMatcher<M> Contains(M matcher) {
4641 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004642}
4643
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004644// IsSupersetOf(iterator_first, iterator_last)
4645// IsSupersetOf(pointer, count)
4646// IsSupersetOf(array)
4647// IsSupersetOf(container)
4648// IsSupersetOf({e1, e2, ..., en})
4649//
4650// IsSupersetOf() verifies that a surjective partial mapping onto a collection
4651// of matchers exists. In other words, a container matches
4652// IsSupersetOf({e1, ..., en}) if and only if there is a permutation
4653// {y1, ..., yn} of some of the container's elements where y1 matches e1,
4654// ..., and yn matches en. Obviously, the size of the container must be >= n
4655// in order to have a match. Examples:
4656//
4657// - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and
4658// 1 matches Ne(0).
4659// - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches
4660// both Eq(1) and Lt(2). The reason is that different matchers must be used
4661// for elements in different slots of the container.
4662// - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches
4663// Eq(1) and (the second) 1 matches Lt(2).
4664// - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)
4665// Gt(1) and 3 matches (the second) Gt(1).
4666//
4667// The matchers can be specified as an array, a pointer and count, a container,
4668// an initializer list, or an STL iterator range. In each of these cases, the
4669// underlying matchers can be either values or matchers.
4670
4671template <typename Iter>
4672inline internal::UnorderedElementsAreArrayMatcher<
4673 typename ::std::iterator_traits<Iter>::value_type>
4674IsSupersetOf(Iter first, Iter last) {
4675 typedef typename ::std::iterator_traits<Iter>::value_type T;
4676 return internal::UnorderedElementsAreArrayMatcher<T>(
4677 internal::UnorderedMatcherRequire::Superset, first, last);
4678}
4679
4680template <typename T>
4681inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
4682 const T* pointer, size_t count) {
4683 return IsSupersetOf(pointer, pointer + count);
4684}
4685
4686template <typename T, size_t N>
4687inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
4688 const T (&array)[N]) {
4689 return IsSupersetOf(array, N);
4690}
4691
4692template <typename Container>
4693inline internal::UnorderedElementsAreArrayMatcher<
4694 typename Container::value_type>
4695IsSupersetOf(const Container& container) {
4696 return IsSupersetOf(container.begin(), container.end());
4697}
4698
4699#if GTEST_HAS_STD_INITIALIZER_LIST_
4700template <typename T>
4701inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
4702 ::std::initializer_list<T> xs) {
4703 return IsSupersetOf(xs.begin(), xs.end());
4704}
4705#endif
4706
4707// IsSubsetOf(iterator_first, iterator_last)
4708// IsSubsetOf(pointer, count)
4709// IsSubsetOf(array)
4710// IsSubsetOf(container)
4711// IsSubsetOf({e1, e2, ..., en})
4712//
4713// IsSubsetOf() verifies that an injective mapping onto a collection of matchers
4714// exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and
4715// only if there is a subset of matchers {m1, ..., mk} which would match the
4716// container using UnorderedElementsAre. Obviously, the size of the container
4717// must be <= n in order to have a match. Examples:
4718//
4719// - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).
4720// - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1
4721// matches Lt(0).
4722// - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both
4723// match Gt(0). The reason is that different matchers must be used for
4724// elements in different slots of the container.
4725//
4726// The matchers can be specified as an array, a pointer and count, a container,
4727// an initializer list, or an STL iterator range. In each of these cases, the
4728// underlying matchers can be either values or matchers.
4729
4730template <typename Iter>
4731inline internal::UnorderedElementsAreArrayMatcher<
4732 typename ::std::iterator_traits<Iter>::value_type>
4733IsSubsetOf(Iter first, Iter last) {
4734 typedef typename ::std::iterator_traits<Iter>::value_type T;
4735 return internal::UnorderedElementsAreArrayMatcher<T>(
4736 internal::UnorderedMatcherRequire::Subset, first, last);
4737}
4738
4739template <typename T>
4740inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
4741 const T* pointer, size_t count) {
4742 return IsSubsetOf(pointer, pointer + count);
4743}
4744
4745template <typename T, size_t N>
4746inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
4747 const T (&array)[N]) {
4748 return IsSubsetOf(array, N);
4749}
4750
4751template <typename Container>
4752inline internal::UnorderedElementsAreArrayMatcher<
4753 typename Container::value_type>
4754IsSubsetOf(const Container& container) {
4755 return IsSubsetOf(container.begin(), container.end());
4756}
4757
4758#if GTEST_HAS_STD_INITIALIZER_LIST_
4759template <typename T>
4760inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
4761 ::std::initializer_list<T> xs) {
4762 return IsSubsetOf(xs.begin(), xs.end());
4763}
4764#endif
4765
zhanyong.wan33605ba2010-04-22 23:37:47 +00004766// Matches an STL-style container or a native array that contains only
4767// elements matching the given value or matcher.
4768//
4769// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
4770// the messages are different.
4771//
4772// Examples:
4773// ::std::set<int> page_ids;
4774// // Each(m) matches an empty container, regardless of what m is.
4775// EXPECT_THAT(page_ids, Each(Eq(1)));
4776// EXPECT_THAT(page_ids, Each(Eq(77)));
4777//
4778// page_ids.insert(3);
4779// EXPECT_THAT(page_ids, Each(Gt(0)));
4780// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
4781// page_ids.insert(1);
4782// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
4783//
4784// ::std::map<int, size_t> page_lengths;
4785// page_lengths[1] = 100;
4786// page_lengths[2] = 200;
4787// page_lengths[3] = 300;
4788// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
4789// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
4790//
4791// const char* user_ids[] = { "joe", "mike", "tom" };
4792// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
4793template <typename M>
4794inline internal::EachMatcher<M> Each(M matcher) {
4795 return internal::EachMatcher<M>(matcher);
4796}
4797
zhanyong.wanb5937da2009-07-16 20:26:41 +00004798// Key(inner_matcher) matches an std::pair whose 'first' field matches
4799// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
4800// std::map that contains at least one element whose key is >= 5.
4801template <typename M>
4802inline internal::KeyMatcher<M> Key(M inner_matcher) {
4803 return internal::KeyMatcher<M>(inner_matcher);
4804}
4805
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00004806// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
4807// matches first_matcher and whose 'second' field matches second_matcher. For
4808// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
4809// to match a std::map<int, string> that contains exactly one element whose key
4810// is >= 5 and whose value equals "foo".
4811template <typename FirstMatcher, typename SecondMatcher>
4812inline internal::PairMatcher<FirstMatcher, SecondMatcher>
4813Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
4814 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
4815 first_matcher, second_matcher);
4816}
4817
shiqiane35fdd92008-12-10 05:08:54 +00004818// Returns a predicate that is satisfied by anything that matches the
4819// given matcher.
4820template <typename M>
4821inline internal::MatcherAsPredicate<M> Matches(M matcher) {
4822 return internal::MatcherAsPredicate<M>(matcher);
4823}
4824
zhanyong.wanb8243162009-06-04 05:48:20 +00004825// Returns true iff the value matches the matcher.
4826template <typename T, typename M>
4827inline bool Value(const T& value, M matcher) {
4828 return testing::Matches(matcher)(value);
4829}
4830
zhanyong.wan34b034c2010-03-05 21:23:23 +00004831// Matches the value against the given matcher and explains the match
4832// result to listener.
4833template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00004834inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00004835 M matcher, const T& value, MatchResultListener* listener) {
4836 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
4837}
4838
zhanyong.wan616180e2013-06-18 18:49:51 +00004839#if GTEST_LANG_CXX11
4840// Define variadic matcher versions. They are overloaded in
4841// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
4842template <typename... Args>
4843inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
4844 return internal::AllOfMatcher<Args...>(matchers...);
4845}
4846
4847template <typename... Args>
4848inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
4849 return internal::AnyOfMatcher<Args...>(matchers...);
4850}
4851
4852#endif // GTEST_LANG_CXX11
4853
zhanyong.wanbf550852009-06-09 06:09:53 +00004854// AllArgs(m) is a synonym of m. This is useful in
4855//
4856// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
4857//
4858// which is easier to read than
4859//
4860// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
4861template <typename InnerMatcher>
4862inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
4863
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05004864// Returns a matcher that matches the value of a variant<> type variable.
4865// The matcher implementation uses ADL to find the holds_alternative and get
4866// functions.
4867// It is compatible with std::variant.
4868template <typename T>
4869PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
4870 const Matcher<const T&>& matcher) {
4871 return MakePolymorphicMatcher(
4872 internal::variant_matcher::VariantMatcher<T>(matcher));
4873}
4874
shiqiane35fdd92008-12-10 05:08:54 +00004875// These macros allow using matchers to check values in Google Test
4876// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
4877// succeed iff the value matches the matcher. If the assertion fails,
4878// the value and the description of the matcher will be printed.
4879#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
4880 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4881#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
4882 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4883
4884} // namespace testing
4885
kosak6702b972015-07-27 23:05:57 +00004886// Include any custom callback matchers added by the local installation.
4887// We must include this header at the end to make sure it can use the
4888// declarations from this file.
4889#include "gmock/internal/custom/gmock-matchers.h"
shiqiane35fdd92008-12-10 05:08:54 +00004890#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_