blob: db154743a0b6a87af99e321e9786976478604fdc [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 {
Gennadiy Civilb907c262018-03-23 11:42:41 -0400654#if GTEST_LANG_CXX11
655 using FromType = typename std::remove_cv<typename std::remove_pointer<
656 typename std::remove_reference<T>::type>::type>::type;
657 using ToType = typename std::remove_cv<typename std::remove_pointer<
658 typename std::remove_reference<U>::type>::type>::type;
659 // Do not allow implicitly converting base*/& to derived*/&.
660 static_assert(
661 // Do not trigger if only one of them is a pointer. That implies a
662 // regular conversion and not a down_cast.
663 (std::is_pointer<typename std::remove_reference<T>::type>::value !=
664 std::is_pointer<typename std::remove_reference<U>::type>::value) ||
665 std::is_same<FromType, ToType>::value ||
666 !std::is_base_of<FromType, ToType>::value,
667 "Can't implicitly convert from <base> to <derived>");
668#endif // GTEST_LANG_CXX11
669
jgm79a367e2012-04-10 16:02:11 +0000670 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
671 }
672
673 virtual void DescribeTo(::std::ostream* os) const {
674 source_matcher_.DescribeTo(os);
675 }
676
677 virtual void DescribeNegationTo(::std::ostream* os) const {
678 source_matcher_.DescribeNegationTo(os);
679 }
680
681 private:
682 const Matcher<U> source_matcher_;
683
684 GTEST_DISALLOW_ASSIGN_(Impl);
685 };
686};
687
688// This even more specialized version is used for efficiently casting
689// a matcher to its own type.
690template <typename T>
691class MatcherCastImpl<T, Matcher<T> > {
692 public:
693 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
694};
695
696} // namespace internal
697
shiqiane35fdd92008-12-10 05:08:54 +0000698// In order to be safe and clear, casting between different matcher
699// types is done explicitly via MatcherCast<T>(m), which takes a
700// matcher m and returns a Matcher<T>. It compiles only when T can be
701// statically converted to the argument type of m.
702template <typename T, typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000703inline Matcher<T> MatcherCast(const M& matcher) {
jgm79a367e2012-04-10 16:02:11 +0000704 return internal::MatcherCastImpl<T, M>::Cast(matcher);
705}
shiqiane35fdd92008-12-10 05:08:54 +0000706
zhanyong.wan18490652009-05-11 18:54:08 +0000707// Implements SafeMatcherCast().
708//
zhanyong.wan95b12332009-09-25 18:55:50 +0000709// We use an intermediate class to do the actual safe casting as Nokia's
710// Symbian compiler cannot decide between
711// template <T, M> ... (M) and
712// template <T, U> ... (const Matcher<U>&)
713// for function templates but can for member function templates.
714template <typename T>
715class SafeMatcherCastImpl {
716 public:
jgm79a367e2012-04-10 16:02:11 +0000717 // This overload handles polymorphic matchers and values only since
718 // monomorphic matchers are handled by the next one.
zhanyong.wan95b12332009-09-25 18:55:50 +0000719 template <typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000720 static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
jgm79a367e2012-04-10 16:02:11 +0000721 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
zhanyong.wan95b12332009-09-25 18:55:50 +0000722 }
zhanyong.wan18490652009-05-11 18:54:08 +0000723
zhanyong.wan95b12332009-09-25 18:55:50 +0000724 // This overload handles monomorphic matchers.
725 //
726 // In general, if type T can be implicitly converted to type U, we can
727 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
728 // contravariant): just keep a copy of the original Matcher<U>, convert the
729 // argument from type T to U, and then pass it to the underlying Matcher<U>.
730 // The only exception is when U is a reference and T is not, as the
731 // underlying Matcher<U> may be interested in the argument's address, which
732 // is not preserved in the conversion from T to U.
733 template <typename U>
734 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
735 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000736 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000737 T_must_be_implicitly_convertible_to_U);
738 // Enforce that we are not converting a non-reference type T to a reference
739 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000740 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000741 internal::is_reference<T>::value || !internal::is_reference<U>::value,
Hector Dearman24054ff2017-06-19 18:27:33 +0100742 cannot_convert_non_reference_arg_to_reference);
zhanyong.wan95b12332009-09-25 18:55:50 +0000743 // In case both T and U are arithmetic types, enforce that the
744 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000745 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
746 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000747 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
748 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000749 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000750 kTIsOther || kUIsOther ||
751 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
752 conversion_of_arithmetic_types_must_be_lossless);
753 return MatcherCast<T>(matcher);
754 }
755};
756
757template <typename T, typename M>
758inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
759 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000760}
761
shiqiane35fdd92008-12-10 05:08:54 +0000762// A<T>() returns a matcher that matches any value of type T.
763template <typename T>
764Matcher<T> A();
765
766// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
767// and MUST NOT BE USED IN USER CODE!!!
768namespace internal {
769
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000770// If the explanation is not empty, prints it to the ostream.
Nico Weber09fd5b32017-05-15 17:07:03 -0400771inline void PrintIfNotEmpty(const std::string& explanation,
zhanyong.wanfb25d532013-07-28 08:24:00 +0000772 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000773 if (explanation != "" && os != NULL) {
774 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000775 }
776}
777
zhanyong.wan736baa82010-09-27 17:44:16 +0000778// Returns true if the given type name is easy to read by a human.
779// This is used to decide whether printing the type of a value might
780// be helpful.
Nico Weber09fd5b32017-05-15 17:07:03 -0400781inline bool IsReadableTypeName(const std::string& type_name) {
zhanyong.wan736baa82010-09-27 17:44:16 +0000782 // We consider a type name readable if it's short or doesn't contain
783 // a template or function type.
784 return (type_name.length() <= 20 ||
Nico Weber09fd5b32017-05-15 17:07:03 -0400785 type_name.find_first_of("<(") == std::string::npos);
zhanyong.wan736baa82010-09-27 17:44:16 +0000786}
787
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000788// Matches the value against the given matcher, prints the value and explains
789// the match result to the listener. Returns the match result.
790// 'listener' must not be NULL.
791// Value cannot be passed by const reference, because some matchers take a
792// non-const argument.
793template <typename Value, typename T>
794bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
795 MatchResultListener* listener) {
796 if (!listener->IsInterested()) {
797 // If the listener is not interested, we do not need to construct the
798 // inner explanation.
799 return matcher.Matches(value);
800 }
801
802 StringMatchResultListener inner_listener;
803 const bool match = matcher.MatchAndExplain(value, &inner_listener);
804
805 UniversalPrint(value, listener->stream());
zhanyong.wan736baa82010-09-27 17:44:16 +0000806#if GTEST_HAS_RTTI
Nico Weber09fd5b32017-05-15 17:07:03 -0400807 const std::string& type_name = GetTypeName<Value>();
zhanyong.wan736baa82010-09-27 17:44:16 +0000808 if (IsReadableTypeName(type_name))
809 *listener->stream() << " (of type " << type_name << ")";
810#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000811 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000812
813 return match;
814}
815
shiqiane35fdd92008-12-10 05:08:54 +0000816// An internal helper class for doing compile-time loop on a tuple's
817// fields.
818template <size_t N>
819class TuplePrefix {
820 public:
821 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
822 // iff the first N fields of matcher_tuple matches the first N
823 // fields of value_tuple, respectively.
824 template <typename MatcherTuple, typename ValueTuple>
825 static bool Matches(const MatcherTuple& matcher_tuple,
826 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000827 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
828 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
829 }
830
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000831 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000832 // describes failures in matching the first N fields of matchers
833 // against the first N fields of values. If there is no failure,
834 // nothing will be streamed to os.
835 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000836 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
837 const ValueTuple& values,
838 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000839 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000840 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000841
842 // Then describes the failure (if any) in the (N - 1)-th (0-based)
843 // field.
844 typename tuple_element<N - 1, MatcherTuple>::type matcher =
845 get<N - 1>(matchers);
846 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
847 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000848 StringMatchResultListener listener;
849 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000850 // TODO(wan): include in the message the name of the parameter
851 // as used in MOCK_METHOD*() when possible.
852 *os << " Expected arg #" << N - 1 << ": ";
853 get<N - 1>(matchers).DescribeTo(os);
854 *os << "\n Actual: ";
855 // We remove the reference in type Value to prevent the
856 // universal printer from printing the address of value, which
857 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000858 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000859 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000860 internal::UniversalPrint(value, os);
861 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000862 *os << "\n";
863 }
864 }
865};
866
867// The base case.
868template <>
869class TuplePrefix<0> {
870 public:
871 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000872 static bool Matches(const MatcherTuple& /* matcher_tuple */,
873 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000874 return true;
875 }
876
877 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000878 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
879 const ValueTuple& /* values */,
880 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000881};
882
883// TupleMatches(matcher_tuple, value_tuple) returns true iff all
884// matchers in matcher_tuple match the corresponding fields in
885// value_tuple. It is a compiler error if matcher_tuple and
886// value_tuple have different number of fields or incompatible field
887// types.
888template <typename MatcherTuple, typename ValueTuple>
889bool TupleMatches(const MatcherTuple& matcher_tuple,
890 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000891 // Makes sure that matcher_tuple and value_tuple have the same
892 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000893 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000894 tuple_size<ValueTuple>::value,
895 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000896 return TuplePrefix<tuple_size<ValueTuple>::value>::
897 Matches(matcher_tuple, value_tuple);
898}
899
900// Describes failures in matching matchers against values. If there
901// is no failure, nothing will be streamed to os.
902template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000903void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
904 const ValueTuple& values,
905 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000906 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000907 matchers, values, os);
908}
909
zhanyong.wanfb25d532013-07-28 08:24:00 +0000910// TransformTupleValues and its helper.
911//
912// TransformTupleValuesHelper hides the internal machinery that
913// TransformTupleValues uses to implement a tuple traversal.
914template <typename Tuple, typename Func, typename OutIter>
915class TransformTupleValuesHelper {
916 private:
kosakbd018832014-04-02 20:30:00 +0000917 typedef ::testing::tuple_size<Tuple> TupleSize;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000918
919 public:
920 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
921 // Returns the final value of 'out' in case the caller needs it.
922 static OutIter Run(Func f, const Tuple& t, OutIter out) {
923 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
924 }
925
926 private:
927 template <typename Tup, size_t kRemainingSize>
928 struct IterateOverTuple {
929 OutIter operator() (Func f, const Tup& t, OutIter out) const {
kosakbd018832014-04-02 20:30:00 +0000930 *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
zhanyong.wanfb25d532013-07-28 08:24:00 +0000931 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
932 }
933 };
934 template <typename Tup>
935 struct IterateOverTuple<Tup, 0> {
936 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
937 return out;
938 }
939 };
940};
941
942// Successively invokes 'f(element)' on each element of the tuple 't',
943// appending each result to the 'out' iterator. Returns the final value
944// of 'out'.
945template <typename Tuple, typename Func, typename OutIter>
946OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
947 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
948}
949
shiqiane35fdd92008-12-10 05:08:54 +0000950// Implements A<T>().
951template <typename T>
952class AnyMatcherImpl : public MatcherInterface<T> {
953 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000954 virtual bool MatchAndExplain(
955 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000956 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
957 virtual void DescribeNegationTo(::std::ostream* os) const {
958 // This is mostly for completeness' safe, as it's not very useful
959 // to write Not(A<bool>()). However we cannot completely rule out
960 // such a possibility, and it doesn't hurt to be prepared.
961 *os << "never matches";
962 }
963};
964
965// Implements _, a matcher that matches any value of any
966// type. This is a polymorphic matcher, so we need a template type
967// conversion operator to make it appearing as a Matcher<T> for any
968// type T.
969class AnythingMatcher {
970 public:
971 template <typename T>
972 operator Matcher<T>() const { return A<T>(); }
973};
974
975// Implements a matcher that compares a given value with a
976// pre-supplied value using one of the ==, <=, <, etc, operators. The
977// two values being compared don't have to have the same type.
978//
979// The matcher defined here is polymorphic (for example, Eq(5) can be
980// used to match an int, a short, a double, etc). Therefore we use
981// a template type conversion operator in the implementation.
982//
shiqiane35fdd92008-12-10 05:08:54 +0000983// The following template definition assumes that the Rhs parameter is
984// a "bare" type (i.e. neither 'const T' nor 'T&').
kosak506340a2014-11-17 01:47:54 +0000985template <typename D, typename Rhs, typename Op>
986class ComparisonBase {
987 public:
988 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
989 template <typename Lhs>
990 operator Matcher<Lhs>() const {
991 return MakeMatcher(new Impl<Lhs>(rhs_));
shiqiane35fdd92008-12-10 05:08:54 +0000992 }
993
kosak506340a2014-11-17 01:47:54 +0000994 private:
995 template <typename Lhs>
996 class Impl : public MatcherInterface<Lhs> {
997 public:
998 explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
999 virtual bool MatchAndExplain(
1000 Lhs lhs, MatchResultListener* /* listener */) const {
1001 return Op()(lhs, rhs_);
1002 }
1003 virtual void DescribeTo(::std::ostream* os) const {
1004 *os << D::Desc() << " ";
1005 UniversalPrint(rhs_, os);
1006 }
1007 virtual void DescribeNegationTo(::std::ostream* os) const {
1008 *os << D::NegatedDesc() << " ";
1009 UniversalPrint(rhs_, os);
1010 }
1011 private:
1012 Rhs rhs_;
1013 GTEST_DISALLOW_ASSIGN_(Impl);
1014 };
1015 Rhs rhs_;
1016 GTEST_DISALLOW_ASSIGN_(ComparisonBase);
1017};
shiqiane35fdd92008-12-10 05:08:54 +00001018
kosak506340a2014-11-17 01:47:54 +00001019template <typename Rhs>
1020class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
1021 public:
1022 explicit EqMatcher(const Rhs& rhs)
1023 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
1024 static const char* Desc() { return "is equal to"; }
1025 static const char* NegatedDesc() { return "isn't equal to"; }
1026};
1027template <typename Rhs>
1028class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
1029 public:
1030 explicit NeMatcher(const Rhs& rhs)
1031 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
1032 static const char* Desc() { return "isn't equal to"; }
1033 static const char* NegatedDesc() { return "is equal to"; }
1034};
1035template <typename Rhs>
1036class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
1037 public:
1038 explicit LtMatcher(const Rhs& rhs)
1039 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
1040 static const char* Desc() { return "is <"; }
1041 static const char* NegatedDesc() { return "isn't <"; }
1042};
1043template <typename Rhs>
1044class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
1045 public:
1046 explicit GtMatcher(const Rhs& rhs)
1047 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
1048 static const char* Desc() { return "is >"; }
1049 static const char* NegatedDesc() { return "isn't >"; }
1050};
1051template <typename Rhs>
1052class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
1053 public:
1054 explicit LeMatcher(const Rhs& rhs)
1055 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
1056 static const char* Desc() { return "is <="; }
1057 static const char* NegatedDesc() { return "isn't <="; }
1058};
1059template <typename Rhs>
1060class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
1061 public:
1062 explicit GeMatcher(const Rhs& rhs)
1063 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
1064 static const char* Desc() { return "is >="; }
1065 static const char* NegatedDesc() { return "isn't >="; }
1066};
shiqiane35fdd92008-12-10 05:08:54 +00001067
vladlosev79b83502009-11-18 00:43:37 +00001068// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001069// pointer that is NULL.
1070class IsNullMatcher {
1071 public:
vladlosev79b83502009-11-18 00:43:37 +00001072 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +00001073 bool MatchAndExplain(const Pointer& p,
1074 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001075#if GTEST_LANG_CXX11
1076 return p == nullptr;
1077#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001078 return GetRawPointer(p) == NULL;
kosak6305ff52015-04-28 22:36:31 +00001079#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001080 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001081
1082 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
1083 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001084 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001085 }
1086};
1087
vladlosev79b83502009-11-18 00:43:37 +00001088// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +00001089// pointer that is not NULL.
1090class NotNullMatcher {
1091 public:
vladlosev79b83502009-11-18 00:43:37 +00001092 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +00001093 bool MatchAndExplain(const Pointer& p,
1094 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001095#if GTEST_LANG_CXX11
1096 return p != nullptr;
1097#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001098 return GetRawPointer(p) != NULL;
kosak6305ff52015-04-28 22:36:31 +00001099#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001100 }
shiqiane35fdd92008-12-10 05:08:54 +00001101
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001102 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +00001103 void DescribeNegationTo(::std::ostream* os) const {
1104 *os << "is NULL";
1105 }
1106};
1107
1108// Ref(variable) matches any argument that is a reference to
1109// 'variable'. This matcher is polymorphic as it can match any
1110// super type of the type of 'variable'.
1111//
1112// The RefMatcher template class implements Ref(variable). It can
1113// only be instantiated with a reference type. This prevents a user
1114// from mistakenly using Ref(x) to match a non-reference function
1115// argument. For example, the following will righteously cause a
1116// compiler error:
1117//
1118// int n;
1119// Matcher<int> m1 = Ref(n); // This won't compile.
1120// Matcher<int&> m2 = Ref(n); // This will compile.
1121template <typename T>
1122class RefMatcher;
1123
1124template <typename T>
1125class RefMatcher<T&> {
1126 // Google Mock is a generic framework and thus needs to support
1127 // mocking any function types, including those that take non-const
1128 // reference arguments. Therefore the template parameter T (and
1129 // Super below) can be instantiated to either a const type or a
1130 // non-const type.
1131 public:
1132 // RefMatcher() takes a T& instead of const T&, as we want the
1133 // compiler to catch using Ref(const_value) as a matcher for a
1134 // non-const reference.
1135 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
1136
1137 template <typename Super>
1138 operator Matcher<Super&>() const {
1139 // By passing object_ (type T&) to Impl(), which expects a Super&,
1140 // we make sure that Super is a super type of T. In particular,
1141 // this catches using Ref(const_value) as a matcher for a
1142 // non-const reference, as you cannot implicitly convert a const
1143 // reference to a non-const reference.
1144 return MakeMatcher(new Impl<Super>(object_));
1145 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001146
shiqiane35fdd92008-12-10 05:08:54 +00001147 private:
1148 template <typename Super>
1149 class Impl : public MatcherInterface<Super&> {
1150 public:
1151 explicit Impl(Super& x) : object_(x) {} // NOLINT
1152
zhanyong.wandb22c222010-01-28 21:52:29 +00001153 // MatchAndExplain() takes a Super& (as opposed to const Super&)
1154 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +00001155 virtual bool MatchAndExplain(
1156 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001157 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +00001158 return &x == &object_;
1159 }
shiqiane35fdd92008-12-10 05:08:54 +00001160
1161 virtual void DescribeTo(::std::ostream* os) const {
1162 *os << "references the variable ";
1163 UniversalPrinter<Super&>::Print(object_, os);
1164 }
1165
1166 virtual void DescribeNegationTo(::std::ostream* os) const {
1167 *os << "does not reference the variable ";
1168 UniversalPrinter<Super&>::Print(object_, os);
1169 }
1170
shiqiane35fdd92008-12-10 05:08:54 +00001171 private:
1172 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001173
1174 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001175 };
1176
1177 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001178
1179 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001180};
1181
1182// Polymorphic helper functions for narrow and wide string matchers.
1183inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1184 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1185}
1186
1187inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1188 const wchar_t* rhs) {
1189 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1190}
1191
1192// String comparison for narrow or wide strings that can have embedded NUL
1193// characters.
1194template <typename StringType>
1195bool CaseInsensitiveStringEquals(const StringType& s1,
1196 const StringType& s2) {
1197 // Are the heads equal?
1198 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1199 return false;
1200 }
1201
1202 // Skip the equal heads.
1203 const typename StringType::value_type nul = 0;
1204 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1205
1206 // Are we at the end of either s1 or s2?
1207 if (i1 == StringType::npos || i2 == StringType::npos) {
1208 return i1 == i2;
1209 }
1210
1211 // Are the tails equal?
1212 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1213}
1214
1215// String matchers.
1216
1217// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1218template <typename StringType>
1219class StrEqualityMatcher {
1220 public:
shiqiane35fdd92008-12-10 05:08:54 +00001221 StrEqualityMatcher(const StringType& str, bool expect_eq,
1222 bool case_sensitive)
1223 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1224
jgm38513a82012-11-15 15:50:36 +00001225 // Accepts pointer types, particularly:
1226 // const char*
1227 // char*
1228 // const wchar_t*
1229 // wchar_t*
1230 template <typename CharType>
1231 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001232 if (s == NULL) {
1233 return !expect_eq_;
1234 }
zhanyong.wandb22c222010-01-28 21:52:29 +00001235 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001236 }
1237
jgm38513a82012-11-15 15:50:36 +00001238 // Matches anything that can convert to StringType.
1239 //
1240 // This is a template, not just a plain function with const StringType&,
1241 // because StringPiece has some interfering non-explicit constructors.
1242 template <typename MatcheeStringType>
1243 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001244 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001245 const StringType& s2(s);
1246 const bool eq = case_sensitive_ ? s2 == string_ :
1247 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +00001248 return expect_eq_ == eq;
1249 }
1250
1251 void DescribeTo(::std::ostream* os) const {
1252 DescribeToHelper(expect_eq_, os);
1253 }
1254
1255 void DescribeNegationTo(::std::ostream* os) const {
1256 DescribeToHelper(!expect_eq_, os);
1257 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001258
shiqiane35fdd92008-12-10 05:08:54 +00001259 private:
1260 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001261 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +00001262 *os << "equal to ";
1263 if (!case_sensitive_) {
1264 *os << "(ignoring case) ";
1265 }
vladloseve2e8ba42010-05-13 18:16:03 +00001266 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001267 }
1268
1269 const StringType string_;
1270 const bool expect_eq_;
1271 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001272
1273 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001274};
1275
1276// Implements the polymorphic HasSubstr(substring) matcher, which
1277// can be used as a Matcher<T> as long as T can be converted to a
1278// string.
1279template <typename StringType>
1280class HasSubstrMatcher {
1281 public:
shiqiane35fdd92008-12-10 05:08:54 +00001282 explicit HasSubstrMatcher(const StringType& substring)
1283 : substring_(substring) {}
1284
jgm38513a82012-11-15 15:50:36 +00001285 // Accepts pointer types, particularly:
1286 // const char*
1287 // char*
1288 // const wchar_t*
1289 // wchar_t*
1290 template <typename CharType>
1291 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001292 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001293 }
1294
jgm38513a82012-11-15 15:50:36 +00001295 // Matches anything that can convert to StringType.
1296 //
1297 // This is a template, not just a plain function with const StringType&,
1298 // because StringPiece has some interfering non-explicit constructors.
1299 template <typename MatcheeStringType>
1300 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001301 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001302 const StringType& s2(s);
1303 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001304 }
1305
1306 // Describes what this matcher matches.
1307 void DescribeTo(::std::ostream* os) const {
1308 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001309 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001310 }
1311
1312 void DescribeNegationTo(::std::ostream* os) const {
1313 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001314 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001315 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001316
shiqiane35fdd92008-12-10 05:08:54 +00001317 private:
1318 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001319
1320 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001321};
1322
1323// Implements the polymorphic StartsWith(substring) matcher, which
1324// can be used as a Matcher<T> as long as T can be converted to a
1325// string.
1326template <typename StringType>
1327class StartsWithMatcher {
1328 public:
shiqiane35fdd92008-12-10 05:08:54 +00001329 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1330 }
1331
jgm38513a82012-11-15 15:50:36 +00001332 // Accepts pointer types, particularly:
1333 // const char*
1334 // char*
1335 // const wchar_t*
1336 // wchar_t*
1337 template <typename CharType>
1338 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001339 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001340 }
1341
jgm38513a82012-11-15 15:50:36 +00001342 // Matches anything that can convert to StringType.
1343 //
1344 // This is a template, not just a plain function with const StringType&,
1345 // because StringPiece has some interfering non-explicit constructors.
1346 template <typename MatcheeStringType>
1347 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001348 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001349 const StringType& s2(s);
1350 return s2.length() >= prefix_.length() &&
1351 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001352 }
1353
1354 void DescribeTo(::std::ostream* os) const {
1355 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001356 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001357 }
1358
1359 void DescribeNegationTo(::std::ostream* os) const {
1360 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001361 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001362 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001363
shiqiane35fdd92008-12-10 05:08:54 +00001364 private:
1365 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001366
1367 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001368};
1369
1370// Implements the polymorphic EndsWith(substring) matcher, which
1371// can be used as a Matcher<T> as long as T can be converted to a
1372// string.
1373template <typename StringType>
1374class EndsWithMatcher {
1375 public:
shiqiane35fdd92008-12-10 05:08:54 +00001376 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1377
jgm38513a82012-11-15 15:50:36 +00001378 // Accepts pointer types, particularly:
1379 // const char*
1380 // char*
1381 // const wchar_t*
1382 // wchar_t*
1383 template <typename CharType>
1384 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001385 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001386 }
1387
jgm38513a82012-11-15 15:50:36 +00001388 // Matches anything that can convert to StringType.
1389 //
1390 // This is a template, not just a plain function with const StringType&,
1391 // because StringPiece has some interfering non-explicit constructors.
1392 template <typename MatcheeStringType>
1393 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001394 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001395 const StringType& s2(s);
1396 return s2.length() >= suffix_.length() &&
1397 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001398 }
1399
1400 void DescribeTo(::std::ostream* os) const {
1401 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001402 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001403 }
1404
1405 void DescribeNegationTo(::std::ostream* os) const {
1406 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001407 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001408 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001409
shiqiane35fdd92008-12-10 05:08:54 +00001410 private:
1411 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001412
1413 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001414};
1415
shiqiane35fdd92008-12-10 05:08:54 +00001416// Implements polymorphic matchers MatchesRegex(regex) and
1417// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1418// T can be converted to a string.
1419class MatchesRegexMatcher {
1420 public:
1421 MatchesRegexMatcher(const RE* regex, bool full_match)
1422 : regex_(regex), full_match_(full_match) {}
1423
jgm38513a82012-11-15 15:50:36 +00001424 // Accepts pointer types, particularly:
1425 // const char*
1426 // char*
1427 // const wchar_t*
1428 // wchar_t*
1429 template <typename CharType>
1430 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001431 return s != NULL && MatchAndExplain(std::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001432 }
1433
Nico Weber09fd5b32017-05-15 17:07:03 -04001434 // Matches anything that can convert to std::string.
jgm38513a82012-11-15 15:50:36 +00001435 //
Nico Weber09fd5b32017-05-15 17:07:03 -04001436 // This is a template, not just a plain function with const std::string&,
Gennadiy Civilb7c56832018-03-22 15:35:37 -04001437 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001438 template <class MatcheeStringType>
1439 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001440 MatchResultListener* /* listener */) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001441 const std::string& s2(s);
jgm38513a82012-11-15 15:50:36 +00001442 return full_match_ ? RE::FullMatch(s2, *regex_) :
1443 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001444 }
1445
1446 void DescribeTo(::std::ostream* os) const {
1447 *os << (full_match_ ? "matches" : "contains")
1448 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001449 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001450 }
1451
1452 void DescribeNegationTo(::std::ostream* os) const {
1453 *os << "doesn't " << (full_match_ ? "match" : "contain")
1454 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001455 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001456 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001457
shiqiane35fdd92008-12-10 05:08:54 +00001458 private:
1459 const internal::linked_ptr<const RE> regex_;
1460 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001461
1462 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001463};
1464
shiqiane35fdd92008-12-10 05:08:54 +00001465// Implements a matcher that compares the two fields of a 2-tuple
1466// using one of the ==, <=, <, etc, operators. The two fields being
1467// compared don't have to have the same type.
1468//
1469// The matcher defined here is polymorphic (for example, Eq() can be
1470// used to match a tuple<int, short>, a tuple<const long&, double>,
1471// etc). Therefore we use a template type conversion operator in the
1472// implementation.
kosak506340a2014-11-17 01:47:54 +00001473template <typename D, typename Op>
1474class PairMatchBase {
1475 public:
1476 template <typename T1, typename T2>
1477 operator Matcher< ::testing::tuple<T1, T2> >() const {
1478 return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >);
1479 }
1480 template <typename T1, typename T2>
1481 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
1482 return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>);
shiqiane35fdd92008-12-10 05:08:54 +00001483 }
1484
kosak506340a2014-11-17 01:47:54 +00001485 private:
1486 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
1487 return os << D::Desc();
1488 }
shiqiane35fdd92008-12-10 05:08:54 +00001489
kosak506340a2014-11-17 01:47:54 +00001490 template <typename Tuple>
1491 class Impl : public MatcherInterface<Tuple> {
1492 public:
1493 virtual bool MatchAndExplain(
1494 Tuple args,
1495 MatchResultListener* /* listener */) const {
1496 return Op()(::testing::get<0>(args), ::testing::get<1>(args));
1497 }
1498 virtual void DescribeTo(::std::ostream* os) const {
1499 *os << "are " << GetDesc;
1500 }
1501 virtual void DescribeNegationTo(::std::ostream* os) const {
1502 *os << "aren't " << GetDesc;
1503 }
1504 };
1505};
1506
1507class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
1508 public:
1509 static const char* Desc() { return "an equal pair"; }
1510};
1511class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
1512 public:
1513 static const char* Desc() { return "an unequal pair"; }
1514};
1515class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
1516 public:
1517 static const char* Desc() { return "a pair where the first < the second"; }
1518};
1519class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
1520 public:
1521 static const char* Desc() { return "a pair where the first > the second"; }
1522};
1523class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
1524 public:
1525 static const char* Desc() { return "a pair where the first <= the second"; }
1526};
1527class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
1528 public:
1529 static const char* Desc() { return "a pair where the first >= the second"; }
1530};
shiqiane35fdd92008-12-10 05:08:54 +00001531
zhanyong.wanc6a41232009-05-13 23:38:40 +00001532// Implements the Not(...) matcher for a particular argument type T.
1533// We do not nest it inside the NotMatcher class template, as that
1534// will prevent different instantiations of NotMatcher from sharing
1535// the same NotMatcherImpl<T> class.
1536template <typename T>
1537class NotMatcherImpl : public MatcherInterface<T> {
1538 public:
1539 explicit NotMatcherImpl(const Matcher<T>& matcher)
1540 : matcher_(matcher) {}
1541
zhanyong.wan82113312010-01-08 21:55:40 +00001542 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1543 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001544 }
1545
1546 virtual void DescribeTo(::std::ostream* os) const {
1547 matcher_.DescribeNegationTo(os);
1548 }
1549
1550 virtual void DescribeNegationTo(::std::ostream* os) const {
1551 matcher_.DescribeTo(os);
1552 }
1553
zhanyong.wanc6a41232009-05-13 23:38:40 +00001554 private:
1555 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001556
1557 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001558};
1559
shiqiane35fdd92008-12-10 05:08:54 +00001560// Implements the Not(m) matcher, which matches a value that doesn't
1561// match matcher m.
1562template <typename InnerMatcher>
1563class NotMatcher {
1564 public:
1565 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1566
1567 // This template type conversion operator allows Not(m) to be used
1568 // to match any type m can match.
1569 template <typename T>
1570 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001571 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001572 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001573
shiqiane35fdd92008-12-10 05:08:54 +00001574 private:
shiqiane35fdd92008-12-10 05:08:54 +00001575 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001576
1577 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001578};
1579
zhanyong.wanc6a41232009-05-13 23:38:40 +00001580// Implements the AllOf(m1, m2) matcher for a particular argument type
1581// T. We do not nest it inside the BothOfMatcher class template, as
1582// that will prevent different instantiations of BothOfMatcher from
1583// sharing the same BothOfMatcherImpl<T> class.
1584template <typename T>
1585class BothOfMatcherImpl : public MatcherInterface<T> {
1586 public:
1587 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1588 : matcher1_(matcher1), matcher2_(matcher2) {}
1589
zhanyong.wanc6a41232009-05-13 23:38:40 +00001590 virtual void DescribeTo(::std::ostream* os) const {
1591 *os << "(";
1592 matcher1_.DescribeTo(os);
1593 *os << ") and (";
1594 matcher2_.DescribeTo(os);
1595 *os << ")";
1596 }
1597
1598 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001599 *os << "(";
1600 matcher1_.DescribeNegationTo(os);
1601 *os << ") or (";
1602 matcher2_.DescribeNegationTo(os);
1603 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001604 }
1605
zhanyong.wan82113312010-01-08 21:55:40 +00001606 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1607 // If either matcher1_ or matcher2_ doesn't match x, we only need
1608 // to explain why one of them fails.
1609 StringMatchResultListener listener1;
1610 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1611 *listener << listener1.str();
1612 return false;
1613 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001614
zhanyong.wan82113312010-01-08 21:55:40 +00001615 StringMatchResultListener listener2;
1616 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1617 *listener << listener2.str();
1618 return false;
1619 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001620
zhanyong.wan82113312010-01-08 21:55:40 +00001621 // Otherwise we need to explain why *both* of them match.
Nico Weber09fd5b32017-05-15 17:07:03 -04001622 const std::string s1 = listener1.str();
1623 const std::string s2 = listener2.str();
zhanyong.wan82113312010-01-08 21:55:40 +00001624
1625 if (s1 == "") {
1626 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001627 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001628 *listener << s1;
1629 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001630 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001631 }
1632 }
zhanyong.wan82113312010-01-08 21:55:40 +00001633 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001634 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001635
zhanyong.wanc6a41232009-05-13 23:38:40 +00001636 private:
1637 const Matcher<T> matcher1_;
1638 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001639
1640 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001641};
1642
zhanyong.wan616180e2013-06-18 18:49:51 +00001643#if GTEST_LANG_CXX11
1644// MatcherList provides mechanisms for storing a variable number of matchers in
1645// a list structure (ListType) and creating a combining matcher from such a
1646// list.
Troy Holsapplec8510502018-02-07 22:06:00 -08001647// The template is defined recursively using the following template parameters:
zhanyong.wan616180e2013-06-18 18:49:51 +00001648// * kSize is the length of the MatcherList.
1649// * Head is the type of the first matcher of the list.
1650// * Tail denotes the types of the remaining matchers of the list.
1651template <int kSize, typename Head, typename... Tail>
1652struct MatcherList {
1653 typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
zhanyong.wan29897032013-06-20 18:59:15 +00001654 typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001655
1656 // BuildList stores variadic type values in a nested pair structure.
1657 // Example:
1658 // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
1659 // the corresponding result of type pair<int, pair<string, float>>.
1660 static ListType BuildList(const Head& matcher, const Tail&... tail) {
1661 return ListType(matcher, MatcherListTail::BuildList(tail...));
1662 }
1663
1664 // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
1665 // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
1666 // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
1667 // constructor taking two Matcher<T>s as input.
1668 template <typename T, template <typename /* T */> class CombiningMatcher>
1669 static Matcher<T> CreateMatcher(const ListType& matchers) {
1670 return Matcher<T>(new CombiningMatcher<T>(
1671 SafeMatcherCast<T>(matchers.first),
1672 MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
1673 matchers.second)));
1674 }
1675};
1676
1677// The following defines the base case for the recursive definition of
1678// MatcherList.
1679template <typename Matcher1, typename Matcher2>
1680struct MatcherList<2, Matcher1, Matcher2> {
zhanyong.wan29897032013-06-20 18:59:15 +00001681 typedef ::std::pair<Matcher1, Matcher2> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001682
1683 static ListType BuildList(const Matcher1& matcher1,
1684 const Matcher2& matcher2) {
zhanyong.wan29897032013-06-20 18:59:15 +00001685 return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
zhanyong.wan616180e2013-06-18 18:49:51 +00001686 }
1687
1688 template <typename T, template <typename /* T */> class CombiningMatcher>
1689 static Matcher<T> CreateMatcher(const ListType& matchers) {
1690 return Matcher<T>(new CombiningMatcher<T>(
1691 SafeMatcherCast<T>(matchers.first),
1692 SafeMatcherCast<T>(matchers.second)));
1693 }
1694};
1695
1696// VariadicMatcher is used for the variadic implementation of
1697// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1698// CombiningMatcher<T> is used to recursively combine the provided matchers
1699// (of type Args...).
1700template <template <typename T> class CombiningMatcher, typename... Args>
1701class VariadicMatcher {
1702 public:
1703 VariadicMatcher(const Args&... matchers) // NOLINT
1704 : matchers_(MatcherListType::BuildList(matchers...)) {}
1705
1706 // This template type conversion operator allows an
1707 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1708 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1709 template <typename T>
1710 operator Matcher<T>() const {
1711 return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
1712 matchers_);
1713 }
1714
1715 private:
1716 typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
1717
1718 const typename MatcherListType::ListType matchers_;
1719
1720 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1721};
1722
1723template <typename... Args>
1724using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
1725
1726#endif // GTEST_LANG_CXX11
1727
shiqiane35fdd92008-12-10 05:08:54 +00001728// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1729// matches a value that matches all of the matchers m_1, ..., and m_n.
1730template <typename Matcher1, typename Matcher2>
1731class BothOfMatcher {
1732 public:
1733 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1734 : matcher1_(matcher1), matcher2_(matcher2) {}
1735
1736 // This template type conversion operator allows a
1737 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1738 // both Matcher1 and Matcher2 can match.
1739 template <typename T>
1740 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001741 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1742 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001743 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001744
shiqiane35fdd92008-12-10 05:08:54 +00001745 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001746 Matcher1 matcher1_;
1747 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001748
1749 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001750};
shiqiane35fdd92008-12-10 05:08:54 +00001751
zhanyong.wanc6a41232009-05-13 23:38:40 +00001752// Implements the AnyOf(m1, m2) matcher for a particular argument type
1753// T. We do not nest it inside the AnyOfMatcher class template, as
1754// that will prevent different instantiations of AnyOfMatcher from
1755// sharing the same EitherOfMatcherImpl<T> class.
1756template <typename T>
1757class EitherOfMatcherImpl : public MatcherInterface<T> {
1758 public:
1759 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1760 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001761
zhanyong.wanc6a41232009-05-13 23:38:40 +00001762 virtual void DescribeTo(::std::ostream* os) const {
1763 *os << "(";
1764 matcher1_.DescribeTo(os);
1765 *os << ") or (";
1766 matcher2_.DescribeTo(os);
1767 *os << ")";
1768 }
shiqiane35fdd92008-12-10 05:08:54 +00001769
zhanyong.wanc6a41232009-05-13 23:38:40 +00001770 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001771 *os << "(";
1772 matcher1_.DescribeNegationTo(os);
1773 *os << ") and (";
1774 matcher2_.DescribeNegationTo(os);
1775 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001776 }
shiqiane35fdd92008-12-10 05:08:54 +00001777
zhanyong.wan82113312010-01-08 21:55:40 +00001778 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1779 // If either matcher1_ or matcher2_ matches x, we just need to
1780 // explain why *one* of them matches.
1781 StringMatchResultListener listener1;
1782 if (matcher1_.MatchAndExplain(x, &listener1)) {
1783 *listener << listener1.str();
1784 return true;
1785 }
1786
1787 StringMatchResultListener listener2;
1788 if (matcher2_.MatchAndExplain(x, &listener2)) {
1789 *listener << listener2.str();
1790 return true;
1791 }
1792
1793 // Otherwise we need to explain why *both* of them fail.
Nico Weber09fd5b32017-05-15 17:07:03 -04001794 const std::string s1 = listener1.str();
1795 const std::string s2 = listener2.str();
zhanyong.wan82113312010-01-08 21:55:40 +00001796
1797 if (s1 == "") {
1798 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001799 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001800 *listener << s1;
1801 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001802 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001803 }
1804 }
zhanyong.wan82113312010-01-08 21:55:40 +00001805 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001806 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001807
zhanyong.wanc6a41232009-05-13 23:38:40 +00001808 private:
1809 const Matcher<T> matcher1_;
1810 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001811
1812 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001813};
1814
zhanyong.wan616180e2013-06-18 18:49:51 +00001815#if GTEST_LANG_CXX11
1816// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1817template <typename... Args>
1818using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
1819
1820#endif // GTEST_LANG_CXX11
1821
shiqiane35fdd92008-12-10 05:08:54 +00001822// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1823// matches a value that matches at least one of the matchers m_1, ...,
1824// and m_n.
1825template <typename Matcher1, typename Matcher2>
1826class EitherOfMatcher {
1827 public:
1828 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1829 : matcher1_(matcher1), matcher2_(matcher2) {}
1830
1831 // This template type conversion operator allows a
1832 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1833 // both Matcher1 and Matcher2 can match.
1834 template <typename T>
1835 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001836 return Matcher<T>(new EitherOfMatcherImpl<T>(
1837 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001838 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001839
shiqiane35fdd92008-12-10 05:08:54 +00001840 private:
shiqiane35fdd92008-12-10 05:08:54 +00001841 Matcher1 matcher1_;
1842 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001843
1844 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001845};
1846
1847// Used for implementing Truly(pred), which turns a predicate into a
1848// matcher.
1849template <typename Predicate>
1850class TrulyMatcher {
1851 public:
1852 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1853
1854 // This method template allows Truly(pred) to be used as a matcher
1855 // for type T where T is the argument type of predicate 'pred'. The
1856 // argument is passed by reference as the predicate may be
1857 // interested in the address of the argument.
1858 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001859 bool MatchAndExplain(T& x, // NOLINT
1860 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001861 // Without the if-statement, MSVC sometimes warns about converting
1862 // a value to bool (warning 4800).
1863 //
1864 // We cannot write 'return !!predicate_(x);' as that doesn't work
1865 // when predicate_(x) returns a class convertible to bool but
1866 // having no operator!().
1867 if (predicate_(x))
1868 return true;
1869 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001870 }
1871
1872 void DescribeTo(::std::ostream* os) const {
1873 *os << "satisfies the given predicate";
1874 }
1875
1876 void DescribeNegationTo(::std::ostream* os) const {
1877 *os << "doesn't satisfy the given predicate";
1878 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001879
shiqiane35fdd92008-12-10 05:08:54 +00001880 private:
1881 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001882
1883 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001884};
1885
1886// Used for implementing Matches(matcher), which turns a matcher into
1887// a predicate.
1888template <typename M>
1889class MatcherAsPredicate {
1890 public:
1891 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1892
1893 // This template operator() allows Matches(m) to be used as a
1894 // predicate on type T where m is a matcher on type T.
1895 //
1896 // The argument x is passed by reference instead of by value, as
1897 // some matcher may be interested in its address (e.g. as in
1898 // Matches(Ref(n))(x)).
1899 template <typename T>
1900 bool operator()(const T& x) const {
1901 // We let matcher_ commit to a particular type here instead of
1902 // when the MatcherAsPredicate object was constructed. This
1903 // allows us to write Matches(m) where m is a polymorphic matcher
1904 // (e.g. Eq(5)).
1905 //
1906 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1907 // compile when matcher_ has type Matcher<const T&>; if we write
1908 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1909 // when matcher_ has type Matcher<T>; if we just write
1910 // matcher_.Matches(x), it won't compile when matcher_ is
1911 // polymorphic, e.g. Eq(5).
1912 //
1913 // MatcherCast<const T&>() is necessary for making the code work
1914 // in all of the above situations.
1915 return MatcherCast<const T&>(matcher_).Matches(x);
1916 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001917
shiqiane35fdd92008-12-10 05:08:54 +00001918 private:
1919 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001920
1921 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001922};
1923
1924// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1925// argument M must be a type that can be converted to a matcher.
1926template <typename M>
1927class PredicateFormatterFromMatcher {
1928 public:
kosak9b1a9442015-04-28 23:06:58 +00001929 explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {}
shiqiane35fdd92008-12-10 05:08:54 +00001930
1931 // This template () operator allows a PredicateFormatterFromMatcher
1932 // object to act as a predicate-formatter suitable for using with
1933 // Google Test's EXPECT_PRED_FORMAT1() macro.
1934 template <typename T>
1935 AssertionResult operator()(const char* value_text, const T& x) const {
1936 // We convert matcher_ to a Matcher<const T&> *now* instead of
1937 // when the PredicateFormatterFromMatcher object was constructed,
1938 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1939 // know which type to instantiate it to until we actually see the
1940 // type of x here.
1941 //
zhanyong.wanf4274522013-04-24 02:49:43 +00001942 // We write SafeMatcherCast<const T&>(matcher_) instead of
shiqiane35fdd92008-12-10 05:08:54 +00001943 // Matcher<const T&>(matcher_), as the latter won't compile when
1944 // matcher_ has type Matcher<T> (e.g. An<int>()).
zhanyong.wanf4274522013-04-24 02:49:43 +00001945 // We don't write MatcherCast<const T&> either, as that allows
1946 // potentially unsafe downcasting of the matcher argument.
1947 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001948 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001949 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001950 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001951
1952 ::std::stringstream ss;
1953 ss << "Value of: " << value_text << "\n"
1954 << "Expected: ";
1955 matcher.DescribeTo(&ss);
1956 ss << "\n Actual: " << listener.str();
1957 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001958 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001959
shiqiane35fdd92008-12-10 05:08:54 +00001960 private:
1961 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001962
1963 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001964};
1965
1966// A helper function for converting a matcher to a predicate-formatter
1967// without the user needing to explicitly write the type. This is
1968// used for implementing ASSERT_THAT() and EXPECT_THAT().
kosak9b1a9442015-04-28 23:06:58 +00001969// Implementation detail: 'matcher' is received by-value to force decaying.
shiqiane35fdd92008-12-10 05:08:54 +00001970template <typename M>
1971inline PredicateFormatterFromMatcher<M>
kosak9b1a9442015-04-28 23:06:58 +00001972MakePredicateFormatterFromMatcher(M matcher) {
1973 return PredicateFormatterFromMatcher<M>(internal::move(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00001974}
1975
zhanyong.wan616180e2013-06-18 18:49:51 +00001976// Implements the polymorphic floating point equality matcher, which matches
1977// two float values using ULP-based approximation or, optionally, a
1978// user-specified epsilon. The template is meant to be instantiated with
1979// FloatType being either float or double.
shiqiane35fdd92008-12-10 05:08:54 +00001980template <typename FloatType>
1981class FloatingEqMatcher {
1982 public:
1983 // Constructor for FloatingEqMatcher.
kosak6b817802015-01-08 02:38:14 +00001984 // The matcher's input will be compared with expected. The matcher treats two
shiqiane35fdd92008-12-10 05:08:54 +00001985 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
zhanyong.wan616180e2013-06-18 18:49:51 +00001986 // equality comparisons between NANs will always return false. We specify a
1987 // negative max_abs_error_ term to indicate that ULP-based approximation will
1988 // be used for comparison.
kosak6b817802015-01-08 02:38:14 +00001989 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
1990 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001991 }
1992
1993 // Constructor that supports a user-specified max_abs_error that will be used
1994 // for comparison instead of ULP-based approximation. The max absolute
1995 // should be non-negative.
kosak6b817802015-01-08 02:38:14 +00001996 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
1997 FloatType max_abs_error)
1998 : expected_(expected),
1999 nan_eq_nan_(nan_eq_nan),
2000 max_abs_error_(max_abs_error) {
zhanyong.wan616180e2013-06-18 18:49:51 +00002001 GTEST_CHECK_(max_abs_error >= 0)
2002 << ", where max_abs_error is" << max_abs_error;
2003 }
shiqiane35fdd92008-12-10 05:08:54 +00002004
2005 // Implements floating point equality matcher as a Matcher<T>.
2006 template <typename T>
2007 class Impl : public MatcherInterface<T> {
2008 public:
kosak6b817802015-01-08 02:38:14 +00002009 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
2010 : expected_(expected),
2011 nan_eq_nan_(nan_eq_nan),
2012 max_abs_error_(max_abs_error) {}
shiqiane35fdd92008-12-10 05:08:54 +00002013
zhanyong.wan82113312010-01-08 21:55:40 +00002014 virtual bool MatchAndExplain(T value,
kosak6b817802015-01-08 02:38:14 +00002015 MatchResultListener* listener) const {
2016 const FloatingPoint<FloatType> actual(value), expected(expected_);
shiqiane35fdd92008-12-10 05:08:54 +00002017
2018 // Compares NaNs first, if nan_eq_nan_ is true.
kosak6b817802015-01-08 02:38:14 +00002019 if (actual.is_nan() || expected.is_nan()) {
2020 if (actual.is_nan() && expected.is_nan()) {
zhanyong.wan616180e2013-06-18 18:49:51 +00002021 return nan_eq_nan_;
2022 }
2023 // One is nan; the other is not nan.
2024 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002025 }
zhanyong.wan616180e2013-06-18 18:49:51 +00002026 if (HasMaxAbsError()) {
2027 // We perform an equality check so that inf will match inf, regardless
kosak6b817802015-01-08 02:38:14 +00002028 // of error bounds. If the result of value - expected_ would result in
zhanyong.wan616180e2013-06-18 18:49:51 +00002029 // overflow or if either value is inf, the default result is infinity,
2030 // which should only match if max_abs_error_ is also infinity.
kosak6b817802015-01-08 02:38:14 +00002031 if (value == expected_) {
2032 return true;
2033 }
2034
2035 const FloatType diff = value - expected_;
2036 if (fabs(diff) <= max_abs_error_) {
2037 return true;
2038 }
2039
2040 if (listener->IsInterested()) {
2041 *listener << "which is " << diff << " from " << expected_;
2042 }
2043 return false;
zhanyong.wan616180e2013-06-18 18:49:51 +00002044 } else {
kosak6b817802015-01-08 02:38:14 +00002045 return actual.AlmostEquals(expected);
zhanyong.wan616180e2013-06-18 18:49:51 +00002046 }
shiqiane35fdd92008-12-10 05:08:54 +00002047 }
2048
2049 virtual void DescribeTo(::std::ostream* os) const {
2050 // os->precision() returns the previously set precision, which we
2051 // store to restore the ostream to its original configuration
2052 // after outputting.
2053 const ::std::streamsize old_precision = os->precision(
2054 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00002055 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00002056 if (nan_eq_nan_) {
2057 *os << "is NaN";
2058 } else {
2059 *os << "never matches";
2060 }
2061 } else {
kosak6b817802015-01-08 02:38:14 +00002062 *os << "is approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002063 if (HasMaxAbsError()) {
2064 *os << " (absolute error <= " << max_abs_error_ << ")";
2065 }
shiqiane35fdd92008-12-10 05:08:54 +00002066 }
2067 os->precision(old_precision);
2068 }
2069
2070 virtual void DescribeNegationTo(::std::ostream* os) const {
2071 // As before, get original precision.
2072 const ::std::streamsize old_precision = os->precision(
2073 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00002074 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00002075 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002076 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00002077 } else {
2078 *os << "is anything";
2079 }
2080 } else {
kosak6b817802015-01-08 02:38:14 +00002081 *os << "isn't approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002082 if (HasMaxAbsError()) {
2083 *os << " (absolute error > " << max_abs_error_ << ")";
2084 }
shiqiane35fdd92008-12-10 05:08:54 +00002085 }
2086 // Restore original precision.
2087 os->precision(old_precision);
2088 }
2089
2090 private:
zhanyong.wan616180e2013-06-18 18:49:51 +00002091 bool HasMaxAbsError() const {
2092 return max_abs_error_ >= 0;
2093 }
2094
kosak6b817802015-01-08 02:38:14 +00002095 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002096 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002097 // max_abs_error will be used for value comparison when >= 0.
2098 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002099
2100 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002101 };
2102
kosak6b817802015-01-08 02:38:14 +00002103 // The following 3 type conversion operators allow FloatEq(expected) and
2104 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
shiqiane35fdd92008-12-10 05:08:54 +00002105 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
2106 // (While Google's C++ coding style doesn't allow arguments passed
2107 // by non-const reference, we may see them in code not conforming to
2108 // the style. Therefore Google Mock needs to support them.)
2109 operator Matcher<FloatType>() const {
kosak6b817802015-01-08 02:38:14 +00002110 return MakeMatcher(
2111 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002112 }
2113
2114 operator Matcher<const FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00002115 return MakeMatcher(
kosak6b817802015-01-08 02:38:14 +00002116 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002117 }
2118
2119 operator Matcher<FloatType&>() const {
kosak6b817802015-01-08 02:38:14 +00002120 return MakeMatcher(
2121 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002122 }
jgm79a367e2012-04-10 16:02:11 +00002123
shiqiane35fdd92008-12-10 05:08:54 +00002124 private:
kosak6b817802015-01-08 02:38:14 +00002125 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002126 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002127 // max_abs_error will be used for value comparison when >= 0.
2128 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002129
2130 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002131};
2132
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002133// A 2-tuple ("binary") wrapper around FloatingEqMatcher:
2134// FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false)
2135// against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e)
2136// against y. The former implements "Eq", the latter "Near". At present, there
2137// is no version that compares NaNs as equal.
2138template <typename FloatType>
2139class FloatingEq2Matcher {
2140 public:
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002141 FloatingEq2Matcher() { Init(-1, false); }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002142
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002143 explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002144
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002145 explicit FloatingEq2Matcher(FloatType max_abs_error) {
2146 Init(max_abs_error, false);
2147 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002148
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002149 FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) {
2150 Init(max_abs_error, nan_eq_nan);
2151 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002152
2153 template <typename T1, typename T2>
2154 operator Matcher< ::testing::tuple<T1, T2> >() const {
2155 return MakeMatcher(
2156 new Impl< ::testing::tuple<T1, T2> >(max_abs_error_, nan_eq_nan_));
2157 }
2158 template <typename T1, typename T2>
2159 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
2160 return MakeMatcher(
2161 new Impl<const ::testing::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_));
2162 }
2163
2164 private:
2165 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
2166 return os << "an almost-equal pair";
2167 }
2168
2169 template <typename Tuple>
2170 class Impl : public MatcherInterface<Tuple> {
2171 public:
2172 Impl(FloatType max_abs_error, bool nan_eq_nan) :
2173 max_abs_error_(max_abs_error),
2174 nan_eq_nan_(nan_eq_nan) {}
2175
2176 virtual bool MatchAndExplain(Tuple args,
2177 MatchResultListener* listener) const {
2178 if (max_abs_error_ == -1) {
2179 FloatingEqMatcher<FloatType> fm(::testing::get<0>(args), nan_eq_nan_);
2180 return static_cast<Matcher<FloatType> >(fm).MatchAndExplain(
2181 ::testing::get<1>(args), listener);
2182 } else {
2183 FloatingEqMatcher<FloatType> fm(::testing::get<0>(args), nan_eq_nan_,
2184 max_abs_error_);
2185 return static_cast<Matcher<FloatType> >(fm).MatchAndExplain(
2186 ::testing::get<1>(args), listener);
2187 }
2188 }
2189 virtual void DescribeTo(::std::ostream* os) const {
2190 *os << "are " << GetDesc;
2191 }
2192 virtual void DescribeNegationTo(::std::ostream* os) const {
2193 *os << "aren't " << GetDesc;
2194 }
2195
2196 private:
2197 FloatType max_abs_error_;
2198 const bool nan_eq_nan_;
2199 };
2200
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002201 void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) {
2202 max_abs_error_ = max_abs_error_val;
2203 nan_eq_nan_ = nan_eq_nan_val;
2204 }
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002205 FloatType max_abs_error_;
Gennadiy Civil8ea10d32018-03-26 09:28:16 -04002206 bool nan_eq_nan_;
Gennadiy Civil466a49a2018-03-23 11:23:54 -04002207};
2208
shiqiane35fdd92008-12-10 05:08:54 +00002209// Implements the Pointee(m) matcher for matching a pointer whose
2210// pointee matches matcher m. The pointer can be either raw or smart.
2211template <typename InnerMatcher>
2212class PointeeMatcher {
2213 public:
2214 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
2215
2216 // This type conversion operator template allows Pointee(m) to be
2217 // used as a matcher for any pointer type whose pointee type is
2218 // compatible with the inner matcher, where type Pointer can be
2219 // either a raw pointer or a smart pointer.
2220 //
2221 // The reason we do this instead of relying on
2222 // MakePolymorphicMatcher() is that the latter is not flexible
2223 // enough for implementing the DescribeTo() method of Pointee().
2224 template <typename Pointer>
2225 operator Matcher<Pointer>() const {
2226 return MakeMatcher(new Impl<Pointer>(matcher_));
2227 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002228
shiqiane35fdd92008-12-10 05:08:54 +00002229 private:
2230 // The monomorphic implementation that works for a particular pointer type.
2231 template <typename Pointer>
2232 class Impl : public MatcherInterface<Pointer> {
2233 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00002234 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
2235 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00002236
2237 explicit Impl(const InnerMatcher& matcher)
2238 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
2239
shiqiane35fdd92008-12-10 05:08:54 +00002240 virtual void DescribeTo(::std::ostream* os) const {
2241 *os << "points to a value that ";
2242 matcher_.DescribeTo(os);
2243 }
2244
2245 virtual void DescribeNegationTo(::std::ostream* os) const {
2246 *os << "does not point to a value that ";
2247 matcher_.DescribeTo(os);
2248 }
2249
zhanyong.wan82113312010-01-08 21:55:40 +00002250 virtual bool MatchAndExplain(Pointer pointer,
2251 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00002252 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00002253 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002254
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002255 *listener << "which points to ";
2256 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002257 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002258
shiqiane35fdd92008-12-10 05:08:54 +00002259 private:
2260 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002261
2262 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002263 };
2264
2265 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002266
2267 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002268};
2269
billydonahue1f5fdea2014-05-19 17:54:51 +00002270// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2271// reference that matches inner_matcher when dynamic_cast<T> is applied.
2272// The result of dynamic_cast<To> is forwarded to the inner matcher.
2273// If To is a pointer and the cast fails, the inner matcher will receive NULL.
2274// If To is a reference and the cast fails, this matcher returns false
2275// immediately.
2276template <typename To>
2277class WhenDynamicCastToMatcherBase {
2278 public:
2279 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2280 : matcher_(matcher) {}
2281
2282 void DescribeTo(::std::ostream* os) const {
2283 GetCastTypeDescription(os);
2284 matcher_.DescribeTo(os);
2285 }
2286
2287 void DescribeNegationTo(::std::ostream* os) const {
2288 GetCastTypeDescription(os);
2289 matcher_.DescribeNegationTo(os);
2290 }
2291
2292 protected:
2293 const Matcher<To> matcher_;
2294
Nico Weber09fd5b32017-05-15 17:07:03 -04002295 static std::string GetToName() {
billydonahue1f5fdea2014-05-19 17:54:51 +00002296#if GTEST_HAS_RTTI
2297 return GetTypeName<To>();
2298#else // GTEST_HAS_RTTI
2299 return "the target type";
2300#endif // GTEST_HAS_RTTI
2301 }
2302
2303 private:
2304 static void GetCastTypeDescription(::std::ostream* os) {
2305 *os << "when dynamic_cast to " << GetToName() << ", ";
2306 }
2307
2308 GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2309};
2310
2311// Primary template.
2312// To is a pointer. Cast and forward the result.
2313template <typename To>
2314class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2315 public:
2316 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2317 : WhenDynamicCastToMatcherBase<To>(matcher) {}
2318
2319 template <typename From>
2320 bool MatchAndExplain(From from, MatchResultListener* listener) const {
2321 // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail?
2322 To to = dynamic_cast<To>(from);
2323 return MatchPrintAndExplain(to, this->matcher_, listener);
2324 }
2325};
2326
2327// Specialize for references.
2328// In this case we return false if the dynamic_cast fails.
2329template <typename To>
2330class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2331 public:
2332 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2333 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2334
2335 template <typename From>
2336 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2337 // We don't want an std::bad_cast here, so do the cast with pointers.
2338 To* to = dynamic_cast<To*>(&from);
2339 if (to == NULL) {
2340 *listener << "which cannot be dynamic_cast to " << this->GetToName();
2341 return false;
2342 }
2343 return MatchPrintAndExplain(*to, this->matcher_, listener);
2344 }
2345};
2346
shiqiane35fdd92008-12-10 05:08:54 +00002347// Implements the Field() matcher for matching a field (i.e. member
2348// variable) of an object.
2349template <typename Class, typename FieldType>
2350class FieldMatcher {
2351 public:
2352 FieldMatcher(FieldType Class::*field,
2353 const Matcher<const FieldType&>& matcher)
2354 : field_(field), matcher_(matcher) {}
2355
shiqiane35fdd92008-12-10 05:08:54 +00002356 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002357 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002358 matcher_.DescribeTo(os);
2359 }
2360
2361 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002362 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002363 matcher_.DescribeNegationTo(os);
2364 }
2365
zhanyong.wandb22c222010-01-28 21:52:29 +00002366 template <typename T>
2367 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2368 return MatchAndExplainImpl(
2369 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002370 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002371 value, listener);
2372 }
2373
2374 private:
2375 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002376 // Symbian's C++ compiler choose which overload to use. Its type is
2377 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002378 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2379 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002380 *listener << "whose given field is ";
2381 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002382 }
2383
zhanyong.wandb22c222010-01-28 21:52:29 +00002384 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2385 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002386 if (p == NULL)
2387 return false;
2388
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002389 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002390 // Since *p has a field, it must be a class/struct/union type and
2391 // thus cannot be a pointer. Therefore we pass false_type() as
2392 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002393 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002394 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002395
shiqiane35fdd92008-12-10 05:08:54 +00002396 const FieldType Class::*field_;
2397 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002398
2399 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002400};
2401
shiqiane35fdd92008-12-10 05:08:54 +00002402// Implements the Property() matcher for matching a property
2403// (i.e. return value of a getter method) of an object.
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002404//
2405// Property is a const-qualified member function of Class returning
2406// PropertyType.
2407template <typename Class, typename PropertyType, typename Property>
shiqiane35fdd92008-12-10 05:08:54 +00002408class PropertyMatcher {
2409 public:
2410 // The property may have a reference type, so 'const PropertyType&'
2411 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00002412 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00002413 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00002414 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00002415
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002416 PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)
shiqiane35fdd92008-12-10 05:08:54 +00002417 : property_(property), matcher_(matcher) {}
2418
shiqiane35fdd92008-12-10 05:08:54 +00002419 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002420 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002421 matcher_.DescribeTo(os);
2422 }
2423
2424 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002425 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002426 matcher_.DescribeNegationTo(os);
2427 }
2428
zhanyong.wandb22c222010-01-28 21:52:29 +00002429 template <typename T>
2430 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2431 return MatchAndExplainImpl(
2432 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002433 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002434 value, listener);
2435 }
2436
2437 private:
2438 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002439 // Symbian's C++ compiler choose which overload to use. Its type is
2440 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002441 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2442 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002443 *listener << "whose given property is ";
2444 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2445 // which takes a non-const reference as argument.
kosak02d64792015-02-14 02:22:21 +00002446#if defined(_PREFAST_ ) && _MSC_VER == 1800
2447 // Workaround bug in VC++ 2013's /analyze parser.
2448 // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move
2449 posix::Abort(); // To make sure it is never run.
2450 return false;
2451#else
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002452 RefToConstProperty result = (obj.*property_)();
2453 return MatchPrintAndExplain(result, matcher_, listener);
kosak02d64792015-02-14 02:22:21 +00002454#endif
shiqiane35fdd92008-12-10 05:08:54 +00002455 }
2456
zhanyong.wandb22c222010-01-28 21:52:29 +00002457 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2458 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002459 if (p == NULL)
2460 return false;
2461
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002462 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002463 // Since *p has a property method, it must be a class/struct/union
2464 // type and thus cannot be a pointer. Therefore we pass
2465 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002466 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002467 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002468
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002469 Property property_;
shiqiane35fdd92008-12-10 05:08:54 +00002470 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002471
2472 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002473};
2474
shiqiane35fdd92008-12-10 05:08:54 +00002475// Type traits specifying various features of different functors for ResultOf.
2476// The default template specifies features for functor objects.
2477// Functor classes have to typedef argument_type and result_type
2478// to be compatible with ResultOf.
2479template <typename Functor>
2480struct CallableTraits {
2481 typedef typename Functor::result_type ResultType;
2482 typedef Functor StorageType;
2483
zhanyong.wan32de5f52009-12-23 00:13:23 +00002484 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00002485 template <typename T>
2486 static ResultType Invoke(Functor f, T arg) { return f(arg); }
2487};
2488
2489// Specialization for function pointers.
2490template <typename ArgType, typename ResType>
2491struct CallableTraits<ResType(*)(ArgType)> {
2492 typedef ResType ResultType;
2493 typedef ResType(*StorageType)(ArgType);
2494
2495 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002496 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00002497 << "NULL function pointer is passed into ResultOf().";
2498 }
2499 template <typename T>
2500 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2501 return (*f)(arg);
2502 }
2503};
2504
2505// Implements the ResultOf() matcher for matching a return value of a
2506// unary function of an object.
2507template <typename Callable>
2508class ResultOfMatcher {
2509 public:
2510 typedef typename CallableTraits<Callable>::ResultType ResultType;
2511
2512 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
2513 : callable_(callable), matcher_(matcher) {
2514 CallableTraits<Callable>::CheckIsValid(callable_);
2515 }
2516
2517 template <typename T>
2518 operator Matcher<T>() const {
2519 return Matcher<T>(new Impl<T>(callable_, matcher_));
2520 }
2521
2522 private:
2523 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2524
2525 template <typename T>
2526 class Impl : public MatcherInterface<T> {
2527 public:
2528 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
2529 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00002530
2531 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002532 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002533 matcher_.DescribeTo(os);
2534 }
2535
2536 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002537 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002538 matcher_.DescribeNegationTo(os);
2539 }
2540
zhanyong.wan82113312010-01-08 21:55:40 +00002541 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002542 *listener << "which is mapped by the given callable to ";
2543 // Cannot pass the return value (for example, int) to
2544 // MatchPrintAndExplain, which takes a non-const reference as argument.
2545 ResultType result =
2546 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2547 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002548 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002549
shiqiane35fdd92008-12-10 05:08:54 +00002550 private:
2551 // Functors often define operator() as non-const method even though
Troy Holsapplec8510502018-02-07 22:06:00 -08002552 // they are actually stateless. But we need to use them even when
shiqiane35fdd92008-12-10 05:08:54 +00002553 // 'this' is a const pointer. It's the user's responsibility not to
2554 // use stateful callables with ResultOf(), which does't guarantee
2555 // how many times the callable will be invoked.
2556 mutable CallableStorageType callable_;
2557 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002558
2559 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002560 }; // class Impl
2561
2562 const CallableStorageType callable_;
2563 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002564
2565 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002566};
2567
zhanyong.wana31d9ce2013-03-01 01:50:17 +00002568// Implements a matcher that checks the size of an STL-style container.
2569template <typename SizeMatcher>
2570class SizeIsMatcher {
2571 public:
2572 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2573 : size_matcher_(size_matcher) {
2574 }
2575
2576 template <typename Container>
2577 operator Matcher<Container>() const {
2578 return MakeMatcher(new Impl<Container>(size_matcher_));
2579 }
2580
2581 template <typename Container>
2582 class Impl : public MatcherInterface<Container> {
2583 public:
2584 typedef internal::StlContainerView<
2585 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2586 typedef typename ContainerView::type::size_type SizeType;
2587 explicit Impl(const SizeMatcher& size_matcher)
2588 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2589
2590 virtual void DescribeTo(::std::ostream* os) const {
2591 *os << "size ";
2592 size_matcher_.DescribeTo(os);
2593 }
2594 virtual void DescribeNegationTo(::std::ostream* os) const {
2595 *os << "size ";
2596 size_matcher_.DescribeNegationTo(os);
2597 }
2598
2599 virtual bool MatchAndExplain(Container container,
2600 MatchResultListener* listener) const {
2601 SizeType size = container.size();
2602 StringMatchResultListener size_listener;
2603 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2604 *listener
2605 << "whose size " << size << (result ? " matches" : " doesn't match");
2606 PrintIfNotEmpty(size_listener.str(), listener->stream());
2607 return result;
2608 }
2609
2610 private:
2611 const Matcher<SizeType> size_matcher_;
2612 GTEST_DISALLOW_ASSIGN_(Impl);
2613 };
2614
2615 private:
2616 const SizeMatcher size_matcher_;
2617 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2618};
2619
kosakb6a34882014-03-12 21:06:46 +00002620// Implements a matcher that checks the begin()..end() distance of an STL-style
2621// container.
2622template <typename DistanceMatcher>
2623class BeginEndDistanceIsMatcher {
2624 public:
2625 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2626 : distance_matcher_(distance_matcher) {}
2627
2628 template <typename Container>
2629 operator Matcher<Container>() const {
2630 return MakeMatcher(new Impl<Container>(distance_matcher_));
2631 }
2632
2633 template <typename Container>
2634 class Impl : public MatcherInterface<Container> {
2635 public:
2636 typedef internal::StlContainerView<
2637 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2638 typedef typename std::iterator_traits<
2639 typename ContainerView::type::const_iterator>::difference_type
2640 DistanceType;
2641 explicit Impl(const DistanceMatcher& distance_matcher)
2642 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2643
2644 virtual void DescribeTo(::std::ostream* os) const {
2645 *os << "distance between begin() and end() ";
2646 distance_matcher_.DescribeTo(os);
2647 }
2648 virtual void DescribeNegationTo(::std::ostream* os) const {
2649 *os << "distance between begin() and end() ";
2650 distance_matcher_.DescribeNegationTo(os);
2651 }
2652
2653 virtual bool MatchAndExplain(Container container,
2654 MatchResultListener* listener) const {
kosak5b9cbbb2014-11-17 00:28:55 +00002655#if GTEST_HAS_STD_BEGIN_AND_END_
kosakb6a34882014-03-12 21:06:46 +00002656 using std::begin;
2657 using std::end;
2658 DistanceType distance = std::distance(begin(container), end(container));
2659#else
2660 DistanceType distance = std::distance(container.begin(), container.end());
2661#endif
2662 StringMatchResultListener distance_listener;
2663 const bool result =
2664 distance_matcher_.MatchAndExplain(distance, &distance_listener);
2665 *listener << "whose distance between begin() and end() " << distance
2666 << (result ? " matches" : " doesn't match");
2667 PrintIfNotEmpty(distance_listener.str(), listener->stream());
2668 return result;
2669 }
2670
2671 private:
2672 const Matcher<DistanceType> distance_matcher_;
2673 GTEST_DISALLOW_ASSIGN_(Impl);
2674 };
2675
2676 private:
2677 const DistanceMatcher distance_matcher_;
2678 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2679};
2680
zhanyong.wan6a896b52009-01-16 01:13:50 +00002681// Implements an equality matcher for any STL-style container whose elements
2682// support ==. This matcher is like Eq(), but its failure explanations provide
2683// more detailed information that is useful when the container is used as a set.
2684// The failure message reports elements that are in one of the operands but not
2685// the other. The failure messages do not report duplicate or out-of-order
2686// elements in the containers (which don't properly matter to sets, but can
2687// occur if the containers are vectors or lists, for example).
2688//
2689// Uses the container's const_iterator, value_type, operator ==,
2690// begin(), and end().
2691template <typename Container>
2692class ContainerEqMatcher {
2693 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002694 typedef internal::StlContainerView<Container> View;
2695 typedef typename View::type StlContainer;
2696 typedef typename View::const_reference StlContainerReference;
2697
kosak6b817802015-01-08 02:38:14 +00002698 // We make a copy of expected in case the elements in it are modified
zhanyong.wanb8243162009-06-04 05:48:20 +00002699 // after this matcher is created.
kosak6b817802015-01-08 02:38:14 +00002700 explicit ContainerEqMatcher(const Container& expected)
2701 : expected_(View::Copy(expected)) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002702 // Makes sure the user doesn't instantiate this class template
2703 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002704 (void)testing::StaticAssertTypeEq<Container,
2705 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002706 }
2707
zhanyong.wan6a896b52009-01-16 01:13:50 +00002708 void DescribeTo(::std::ostream* os) const {
2709 *os << "equals ";
kosak6b817802015-01-08 02:38:14 +00002710 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002711 }
2712 void DescribeNegationTo(::std::ostream* os) const {
2713 *os << "does not equal ";
kosak6b817802015-01-08 02:38:14 +00002714 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002715 }
2716
zhanyong.wanb8243162009-06-04 05:48:20 +00002717 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002718 bool MatchAndExplain(const LhsContainer& lhs,
2719 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002720 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002721 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002722 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002723 LhsView;
2724 typedef typename LhsView::type LhsStlContainer;
2725 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
kosak6b817802015-01-08 02:38:14 +00002726 if (lhs_stl_container == expected_)
zhanyong.wane122e452010-01-12 09:03:52 +00002727 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002728
zhanyong.wane122e452010-01-12 09:03:52 +00002729 ::std::ostream* const os = listener->stream();
2730 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002731 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002732 bool printed_header = false;
2733 for (typename LhsStlContainer::const_iterator it =
2734 lhs_stl_container.begin();
2735 it != lhs_stl_container.end(); ++it) {
kosak6b817802015-01-08 02:38:14 +00002736 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
2737 expected_.end()) {
zhanyong.wane122e452010-01-12 09:03:52 +00002738 if (printed_header) {
2739 *os << ", ";
2740 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002741 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002742 printed_header = true;
2743 }
vladloseve2e8ba42010-05-13 18:16:03 +00002744 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002745 }
zhanyong.wane122e452010-01-12 09:03:52 +00002746 }
2747
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002748 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002749 bool printed_header2 = false;
kosak6b817802015-01-08 02:38:14 +00002750 for (typename StlContainer::const_iterator it = expected_.begin();
2751 it != expected_.end(); ++it) {
zhanyong.wane122e452010-01-12 09:03:52 +00002752 if (internal::ArrayAwareFind(
2753 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2754 lhs_stl_container.end()) {
2755 if (printed_header2) {
2756 *os << ", ";
2757 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002758 *os << (printed_header ? ",\nand" : "which")
2759 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002760 printed_header2 = true;
2761 }
vladloseve2e8ba42010-05-13 18:16:03 +00002762 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002763 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002764 }
2765 }
2766
zhanyong.wane122e452010-01-12 09:03:52 +00002767 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002768 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002769
zhanyong.wan6a896b52009-01-16 01:13:50 +00002770 private:
kosak6b817802015-01-08 02:38:14 +00002771 const StlContainer expected_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002772
2773 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002774};
2775
zhanyong.wan898725c2011-09-16 16:45:39 +00002776// A comparator functor that uses the < operator to compare two values.
2777struct LessComparator {
2778 template <typename T, typename U>
2779 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2780};
2781
2782// Implements WhenSortedBy(comparator, container_matcher).
2783template <typename Comparator, typename ContainerMatcher>
2784class WhenSortedByMatcher {
2785 public:
2786 WhenSortedByMatcher(const Comparator& comparator,
2787 const ContainerMatcher& matcher)
2788 : comparator_(comparator), matcher_(matcher) {}
2789
2790 template <typename LhsContainer>
2791 operator Matcher<LhsContainer>() const {
2792 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2793 }
2794
2795 template <typename LhsContainer>
2796 class Impl : public MatcherInterface<LhsContainer> {
2797 public:
2798 typedef internal::StlContainerView<
2799 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2800 typedef typename LhsView::type LhsStlContainer;
2801 typedef typename LhsView::const_reference LhsStlContainerReference;
zhanyong.wana9a59e02013-03-27 16:14:55 +00002802 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2803 // so that we can match associative containers.
2804 typedef typename RemoveConstFromKey<
2805 typename LhsStlContainer::value_type>::type LhsValue;
zhanyong.wan898725c2011-09-16 16:45:39 +00002806
2807 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2808 : comparator_(comparator), matcher_(matcher) {}
2809
2810 virtual void DescribeTo(::std::ostream* os) const {
2811 *os << "(when sorted) ";
2812 matcher_.DescribeTo(os);
2813 }
2814
2815 virtual void DescribeNegationTo(::std::ostream* os) const {
2816 *os << "(when sorted) ";
2817 matcher_.DescribeNegationTo(os);
2818 }
2819
2820 virtual bool MatchAndExplain(LhsContainer lhs,
2821 MatchResultListener* listener) const {
2822 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wanfb25d532013-07-28 08:24:00 +00002823 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2824 lhs_stl_container.end());
2825 ::std::sort(
2826 sorted_container.begin(), sorted_container.end(), comparator_);
zhanyong.wan898725c2011-09-16 16:45:39 +00002827
2828 if (!listener->IsInterested()) {
2829 // If the listener is not interested, we do not need to
2830 // construct the inner explanation.
2831 return matcher_.Matches(sorted_container);
2832 }
2833
2834 *listener << "which is ";
2835 UniversalPrint(sorted_container, listener->stream());
2836 *listener << " when sorted";
2837
2838 StringMatchResultListener inner_listener;
2839 const bool match = matcher_.MatchAndExplain(sorted_container,
2840 &inner_listener);
2841 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2842 return match;
2843 }
2844
2845 private:
2846 const Comparator comparator_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00002847 const Matcher<const ::std::vector<LhsValue>&> matcher_;
zhanyong.wan898725c2011-09-16 16:45:39 +00002848
2849 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2850 };
2851
2852 private:
2853 const Comparator comparator_;
2854 const ContainerMatcher matcher_;
2855
2856 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2857};
2858
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002859// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2860// must be able to be safely cast to Matcher<tuple<const T1&, const
2861// T2&> >, where T1 and T2 are the types of elements in the LHS
2862// container and the RHS container respectively.
2863template <typename TupleMatcher, typename RhsContainer>
2864class PointwiseMatcher {
2865 public:
2866 typedef internal::StlContainerView<RhsContainer> RhsView;
2867 typedef typename RhsView::type RhsStlContainer;
2868 typedef typename RhsStlContainer::value_type RhsValue;
2869
2870 // Like ContainerEq, we make a copy of rhs in case the elements in
2871 // it are modified after this matcher is created.
2872 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2873 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2874 // Makes sure the user doesn't instantiate this class template
2875 // with a const or reference type.
2876 (void)testing::StaticAssertTypeEq<RhsContainer,
2877 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2878 }
2879
2880 template <typename LhsContainer>
2881 operator Matcher<LhsContainer>() const {
2882 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2883 }
2884
2885 template <typename LhsContainer>
2886 class Impl : public MatcherInterface<LhsContainer> {
2887 public:
2888 typedef internal::StlContainerView<
2889 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2890 typedef typename LhsView::type LhsStlContainer;
2891 typedef typename LhsView::const_reference LhsStlContainerReference;
2892 typedef typename LhsStlContainer::value_type LhsValue;
2893 // We pass the LHS value and the RHS value to the inner matcher by
2894 // reference, as they may be expensive to copy. We must use tuple
2895 // instead of pair here, as a pair cannot hold references (C++ 98,
2896 // 20.2.2 [lib.pairs]).
kosakbd018832014-04-02 20:30:00 +00002897 typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002898
2899 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2900 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2901 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2902 rhs_(rhs) {}
2903
2904 virtual void DescribeTo(::std::ostream* os) const {
2905 *os << "contains " << rhs_.size()
2906 << " values, where each value and its corresponding value in ";
2907 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2908 *os << " ";
2909 mono_tuple_matcher_.DescribeTo(os);
2910 }
2911 virtual void DescribeNegationTo(::std::ostream* os) const {
2912 *os << "doesn't contain exactly " << rhs_.size()
2913 << " values, or contains a value x at some index i"
2914 << " where x and the i-th value of ";
2915 UniversalPrint(rhs_, os);
2916 *os << " ";
2917 mono_tuple_matcher_.DescribeNegationTo(os);
2918 }
2919
2920 virtual bool MatchAndExplain(LhsContainer lhs,
2921 MatchResultListener* listener) const {
2922 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2923 const size_t actual_size = lhs_stl_container.size();
2924 if (actual_size != rhs_.size()) {
2925 *listener << "which contains " << actual_size << " values";
2926 return false;
2927 }
2928
2929 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2930 typename RhsStlContainer::const_iterator right = rhs_.begin();
2931 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2932 const InnerMatcherArg value_pair(*left, *right);
2933
2934 if (listener->IsInterested()) {
2935 StringMatchResultListener inner_listener;
2936 if (!mono_tuple_matcher_.MatchAndExplain(
2937 value_pair, &inner_listener)) {
2938 *listener << "where the value pair (";
2939 UniversalPrint(*left, listener->stream());
2940 *listener << ", ";
2941 UniversalPrint(*right, listener->stream());
2942 *listener << ") at index #" << i << " don't match";
2943 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2944 return false;
2945 }
2946 } else {
2947 if (!mono_tuple_matcher_.Matches(value_pair))
2948 return false;
2949 }
2950 }
2951
2952 return true;
2953 }
2954
2955 private:
2956 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2957 const RhsStlContainer rhs_;
2958
2959 GTEST_DISALLOW_ASSIGN_(Impl);
2960 };
2961
2962 private:
2963 const TupleMatcher tuple_matcher_;
2964 const RhsStlContainer rhs_;
2965
2966 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2967};
2968
zhanyong.wan33605ba2010-04-22 23:37:47 +00002969// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002970template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002971class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002972 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002973 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002974 typedef StlContainerView<RawContainer> View;
2975 typedef typename View::type StlContainer;
2976 typedef typename View::const_reference StlContainerReference;
2977 typedef typename StlContainer::value_type Element;
2978
2979 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002980 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002981 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002982 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002983
zhanyong.wan33605ba2010-04-22 23:37:47 +00002984 // Checks whether:
2985 // * All elements in the container match, if all_elements_should_match.
2986 // * Any element in the container matches, if !all_elements_should_match.
2987 bool MatchAndExplainImpl(bool all_elements_should_match,
2988 Container container,
2989 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002990 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002991 size_t i = 0;
2992 for (typename StlContainer::const_iterator it = stl_container.begin();
2993 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002994 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002995 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2996
2997 if (matches != all_elements_should_match) {
2998 *listener << "whose element #" << i
2999 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003000 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00003001 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00003002 }
3003 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00003004 return all_elements_should_match;
3005 }
3006
3007 protected:
3008 const Matcher<const Element&> inner_matcher_;
3009
3010 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
3011};
3012
3013// Implements Contains(element_matcher) for the given argument type Container.
3014// Symmetric to EachMatcherImpl.
3015template <typename Container>
3016class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
3017 public:
3018 template <typename InnerMatcher>
3019 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
3020 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3021
3022 // Describes what this matcher does.
3023 virtual void DescribeTo(::std::ostream* os) const {
3024 *os << "contains at least one element that ";
3025 this->inner_matcher_.DescribeTo(os);
3026 }
3027
3028 virtual void DescribeNegationTo(::std::ostream* os) const {
3029 *os << "doesn't contain any element that ";
3030 this->inner_matcher_.DescribeTo(os);
3031 }
3032
3033 virtual bool MatchAndExplain(Container container,
3034 MatchResultListener* listener) const {
3035 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00003036 }
3037
3038 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003039 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00003040};
3041
zhanyong.wan33605ba2010-04-22 23:37:47 +00003042// Implements Each(element_matcher) for the given argument type Container.
3043// Symmetric to ContainsMatcherImpl.
3044template <typename Container>
3045class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
3046 public:
3047 template <typename InnerMatcher>
3048 explicit EachMatcherImpl(InnerMatcher inner_matcher)
3049 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3050
3051 // Describes what this matcher does.
3052 virtual void DescribeTo(::std::ostream* os) const {
3053 *os << "only contains elements that ";
3054 this->inner_matcher_.DescribeTo(os);
3055 }
3056
3057 virtual void DescribeNegationTo(::std::ostream* os) const {
3058 *os << "contains some element that ";
3059 this->inner_matcher_.DescribeNegationTo(os);
3060 }
3061
3062 virtual bool MatchAndExplain(Container container,
3063 MatchResultListener* listener) const {
3064 return this->MatchAndExplainImpl(true, container, listener);
3065 }
3066
3067 private:
3068 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
3069};
3070
zhanyong.wanb8243162009-06-04 05:48:20 +00003071// Implements polymorphic Contains(element_matcher).
3072template <typename M>
3073class ContainsMatcher {
3074 public:
3075 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
3076
3077 template <typename Container>
3078 operator Matcher<Container>() const {
3079 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
3080 }
3081
3082 private:
3083 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003084
3085 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00003086};
3087
zhanyong.wan33605ba2010-04-22 23:37:47 +00003088// Implements polymorphic Each(element_matcher).
3089template <typename M>
3090class EachMatcher {
3091 public:
3092 explicit EachMatcher(M m) : inner_matcher_(m) {}
3093
3094 template <typename Container>
3095 operator Matcher<Container>() const {
3096 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
3097 }
3098
3099 private:
3100 const M inner_matcher_;
3101
3102 GTEST_DISALLOW_ASSIGN_(EachMatcher);
3103};
3104
Gennadiy Civil466a49a2018-03-23 11:23:54 -04003105struct Rank1 {};
3106struct Rank0 : Rank1 {};
3107
3108namespace pair_getters {
3109#if GTEST_LANG_CXX11
3110using std::get;
3111template <typename T>
3112auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT
3113 return get<0>(x);
3114}
3115template <typename T>
3116auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT
3117 return x.first;
3118}
3119
3120template <typename T>
3121auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT
3122 return get<1>(x);
3123}
3124template <typename T>
3125auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT
3126 return x.second;
3127}
3128#else
3129template <typename T>
3130typename T::first_type& First(T& x, Rank0) { // NOLINT
3131 return x.first;
3132}
3133template <typename T>
3134const typename T::first_type& First(const T& x, Rank0) {
3135 return x.first;
3136}
3137
3138template <typename T>
3139typename T::second_type& Second(T& x, Rank0) { // NOLINT
3140 return x.second;
3141}
3142template <typename T>
3143const typename T::second_type& Second(const T& x, Rank0) {
3144 return x.second;
3145}
3146#endif // GTEST_LANG_CXX11
3147} // namespace pair_getters
3148
zhanyong.wanb5937da2009-07-16 20:26:41 +00003149// Implements Key(inner_matcher) for the given argument pair type.
3150// Key(inner_matcher) matches an std::pair whose 'first' field matches
3151// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3152// std::map that contains at least one element whose key is >= 5.
3153template <typename PairType>
3154class KeyMatcherImpl : public MatcherInterface<PairType> {
3155 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003156 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00003157 typedef typename RawPairType::first_type KeyType;
3158
3159 template <typename InnerMatcher>
3160 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
3161 : inner_matcher_(
3162 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
3163 }
3164
3165 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00003166 virtual bool MatchAndExplain(PairType key_value,
3167 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003168 StringMatchResultListener inner_listener;
3169 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
3170 &inner_listener);
Nico Weber09fd5b32017-05-15 17:07:03 -04003171 const std::string explanation = inner_listener.str();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003172 if (explanation != "") {
3173 *listener << "whose first field is a value " << explanation;
3174 }
3175 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00003176 }
3177
3178 // Describes what this matcher does.
3179 virtual void DescribeTo(::std::ostream* os) const {
3180 *os << "has a key that ";
3181 inner_matcher_.DescribeTo(os);
3182 }
3183
3184 // Describes what the negation of this matcher does.
3185 virtual void DescribeNegationTo(::std::ostream* os) const {
3186 *os << "doesn't have a key that ";
3187 inner_matcher_.DescribeTo(os);
3188 }
3189
zhanyong.wanb5937da2009-07-16 20:26:41 +00003190 private:
3191 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003192
3193 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00003194};
3195
3196// Implements polymorphic Key(matcher_for_key).
3197template <typename M>
3198class KeyMatcher {
3199 public:
3200 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
3201
3202 template <typename PairType>
3203 operator Matcher<PairType>() const {
3204 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
3205 }
3206
3207 private:
3208 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003209
3210 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00003211};
3212
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003213// Implements Pair(first_matcher, second_matcher) for the given argument pair
3214// type with its two matchers. See Pair() function below.
3215template <typename PairType>
3216class PairMatcherImpl : public MatcherInterface<PairType> {
3217 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003218 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003219 typedef typename RawPairType::first_type FirstType;
3220 typedef typename RawPairType::second_type SecondType;
3221
3222 template <typename FirstMatcher, typename SecondMatcher>
3223 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
3224 : first_matcher_(
3225 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
3226 second_matcher_(
3227 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
3228 }
3229
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003230 // Describes what this matcher does.
3231 virtual void DescribeTo(::std::ostream* os) const {
3232 *os << "has a first field that ";
3233 first_matcher_.DescribeTo(os);
3234 *os << ", and has a second field that ";
3235 second_matcher_.DescribeTo(os);
3236 }
3237
3238 // Describes what the negation of this matcher does.
3239 virtual void DescribeNegationTo(::std::ostream* os) const {
3240 *os << "has a first field that ";
3241 first_matcher_.DescribeNegationTo(os);
3242 *os << ", or has a second field that ";
3243 second_matcher_.DescribeNegationTo(os);
3244 }
3245
zhanyong.wan82113312010-01-08 21:55:40 +00003246 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3247 // matches second_matcher.
3248 virtual bool MatchAndExplain(PairType a_pair,
3249 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003250 if (!listener->IsInterested()) {
3251 // If the listener is not interested, we don't need to construct the
3252 // explanation.
3253 return first_matcher_.Matches(a_pair.first) &&
3254 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00003255 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003256 StringMatchResultListener first_inner_listener;
3257 if (!first_matcher_.MatchAndExplain(a_pair.first,
3258 &first_inner_listener)) {
3259 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003260 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003261 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003262 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003263 StringMatchResultListener second_inner_listener;
3264 if (!second_matcher_.MatchAndExplain(a_pair.second,
3265 &second_inner_listener)) {
3266 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003267 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003268 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003269 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003270 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3271 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00003272 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003273 }
3274
3275 private:
Nico Weber09fd5b32017-05-15 17:07:03 -04003276 void ExplainSuccess(const std::string& first_explanation,
3277 const std::string& second_explanation,
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003278 MatchResultListener* listener) const {
3279 *listener << "whose both fields match";
3280 if (first_explanation != "") {
3281 *listener << ", where the first field is a value " << first_explanation;
3282 }
3283 if (second_explanation != "") {
3284 *listener << ", ";
3285 if (first_explanation != "") {
3286 *listener << "and ";
3287 } else {
3288 *listener << "where ";
3289 }
3290 *listener << "the second field is a value " << second_explanation;
3291 }
3292 }
3293
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003294 const Matcher<const FirstType&> first_matcher_;
3295 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003296
3297 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003298};
3299
3300// Implements polymorphic Pair(first_matcher, second_matcher).
3301template <typename FirstMatcher, typename SecondMatcher>
3302class PairMatcher {
3303 public:
3304 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3305 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3306
3307 template <typename PairType>
3308 operator Matcher<PairType> () const {
3309 return MakeMatcher(
3310 new PairMatcherImpl<PairType>(
3311 first_matcher_, second_matcher_));
3312 }
3313
3314 private:
3315 const FirstMatcher first_matcher_;
3316 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003317
3318 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003319};
3320
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003321// Implements ElementsAre() and ElementsAreArray().
3322template <typename Container>
3323class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3324 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003325 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003326 typedef internal::StlContainerView<RawContainer> View;
3327 typedef typename View::type StlContainer;
3328 typedef typename View::const_reference StlContainerReference;
3329 typedef typename StlContainer::value_type Element;
3330
3331 // Constructs the matcher from a sequence of element values or
3332 // element matchers.
3333 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00003334 ElementsAreMatcherImpl(InputIter first, InputIter last) {
3335 while (first != last) {
3336 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003337 }
3338 }
3339
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003340 // Describes what this matcher does.
3341 virtual void DescribeTo(::std::ostream* os) const {
3342 if (count() == 0) {
3343 *os << "is empty";
3344 } else if (count() == 1) {
3345 *os << "has 1 element that ";
3346 matchers_[0].DescribeTo(os);
3347 } else {
3348 *os << "has " << Elements(count()) << " where\n";
3349 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003350 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003351 matchers_[i].DescribeTo(os);
3352 if (i + 1 < count()) {
3353 *os << ",\n";
3354 }
3355 }
3356 }
3357 }
3358
3359 // Describes what the negation of this matcher does.
3360 virtual void DescribeNegationTo(::std::ostream* os) const {
3361 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003362 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003363 return;
3364 }
3365
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003366 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003367 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003368 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003369 matchers_[i].DescribeNegationTo(os);
3370 if (i + 1 < count()) {
3371 *os << ", or\n";
3372 }
3373 }
3374 }
3375
zhanyong.wan82113312010-01-08 21:55:40 +00003376 virtual bool MatchAndExplain(Container container,
3377 MatchResultListener* listener) const {
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003378 // To work with stream-like "containers", we must only walk
3379 // through the elements in one pass.
3380
3381 const bool listener_interested = listener->IsInterested();
3382
3383 // explanations[i] is the explanation of the element at index i.
Nico Weber09fd5b32017-05-15 17:07:03 -04003384 ::std::vector<std::string> explanations(count());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003385 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003386 typename StlContainer::const_iterator it = stl_container.begin();
3387 size_t exam_pos = 0;
3388 bool mismatch_found = false; // Have we found a mismatched element yet?
3389
3390 // Go through the elements and matchers in pairs, until we reach
3391 // the end of either the elements or the matchers, or until we find a
3392 // mismatch.
3393 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3394 bool match; // Does the current element match the current matcher?
3395 if (listener_interested) {
3396 StringMatchResultListener s;
3397 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3398 explanations[exam_pos] = s.str();
3399 } else {
3400 match = matchers_[exam_pos].Matches(*it);
3401 }
3402
3403 if (!match) {
3404 mismatch_found = true;
3405 break;
3406 }
3407 }
3408 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3409
3410 // Find how many elements the actual container has. We avoid
3411 // calling size() s.t. this code works for stream-like "containers"
3412 // that don't define size().
3413 size_t actual_count = exam_pos;
3414 for (; it != stl_container.end(); ++it) {
3415 ++actual_count;
3416 }
3417
zhanyong.wan82113312010-01-08 21:55:40 +00003418 if (actual_count != count()) {
3419 // The element count doesn't match. If the container is empty,
3420 // there's no need to explain anything as Google Mock already
3421 // prints the empty container. Otherwise we just need to show
3422 // how many elements there actually are.
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003423 if (listener_interested && (actual_count != 0)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003424 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003425 }
zhanyong.wan82113312010-01-08 21:55:40 +00003426 return false;
3427 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003428
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003429 if (mismatch_found) {
3430 // The element count matches, but the exam_pos-th element doesn't match.
3431 if (listener_interested) {
3432 *listener << "whose element #" << exam_pos << " doesn't match";
3433 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003434 }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003435 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003436 }
zhanyong.wan82113312010-01-08 21:55:40 +00003437
3438 // Every element matches its expectation. We need to explain why
3439 // (the obvious ones can be skipped).
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003440 if (listener_interested) {
3441 bool reason_printed = false;
3442 for (size_t i = 0; i != count(); ++i) {
Nico Weber09fd5b32017-05-15 17:07:03 -04003443 const std::string& s = explanations[i];
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003444 if (!s.empty()) {
3445 if (reason_printed) {
3446 *listener << ",\nand ";
3447 }
3448 *listener << "whose element #" << i << " matches, " << s;
3449 reason_printed = true;
zhanyong.wan82113312010-01-08 21:55:40 +00003450 }
zhanyong.wan82113312010-01-08 21:55:40 +00003451 }
3452 }
zhanyong.wan82113312010-01-08 21:55:40 +00003453 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003454 }
3455
3456 private:
3457 static Message Elements(size_t count) {
3458 return Message() << count << (count == 1 ? " element" : " elements");
3459 }
3460
3461 size_t count() const { return matchers_.size(); }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003462
3463 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003464
3465 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003466};
3467
zhanyong.wanfb25d532013-07-28 08:24:00 +00003468// Connectivity matrix of (elements X matchers), in element-major order.
3469// Initially, there are no edges.
3470// Use NextGraph() to iterate over all possible edge configurations.
3471// Use Randomize() to generate a random edge configuration.
3472class GTEST_API_ MatchMatrix {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003473 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003474 MatchMatrix(size_t num_elements, size_t num_matchers)
3475 : num_elements_(num_elements),
3476 num_matchers_(num_matchers),
3477 matched_(num_elements_* num_matchers_, 0) {
3478 }
3479
3480 size_t LhsSize() const { return num_elements_; }
3481 size_t RhsSize() const { return num_matchers_; }
3482 bool HasEdge(size_t ilhs, size_t irhs) const {
3483 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3484 }
3485 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3486 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3487 }
3488
3489 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3490 // adds 1 to that number; returns false if incrementing the graph left it
3491 // empty.
3492 bool NextGraph();
3493
3494 void Randomize();
3495
Nico Weber09fd5b32017-05-15 17:07:03 -04003496 std::string DebugString() const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003497
3498 private:
3499 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3500 return ilhs * num_matchers_ + irhs;
3501 }
3502
3503 size_t num_elements_;
3504 size_t num_matchers_;
3505
3506 // Each element is a char interpreted as bool. They are stored as a
3507 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3508 // a (ilhs, irhs) matrix coordinate into an offset.
3509 ::std::vector<char> matched_;
3510};
3511
3512typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3513typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3514
3515// Returns a maximum bipartite matching for the specified graph 'g'.
3516// The matching is represented as a vector of {element, matcher} pairs.
3517GTEST_API_ ElementMatcherPairs
3518FindMaxBipartiteMatching(const MatchMatrix& g);
3519
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003520struct UnorderedMatcherRequire {
3521 enum Flags {
3522 Superset = 1 << 0,
3523 Subset = 1 << 1,
3524 ExactMatch = Superset | Subset,
3525 };
3526};
zhanyong.wanfb25d532013-07-28 08:24:00 +00003527
3528// Untyped base class for implementing UnorderedElementsAre. By
3529// putting logic that's not specific to the element type here, we
3530// reduce binary bloat and increase compilation speed.
3531class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3532 protected:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003533 explicit UnorderedElementsAreMatcherImplBase(
3534 UnorderedMatcherRequire::Flags matcher_flags)
3535 : match_flags_(matcher_flags) {}
3536
zhanyong.wanfb25d532013-07-28 08:24:00 +00003537 // A vector of matcher describers, one for each element matcher.
3538 // Does not own the describers (and thus can be used only when the
3539 // element matchers are alive).
3540 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3541
3542 // Describes this UnorderedElementsAre matcher.
3543 void DescribeToImpl(::std::ostream* os) const;
3544
3545 // Describes the negation of this UnorderedElementsAre matcher.
3546 void DescribeNegationToImpl(::std::ostream* os) const;
3547
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003548 bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,
3549 const MatchMatrix& matrix,
3550 MatchResultListener* listener) const;
3551
3552 bool FindPairing(const MatchMatrix& matrix,
3553 MatchResultListener* listener) const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003554
3555 MatcherDescriberVec& matcher_describers() {
3556 return matcher_describers_;
3557 }
3558
3559 static Message Elements(size_t n) {
3560 return Message() << n << " element" << (n == 1 ? "" : "s");
3561 }
3562
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003563 UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }
3564
zhanyong.wanfb25d532013-07-28 08:24:00 +00003565 private:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003566 UnorderedMatcherRequire::Flags match_flags_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003567 MatcherDescriberVec matcher_describers_;
3568
3569 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3570};
3571
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003572// Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
3573// IsSupersetOf.
zhanyong.wanfb25d532013-07-28 08:24:00 +00003574template <typename Container>
3575class UnorderedElementsAreMatcherImpl
3576 : public MatcherInterface<Container>,
3577 public UnorderedElementsAreMatcherImplBase {
3578 public:
3579 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3580 typedef internal::StlContainerView<RawContainer> View;
3581 typedef typename View::type StlContainer;
3582 typedef typename View::const_reference StlContainerReference;
3583 typedef typename StlContainer::const_iterator StlContainerConstIterator;
3584 typedef typename StlContainer::value_type Element;
3585
zhanyong.wanfb25d532013-07-28 08:24:00 +00003586 template <typename InputIter>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003587 UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,
3588 InputIter first, InputIter last)
3589 : UnorderedElementsAreMatcherImplBase(matcher_flags) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00003590 for (; first != last; ++first) {
3591 matchers_.push_back(MatcherCast<const Element&>(*first));
3592 matcher_describers().push_back(matchers_.back().GetDescriber());
3593 }
3594 }
3595
3596 // Describes what this matcher does.
3597 virtual void DescribeTo(::std::ostream* os) const {
3598 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3599 }
3600
3601 // Describes what the negation of this matcher does.
3602 virtual void DescribeNegationTo(::std::ostream* os) const {
3603 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3604 }
3605
3606 virtual bool MatchAndExplain(Container container,
3607 MatchResultListener* listener) const {
3608 StlContainerReference stl_container = View::ConstReference(container);
Nico Weber09fd5b32017-05-15 17:07:03 -04003609 ::std::vector<std::string> element_printouts;
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003610 MatchMatrix matrix =
3611 AnalyzeElements(stl_container.begin(), stl_container.end(),
3612 &element_printouts, listener);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003613
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003614 if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00003615 return true;
3616 }
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003617
3618 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
3619 if (matrix.LhsSize() != matrix.RhsSize()) {
3620 // The element count doesn't match. If the container is empty,
3621 // there's no need to explain anything as Google Mock already
3622 // prints the empty container. Otherwise we just need to show
3623 // how many elements there actually are.
3624 if (matrix.LhsSize() != 0 && listener->IsInterested()) {
3625 *listener << "which has " << Elements(matrix.LhsSize());
3626 }
3627 return false;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003628 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003629 }
3630
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003631 return VerifyMatchMatrix(element_printouts, matrix, listener) &&
zhanyong.wanfb25d532013-07-28 08:24:00 +00003632 FindPairing(matrix, listener);
3633 }
3634
3635 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003636 template <typename ElementIter>
3637 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
Nico Weber09fd5b32017-05-15 17:07:03 -04003638 ::std::vector<std::string>* element_printouts,
zhanyong.wanfb25d532013-07-28 08:24:00 +00003639 MatchResultListener* listener) const {
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003640 element_printouts->clear();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003641 ::std::vector<char> did_match;
3642 size_t num_elements = 0;
3643 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3644 if (listener->IsInterested()) {
3645 element_printouts->push_back(PrintToString(*elem_first));
3646 }
3647 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3648 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3649 }
3650 }
3651
3652 MatchMatrix matrix(num_elements, matchers_.size());
3653 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3654 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3655 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3656 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3657 }
3658 }
3659 return matrix;
3660 }
3661
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003662 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003663
3664 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3665};
3666
3667// Functor for use in TransformTuple.
3668// Performs MatcherCast<Target> on an input argument of any type.
3669template <typename Target>
3670struct CastAndAppendTransform {
3671 template <typename Arg>
3672 Matcher<Target> operator()(const Arg& a) const {
3673 return MatcherCast<Target>(a);
3674 }
3675};
3676
3677// Implements UnorderedElementsAre.
3678template <typename MatcherTuple>
3679class UnorderedElementsAreMatcher {
3680 public:
3681 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3682 : matchers_(args) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003683
3684 template <typename Container>
3685 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003686 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003687 typedef typename internal::StlContainerView<RawContainer>::type View;
3688 typedef typename View::value_type Element;
3689 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3690 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003691 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003692 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3693 ::std::back_inserter(matchers));
3694 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003695 UnorderedMatcherRequire::ExactMatch, matchers.begin(), matchers.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003696 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003697
3698 private:
3699 const MatcherTuple matchers_;
3700 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3701};
3702
3703// Implements ElementsAre.
3704template <typename MatcherTuple>
3705class ElementsAreMatcher {
3706 public:
3707 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3708
3709 template <typename Container>
3710 operator Matcher<Container>() const {
3711 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3712 typedef typename internal::StlContainerView<RawContainer>::type View;
3713 typedef typename View::value_type Element;
3714 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3715 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003716 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003717 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3718 ::std::back_inserter(matchers));
3719 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3720 matchers.begin(), matchers.end()));
3721 }
3722
3723 private:
3724 const MatcherTuple matchers_;
3725 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3726};
3727
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003728// Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
zhanyong.wanfb25d532013-07-28 08:24:00 +00003729template <typename T>
3730class UnorderedElementsAreArrayMatcher {
3731 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003732 template <typename Iter>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003733 UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,
3734 Iter first, Iter last)
3735 : match_flags_(match_flags), matchers_(first, last) {}
zhanyong.wanfb25d532013-07-28 08:24:00 +00003736
3737 template <typename Container>
3738 operator Matcher<Container>() const {
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003739 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3740 match_flags_, matchers_.begin(), matchers_.end()));
zhanyong.wanfb25d532013-07-28 08:24:00 +00003741 }
3742
3743 private:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003744 UnorderedMatcherRequire::Flags match_flags_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003745 ::std::vector<T> matchers_;
3746
3747 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003748};
3749
3750// Implements ElementsAreArray().
3751template <typename T>
3752class ElementsAreArrayMatcher {
3753 public:
jgm38513a82012-11-15 15:50:36 +00003754 template <typename Iter>
3755 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003756
3757 template <typename Container>
3758 operator Matcher<Container>() const {
jgm38513a82012-11-15 15:50:36 +00003759 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3760 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003761 }
3762
3763 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003764 const ::std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003765
3766 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003767};
3768
kosak2336e9c2014-07-28 22:57:30 +00003769// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3770// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3771// second) is a polymorphic matcher that matches a value x iff tm
3772// matches tuple (x, second). Useful for implementing
3773// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3774//
3775// BoundSecondMatcher is copyable and assignable, as we need to put
3776// instances of this class in a vector when implementing
3777// UnorderedPointwise().
3778template <typename Tuple2Matcher, typename Second>
3779class BoundSecondMatcher {
3780 public:
3781 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3782 : tuple2_matcher_(tm), second_value_(second) {}
3783
3784 template <typename T>
3785 operator Matcher<T>() const {
3786 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3787 }
3788
3789 // We have to define this for UnorderedPointwise() to compile in
3790 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3791 // which requires the elements to be assignable in C++98. The
3792 // compiler cannot generate the operator= for us, as Tuple2Matcher
3793 // and Second may not be assignable.
3794 //
3795 // However, this should never be called, so the implementation just
3796 // need to assert.
3797 void operator=(const BoundSecondMatcher& /*rhs*/) {
3798 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3799 }
3800
3801 private:
3802 template <typename T>
3803 class Impl : public MatcherInterface<T> {
3804 public:
3805 typedef ::testing::tuple<T, Second> ArgTuple;
3806
3807 Impl(const Tuple2Matcher& tm, const Second& second)
3808 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3809 second_value_(second) {}
3810
3811 virtual void DescribeTo(::std::ostream* os) const {
3812 *os << "and ";
3813 UniversalPrint(second_value_, os);
3814 *os << " ";
3815 mono_tuple2_matcher_.DescribeTo(os);
3816 }
3817
3818 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3819 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3820 listener);
3821 }
3822
3823 private:
3824 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3825 const Second second_value_;
3826
3827 GTEST_DISALLOW_ASSIGN_(Impl);
3828 };
3829
3830 const Tuple2Matcher tuple2_matcher_;
3831 const Second second_value_;
3832};
3833
3834// Given a 2-tuple matcher tm and a value second,
3835// MatcherBindSecond(tm, second) returns a matcher that matches a
3836// value x iff tm matches tuple (x, second). Useful for implementing
3837// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3838template <typename Tuple2Matcher, typename Second>
3839BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
3840 const Tuple2Matcher& tm, const Second& second) {
3841 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
3842}
3843
zhanyong.wanb4140802010-06-08 22:53:57 +00003844// Returns the description for a matcher defined using the MATCHER*()
3845// macro where the user-supplied description string is "", if
3846// 'negation' is false; otherwise returns the description of the
3847// negation of the matcher. 'param_values' contains a list of strings
3848// that are the print-out of the matcher's parameters.
Nico Weber09fd5b32017-05-15 17:07:03 -04003849GTEST_API_ std::string FormatMatcherDescription(bool negation,
3850 const char* matcher_name,
3851 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003852
Gennadiy Civilb907c262018-03-23 11:42:41 -04003853// Implements a matcher that checks the value of a optional<> type variable.
3854template <typename ValueMatcher>
3855class OptionalMatcher {
3856 public:
3857 explicit OptionalMatcher(const ValueMatcher& value_matcher)
3858 : value_matcher_(value_matcher) {}
3859
3860 template <typename Optional>
3861 operator Matcher<Optional>() const {
3862 return MakeMatcher(new Impl<Optional>(value_matcher_));
3863 }
3864
3865 template <typename Optional>
3866 class Impl : public MatcherInterface<Optional> {
3867 public:
3868 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView;
3869 typedef typename OptionalView::value_type ValueType;
3870 explicit Impl(const ValueMatcher& value_matcher)
3871 : value_matcher_(MatcherCast<ValueType>(value_matcher)) {}
3872
3873 virtual void DescribeTo(::std::ostream* os) const {
3874 *os << "value ";
3875 value_matcher_.DescribeTo(os);
3876 }
3877
3878 virtual void DescribeNegationTo(::std::ostream* os) const {
3879 *os << "value ";
3880 value_matcher_.DescribeNegationTo(os);
3881 }
3882
3883 virtual bool MatchAndExplain(Optional optional,
3884 MatchResultListener* listener) const {
3885 if (!optional) {
3886 *listener << "which is not engaged";
3887 return false;
3888 }
3889 const ValueType& value = *optional;
3890 StringMatchResultListener value_listener;
3891 const bool match = value_matcher_.MatchAndExplain(value, &value_listener);
3892 *listener << "whose value " << PrintToString(value)
3893 << (match ? " matches" : " doesn't match");
3894 PrintIfNotEmpty(value_listener.str(), listener->stream());
3895 return match;
3896 }
3897
3898 private:
3899 const Matcher<ValueType> value_matcher_;
3900 GTEST_DISALLOW_ASSIGN_(Impl);
3901 };
3902
3903 private:
3904 const ValueMatcher value_matcher_;
3905 GTEST_DISALLOW_ASSIGN_(OptionalMatcher);
3906};
3907
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05003908namespace variant_matcher {
3909// Overloads to allow VariantMatcher to do proper ADL lookup.
3910template <typename T>
3911void holds_alternative() {}
3912template <typename T>
3913void get() {}
3914
3915// Implements a matcher that checks the value of a variant<> type variable.
3916template <typename T>
3917class VariantMatcher {
3918 public:
3919 explicit VariantMatcher(::testing::Matcher<const T&> matcher)
3920 : matcher_(internal::move(matcher)) {}
3921
3922 template <typename Variant>
3923 bool MatchAndExplain(const Variant& value,
3924 ::testing::MatchResultListener* listener) const {
3925 if (!listener->IsInterested()) {
3926 return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));
3927 }
3928
3929 if (!holds_alternative<T>(value)) {
3930 *listener << "whose value is not of type '" << GetTypeName() << "'";
3931 return false;
3932 }
3933
3934 const T& elem = get<T>(value);
3935 StringMatchResultListener elem_listener;
3936 const bool match = matcher_.MatchAndExplain(elem, &elem_listener);
3937 *listener << "whose value " << PrintToString(elem)
3938 << (match ? " matches" : " doesn't match");
3939 PrintIfNotEmpty(elem_listener.str(), listener->stream());
3940 return match;
3941 }
3942
3943 void DescribeTo(std::ostream* os) const {
3944 *os << "is a variant<> with value of type '" << GetTypeName()
3945 << "' and the value ";
3946 matcher_.DescribeTo(os);
3947 }
3948
3949 void DescribeNegationTo(std::ostream* os) const {
3950 *os << "is a variant<> with value of type other than '" << GetTypeName()
3951 << "' or the value ";
3952 matcher_.DescribeNegationTo(os);
3953 }
3954
3955 private:
3956 static string GetTypeName() {
3957#if GTEST_HAS_RTTI
3958 return internal::GetTypeName<T>();
3959#endif
3960 return "the element type";
3961 }
3962
3963 const ::testing::Matcher<const T&> matcher_;
3964};
3965
3966} // namespace variant_matcher
3967
Gennadiy Civil466a49a2018-03-23 11:23:54 -04003968namespace any_cast_matcher {
3969
3970// Overloads to allow AnyCastMatcher to do proper ADL lookup.
3971template <typename T>
3972void any_cast() {}
3973
3974// Implements a matcher that any_casts the value.
3975template <typename T>
3976class AnyCastMatcher {
3977 public:
3978 explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher)
3979 : matcher_(matcher) {}
3980
3981 template <typename AnyType>
3982 bool MatchAndExplain(const AnyType& value,
3983 ::testing::MatchResultListener* listener) const {
3984 if (!listener->IsInterested()) {
3985 const T* ptr = any_cast<T>(&value);
3986 return ptr != NULL && matcher_.Matches(*ptr);
3987 }
3988
3989 const T* elem = any_cast<T>(&value);
3990 if (elem == NULL) {
3991 *listener << "whose value is not of type '" << GetTypeName() << "'";
3992 return false;
3993 }
3994
3995 StringMatchResultListener elem_listener;
3996 const bool match = matcher_.MatchAndExplain(*elem, &elem_listener);
3997 *listener << "whose value " << PrintToString(*elem)
3998 << (match ? " matches" : " doesn't match");
3999 PrintIfNotEmpty(elem_listener.str(), listener->stream());
4000 return match;
4001 }
4002
4003 void DescribeTo(std::ostream* os) const {
4004 *os << "is an 'any' type with value of type '" << GetTypeName()
4005 << "' and the value ";
4006 matcher_.DescribeTo(os);
4007 }
4008
4009 void DescribeNegationTo(std::ostream* os) const {
4010 *os << "is an 'any' type with value of type other than '" << GetTypeName()
4011 << "' or the value ";
4012 matcher_.DescribeNegationTo(os);
4013 }
4014
4015 private:
4016 static std::string GetTypeName() {
4017#if GTEST_HAS_RTTI
4018 return internal::GetTypeName<T>();
4019#endif
4020 return "the element type";
4021 }
4022
4023 const ::testing::Matcher<const T&> matcher_;
4024};
4025
4026} // namespace any_cast_matcher
shiqiane35fdd92008-12-10 05:08:54 +00004027} // namespace internal
4028
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004029// ElementsAreArray(iterator_first, iterator_last)
zhanyong.wanfb25d532013-07-28 08:24:00 +00004030// ElementsAreArray(pointer, count)
4031// ElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00004032// ElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004033// ElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00004034//
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004035// The ElementsAreArray() functions are like ElementsAre(...), except
4036// that they are given a homogeneous sequence rather than taking each
4037// element as a function argument. The sequence can be specified as an
4038// array, a pointer and count, a vector, an initializer list, or an
4039// STL iterator range. In each of these cases, the underlying sequence
4040// can be either a sequence of values or a sequence of matchers.
zhanyong.wanfb25d532013-07-28 08:24:00 +00004041//
4042// All forms of ElementsAreArray() make a copy of the input matcher sequence.
4043
4044template <typename Iter>
4045inline internal::ElementsAreArrayMatcher<
4046 typename ::std::iterator_traits<Iter>::value_type>
4047ElementsAreArray(Iter first, Iter last) {
4048 typedef typename ::std::iterator_traits<Iter>::value_type T;
4049 return internal::ElementsAreArrayMatcher<T>(first, last);
4050}
4051
4052template <typename T>
4053inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
4054 const T* pointer, size_t count) {
4055 return ElementsAreArray(pointer, pointer + count);
4056}
4057
4058template <typename T, size_t N>
4059inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
4060 const T (&array)[N]) {
4061 return ElementsAreArray(array, N);
4062}
4063
kosak06678922014-07-28 20:01:28 +00004064template <typename Container>
4065inline internal::ElementsAreArrayMatcher<typename Container::value_type>
4066ElementsAreArray(const Container& container) {
4067 return ElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00004068}
4069
kosak18489fa2013-12-04 23:49:07 +00004070#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004071template <typename T>
4072inline internal::ElementsAreArrayMatcher<T>
4073ElementsAreArray(::std::initializer_list<T> xs) {
4074 return ElementsAreArray(xs.begin(), xs.end());
4075}
4076#endif
4077
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004078// UnorderedElementsAreArray(iterator_first, iterator_last)
zhanyong.wanfb25d532013-07-28 08:24:00 +00004079// UnorderedElementsAreArray(pointer, count)
4080// UnorderedElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00004081// UnorderedElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004082// UnorderedElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00004083//
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004084// UnorderedElementsAreArray() verifies that a bijective mapping onto a
4085// collection of matchers exists.
4086//
4087// The matchers can be specified as an array, a pointer and count, a container,
4088// an initializer list, or an STL iterator range. In each of these cases, the
4089// underlying matchers can be either values or matchers.
4090
zhanyong.wanfb25d532013-07-28 08:24:00 +00004091template <typename Iter>
4092inline internal::UnorderedElementsAreArrayMatcher<
4093 typename ::std::iterator_traits<Iter>::value_type>
4094UnorderedElementsAreArray(Iter first, Iter last) {
4095 typedef typename ::std::iterator_traits<Iter>::value_type T;
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004096 return internal::UnorderedElementsAreArrayMatcher<T>(
4097 internal::UnorderedMatcherRequire::ExactMatch, first, last);
zhanyong.wanfb25d532013-07-28 08:24:00 +00004098}
4099
4100template <typename T>
4101inline internal::UnorderedElementsAreArrayMatcher<T>
4102UnorderedElementsAreArray(const T* pointer, size_t count) {
4103 return UnorderedElementsAreArray(pointer, pointer + count);
4104}
4105
4106template <typename T, size_t N>
4107inline internal::UnorderedElementsAreArrayMatcher<T>
4108UnorderedElementsAreArray(const T (&array)[N]) {
4109 return UnorderedElementsAreArray(array, N);
4110}
4111
kosak06678922014-07-28 20:01:28 +00004112template <typename Container>
4113inline internal::UnorderedElementsAreArrayMatcher<
4114 typename Container::value_type>
4115UnorderedElementsAreArray(const Container& container) {
4116 return UnorderedElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00004117}
4118
kosak18489fa2013-12-04 23:49:07 +00004119#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004120template <typename T>
4121inline internal::UnorderedElementsAreArrayMatcher<T>
4122UnorderedElementsAreArray(::std::initializer_list<T> xs) {
4123 return UnorderedElementsAreArray(xs.begin(), xs.end());
4124}
4125#endif
zhanyong.wanfb25d532013-07-28 08:24:00 +00004126
shiqiane35fdd92008-12-10 05:08:54 +00004127// _ is a matcher that matches anything of any type.
4128//
4129// This definition is fine as:
4130//
4131// 1. The C++ standard permits using the name _ in a namespace that
4132// is not the global namespace or ::std.
4133// 2. The AnythingMatcher class has no data member or constructor,
4134// so it's OK to create global variables of this type.
4135// 3. c-style has approved of using _ in this case.
4136const internal::AnythingMatcher _ = {};
4137// Creates a matcher that matches any value of the given type T.
4138template <typename T>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004139inline Matcher<T> A() {
4140 return Matcher<T>(new internal::AnyMatcherImpl<T>());
4141}
shiqiane35fdd92008-12-10 05:08:54 +00004142
4143// Creates a matcher that matches any value of the given type T.
4144template <typename T>
4145inline Matcher<T> An() { return A<T>(); }
4146
4147// Creates a polymorphic matcher that matches anything equal to x.
4148// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
4149// wouldn't compile.
4150template <typename T>
4151inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
4152
4153// Constructs a Matcher<T> from a 'value' of type T. The constructed
4154// matcher matches any value that's equal to 'value'.
4155template <typename T>
4156Matcher<T>::Matcher(T value) { *this = Eq(value); }
4157
Gennadiy Civil466a49a2018-03-23 11:23:54 -04004158template <typename T, typename M>
4159Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(
4160 const M& value,
4161 internal::BooleanConstant<false> /* convertible_to_matcher */,
4162 internal::BooleanConstant<false> /* convertible_to_T */) {
4163 return Eq(value);
4164}
4165
shiqiane35fdd92008-12-10 05:08:54 +00004166// Creates a monomorphic matcher that matches anything with type Lhs
4167// and equal to rhs. A user may need to use this instead of Eq(...)
4168// in order to resolve an overloading ambiguity.
4169//
4170// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
4171// or Matcher<T>(x), but more readable than the latter.
4172//
4173// We could define similar monomorphic matchers for other comparison
4174// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
4175// it yet as those are used much less than Eq() in practice. A user
4176// can always write Matcher<T>(Lt(5)) to be explicit about the type,
4177// for example.
4178template <typename Lhs, typename Rhs>
4179inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
4180
4181// Creates a polymorphic matcher that matches anything >= x.
4182template <typename Rhs>
4183inline internal::GeMatcher<Rhs> Ge(Rhs x) {
4184 return internal::GeMatcher<Rhs>(x);
4185}
4186
4187// Creates a polymorphic matcher that matches anything > x.
4188template <typename Rhs>
4189inline internal::GtMatcher<Rhs> Gt(Rhs x) {
4190 return internal::GtMatcher<Rhs>(x);
4191}
4192
4193// Creates a polymorphic matcher that matches anything <= x.
4194template <typename Rhs>
4195inline internal::LeMatcher<Rhs> Le(Rhs x) {
4196 return internal::LeMatcher<Rhs>(x);
4197}
4198
4199// Creates a polymorphic matcher that matches anything < x.
4200template <typename Rhs>
4201inline internal::LtMatcher<Rhs> Lt(Rhs x) {
4202 return internal::LtMatcher<Rhs>(x);
4203}
4204
4205// Creates a polymorphic matcher that matches anything != x.
4206template <typename Rhs>
4207inline internal::NeMatcher<Rhs> Ne(Rhs x) {
4208 return internal::NeMatcher<Rhs>(x);
4209}
4210
zhanyong.wan2d970ee2009-09-24 21:41:36 +00004211// Creates a polymorphic matcher that matches any NULL pointer.
4212inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
4213 return MakePolymorphicMatcher(internal::IsNullMatcher());
4214}
4215
shiqiane35fdd92008-12-10 05:08:54 +00004216// Creates a polymorphic matcher that matches any non-NULL pointer.
4217// This is convenient as Not(NULL) doesn't compile (the compiler
4218// thinks that that expression is comparing a pointer with an integer).
4219inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
4220 return MakePolymorphicMatcher(internal::NotNullMatcher());
4221}
4222
4223// Creates a polymorphic matcher that matches any argument that
4224// references variable x.
4225template <typename T>
4226inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
4227 return internal::RefMatcher<T&>(x);
4228}
4229
4230// Creates a matcher that matches any double argument approximately
4231// equal to rhs, where two NANs are considered unequal.
4232inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
4233 return internal::FloatingEqMatcher<double>(rhs, false);
4234}
4235
4236// Creates a matcher that matches any double argument approximately
4237// equal to rhs, including NaN values when rhs is NaN.
4238inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
4239 return internal::FloatingEqMatcher<double>(rhs, true);
4240}
4241
zhanyong.wan616180e2013-06-18 18:49:51 +00004242// Creates a matcher that matches any double argument approximately equal to
4243// rhs, up to the specified max absolute error bound, where two NANs are
4244// considered unequal. The max absolute error bound must be non-negative.
4245inline internal::FloatingEqMatcher<double> DoubleNear(
4246 double rhs, double max_abs_error) {
4247 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
4248}
4249
4250// Creates a matcher that matches any double argument approximately equal to
4251// rhs, up to the specified max absolute error bound, including NaN values when
4252// rhs is NaN. The max absolute error bound must be non-negative.
4253inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
4254 double rhs, double max_abs_error) {
4255 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
4256}
4257
shiqiane35fdd92008-12-10 05:08:54 +00004258// Creates a matcher that matches any float argument approximately
4259// equal to rhs, where two NANs are considered unequal.
4260inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
4261 return internal::FloatingEqMatcher<float>(rhs, false);
4262}
4263
zhanyong.wan616180e2013-06-18 18:49:51 +00004264// Creates a matcher that matches any float argument approximately
shiqiane35fdd92008-12-10 05:08:54 +00004265// equal to rhs, including NaN values when rhs is NaN.
4266inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
4267 return internal::FloatingEqMatcher<float>(rhs, true);
4268}
4269
zhanyong.wan616180e2013-06-18 18:49:51 +00004270// Creates a matcher that matches any float argument approximately equal to
4271// rhs, up to the specified max absolute error bound, where two NANs are
4272// considered unequal. The max absolute error bound must be non-negative.
4273inline internal::FloatingEqMatcher<float> FloatNear(
4274 float rhs, float max_abs_error) {
4275 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
4276}
4277
4278// Creates a matcher that matches any float argument approximately equal to
4279// rhs, up to the specified max absolute error bound, including NaN values when
4280// rhs is NaN. The max absolute error bound must be non-negative.
4281inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
4282 float rhs, float max_abs_error) {
4283 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
4284}
4285
shiqiane35fdd92008-12-10 05:08:54 +00004286// Creates a matcher that matches a pointer (raw or smart) that points
4287// to a value that matches inner_matcher.
4288template <typename InnerMatcher>
4289inline internal::PointeeMatcher<InnerMatcher> Pointee(
4290 const InnerMatcher& inner_matcher) {
4291 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
4292}
4293
billydonahue1f5fdea2014-05-19 17:54:51 +00004294// Creates a matcher that matches a pointer or reference that matches
4295// inner_matcher when dynamic_cast<To> is applied.
4296// The result of dynamic_cast<To> is forwarded to the inner matcher.
4297// If To is a pointer and the cast fails, the inner matcher will receive NULL.
4298// If To is a reference and the cast fails, this matcher returns false
4299// immediately.
4300template <typename To>
4301inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
4302WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
4303 return MakePolymorphicMatcher(
4304 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
4305}
4306
shiqiane35fdd92008-12-10 05:08:54 +00004307// Creates a matcher that matches an object whose given field matches
4308// 'matcher'. For example,
4309// Field(&Foo::number, Ge(5))
4310// matches a Foo object x iff x.number >= 5.
4311template <typename Class, typename FieldType, typename FieldMatcher>
4312inline PolymorphicMatcher<
4313 internal::FieldMatcher<Class, FieldType> > Field(
4314 FieldType Class::*field, const FieldMatcher& matcher) {
4315 return MakePolymorphicMatcher(
4316 internal::FieldMatcher<Class, FieldType>(
4317 field, MatcherCast<const FieldType&>(matcher)));
4318 // The call to MatcherCast() is required for supporting inner
4319 // matchers of compatible types. For example, it allows
4320 // Field(&Foo::bar, m)
4321 // to compile where bar is an int32 and m is a matcher for int64.
4322}
4323
Gennadiy Civilb907c262018-03-23 11:42:41 -04004324// Same as Field() but also takes the name of the field to provide better error
4325// messages.
4326template <typename Class, typename FieldType, typename FieldMatcher>
4327inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType> > Field(
4328 const std::string& field_name, FieldType Class::*field,
4329 const FieldMatcher& matcher) {
4330 return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(
4331 field_name, field, MatcherCast<const FieldType&>(matcher)));
4332}
4333
shiqiane35fdd92008-12-10 05:08:54 +00004334// Creates a matcher that matches an object whose given property
4335// matches 'matcher'. For example,
4336// Property(&Foo::str, StartsWith("hi"))
4337// matches a Foo object x iff x.str() starts with "hi".
4338template <typename Class, typename PropertyType, typename PropertyMatcher>
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004339inline PolymorphicMatcher<internal::PropertyMatcher<
4340 Class, PropertyType, PropertyType (Class::*)() const> >
4341Property(PropertyType (Class::*property)() const,
4342 const PropertyMatcher& matcher) {
shiqiane35fdd92008-12-10 05:08:54 +00004343 return MakePolymorphicMatcher(
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004344 internal::PropertyMatcher<Class, PropertyType,
4345 PropertyType (Class::*)() const>(
shiqiane35fdd92008-12-10 05:08:54 +00004346 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00004347 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00004348 // The call to MatcherCast() is required for supporting inner
4349 // matchers of compatible types. For example, it allows
4350 // Property(&Foo::bar, m)
4351 // to compile where bar() returns an int32 and m is a matcher for int64.
4352}
4353
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004354#if GTEST_LANG_CXX11
4355// The same as above but for reference-qualified member functions.
4356template <typename Class, typename PropertyType, typename PropertyMatcher>
4357inline PolymorphicMatcher<internal::PropertyMatcher<
4358 Class, PropertyType, PropertyType (Class::*)() const &> >
4359Property(PropertyType (Class::*property)() const &,
4360 const PropertyMatcher& matcher) {
4361 return MakePolymorphicMatcher(
4362 internal::PropertyMatcher<Class, PropertyType,
4363 PropertyType (Class::*)() const &>(
4364 property,
4365 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4366}
4367#endif
4368
shiqiane35fdd92008-12-10 05:08:54 +00004369// Creates a matcher that matches an object iff the result of applying
4370// a callable to x matches 'matcher'.
4371// For example,
4372// ResultOf(f, StartsWith("hi"))
4373// matches a Foo object x iff f(x) starts with "hi".
4374// callable parameter can be a function, function pointer, or a functor.
4375// Callable has to satisfy the following conditions:
4376// * It is required to keep no state affecting the results of
4377// the calls on it and make no assumptions about how many calls
4378// will be made. Any state it keeps must be protected from the
4379// concurrent access.
4380// * If it is a function object, it has to define type result_type.
4381// We recommend deriving your functor classes from std::unary_function.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004382//
shiqiane35fdd92008-12-10 05:08:54 +00004383template <typename Callable, typename ResultOfMatcher>
4384internal::ResultOfMatcher<Callable> ResultOf(
4385 Callable callable, const ResultOfMatcher& matcher) {
4386 return internal::ResultOfMatcher<Callable>(
4387 callable,
4388 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
4389 matcher));
4390 // The call to MatcherCast() is required for supporting inner
4391 // matchers of compatible types. For example, it allows
4392 // ResultOf(Function, m)
4393 // to compile where Function() returns an int32 and m is a matcher for int64.
4394}
4395
4396// String matchers.
4397
4398// Matches a string equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04004399inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
4400 const std::string& str) {
4401 return MakePolymorphicMatcher(
4402 internal::StrEqualityMatcher<std::string>(str, true, true));
shiqiane35fdd92008-12-10 05:08:54 +00004403}
4404
4405// Matches a string not equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04004406inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
4407 const std::string& str) {
4408 return MakePolymorphicMatcher(
4409 internal::StrEqualityMatcher<std::string>(str, false, true));
shiqiane35fdd92008-12-10 05:08:54 +00004410}
4411
4412// Matches a string equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04004413inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
4414 const std::string& str) {
4415 return MakePolymorphicMatcher(
4416 internal::StrEqualityMatcher<std::string>(str, true, false));
shiqiane35fdd92008-12-10 05:08:54 +00004417}
4418
4419// Matches a string not equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04004420inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
4421 const std::string& str) {
4422 return MakePolymorphicMatcher(
4423 internal::StrEqualityMatcher<std::string>(str, false, false));
shiqiane35fdd92008-12-10 05:08:54 +00004424}
4425
4426// Creates a matcher that matches any string, std::string, or C string
4427// that contains the given substring.
Nico Weber09fd5b32017-05-15 17:07:03 -04004428inline PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
4429 const std::string& substring) {
4430 return MakePolymorphicMatcher(
4431 internal::HasSubstrMatcher<std::string>(substring));
shiqiane35fdd92008-12-10 05:08:54 +00004432}
4433
4434// Matches a string that starts with 'prefix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004435inline PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
4436 const std::string& prefix) {
4437 return MakePolymorphicMatcher(
4438 internal::StartsWithMatcher<std::string>(prefix));
shiqiane35fdd92008-12-10 05:08:54 +00004439}
4440
4441// Matches a string that ends with 'suffix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004442inline PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
4443 const std::string& suffix) {
4444 return MakePolymorphicMatcher(internal::EndsWithMatcher<std::string>(suffix));
shiqiane35fdd92008-12-10 05:08:54 +00004445}
4446
shiqiane35fdd92008-12-10 05:08:54 +00004447// Matches a string that fully matches regular expression 'regex'.
4448// The matcher takes ownership of 'regex'.
4449inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4450 const internal::RE* regex) {
4451 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
4452}
4453inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004454 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004455 return MatchesRegex(new internal::RE(regex));
4456}
4457
4458// Matches a string that contains regular expression 'regex'.
4459// The matcher takes ownership of 'regex'.
4460inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4461 const internal::RE* regex) {
4462 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4463}
4464inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004465 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004466 return ContainsRegex(new internal::RE(regex));
4467}
4468
shiqiane35fdd92008-12-10 05:08:54 +00004469#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4470// Wide string matchers.
4471
4472// Matches a string equal to str.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004473inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrEq(
4474 const std::wstring& str) {
4475 return MakePolymorphicMatcher(
4476 internal::StrEqualityMatcher<std::wstring>(str, true, true));
shiqiane35fdd92008-12-10 05:08:54 +00004477}
4478
4479// Matches a string not equal to str.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004480inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrNe(
4481 const std::wstring& str) {
4482 return MakePolymorphicMatcher(
4483 internal::StrEqualityMatcher<std::wstring>(str, false, true));
shiqiane35fdd92008-12-10 05:08:54 +00004484}
4485
4486// Matches a string equal to str, ignoring case.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004487inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
4488StrCaseEq(const std::wstring& str) {
4489 return MakePolymorphicMatcher(
4490 internal::StrEqualityMatcher<std::wstring>(str, true, false));
shiqiane35fdd92008-12-10 05:08:54 +00004491}
4492
4493// Matches a string not equal to str, ignoring case.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004494inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
4495StrCaseNe(const std::wstring& str) {
4496 return MakePolymorphicMatcher(
4497 internal::StrEqualityMatcher<std::wstring>(str, false, false));
shiqiane35fdd92008-12-10 05:08:54 +00004498}
4499
Gennadiy Civilb907c262018-03-23 11:42:41 -04004500// Creates a matcher that matches any ::wstring, std::wstring, or C wide string
shiqiane35fdd92008-12-10 05:08:54 +00004501// that contains the given substring.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004502inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring> > HasSubstr(
4503 const std::wstring& substring) {
4504 return MakePolymorphicMatcher(
4505 internal::HasSubstrMatcher<std::wstring>(substring));
shiqiane35fdd92008-12-10 05:08:54 +00004506}
4507
4508// Matches a string that starts with 'prefix' (case-sensitive).
Gennadiy Civilb907c262018-03-23 11:42:41 -04004509inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring> >
4510StartsWith(const std::wstring& prefix) {
4511 return MakePolymorphicMatcher(
4512 internal::StartsWithMatcher<std::wstring>(prefix));
shiqiane35fdd92008-12-10 05:08:54 +00004513}
4514
4515// Matches a string that ends with 'suffix' (case-sensitive).
Gennadiy Civilb907c262018-03-23 11:42:41 -04004516inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring> > EndsWith(
4517 const std::wstring& suffix) {
4518 return MakePolymorphicMatcher(
4519 internal::EndsWithMatcher<std::wstring>(suffix));
shiqiane35fdd92008-12-10 05:08:54 +00004520}
4521
4522#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4523
4524// Creates a polymorphic matcher that matches a 2-tuple where the
4525// first field == the second field.
4526inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4527
4528// Creates a polymorphic matcher that matches a 2-tuple where the
4529// first field >= the second field.
4530inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4531
4532// Creates a polymorphic matcher that matches a 2-tuple where the
4533// first field > the second field.
4534inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4535
4536// Creates a polymorphic matcher that matches a 2-tuple where the
4537// first field <= the second field.
4538inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4539
4540// Creates a polymorphic matcher that matches a 2-tuple where the
4541// first field < the second field.
4542inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4543
4544// Creates a polymorphic matcher that matches a 2-tuple where the
4545// first field != the second field.
4546inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4547
Gennadiy Civilb907c262018-03-23 11:42:41 -04004548// Creates a polymorphic matcher that matches a 2-tuple where
4549// FloatEq(first field) matches the second field.
4550inline internal::FloatingEq2Matcher<float> FloatEq() {
4551 return internal::FloatingEq2Matcher<float>();
4552}
4553
4554// Creates a polymorphic matcher that matches a 2-tuple where
4555// DoubleEq(first field) matches the second field.
4556inline internal::FloatingEq2Matcher<double> DoubleEq() {
4557 return internal::FloatingEq2Matcher<double>();
4558}
4559
4560// Creates a polymorphic matcher that matches a 2-tuple where
4561// FloatEq(first field) matches the second field with NaN equality.
4562inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() {
4563 return internal::FloatingEq2Matcher<float>(true);
4564}
4565
4566// Creates a polymorphic matcher that matches a 2-tuple where
4567// DoubleEq(first field) matches the second field with NaN equality.
4568inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() {
4569 return internal::FloatingEq2Matcher<double>(true);
4570}
4571
4572// Creates a polymorphic matcher that matches a 2-tuple where
4573// FloatNear(first field, max_abs_error) matches the second field.
4574inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) {
4575 return internal::FloatingEq2Matcher<float>(max_abs_error);
4576}
4577
4578// Creates a polymorphic matcher that matches a 2-tuple where
4579// DoubleNear(first field, max_abs_error) matches the second field.
4580inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) {
4581 return internal::FloatingEq2Matcher<double>(max_abs_error);
4582}
4583
4584// Creates a polymorphic matcher that matches a 2-tuple where
4585// FloatNear(first field, max_abs_error) matches the second field with NaN
4586// equality.
4587inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear(
4588 float max_abs_error) {
4589 return internal::FloatingEq2Matcher<float>(max_abs_error, true);
4590}
4591
4592// Creates a polymorphic matcher that matches a 2-tuple where
4593// DoubleNear(first field, max_abs_error) matches the second field with NaN
4594// equality.
4595inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear(
4596 double max_abs_error) {
4597 return internal::FloatingEq2Matcher<double>(max_abs_error, true);
4598}
4599
shiqiane35fdd92008-12-10 05:08:54 +00004600// Creates a matcher that matches any value of type T that m doesn't
4601// match.
4602template <typename InnerMatcher>
4603inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4604 return internal::NotMatcher<InnerMatcher>(m);
4605}
4606
shiqiane35fdd92008-12-10 05:08:54 +00004607// Returns a matcher that matches anything that satisfies the given
4608// predicate. The predicate can be any unary function or functor
4609// whose return type can be implicitly converted to bool.
4610template <typename Predicate>
4611inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4612Truly(Predicate pred) {
4613 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4614}
4615
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004616// Returns a matcher that matches the container size. The container must
4617// support both size() and size_type which all STL-like containers provide.
4618// Note that the parameter 'size' can be a value of type size_type as well as
4619// matcher. For instance:
4620// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
4621// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
4622template <typename SizeMatcher>
4623inline internal::SizeIsMatcher<SizeMatcher>
4624SizeIs(const SizeMatcher& size_matcher) {
4625 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4626}
4627
kosakb6a34882014-03-12 21:06:46 +00004628// Returns a matcher that matches the distance between the container's begin()
4629// iterator and its end() iterator, i.e. the size of the container. This matcher
4630// can be used instead of SizeIs with containers such as std::forward_list which
4631// do not implement size(). The container must provide const_iterator (with
4632// valid iterator_traits), begin() and end().
4633template <typename DistanceMatcher>
4634inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4635BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4636 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4637}
4638
zhanyong.wan6a896b52009-01-16 01:13:50 +00004639// Returns a matcher that matches an equal container.
4640// This matcher behaves like Eq(), but in the event of mismatch lists the
4641// values that are included in one container but not the other. (Duplicate
4642// values and order differences are not explained.)
4643template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00004644inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00004645 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004646 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00004647 // This following line is for working around a bug in MSVC 8.0,
4648 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00004649 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00004650 return MakePolymorphicMatcher(
4651 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00004652}
4653
zhanyong.wan898725c2011-09-16 16:45:39 +00004654// Returns a matcher that matches a container that, when sorted using
4655// the given comparator, matches container_matcher.
4656template <typename Comparator, typename ContainerMatcher>
4657inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4658WhenSortedBy(const Comparator& comparator,
4659 const ContainerMatcher& container_matcher) {
4660 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4661 comparator, container_matcher);
4662}
4663
4664// Returns a matcher that matches a container that, when sorted using
4665// the < operator, matches container_matcher.
4666template <typename ContainerMatcher>
4667inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4668WhenSorted(const ContainerMatcher& container_matcher) {
4669 return
4670 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4671 internal::LessComparator(), container_matcher);
4672}
4673
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004674// Matches an STL-style container or a native array that contains the
4675// same number of elements as in rhs, where its i-th element and rhs's
4676// i-th element (as a pair) satisfy the given pair matcher, for all i.
4677// TupleMatcher must be able to be safely cast to Matcher<tuple<const
4678// T1&, const T2&> >, where T1 and T2 are the types of elements in the
4679// LHS container and the RHS container respectively.
4680template <typename TupleMatcher, typename Container>
4681inline internal::PointwiseMatcher<TupleMatcher,
4682 GTEST_REMOVE_CONST_(Container)>
4683Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4684 // This following line is for working around a bug in MSVC 8.0,
kosak2336e9c2014-07-28 22:57:30 +00004685 // which causes Container to be a const type sometimes (e.g. when
4686 // rhs is a const int[])..
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004687 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4688 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4689 tuple_matcher, rhs);
4690}
4691
kosak2336e9c2014-07-28 22:57:30 +00004692#if GTEST_HAS_STD_INITIALIZER_LIST_
4693
4694// Supports the Pointwise(m, {a, b, c}) syntax.
4695template <typename TupleMatcher, typename T>
4696inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4697 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4698 return Pointwise(tuple_matcher, std::vector<T>(rhs));
4699}
4700
4701#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4702
4703// UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4704// container or a native array that contains the same number of
4705// elements as in rhs, where in some permutation of the container, its
4706// i-th element and rhs's i-th element (as a pair) satisfy the given
4707// pair matcher, for all i. Tuple2Matcher must be able to be safely
4708// cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4709// the types of elements in the LHS container and the RHS container
4710// respectively.
4711//
4712// This is like Pointwise(pair_matcher, rhs), except that the element
4713// order doesn't matter.
4714template <typename Tuple2Matcher, typename RhsContainer>
4715inline internal::UnorderedElementsAreArrayMatcher<
4716 typename internal::BoundSecondMatcher<
4717 Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4718 RhsContainer)>::type::value_type> >
4719UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4720 const RhsContainer& rhs_container) {
4721 // This following line is for working around a bug in MSVC 8.0,
4722 // which causes RhsContainer to be a const type sometimes (e.g. when
4723 // rhs_container is a const int[]).
4724 typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4725
4726 // RhsView allows the same code to handle RhsContainer being a
4727 // STL-style container and it being a native C-style array.
4728 typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4729 typedef typename RhsView::type RhsStlContainer;
4730 typedef typename RhsStlContainer::value_type Second;
4731 const RhsStlContainer& rhs_stl_container =
4732 RhsView::ConstReference(rhs_container);
4733
4734 // Create a matcher for each element in rhs_container.
4735 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4736 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4737 it != rhs_stl_container.end(); ++it) {
4738 matchers.push_back(
4739 internal::MatcherBindSecond(tuple2_matcher, *it));
4740 }
4741
4742 // Delegate the work to UnorderedElementsAreArray().
4743 return UnorderedElementsAreArray(matchers);
4744}
4745
4746#if GTEST_HAS_STD_INITIALIZER_LIST_
4747
4748// Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4749template <typename Tuple2Matcher, typename T>
4750inline internal::UnorderedElementsAreArrayMatcher<
4751 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4752UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4753 std::initializer_list<T> rhs) {
4754 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4755}
4756
4757#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4758
zhanyong.wanb8243162009-06-04 05:48:20 +00004759// Matches an STL-style container or a native array that contains at
4760// least one element matching the given value or matcher.
4761//
4762// Examples:
4763// ::std::set<int> page_ids;
4764// page_ids.insert(3);
4765// page_ids.insert(1);
4766// EXPECT_THAT(page_ids, Contains(1));
4767// EXPECT_THAT(page_ids, Contains(Gt(2)));
4768// EXPECT_THAT(page_ids, Not(Contains(4)));
4769//
4770// ::std::map<int, size_t> page_lengths;
4771// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00004772// EXPECT_THAT(page_lengths,
4773// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004774//
4775// const char* user_ids[] = { "joe", "mike", "tom" };
4776// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4777template <typename M>
4778inline internal::ContainsMatcher<M> Contains(M matcher) {
4779 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004780}
4781
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004782// IsSupersetOf(iterator_first, iterator_last)
4783// IsSupersetOf(pointer, count)
4784// IsSupersetOf(array)
4785// IsSupersetOf(container)
4786// IsSupersetOf({e1, e2, ..., en})
4787//
4788// IsSupersetOf() verifies that a surjective partial mapping onto a collection
4789// of matchers exists. In other words, a container matches
4790// IsSupersetOf({e1, ..., en}) if and only if there is a permutation
4791// {y1, ..., yn} of some of the container's elements where y1 matches e1,
4792// ..., and yn matches en. Obviously, the size of the container must be >= n
4793// in order to have a match. Examples:
4794//
4795// - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and
4796// 1 matches Ne(0).
4797// - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches
4798// both Eq(1) and Lt(2). The reason is that different matchers must be used
4799// for elements in different slots of the container.
4800// - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches
4801// Eq(1) and (the second) 1 matches Lt(2).
4802// - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)
4803// Gt(1) and 3 matches (the second) Gt(1).
4804//
4805// The matchers can be specified as an array, a pointer and count, a container,
4806// an initializer list, or an STL iterator range. In each of these cases, the
4807// underlying matchers can be either values or matchers.
4808
4809template <typename Iter>
4810inline internal::UnorderedElementsAreArrayMatcher<
4811 typename ::std::iterator_traits<Iter>::value_type>
4812IsSupersetOf(Iter first, Iter last) {
4813 typedef typename ::std::iterator_traits<Iter>::value_type T;
4814 return internal::UnorderedElementsAreArrayMatcher<T>(
4815 internal::UnorderedMatcherRequire::Superset, first, last);
4816}
4817
4818template <typename T>
4819inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
4820 const T* pointer, size_t count) {
4821 return IsSupersetOf(pointer, pointer + count);
4822}
4823
4824template <typename T, size_t N>
4825inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
4826 const T (&array)[N]) {
4827 return IsSupersetOf(array, N);
4828}
4829
4830template <typename Container>
4831inline internal::UnorderedElementsAreArrayMatcher<
4832 typename Container::value_type>
4833IsSupersetOf(const Container& container) {
4834 return IsSupersetOf(container.begin(), container.end());
4835}
4836
4837#if GTEST_HAS_STD_INITIALIZER_LIST_
4838template <typename T>
4839inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
4840 ::std::initializer_list<T> xs) {
4841 return IsSupersetOf(xs.begin(), xs.end());
4842}
4843#endif
4844
4845// IsSubsetOf(iterator_first, iterator_last)
4846// IsSubsetOf(pointer, count)
4847// IsSubsetOf(array)
4848// IsSubsetOf(container)
4849// IsSubsetOf({e1, e2, ..., en})
4850//
4851// IsSubsetOf() verifies that an injective mapping onto a collection of matchers
4852// exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and
4853// only if there is a subset of matchers {m1, ..., mk} which would match the
4854// container using UnorderedElementsAre. Obviously, the size of the container
4855// must be <= n in order to have a match. Examples:
4856//
4857// - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).
4858// - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1
4859// matches Lt(0).
4860// - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both
4861// match Gt(0). The reason is that different matchers must be used for
4862// elements in different slots of the container.
4863//
4864// The matchers can be specified as an array, a pointer and count, a container,
4865// an initializer list, or an STL iterator range. In each of these cases, the
4866// underlying matchers can be either values or matchers.
4867
4868template <typename Iter>
4869inline internal::UnorderedElementsAreArrayMatcher<
4870 typename ::std::iterator_traits<Iter>::value_type>
4871IsSubsetOf(Iter first, Iter last) {
4872 typedef typename ::std::iterator_traits<Iter>::value_type T;
4873 return internal::UnorderedElementsAreArrayMatcher<T>(
4874 internal::UnorderedMatcherRequire::Subset, first, last);
4875}
4876
4877template <typename T>
4878inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
4879 const T* pointer, size_t count) {
4880 return IsSubsetOf(pointer, pointer + count);
4881}
4882
4883template <typename T, size_t N>
4884inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
4885 const T (&array)[N]) {
4886 return IsSubsetOf(array, N);
4887}
4888
4889template <typename Container>
4890inline internal::UnorderedElementsAreArrayMatcher<
4891 typename Container::value_type>
4892IsSubsetOf(const Container& container) {
4893 return IsSubsetOf(container.begin(), container.end());
4894}
4895
4896#if GTEST_HAS_STD_INITIALIZER_LIST_
4897template <typename T>
4898inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
4899 ::std::initializer_list<T> xs) {
4900 return IsSubsetOf(xs.begin(), xs.end());
4901}
4902#endif
4903
zhanyong.wan33605ba2010-04-22 23:37:47 +00004904// Matches an STL-style container or a native array that contains only
4905// elements matching the given value or matcher.
4906//
4907// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
4908// the messages are different.
4909//
4910// Examples:
4911// ::std::set<int> page_ids;
4912// // Each(m) matches an empty container, regardless of what m is.
4913// EXPECT_THAT(page_ids, Each(Eq(1)));
4914// EXPECT_THAT(page_ids, Each(Eq(77)));
4915//
4916// page_ids.insert(3);
4917// EXPECT_THAT(page_ids, Each(Gt(0)));
4918// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
4919// page_ids.insert(1);
4920// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
4921//
4922// ::std::map<int, size_t> page_lengths;
4923// page_lengths[1] = 100;
4924// page_lengths[2] = 200;
4925// page_lengths[3] = 300;
4926// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
4927// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
4928//
4929// const char* user_ids[] = { "joe", "mike", "tom" };
4930// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
4931template <typename M>
4932inline internal::EachMatcher<M> Each(M matcher) {
4933 return internal::EachMatcher<M>(matcher);
4934}
4935
zhanyong.wanb5937da2009-07-16 20:26:41 +00004936// Key(inner_matcher) matches an std::pair whose 'first' field matches
4937// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
4938// std::map that contains at least one element whose key is >= 5.
4939template <typename M>
4940inline internal::KeyMatcher<M> Key(M inner_matcher) {
4941 return internal::KeyMatcher<M>(inner_matcher);
4942}
4943
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00004944// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
4945// matches first_matcher and whose 'second' field matches second_matcher. For
4946// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
4947// to match a std::map<int, string> that contains exactly one element whose key
4948// is >= 5 and whose value equals "foo".
4949template <typename FirstMatcher, typename SecondMatcher>
4950inline internal::PairMatcher<FirstMatcher, SecondMatcher>
4951Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
4952 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
4953 first_matcher, second_matcher);
4954}
4955
shiqiane35fdd92008-12-10 05:08:54 +00004956// Returns a predicate that is satisfied by anything that matches the
4957// given matcher.
4958template <typename M>
4959inline internal::MatcherAsPredicate<M> Matches(M matcher) {
4960 return internal::MatcherAsPredicate<M>(matcher);
4961}
4962
zhanyong.wanb8243162009-06-04 05:48:20 +00004963// Returns true iff the value matches the matcher.
4964template <typename T, typename M>
4965inline bool Value(const T& value, M matcher) {
4966 return testing::Matches(matcher)(value);
4967}
4968
zhanyong.wan34b034c2010-03-05 21:23:23 +00004969// Matches the value against the given matcher and explains the match
4970// result to listener.
4971template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00004972inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00004973 M matcher, const T& value, MatchResultListener* listener) {
4974 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
4975}
4976
Gennadiy Civilb907c262018-03-23 11:42:41 -04004977// Returns a string representation of the given matcher. Useful for description
4978// strings of matchers defined using MATCHER_P* macros that accept matchers as
4979// their arguments. For example:
4980//
4981// MATCHER_P(XAndYThat, matcher,
4982// "X that " + DescribeMatcher<int>(matcher, negation) +
4983// " and Y that " + DescribeMatcher<double>(matcher, negation)) {
4984// return ExplainMatchResult(matcher, arg.x(), result_listener) &&
4985// ExplainMatchResult(matcher, arg.y(), result_listener);
4986// }
4987template <typename T, typename M>
4988std::string DescribeMatcher(const M& matcher, bool negation = false) {
4989 ::std::stringstream ss;
4990 Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher);
4991 if (negation) {
4992 monomorphic_matcher.DescribeNegationTo(&ss);
4993 } else {
4994 monomorphic_matcher.DescribeTo(&ss);
4995 }
4996 return ss.str();
4997}
4998
zhanyong.wan616180e2013-06-18 18:49:51 +00004999#if GTEST_LANG_CXX11
5000// Define variadic matcher versions. They are overloaded in
5001// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
5002template <typename... Args>
5003inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
5004 return internal::AllOfMatcher<Args...>(matchers...);
5005}
5006
5007template <typename... Args>
5008inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
5009 return internal::AnyOfMatcher<Args...>(matchers...);
5010}
5011
5012#endif // GTEST_LANG_CXX11
5013
zhanyong.wanbf550852009-06-09 06:09:53 +00005014// AllArgs(m) is a synonym of m. This is useful in
5015//
5016// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
5017//
5018// which is easier to read than
5019//
5020// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
5021template <typename InnerMatcher>
5022inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
5023
Gennadiy Civilb907c262018-03-23 11:42:41 -04005024// Returns a matcher that matches the value of an optional<> type variable.
5025// The matcher implementation only uses '!arg' and requires that the optional<>
5026// type has a 'value_type' member type and that '*arg' is of type 'value_type'
5027// and is printable using 'PrintToString'. It is compatible with
5028// std::optional/std::experimental::optional.
5029// Note that to compare an optional type variable against nullopt you should
5030// use Eq(nullopt) and not Optional(Eq(nullopt)). The latter implies that the
5031// optional value contains an optional itself.
5032template <typename ValueMatcher>
5033inline internal::OptionalMatcher<ValueMatcher> Optional(
5034 const ValueMatcher& value_matcher) {
5035 return internal::OptionalMatcher<ValueMatcher>(value_matcher);
5036}
5037
5038// Returns a matcher that matches the value of a absl::any type variable.
5039template <typename T>
5040PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T> > AnyWith(
5041 const Matcher<const T&>& matcher) {
5042 return MakePolymorphicMatcher(
5043 internal::any_cast_matcher::AnyCastMatcher<T>(matcher));
5044}
5045
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05005046// Returns a matcher that matches the value of a variant<> type variable.
5047// The matcher implementation uses ADL to find the holds_alternative and get
5048// functions.
5049// It is compatible with std::variant.
5050template <typename T>
5051PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
5052 const Matcher<const T&>& matcher) {
5053 return MakePolymorphicMatcher(
5054 internal::variant_matcher::VariantMatcher<T>(matcher));
5055}
5056
shiqiane35fdd92008-12-10 05:08:54 +00005057// These macros allow using matchers to check values in Google Test
5058// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
5059// succeed iff the value matches the matcher. If the assertion fails,
5060// the value and the description of the matcher will be printed.
5061#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
5062 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
5063#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
5064 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
5065
5066} // namespace testing
5067
kosak6702b972015-07-27 23:05:57 +00005068// Include any custom callback matchers added by the local installation.
5069// We must include this header at the end to make sure it can use the
5070// declarations from this file.
5071#include "gmock/internal/custom/gmock-matchers.h"
Gennadiy Civilb907c262018-03-23 11:42:41 -04005072
shiqiane35fdd92008-12-10 05:08:54 +00005073#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_