blob: e67500d16af1cdb0816bef5b7812cb7e3786dd2b [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 {
Gennadiy Civil23187052018-03-26 10:16:59 -04002865 GTEST_COMPILE_ASSERT_(
2866 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value,
2867 use_UnorderedPointwise_with_hash_tables);
2868
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002869 public:
2870 typedef internal::StlContainerView<RhsContainer> RhsView;
2871 typedef typename RhsView::type RhsStlContainer;
2872 typedef typename RhsStlContainer::value_type RhsValue;
2873
2874 // Like ContainerEq, we make a copy of rhs in case the elements in
2875 // it are modified after this matcher is created.
2876 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2877 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2878 // Makes sure the user doesn't instantiate this class template
2879 // with a const or reference type.
2880 (void)testing::StaticAssertTypeEq<RhsContainer,
2881 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2882 }
2883
2884 template <typename LhsContainer>
2885 operator Matcher<LhsContainer>() const {
Gennadiy Civil23187052018-03-26 10:16:59 -04002886 GTEST_COMPILE_ASSERT_(
2887 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value,
2888 use_UnorderedPointwise_with_hash_tables);
2889
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002890 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2891 }
2892
2893 template <typename LhsContainer>
2894 class Impl : public MatcherInterface<LhsContainer> {
2895 public:
2896 typedef internal::StlContainerView<
2897 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2898 typedef typename LhsView::type LhsStlContainer;
2899 typedef typename LhsView::const_reference LhsStlContainerReference;
2900 typedef typename LhsStlContainer::value_type LhsValue;
2901 // We pass the LHS value and the RHS value to the inner matcher by
2902 // reference, as they may be expensive to copy. We must use tuple
2903 // instead of pair here, as a pair cannot hold references (C++ 98,
2904 // 20.2.2 [lib.pairs]).
kosakbd018832014-04-02 20:30:00 +00002905 typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002906
2907 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2908 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2909 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2910 rhs_(rhs) {}
2911
2912 virtual void DescribeTo(::std::ostream* os) const {
2913 *os << "contains " << rhs_.size()
2914 << " values, where each value and its corresponding value in ";
2915 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2916 *os << " ";
2917 mono_tuple_matcher_.DescribeTo(os);
2918 }
2919 virtual void DescribeNegationTo(::std::ostream* os) const {
2920 *os << "doesn't contain exactly " << rhs_.size()
2921 << " values, or contains a value x at some index i"
2922 << " where x and the i-th value of ";
2923 UniversalPrint(rhs_, os);
2924 *os << " ";
2925 mono_tuple_matcher_.DescribeNegationTo(os);
2926 }
2927
2928 virtual bool MatchAndExplain(LhsContainer lhs,
2929 MatchResultListener* listener) const {
2930 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2931 const size_t actual_size = lhs_stl_container.size();
2932 if (actual_size != rhs_.size()) {
2933 *listener << "which contains " << actual_size << " values";
2934 return false;
2935 }
2936
2937 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2938 typename RhsStlContainer::const_iterator right = rhs_.begin();
2939 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002940 if (listener->IsInterested()) {
2941 StringMatchResultListener inner_listener;
Gennadiy Civil23187052018-03-26 10:16:59 -04002942 // Create InnerMatcherArg as a temporarily object to avoid it outlives
2943 // *left and *right. Dereference or the conversion to `const T&` may
2944 // return temp objects, e.g for vector<bool>.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002945 if (!mono_tuple_matcher_.MatchAndExplain(
Gennadiy Civil23187052018-03-26 10:16:59 -04002946 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
2947 ImplicitCast_<const RhsValue&>(*right)),
2948 &inner_listener)) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002949 *listener << "where the value pair (";
2950 UniversalPrint(*left, listener->stream());
2951 *listener << ", ";
2952 UniversalPrint(*right, listener->stream());
2953 *listener << ") at index #" << i << " don't match";
2954 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2955 return false;
2956 }
2957 } else {
Gennadiy Civil23187052018-03-26 10:16:59 -04002958 if (!mono_tuple_matcher_.Matches(
2959 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
2960 ImplicitCast_<const RhsValue&>(*right))))
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002961 return false;
2962 }
2963 }
2964
2965 return true;
2966 }
2967
2968 private:
2969 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2970 const RhsStlContainer rhs_;
2971
2972 GTEST_DISALLOW_ASSIGN_(Impl);
2973 };
2974
2975 private:
2976 const TupleMatcher tuple_matcher_;
2977 const RhsStlContainer rhs_;
2978
2979 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2980};
2981
zhanyong.wan33605ba2010-04-22 23:37:47 +00002982// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002983template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002984class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002985 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002986 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002987 typedef StlContainerView<RawContainer> View;
2988 typedef typename View::type StlContainer;
2989 typedef typename View::const_reference StlContainerReference;
2990 typedef typename StlContainer::value_type Element;
2991
2992 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002993 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002994 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002995 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002996
zhanyong.wan33605ba2010-04-22 23:37:47 +00002997 // Checks whether:
2998 // * All elements in the container match, if all_elements_should_match.
2999 // * Any element in the container matches, if !all_elements_should_match.
3000 bool MatchAndExplainImpl(bool all_elements_should_match,
3001 Container container,
3002 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00003003 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00003004 size_t i = 0;
3005 for (typename StlContainer::const_iterator it = stl_container.begin();
3006 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003007 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00003008 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
3009
3010 if (matches != all_elements_should_match) {
3011 *listener << "whose element #" << i
3012 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003013 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00003014 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00003015 }
3016 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00003017 return all_elements_should_match;
3018 }
3019
3020 protected:
3021 const Matcher<const Element&> inner_matcher_;
3022
3023 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
3024};
3025
3026// Implements Contains(element_matcher) for the given argument type Container.
3027// Symmetric to EachMatcherImpl.
3028template <typename Container>
3029class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
3030 public:
3031 template <typename InnerMatcher>
3032 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
3033 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3034
3035 // Describes what this matcher does.
3036 virtual void DescribeTo(::std::ostream* os) const {
3037 *os << "contains at least one element that ";
3038 this->inner_matcher_.DescribeTo(os);
3039 }
3040
3041 virtual void DescribeNegationTo(::std::ostream* os) const {
3042 *os << "doesn't contain any element that ";
3043 this->inner_matcher_.DescribeTo(os);
3044 }
3045
3046 virtual bool MatchAndExplain(Container container,
3047 MatchResultListener* listener) const {
3048 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00003049 }
3050
3051 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003052 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00003053};
3054
zhanyong.wan33605ba2010-04-22 23:37:47 +00003055// Implements Each(element_matcher) for the given argument type Container.
3056// Symmetric to ContainsMatcherImpl.
3057template <typename Container>
3058class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
3059 public:
3060 template <typename InnerMatcher>
3061 explicit EachMatcherImpl(InnerMatcher inner_matcher)
3062 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3063
3064 // Describes what this matcher does.
3065 virtual void DescribeTo(::std::ostream* os) const {
3066 *os << "only contains elements that ";
3067 this->inner_matcher_.DescribeTo(os);
3068 }
3069
3070 virtual void DescribeNegationTo(::std::ostream* os) const {
3071 *os << "contains some element that ";
3072 this->inner_matcher_.DescribeNegationTo(os);
3073 }
3074
3075 virtual bool MatchAndExplain(Container container,
3076 MatchResultListener* listener) const {
3077 return this->MatchAndExplainImpl(true, container, listener);
3078 }
3079
3080 private:
3081 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
3082};
3083
zhanyong.wanb8243162009-06-04 05:48:20 +00003084// Implements polymorphic Contains(element_matcher).
3085template <typename M>
3086class ContainsMatcher {
3087 public:
3088 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
3089
3090 template <typename Container>
3091 operator Matcher<Container>() const {
3092 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
3093 }
3094
3095 private:
3096 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003097
3098 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00003099};
3100
zhanyong.wan33605ba2010-04-22 23:37:47 +00003101// Implements polymorphic Each(element_matcher).
3102template <typename M>
3103class EachMatcher {
3104 public:
3105 explicit EachMatcher(M m) : inner_matcher_(m) {}
3106
3107 template <typename Container>
3108 operator Matcher<Container>() const {
3109 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
3110 }
3111
3112 private:
3113 const M inner_matcher_;
3114
3115 GTEST_DISALLOW_ASSIGN_(EachMatcher);
3116};
3117
Gennadiy Civil466a49a2018-03-23 11:23:54 -04003118struct Rank1 {};
3119struct Rank0 : Rank1 {};
3120
3121namespace pair_getters {
3122#if GTEST_LANG_CXX11
3123using std::get;
3124template <typename T>
3125auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT
3126 return get<0>(x);
3127}
3128template <typename T>
3129auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT
3130 return x.first;
3131}
3132
3133template <typename T>
3134auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT
3135 return get<1>(x);
3136}
3137template <typename T>
3138auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT
3139 return x.second;
3140}
3141#else
3142template <typename T>
3143typename T::first_type& First(T& x, Rank0) { // NOLINT
3144 return x.first;
3145}
3146template <typename T>
3147const typename T::first_type& First(const T& x, Rank0) {
3148 return x.first;
3149}
3150
3151template <typename T>
3152typename T::second_type& Second(T& x, Rank0) { // NOLINT
3153 return x.second;
3154}
3155template <typename T>
3156const typename T::second_type& Second(const T& x, Rank0) {
3157 return x.second;
3158}
3159#endif // GTEST_LANG_CXX11
3160} // namespace pair_getters
3161
zhanyong.wanb5937da2009-07-16 20:26:41 +00003162// Implements Key(inner_matcher) for the given argument pair type.
3163// Key(inner_matcher) matches an std::pair whose 'first' field matches
3164// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3165// std::map that contains at least one element whose key is >= 5.
3166template <typename PairType>
3167class KeyMatcherImpl : public MatcherInterface<PairType> {
3168 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003169 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00003170 typedef typename RawPairType::first_type KeyType;
3171
3172 template <typename InnerMatcher>
3173 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
3174 : inner_matcher_(
3175 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
3176 }
3177
3178 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00003179 virtual bool MatchAndExplain(PairType key_value,
3180 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003181 StringMatchResultListener inner_listener;
Gennadiy Civil23187052018-03-26 10:16:59 -04003182 const bool match = inner_matcher_.MatchAndExplain(
3183 pair_getters::First(key_value, Rank0()), &inner_listener);
Nico Weber09fd5b32017-05-15 17:07:03 -04003184 const std::string explanation = inner_listener.str();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003185 if (explanation != "") {
3186 *listener << "whose first field is a value " << explanation;
3187 }
3188 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00003189 }
3190
3191 // Describes what this matcher does.
3192 virtual void DescribeTo(::std::ostream* os) const {
3193 *os << "has a key that ";
3194 inner_matcher_.DescribeTo(os);
3195 }
3196
3197 // Describes what the negation of this matcher does.
3198 virtual void DescribeNegationTo(::std::ostream* os) const {
3199 *os << "doesn't have a key that ";
3200 inner_matcher_.DescribeTo(os);
3201 }
3202
zhanyong.wanb5937da2009-07-16 20:26:41 +00003203 private:
3204 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003205
3206 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00003207};
3208
3209// Implements polymorphic Key(matcher_for_key).
3210template <typename M>
3211class KeyMatcher {
3212 public:
3213 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
3214
3215 template <typename PairType>
3216 operator Matcher<PairType>() const {
3217 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
3218 }
3219
3220 private:
3221 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003222
3223 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00003224};
3225
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003226// Implements Pair(first_matcher, second_matcher) for the given argument pair
3227// type with its two matchers. See Pair() function below.
3228template <typename PairType>
3229class PairMatcherImpl : public MatcherInterface<PairType> {
3230 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003231 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003232 typedef typename RawPairType::first_type FirstType;
3233 typedef typename RawPairType::second_type SecondType;
3234
3235 template <typename FirstMatcher, typename SecondMatcher>
3236 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
3237 : first_matcher_(
3238 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
3239 second_matcher_(
3240 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
3241 }
3242
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003243 // Describes what this matcher does.
3244 virtual void DescribeTo(::std::ostream* os) const {
3245 *os << "has a first field that ";
3246 first_matcher_.DescribeTo(os);
3247 *os << ", and has a second field that ";
3248 second_matcher_.DescribeTo(os);
3249 }
3250
3251 // Describes what the negation of this matcher does.
3252 virtual void DescribeNegationTo(::std::ostream* os) const {
3253 *os << "has a first field that ";
3254 first_matcher_.DescribeNegationTo(os);
3255 *os << ", or has a second field that ";
3256 second_matcher_.DescribeNegationTo(os);
3257 }
3258
zhanyong.wan82113312010-01-08 21:55:40 +00003259 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3260 // matches second_matcher.
3261 virtual bool MatchAndExplain(PairType a_pair,
3262 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003263 if (!listener->IsInterested()) {
3264 // If the listener is not interested, we don't need to construct the
3265 // explanation.
3266 return first_matcher_.Matches(a_pair.first) &&
3267 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00003268 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003269 StringMatchResultListener first_inner_listener;
3270 if (!first_matcher_.MatchAndExplain(a_pair.first,
3271 &first_inner_listener)) {
3272 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003273 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003274 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003275 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003276 StringMatchResultListener second_inner_listener;
3277 if (!second_matcher_.MatchAndExplain(a_pair.second,
3278 &second_inner_listener)) {
3279 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003280 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003281 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003282 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003283 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3284 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00003285 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003286 }
3287
3288 private:
Nico Weber09fd5b32017-05-15 17:07:03 -04003289 void ExplainSuccess(const std::string& first_explanation,
3290 const std::string& second_explanation,
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003291 MatchResultListener* listener) const {
3292 *listener << "whose both fields match";
3293 if (first_explanation != "") {
3294 *listener << ", where the first field is a value " << first_explanation;
3295 }
3296 if (second_explanation != "") {
3297 *listener << ", ";
3298 if (first_explanation != "") {
3299 *listener << "and ";
3300 } else {
3301 *listener << "where ";
3302 }
3303 *listener << "the second field is a value " << second_explanation;
3304 }
3305 }
3306
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003307 const Matcher<const FirstType&> first_matcher_;
3308 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003309
3310 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003311};
3312
3313// Implements polymorphic Pair(first_matcher, second_matcher).
3314template <typename FirstMatcher, typename SecondMatcher>
3315class PairMatcher {
3316 public:
3317 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3318 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3319
3320 template <typename PairType>
3321 operator Matcher<PairType> () const {
3322 return MakeMatcher(
3323 new PairMatcherImpl<PairType>(
3324 first_matcher_, second_matcher_));
3325 }
3326
3327 private:
3328 const FirstMatcher first_matcher_;
3329 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003330
3331 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003332};
3333
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003334// Implements ElementsAre() and ElementsAreArray().
3335template <typename Container>
3336class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3337 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003338 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003339 typedef internal::StlContainerView<RawContainer> View;
3340 typedef typename View::type StlContainer;
3341 typedef typename View::const_reference StlContainerReference;
3342 typedef typename StlContainer::value_type Element;
3343
3344 // Constructs the matcher from a sequence of element values or
3345 // element matchers.
3346 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00003347 ElementsAreMatcherImpl(InputIter first, InputIter last) {
3348 while (first != last) {
3349 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003350 }
3351 }
3352
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003353 // Describes what this matcher does.
3354 virtual void DescribeTo(::std::ostream* os) const {
3355 if (count() == 0) {
3356 *os << "is empty";
3357 } else if (count() == 1) {
3358 *os << "has 1 element that ";
3359 matchers_[0].DescribeTo(os);
3360 } else {
3361 *os << "has " << Elements(count()) << " where\n";
3362 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003363 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003364 matchers_[i].DescribeTo(os);
3365 if (i + 1 < count()) {
3366 *os << ",\n";
3367 }
3368 }
3369 }
3370 }
3371
3372 // Describes what the negation of this matcher does.
3373 virtual void DescribeNegationTo(::std::ostream* os) const {
3374 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003375 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003376 return;
3377 }
3378
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003379 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003380 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003381 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003382 matchers_[i].DescribeNegationTo(os);
3383 if (i + 1 < count()) {
3384 *os << ", or\n";
3385 }
3386 }
3387 }
3388
zhanyong.wan82113312010-01-08 21:55:40 +00003389 virtual bool MatchAndExplain(Container container,
3390 MatchResultListener* listener) const {
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003391 // To work with stream-like "containers", we must only walk
3392 // through the elements in one pass.
3393
3394 const bool listener_interested = listener->IsInterested();
3395
3396 // explanations[i] is the explanation of the element at index i.
Nico Weber09fd5b32017-05-15 17:07:03 -04003397 ::std::vector<std::string> explanations(count());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003398 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003399 typename StlContainer::const_iterator it = stl_container.begin();
3400 size_t exam_pos = 0;
3401 bool mismatch_found = false; // Have we found a mismatched element yet?
3402
3403 // Go through the elements and matchers in pairs, until we reach
3404 // the end of either the elements or the matchers, or until we find a
3405 // mismatch.
3406 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3407 bool match; // Does the current element match the current matcher?
3408 if (listener_interested) {
3409 StringMatchResultListener s;
3410 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3411 explanations[exam_pos] = s.str();
3412 } else {
3413 match = matchers_[exam_pos].Matches(*it);
3414 }
3415
3416 if (!match) {
3417 mismatch_found = true;
3418 break;
3419 }
3420 }
3421 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3422
3423 // Find how many elements the actual container has. We avoid
3424 // calling size() s.t. this code works for stream-like "containers"
3425 // that don't define size().
3426 size_t actual_count = exam_pos;
3427 for (; it != stl_container.end(); ++it) {
3428 ++actual_count;
3429 }
3430
zhanyong.wan82113312010-01-08 21:55:40 +00003431 if (actual_count != count()) {
3432 // The element count doesn't match. If the container is empty,
3433 // there's no need to explain anything as Google Mock already
3434 // prints the empty container. Otherwise we just need to show
3435 // how many elements there actually are.
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003436 if (listener_interested && (actual_count != 0)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003437 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003438 }
zhanyong.wan82113312010-01-08 21:55:40 +00003439 return false;
3440 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003441
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003442 if (mismatch_found) {
3443 // The element count matches, but the exam_pos-th element doesn't match.
3444 if (listener_interested) {
3445 *listener << "whose element #" << exam_pos << " doesn't match";
3446 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003447 }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003448 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003449 }
zhanyong.wan82113312010-01-08 21:55:40 +00003450
3451 // Every element matches its expectation. We need to explain why
3452 // (the obvious ones can be skipped).
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003453 if (listener_interested) {
3454 bool reason_printed = false;
3455 for (size_t i = 0; i != count(); ++i) {
Nico Weber09fd5b32017-05-15 17:07:03 -04003456 const std::string& s = explanations[i];
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003457 if (!s.empty()) {
3458 if (reason_printed) {
3459 *listener << ",\nand ";
3460 }
3461 *listener << "whose element #" << i << " matches, " << s;
3462 reason_printed = true;
zhanyong.wan82113312010-01-08 21:55:40 +00003463 }
zhanyong.wan82113312010-01-08 21:55:40 +00003464 }
3465 }
zhanyong.wan82113312010-01-08 21:55:40 +00003466 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003467 }
3468
3469 private:
3470 static Message Elements(size_t count) {
3471 return Message() << count << (count == 1 ? " element" : " elements");
3472 }
3473
3474 size_t count() const { return matchers_.size(); }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003475
3476 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003477
3478 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003479};
3480
zhanyong.wanfb25d532013-07-28 08:24:00 +00003481// Connectivity matrix of (elements X matchers), in element-major order.
3482// Initially, there are no edges.
3483// Use NextGraph() to iterate over all possible edge configurations.
3484// Use Randomize() to generate a random edge configuration.
3485class GTEST_API_ MatchMatrix {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003486 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003487 MatchMatrix(size_t num_elements, size_t num_matchers)
3488 : num_elements_(num_elements),
3489 num_matchers_(num_matchers),
3490 matched_(num_elements_* num_matchers_, 0) {
3491 }
3492
3493 size_t LhsSize() const { return num_elements_; }
3494 size_t RhsSize() const { return num_matchers_; }
3495 bool HasEdge(size_t ilhs, size_t irhs) const {
3496 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3497 }
3498 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3499 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3500 }
3501
3502 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3503 // adds 1 to that number; returns false if incrementing the graph left it
3504 // empty.
3505 bool NextGraph();
3506
3507 void Randomize();
3508
Nico Weber09fd5b32017-05-15 17:07:03 -04003509 std::string DebugString() const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003510
3511 private:
3512 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3513 return ilhs * num_matchers_ + irhs;
3514 }
3515
3516 size_t num_elements_;
3517 size_t num_matchers_;
3518
3519 // Each element is a char interpreted as bool. They are stored as a
3520 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3521 // a (ilhs, irhs) matrix coordinate into an offset.
3522 ::std::vector<char> matched_;
3523};
3524
3525typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3526typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3527
3528// Returns a maximum bipartite matching for the specified graph 'g'.
3529// The matching is represented as a vector of {element, matcher} pairs.
3530GTEST_API_ ElementMatcherPairs
3531FindMaxBipartiteMatching(const MatchMatrix& g);
3532
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003533struct UnorderedMatcherRequire {
3534 enum Flags {
3535 Superset = 1 << 0,
3536 Subset = 1 << 1,
3537 ExactMatch = Superset | Subset,
3538 };
3539};
zhanyong.wanfb25d532013-07-28 08:24:00 +00003540
3541// Untyped base class for implementing UnorderedElementsAre. By
3542// putting logic that's not specific to the element type here, we
3543// reduce binary bloat and increase compilation speed.
3544class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3545 protected:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003546 explicit UnorderedElementsAreMatcherImplBase(
3547 UnorderedMatcherRequire::Flags matcher_flags)
3548 : match_flags_(matcher_flags) {}
3549
zhanyong.wanfb25d532013-07-28 08:24:00 +00003550 // A vector of matcher describers, one for each element matcher.
3551 // Does not own the describers (and thus can be used only when the
3552 // element matchers are alive).
3553 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3554
3555 // Describes this UnorderedElementsAre matcher.
3556 void DescribeToImpl(::std::ostream* os) const;
3557
3558 // Describes the negation of this UnorderedElementsAre matcher.
3559 void DescribeNegationToImpl(::std::ostream* os) const;
3560
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003561 bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,
3562 const MatchMatrix& matrix,
3563 MatchResultListener* listener) const;
3564
3565 bool FindPairing(const MatchMatrix& matrix,
3566 MatchResultListener* listener) const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003567
3568 MatcherDescriberVec& matcher_describers() {
3569 return matcher_describers_;
3570 }
3571
3572 static Message Elements(size_t n) {
3573 return Message() << n << " element" << (n == 1 ? "" : "s");
3574 }
3575
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003576 UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }
3577
zhanyong.wanfb25d532013-07-28 08:24:00 +00003578 private:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003579 UnorderedMatcherRequire::Flags match_flags_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003580 MatcherDescriberVec matcher_describers_;
3581
3582 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3583};
3584
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003585// Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
3586// IsSupersetOf.
zhanyong.wanfb25d532013-07-28 08:24:00 +00003587template <typename Container>
3588class UnorderedElementsAreMatcherImpl
3589 : public MatcherInterface<Container>,
3590 public UnorderedElementsAreMatcherImplBase {
3591 public:
3592 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3593 typedef internal::StlContainerView<RawContainer> View;
3594 typedef typename View::type StlContainer;
3595 typedef typename View::const_reference StlContainerReference;
3596 typedef typename StlContainer::const_iterator StlContainerConstIterator;
3597 typedef typename StlContainer::value_type Element;
3598
zhanyong.wanfb25d532013-07-28 08:24:00 +00003599 template <typename InputIter>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003600 UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,
3601 InputIter first, InputIter last)
3602 : UnorderedElementsAreMatcherImplBase(matcher_flags) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00003603 for (; first != last; ++first) {
3604 matchers_.push_back(MatcherCast<const Element&>(*first));
3605 matcher_describers().push_back(matchers_.back().GetDescriber());
3606 }
3607 }
3608
3609 // Describes what this matcher does.
3610 virtual void DescribeTo(::std::ostream* os) const {
3611 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3612 }
3613
3614 // Describes what the negation of this matcher does.
3615 virtual void DescribeNegationTo(::std::ostream* os) const {
3616 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3617 }
3618
3619 virtual bool MatchAndExplain(Container container,
3620 MatchResultListener* listener) const {
3621 StlContainerReference stl_container = View::ConstReference(container);
Nico Weber09fd5b32017-05-15 17:07:03 -04003622 ::std::vector<std::string> element_printouts;
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003623 MatchMatrix matrix =
3624 AnalyzeElements(stl_container.begin(), stl_container.end(),
3625 &element_printouts, listener);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003626
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003627 if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00003628 return true;
3629 }
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003630
3631 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
3632 if (matrix.LhsSize() != matrix.RhsSize()) {
3633 // The element count doesn't match. If the container is empty,
3634 // there's no need to explain anything as Google Mock already
3635 // prints the empty container. Otherwise we just need to show
3636 // how many elements there actually are.
3637 if (matrix.LhsSize() != 0 && listener->IsInterested()) {
3638 *listener << "which has " << Elements(matrix.LhsSize());
3639 }
3640 return false;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003641 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003642 }
3643
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003644 return VerifyMatchMatrix(element_printouts, matrix, listener) &&
zhanyong.wanfb25d532013-07-28 08:24:00 +00003645 FindPairing(matrix, listener);
3646 }
3647
3648 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003649 template <typename ElementIter>
3650 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
Nico Weber09fd5b32017-05-15 17:07:03 -04003651 ::std::vector<std::string>* element_printouts,
zhanyong.wanfb25d532013-07-28 08:24:00 +00003652 MatchResultListener* listener) const {
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003653 element_printouts->clear();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003654 ::std::vector<char> did_match;
3655 size_t num_elements = 0;
3656 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3657 if (listener->IsInterested()) {
3658 element_printouts->push_back(PrintToString(*elem_first));
3659 }
3660 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3661 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3662 }
3663 }
3664
3665 MatchMatrix matrix(num_elements, matchers_.size());
3666 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3667 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3668 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3669 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3670 }
3671 }
3672 return matrix;
3673 }
3674
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003675 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003676
3677 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3678};
3679
3680// Functor for use in TransformTuple.
3681// Performs MatcherCast<Target> on an input argument of any type.
3682template <typename Target>
3683struct CastAndAppendTransform {
3684 template <typename Arg>
3685 Matcher<Target> operator()(const Arg& a) const {
3686 return MatcherCast<Target>(a);
3687 }
3688};
3689
3690// Implements UnorderedElementsAre.
3691template <typename MatcherTuple>
3692class UnorderedElementsAreMatcher {
3693 public:
3694 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3695 : matchers_(args) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003696
3697 template <typename Container>
3698 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003699 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003700 typedef typename internal::StlContainerView<RawContainer>::type View;
3701 typedef typename View::value_type Element;
3702 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3703 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003704 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003705 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3706 ::std::back_inserter(matchers));
3707 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003708 UnorderedMatcherRequire::ExactMatch, matchers.begin(), matchers.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003709 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003710
3711 private:
3712 const MatcherTuple matchers_;
3713 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3714};
3715
3716// Implements ElementsAre.
3717template <typename MatcherTuple>
3718class ElementsAreMatcher {
3719 public:
3720 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3721
3722 template <typename Container>
3723 operator Matcher<Container>() const {
Gennadiy Civil23187052018-03-26 10:16:59 -04003724 GTEST_COMPILE_ASSERT_(
3725 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value ||
3726 ::testing::tuple_size<MatcherTuple>::value < 2,
3727 use_UnorderedElementsAre_with_hash_tables);
3728
zhanyong.wanfb25d532013-07-28 08:24:00 +00003729 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3730 typedef typename internal::StlContainerView<RawContainer>::type View;
3731 typedef typename View::value_type Element;
3732 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3733 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003734 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003735 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3736 ::std::back_inserter(matchers));
3737 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3738 matchers.begin(), matchers.end()));
3739 }
3740
3741 private:
3742 const MatcherTuple matchers_;
3743 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3744};
3745
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003746// Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
zhanyong.wanfb25d532013-07-28 08:24:00 +00003747template <typename T>
3748class UnorderedElementsAreArrayMatcher {
3749 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003750 template <typename Iter>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003751 UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,
3752 Iter first, Iter last)
3753 : match_flags_(match_flags), matchers_(first, last) {}
zhanyong.wanfb25d532013-07-28 08:24:00 +00003754
3755 template <typename Container>
3756 operator Matcher<Container>() const {
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003757 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3758 match_flags_, matchers_.begin(), matchers_.end()));
zhanyong.wanfb25d532013-07-28 08:24:00 +00003759 }
3760
3761 private:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003762 UnorderedMatcherRequire::Flags match_flags_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003763 ::std::vector<T> matchers_;
3764
3765 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003766};
3767
3768// Implements ElementsAreArray().
3769template <typename T>
3770class ElementsAreArrayMatcher {
3771 public:
jgm38513a82012-11-15 15:50:36 +00003772 template <typename Iter>
3773 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003774
3775 template <typename Container>
3776 operator Matcher<Container>() const {
Gennadiy Civil23187052018-03-26 10:16:59 -04003777 GTEST_COMPILE_ASSERT_(
3778 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value,
3779 use_UnorderedElementsAreArray_with_hash_tables);
3780
jgm38513a82012-11-15 15:50:36 +00003781 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3782 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003783 }
3784
3785 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003786 const ::std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003787
3788 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003789};
3790
kosak2336e9c2014-07-28 22:57:30 +00003791// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3792// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3793// second) is a polymorphic matcher that matches a value x iff tm
3794// matches tuple (x, second). Useful for implementing
3795// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3796//
3797// BoundSecondMatcher is copyable and assignable, as we need to put
3798// instances of this class in a vector when implementing
3799// UnorderedPointwise().
3800template <typename Tuple2Matcher, typename Second>
3801class BoundSecondMatcher {
3802 public:
3803 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3804 : tuple2_matcher_(tm), second_value_(second) {}
3805
3806 template <typename T>
3807 operator Matcher<T>() const {
3808 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3809 }
3810
3811 // We have to define this for UnorderedPointwise() to compile in
3812 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3813 // which requires the elements to be assignable in C++98. The
3814 // compiler cannot generate the operator= for us, as Tuple2Matcher
3815 // and Second may not be assignable.
3816 //
3817 // However, this should never be called, so the implementation just
3818 // need to assert.
3819 void operator=(const BoundSecondMatcher& /*rhs*/) {
3820 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3821 }
3822
3823 private:
3824 template <typename T>
3825 class Impl : public MatcherInterface<T> {
3826 public:
3827 typedef ::testing::tuple<T, Second> ArgTuple;
3828
3829 Impl(const Tuple2Matcher& tm, const Second& second)
3830 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3831 second_value_(second) {}
3832
3833 virtual void DescribeTo(::std::ostream* os) const {
3834 *os << "and ";
3835 UniversalPrint(second_value_, os);
3836 *os << " ";
3837 mono_tuple2_matcher_.DescribeTo(os);
3838 }
3839
3840 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3841 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3842 listener);
3843 }
3844
3845 private:
3846 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3847 const Second second_value_;
3848
3849 GTEST_DISALLOW_ASSIGN_(Impl);
3850 };
3851
3852 const Tuple2Matcher tuple2_matcher_;
3853 const Second second_value_;
3854};
3855
3856// Given a 2-tuple matcher tm and a value second,
3857// MatcherBindSecond(tm, second) returns a matcher that matches a
3858// value x iff tm matches tuple (x, second). Useful for implementing
3859// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3860template <typename Tuple2Matcher, typename Second>
3861BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
3862 const Tuple2Matcher& tm, const Second& second) {
3863 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
3864}
3865
zhanyong.wanb4140802010-06-08 22:53:57 +00003866// Returns the description for a matcher defined using the MATCHER*()
3867// macro where the user-supplied description string is "", if
3868// 'negation' is false; otherwise returns the description of the
3869// negation of the matcher. 'param_values' contains a list of strings
3870// that are the print-out of the matcher's parameters.
Nico Weber09fd5b32017-05-15 17:07:03 -04003871GTEST_API_ std::string FormatMatcherDescription(bool negation,
3872 const char* matcher_name,
3873 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003874
Gennadiy Civilb907c262018-03-23 11:42:41 -04003875// Implements a matcher that checks the value of a optional<> type variable.
3876template <typename ValueMatcher>
3877class OptionalMatcher {
3878 public:
3879 explicit OptionalMatcher(const ValueMatcher& value_matcher)
3880 : value_matcher_(value_matcher) {}
3881
3882 template <typename Optional>
3883 operator Matcher<Optional>() const {
3884 return MakeMatcher(new Impl<Optional>(value_matcher_));
3885 }
3886
3887 template <typename Optional>
3888 class Impl : public MatcherInterface<Optional> {
3889 public:
3890 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView;
3891 typedef typename OptionalView::value_type ValueType;
3892 explicit Impl(const ValueMatcher& value_matcher)
3893 : value_matcher_(MatcherCast<ValueType>(value_matcher)) {}
3894
3895 virtual void DescribeTo(::std::ostream* os) const {
3896 *os << "value ";
3897 value_matcher_.DescribeTo(os);
3898 }
3899
3900 virtual void DescribeNegationTo(::std::ostream* os) const {
3901 *os << "value ";
3902 value_matcher_.DescribeNegationTo(os);
3903 }
3904
3905 virtual bool MatchAndExplain(Optional optional,
3906 MatchResultListener* listener) const {
3907 if (!optional) {
3908 *listener << "which is not engaged";
3909 return false;
3910 }
3911 const ValueType& value = *optional;
3912 StringMatchResultListener value_listener;
3913 const bool match = value_matcher_.MatchAndExplain(value, &value_listener);
3914 *listener << "whose value " << PrintToString(value)
3915 << (match ? " matches" : " doesn't match");
3916 PrintIfNotEmpty(value_listener.str(), listener->stream());
3917 return match;
3918 }
3919
3920 private:
3921 const Matcher<ValueType> value_matcher_;
3922 GTEST_DISALLOW_ASSIGN_(Impl);
3923 };
3924
3925 private:
3926 const ValueMatcher value_matcher_;
3927 GTEST_DISALLOW_ASSIGN_(OptionalMatcher);
3928};
3929
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05003930namespace variant_matcher {
3931// Overloads to allow VariantMatcher to do proper ADL lookup.
3932template <typename T>
3933void holds_alternative() {}
3934template <typename T>
3935void get() {}
3936
3937// Implements a matcher that checks the value of a variant<> type variable.
3938template <typename T>
3939class VariantMatcher {
3940 public:
3941 explicit VariantMatcher(::testing::Matcher<const T&> matcher)
3942 : matcher_(internal::move(matcher)) {}
3943
3944 template <typename Variant>
3945 bool MatchAndExplain(const Variant& value,
3946 ::testing::MatchResultListener* listener) const {
3947 if (!listener->IsInterested()) {
3948 return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));
3949 }
3950
3951 if (!holds_alternative<T>(value)) {
3952 *listener << "whose value is not of type '" << GetTypeName() << "'";
3953 return false;
3954 }
3955
3956 const T& elem = get<T>(value);
3957 StringMatchResultListener elem_listener;
3958 const bool match = matcher_.MatchAndExplain(elem, &elem_listener);
3959 *listener << "whose value " << PrintToString(elem)
3960 << (match ? " matches" : " doesn't match");
3961 PrintIfNotEmpty(elem_listener.str(), listener->stream());
3962 return match;
3963 }
3964
3965 void DescribeTo(std::ostream* os) const {
3966 *os << "is a variant<> with value of type '" << GetTypeName()
3967 << "' and the value ";
3968 matcher_.DescribeTo(os);
3969 }
3970
3971 void DescribeNegationTo(std::ostream* os) const {
3972 *os << "is a variant<> with value of type other than '" << GetTypeName()
3973 << "' or the value ";
3974 matcher_.DescribeNegationTo(os);
3975 }
3976
3977 private:
Gennadiy Civil23187052018-03-26 10:16:59 -04003978 static std::string GetTypeName() {
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05003979#if GTEST_HAS_RTTI
3980 return internal::GetTypeName<T>();
3981#endif
3982 return "the element type";
3983 }
3984
3985 const ::testing::Matcher<const T&> matcher_;
3986};
3987
3988} // namespace variant_matcher
3989
Gennadiy Civil466a49a2018-03-23 11:23:54 -04003990namespace any_cast_matcher {
3991
3992// Overloads to allow AnyCastMatcher to do proper ADL lookup.
3993template <typename T>
3994void any_cast() {}
3995
3996// Implements a matcher that any_casts the value.
3997template <typename T>
3998class AnyCastMatcher {
3999 public:
4000 explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher)
4001 : matcher_(matcher) {}
4002
4003 template <typename AnyType>
4004 bool MatchAndExplain(const AnyType& value,
4005 ::testing::MatchResultListener* listener) const {
4006 if (!listener->IsInterested()) {
4007 const T* ptr = any_cast<T>(&value);
4008 return ptr != NULL && matcher_.Matches(*ptr);
4009 }
4010
4011 const T* elem = any_cast<T>(&value);
4012 if (elem == NULL) {
4013 *listener << "whose value is not of type '" << GetTypeName() << "'";
4014 return false;
4015 }
4016
4017 StringMatchResultListener elem_listener;
4018 const bool match = matcher_.MatchAndExplain(*elem, &elem_listener);
4019 *listener << "whose value " << PrintToString(*elem)
4020 << (match ? " matches" : " doesn't match");
4021 PrintIfNotEmpty(elem_listener.str(), listener->stream());
4022 return match;
4023 }
4024
4025 void DescribeTo(std::ostream* os) const {
4026 *os << "is an 'any' type with value of type '" << GetTypeName()
4027 << "' and the value ";
4028 matcher_.DescribeTo(os);
4029 }
4030
4031 void DescribeNegationTo(std::ostream* os) const {
4032 *os << "is an 'any' type with value of type other than '" << GetTypeName()
4033 << "' or the value ";
4034 matcher_.DescribeNegationTo(os);
4035 }
4036
4037 private:
4038 static std::string GetTypeName() {
4039#if GTEST_HAS_RTTI
4040 return internal::GetTypeName<T>();
4041#endif
4042 return "the element type";
4043 }
4044
4045 const ::testing::Matcher<const T&> matcher_;
4046};
4047
4048} // namespace any_cast_matcher
shiqiane35fdd92008-12-10 05:08:54 +00004049} // namespace internal
4050
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004051// ElementsAreArray(iterator_first, iterator_last)
zhanyong.wanfb25d532013-07-28 08:24:00 +00004052// ElementsAreArray(pointer, count)
4053// ElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00004054// ElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004055// ElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00004056//
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004057// The ElementsAreArray() functions are like ElementsAre(...), except
4058// that they are given a homogeneous sequence rather than taking each
4059// element as a function argument. The sequence can be specified as an
4060// array, a pointer and count, a vector, an initializer list, or an
4061// STL iterator range. In each of these cases, the underlying sequence
4062// can be either a sequence of values or a sequence of matchers.
zhanyong.wanfb25d532013-07-28 08:24:00 +00004063//
4064// All forms of ElementsAreArray() make a copy of the input matcher sequence.
4065
4066template <typename Iter>
4067inline internal::ElementsAreArrayMatcher<
4068 typename ::std::iterator_traits<Iter>::value_type>
4069ElementsAreArray(Iter first, Iter last) {
4070 typedef typename ::std::iterator_traits<Iter>::value_type T;
4071 return internal::ElementsAreArrayMatcher<T>(first, last);
4072}
4073
4074template <typename T>
4075inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
4076 const T* pointer, size_t count) {
4077 return ElementsAreArray(pointer, pointer + count);
4078}
4079
4080template <typename T, size_t N>
4081inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
4082 const T (&array)[N]) {
4083 return ElementsAreArray(array, N);
4084}
4085
kosak06678922014-07-28 20:01:28 +00004086template <typename Container>
4087inline internal::ElementsAreArrayMatcher<typename Container::value_type>
4088ElementsAreArray(const Container& container) {
4089 return ElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00004090}
4091
kosak18489fa2013-12-04 23:49:07 +00004092#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004093template <typename T>
4094inline internal::ElementsAreArrayMatcher<T>
4095ElementsAreArray(::std::initializer_list<T> xs) {
4096 return ElementsAreArray(xs.begin(), xs.end());
4097}
4098#endif
4099
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004100// UnorderedElementsAreArray(iterator_first, iterator_last)
zhanyong.wanfb25d532013-07-28 08:24:00 +00004101// UnorderedElementsAreArray(pointer, count)
4102// UnorderedElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00004103// UnorderedElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004104// UnorderedElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00004105//
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004106// UnorderedElementsAreArray() verifies that a bijective mapping onto a
4107// collection of matchers exists.
4108//
4109// The matchers can be specified as an array, a pointer and count, a container,
4110// an initializer list, or an STL iterator range. In each of these cases, the
4111// underlying matchers can be either values or matchers.
4112
zhanyong.wanfb25d532013-07-28 08:24:00 +00004113template <typename Iter>
4114inline internal::UnorderedElementsAreArrayMatcher<
4115 typename ::std::iterator_traits<Iter>::value_type>
4116UnorderedElementsAreArray(Iter first, Iter last) {
4117 typedef typename ::std::iterator_traits<Iter>::value_type T;
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004118 return internal::UnorderedElementsAreArrayMatcher<T>(
4119 internal::UnorderedMatcherRequire::ExactMatch, first, last);
zhanyong.wanfb25d532013-07-28 08:24:00 +00004120}
4121
4122template <typename T>
4123inline internal::UnorderedElementsAreArrayMatcher<T>
4124UnorderedElementsAreArray(const T* pointer, size_t count) {
4125 return UnorderedElementsAreArray(pointer, pointer + count);
4126}
4127
4128template <typename T, size_t N>
4129inline internal::UnorderedElementsAreArrayMatcher<T>
4130UnorderedElementsAreArray(const T (&array)[N]) {
4131 return UnorderedElementsAreArray(array, N);
4132}
4133
kosak06678922014-07-28 20:01:28 +00004134template <typename Container>
4135inline internal::UnorderedElementsAreArrayMatcher<
4136 typename Container::value_type>
4137UnorderedElementsAreArray(const Container& container) {
4138 return UnorderedElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00004139}
4140
kosak18489fa2013-12-04 23:49:07 +00004141#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004142template <typename T>
4143inline internal::UnorderedElementsAreArrayMatcher<T>
4144UnorderedElementsAreArray(::std::initializer_list<T> xs) {
4145 return UnorderedElementsAreArray(xs.begin(), xs.end());
4146}
4147#endif
zhanyong.wanfb25d532013-07-28 08:24:00 +00004148
shiqiane35fdd92008-12-10 05:08:54 +00004149// _ is a matcher that matches anything of any type.
4150//
4151// This definition is fine as:
4152//
4153// 1. The C++ standard permits using the name _ in a namespace that
4154// is not the global namespace or ::std.
4155// 2. The AnythingMatcher class has no data member or constructor,
4156// so it's OK to create global variables of this type.
4157// 3. c-style has approved of using _ in this case.
4158const internal::AnythingMatcher _ = {};
4159// Creates a matcher that matches any value of the given type T.
4160template <typename T>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004161inline Matcher<T> A() {
4162 return Matcher<T>(new internal::AnyMatcherImpl<T>());
4163}
shiqiane35fdd92008-12-10 05:08:54 +00004164
4165// Creates a matcher that matches any value of the given type T.
4166template <typename T>
4167inline Matcher<T> An() { return A<T>(); }
4168
4169// Creates a polymorphic matcher that matches anything equal to x.
4170// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
4171// wouldn't compile.
4172template <typename T>
4173inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
4174
4175// Constructs a Matcher<T> from a 'value' of type T. The constructed
4176// matcher matches any value that's equal to 'value'.
4177template <typename T>
4178Matcher<T>::Matcher(T value) { *this = Eq(value); }
4179
Gennadiy Civil466a49a2018-03-23 11:23:54 -04004180template <typename T, typename M>
4181Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(
4182 const M& value,
4183 internal::BooleanConstant<false> /* convertible_to_matcher */,
4184 internal::BooleanConstant<false> /* convertible_to_T */) {
4185 return Eq(value);
4186}
4187
shiqiane35fdd92008-12-10 05:08:54 +00004188// Creates a monomorphic matcher that matches anything with type Lhs
4189// and equal to rhs. A user may need to use this instead of Eq(...)
4190// in order to resolve an overloading ambiguity.
4191//
4192// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
4193// or Matcher<T>(x), but more readable than the latter.
4194//
4195// We could define similar monomorphic matchers for other comparison
4196// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
4197// it yet as those are used much less than Eq() in practice. A user
4198// can always write Matcher<T>(Lt(5)) to be explicit about the type,
4199// for example.
4200template <typename Lhs, typename Rhs>
4201inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
4202
4203// Creates a polymorphic matcher that matches anything >= x.
4204template <typename Rhs>
4205inline internal::GeMatcher<Rhs> Ge(Rhs x) {
4206 return internal::GeMatcher<Rhs>(x);
4207}
4208
4209// Creates a polymorphic matcher that matches anything > x.
4210template <typename Rhs>
4211inline internal::GtMatcher<Rhs> Gt(Rhs x) {
4212 return internal::GtMatcher<Rhs>(x);
4213}
4214
4215// Creates a polymorphic matcher that matches anything <= x.
4216template <typename Rhs>
4217inline internal::LeMatcher<Rhs> Le(Rhs x) {
4218 return internal::LeMatcher<Rhs>(x);
4219}
4220
4221// Creates a polymorphic matcher that matches anything < x.
4222template <typename Rhs>
4223inline internal::LtMatcher<Rhs> Lt(Rhs x) {
4224 return internal::LtMatcher<Rhs>(x);
4225}
4226
4227// Creates a polymorphic matcher that matches anything != x.
4228template <typename Rhs>
4229inline internal::NeMatcher<Rhs> Ne(Rhs x) {
4230 return internal::NeMatcher<Rhs>(x);
4231}
4232
zhanyong.wan2d970ee2009-09-24 21:41:36 +00004233// Creates a polymorphic matcher that matches any NULL pointer.
4234inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
4235 return MakePolymorphicMatcher(internal::IsNullMatcher());
4236}
4237
shiqiane35fdd92008-12-10 05:08:54 +00004238// Creates a polymorphic matcher that matches any non-NULL pointer.
4239// This is convenient as Not(NULL) doesn't compile (the compiler
4240// thinks that that expression is comparing a pointer with an integer).
4241inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
4242 return MakePolymorphicMatcher(internal::NotNullMatcher());
4243}
4244
4245// Creates a polymorphic matcher that matches any argument that
4246// references variable x.
4247template <typename T>
4248inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
4249 return internal::RefMatcher<T&>(x);
4250}
4251
4252// Creates a matcher that matches any double argument approximately
4253// equal to rhs, where two NANs are considered unequal.
4254inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
4255 return internal::FloatingEqMatcher<double>(rhs, false);
4256}
4257
4258// Creates a matcher that matches any double argument approximately
4259// equal to rhs, including NaN values when rhs is NaN.
4260inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
4261 return internal::FloatingEqMatcher<double>(rhs, true);
4262}
4263
zhanyong.wan616180e2013-06-18 18:49:51 +00004264// Creates a matcher that matches any double argument approximately equal to
4265// rhs, up to the specified max absolute error bound, where two NANs are
4266// considered unequal. The max absolute error bound must be non-negative.
4267inline internal::FloatingEqMatcher<double> DoubleNear(
4268 double rhs, double max_abs_error) {
4269 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
4270}
4271
4272// Creates a matcher that matches any double argument approximately equal to
4273// rhs, up to the specified max absolute error bound, including NaN values when
4274// rhs is NaN. The max absolute error bound must be non-negative.
4275inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
4276 double rhs, double max_abs_error) {
4277 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
4278}
4279
shiqiane35fdd92008-12-10 05:08:54 +00004280// Creates a matcher that matches any float argument approximately
4281// equal to rhs, where two NANs are considered unequal.
4282inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
4283 return internal::FloatingEqMatcher<float>(rhs, false);
4284}
4285
zhanyong.wan616180e2013-06-18 18:49:51 +00004286// Creates a matcher that matches any float argument approximately
shiqiane35fdd92008-12-10 05:08:54 +00004287// equal to rhs, including NaN values when rhs is NaN.
4288inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
4289 return internal::FloatingEqMatcher<float>(rhs, true);
4290}
4291
zhanyong.wan616180e2013-06-18 18:49:51 +00004292// Creates a matcher that matches any float argument approximately equal to
4293// rhs, up to the specified max absolute error bound, where two NANs are
4294// considered unequal. The max absolute error bound must be non-negative.
4295inline internal::FloatingEqMatcher<float> FloatNear(
4296 float rhs, float max_abs_error) {
4297 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
4298}
4299
4300// Creates a matcher that matches any float argument approximately equal to
4301// rhs, up to the specified max absolute error bound, including NaN values when
4302// rhs is NaN. The max absolute error bound must be non-negative.
4303inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
4304 float rhs, float max_abs_error) {
4305 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
4306}
4307
shiqiane35fdd92008-12-10 05:08:54 +00004308// Creates a matcher that matches a pointer (raw or smart) that points
4309// to a value that matches inner_matcher.
4310template <typename InnerMatcher>
4311inline internal::PointeeMatcher<InnerMatcher> Pointee(
4312 const InnerMatcher& inner_matcher) {
4313 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
4314}
4315
billydonahue1f5fdea2014-05-19 17:54:51 +00004316// Creates a matcher that matches a pointer or reference that matches
4317// inner_matcher when dynamic_cast<To> is applied.
4318// The result of dynamic_cast<To> is forwarded to the inner matcher.
4319// If To is a pointer and the cast fails, the inner matcher will receive NULL.
4320// If To is a reference and the cast fails, this matcher returns false
4321// immediately.
4322template <typename To>
4323inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
4324WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
4325 return MakePolymorphicMatcher(
4326 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
4327}
4328
shiqiane35fdd92008-12-10 05:08:54 +00004329// Creates a matcher that matches an object whose given field matches
4330// 'matcher'. For example,
4331// Field(&Foo::number, Ge(5))
4332// matches a Foo object x iff x.number >= 5.
4333template <typename Class, typename FieldType, typename FieldMatcher>
4334inline PolymorphicMatcher<
4335 internal::FieldMatcher<Class, FieldType> > Field(
4336 FieldType Class::*field, const FieldMatcher& matcher) {
4337 return MakePolymorphicMatcher(
4338 internal::FieldMatcher<Class, FieldType>(
4339 field, MatcherCast<const FieldType&>(matcher)));
4340 // The call to MatcherCast() is required for supporting inner
4341 // matchers of compatible types. For example, it allows
4342 // Field(&Foo::bar, m)
4343 // to compile where bar is an int32 and m is a matcher for int64.
4344}
4345
Gennadiy Civilb907c262018-03-23 11:42:41 -04004346// Same as Field() but also takes the name of the field to provide better error
4347// messages.
4348template <typename Class, typename FieldType, typename FieldMatcher>
4349inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType> > Field(
4350 const std::string& field_name, FieldType Class::*field,
4351 const FieldMatcher& matcher) {
4352 return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(
4353 field_name, field, MatcherCast<const FieldType&>(matcher)));
4354}
4355
shiqiane35fdd92008-12-10 05:08:54 +00004356// Creates a matcher that matches an object whose given property
4357// matches 'matcher'. For example,
4358// Property(&Foo::str, StartsWith("hi"))
4359// matches a Foo object x iff x.str() starts with "hi".
4360template <typename Class, typename PropertyType, typename PropertyMatcher>
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004361inline PolymorphicMatcher<internal::PropertyMatcher<
4362 Class, PropertyType, PropertyType (Class::*)() const> >
4363Property(PropertyType (Class::*property)() const,
4364 const PropertyMatcher& matcher) {
shiqiane35fdd92008-12-10 05:08:54 +00004365 return MakePolymorphicMatcher(
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004366 internal::PropertyMatcher<Class, PropertyType,
4367 PropertyType (Class::*)() const>(
shiqiane35fdd92008-12-10 05:08:54 +00004368 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00004369 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00004370 // The call to MatcherCast() is required for supporting inner
4371 // matchers of compatible types. For example, it allows
4372 // Property(&Foo::bar, m)
4373 // to compile where bar() returns an int32 and m is a matcher for int64.
4374}
4375
Gennadiy Civil23187052018-03-26 10:16:59 -04004376// Same as Property() above, but also takes the name of the property to provide
4377// better error messages.
4378template <typename Class, typename PropertyType, typename PropertyMatcher>
4379inline PolymorphicMatcher<internal::PropertyMatcher<
4380 Class, PropertyType, PropertyType (Class::*)() const> >
4381Property(const std::string& property_name,
4382 PropertyType (Class::*property)() const,
4383 const PropertyMatcher& matcher) {
4384 return MakePolymorphicMatcher(
4385 internal::PropertyMatcher<Class, PropertyType,
4386 PropertyType (Class::*)() const>(
4387 property_name, property,
4388 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4389}
4390
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004391#if GTEST_LANG_CXX11
4392// The same as above but for reference-qualified member functions.
4393template <typename Class, typename PropertyType, typename PropertyMatcher>
4394inline PolymorphicMatcher<internal::PropertyMatcher<
4395 Class, PropertyType, PropertyType (Class::*)() const &> >
4396Property(PropertyType (Class::*property)() const &,
4397 const PropertyMatcher& matcher) {
4398 return MakePolymorphicMatcher(
4399 internal::PropertyMatcher<Class, PropertyType,
4400 PropertyType (Class::*)() const &>(
4401 property,
4402 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4403}
4404#endif
4405
shiqiane35fdd92008-12-10 05:08:54 +00004406// Creates a matcher that matches an object iff the result of applying
4407// a callable to x matches 'matcher'.
4408// For example,
4409// ResultOf(f, StartsWith("hi"))
4410// matches a Foo object x iff f(x) starts with "hi".
4411// callable parameter can be a function, function pointer, or a functor.
4412// Callable has to satisfy the following conditions:
4413// * It is required to keep no state affecting the results of
4414// the calls on it and make no assumptions about how many calls
4415// will be made. Any state it keeps must be protected from the
4416// concurrent access.
4417// * If it is a function object, it has to define type result_type.
4418// We recommend deriving your functor classes from std::unary_function.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004419//
shiqiane35fdd92008-12-10 05:08:54 +00004420template <typename Callable, typename ResultOfMatcher>
4421internal::ResultOfMatcher<Callable> ResultOf(
4422 Callable callable, const ResultOfMatcher& matcher) {
4423 return internal::ResultOfMatcher<Callable>(
4424 callable,
4425 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
4426 matcher));
4427 // The call to MatcherCast() is required for supporting inner
4428 // matchers of compatible types. For example, it allows
4429 // ResultOf(Function, m)
4430 // to compile where Function() returns an int32 and m is a matcher for int64.
4431}
4432
4433// String matchers.
4434
4435// Matches a string equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04004436inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
4437 const std::string& str) {
4438 return MakePolymorphicMatcher(
4439 internal::StrEqualityMatcher<std::string>(str, true, true));
shiqiane35fdd92008-12-10 05:08:54 +00004440}
4441
4442// Matches a string not equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04004443inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
4444 const std::string& str) {
4445 return MakePolymorphicMatcher(
4446 internal::StrEqualityMatcher<std::string>(str, false, true));
shiqiane35fdd92008-12-10 05:08:54 +00004447}
4448
4449// Matches a string equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04004450inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
4451 const std::string& str) {
4452 return MakePolymorphicMatcher(
4453 internal::StrEqualityMatcher<std::string>(str, true, false));
shiqiane35fdd92008-12-10 05:08:54 +00004454}
4455
4456// Matches a string not equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04004457inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
4458 const std::string& str) {
4459 return MakePolymorphicMatcher(
4460 internal::StrEqualityMatcher<std::string>(str, false, false));
shiqiane35fdd92008-12-10 05:08:54 +00004461}
4462
4463// Creates a matcher that matches any string, std::string, or C string
4464// that contains the given substring.
Nico Weber09fd5b32017-05-15 17:07:03 -04004465inline PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
4466 const std::string& substring) {
4467 return MakePolymorphicMatcher(
4468 internal::HasSubstrMatcher<std::string>(substring));
shiqiane35fdd92008-12-10 05:08:54 +00004469}
4470
4471// Matches a string that starts with 'prefix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004472inline PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
4473 const std::string& prefix) {
4474 return MakePolymorphicMatcher(
4475 internal::StartsWithMatcher<std::string>(prefix));
shiqiane35fdd92008-12-10 05:08:54 +00004476}
4477
4478// Matches a string that ends with 'suffix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004479inline PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
4480 const std::string& suffix) {
4481 return MakePolymorphicMatcher(internal::EndsWithMatcher<std::string>(suffix));
shiqiane35fdd92008-12-10 05:08:54 +00004482}
4483
shiqiane35fdd92008-12-10 05:08:54 +00004484// Matches a string that fully matches regular expression 'regex'.
4485// The matcher takes ownership of 'regex'.
4486inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4487 const internal::RE* regex) {
4488 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
4489}
4490inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004491 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004492 return MatchesRegex(new internal::RE(regex));
4493}
4494
4495// Matches a string that contains regular expression 'regex'.
4496// The matcher takes ownership of 'regex'.
4497inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4498 const internal::RE* regex) {
4499 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4500}
4501inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004502 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004503 return ContainsRegex(new internal::RE(regex));
4504}
4505
shiqiane35fdd92008-12-10 05:08:54 +00004506#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4507// Wide string matchers.
4508
4509// Matches a string equal to str.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004510inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrEq(
4511 const std::wstring& str) {
4512 return MakePolymorphicMatcher(
4513 internal::StrEqualityMatcher<std::wstring>(str, true, true));
shiqiane35fdd92008-12-10 05:08:54 +00004514}
4515
4516// Matches a string not equal to str.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004517inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrNe(
4518 const std::wstring& str) {
4519 return MakePolymorphicMatcher(
4520 internal::StrEqualityMatcher<std::wstring>(str, false, true));
shiqiane35fdd92008-12-10 05:08:54 +00004521}
4522
4523// Matches a string equal to str, ignoring case.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004524inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
4525StrCaseEq(const std::wstring& str) {
4526 return MakePolymorphicMatcher(
4527 internal::StrEqualityMatcher<std::wstring>(str, true, false));
shiqiane35fdd92008-12-10 05:08:54 +00004528}
4529
4530// Matches a string not equal to str, ignoring case.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004531inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
4532StrCaseNe(const std::wstring& str) {
4533 return MakePolymorphicMatcher(
4534 internal::StrEqualityMatcher<std::wstring>(str, false, false));
shiqiane35fdd92008-12-10 05:08:54 +00004535}
4536
Gennadiy Civilb907c262018-03-23 11:42:41 -04004537// Creates a matcher that matches any ::wstring, std::wstring, or C wide string
shiqiane35fdd92008-12-10 05:08:54 +00004538// that contains the given substring.
Gennadiy Civilb907c262018-03-23 11:42:41 -04004539inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring> > HasSubstr(
4540 const std::wstring& substring) {
4541 return MakePolymorphicMatcher(
4542 internal::HasSubstrMatcher<std::wstring>(substring));
shiqiane35fdd92008-12-10 05:08:54 +00004543}
4544
4545// Matches a string that starts with 'prefix' (case-sensitive).
Gennadiy Civilb907c262018-03-23 11:42:41 -04004546inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring> >
4547StartsWith(const std::wstring& prefix) {
4548 return MakePolymorphicMatcher(
4549 internal::StartsWithMatcher<std::wstring>(prefix));
shiqiane35fdd92008-12-10 05:08:54 +00004550}
4551
4552// Matches a string that ends with 'suffix' (case-sensitive).
Gennadiy Civilb907c262018-03-23 11:42:41 -04004553inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring> > EndsWith(
4554 const std::wstring& suffix) {
4555 return MakePolymorphicMatcher(
4556 internal::EndsWithMatcher<std::wstring>(suffix));
shiqiane35fdd92008-12-10 05:08:54 +00004557}
4558
4559#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4560
4561// Creates a polymorphic matcher that matches a 2-tuple where the
4562// first field == the second field.
4563inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4564
4565// Creates a polymorphic matcher that matches a 2-tuple where the
4566// first field >= the second field.
4567inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4568
4569// Creates a polymorphic matcher that matches a 2-tuple where the
4570// first field > the second field.
4571inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4572
4573// Creates a polymorphic matcher that matches a 2-tuple where the
4574// first field <= the second field.
4575inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4576
4577// Creates a polymorphic matcher that matches a 2-tuple where the
4578// first field < the second field.
4579inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4580
4581// Creates a polymorphic matcher that matches a 2-tuple where the
4582// first field != the second field.
4583inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4584
Gennadiy Civilb907c262018-03-23 11:42:41 -04004585// Creates a polymorphic matcher that matches a 2-tuple where
4586// FloatEq(first field) matches the second field.
4587inline internal::FloatingEq2Matcher<float> FloatEq() {
4588 return internal::FloatingEq2Matcher<float>();
4589}
4590
4591// Creates a polymorphic matcher that matches a 2-tuple where
4592// DoubleEq(first field) matches the second field.
4593inline internal::FloatingEq2Matcher<double> DoubleEq() {
4594 return internal::FloatingEq2Matcher<double>();
4595}
4596
4597// Creates a polymorphic matcher that matches a 2-tuple where
4598// FloatEq(first field) matches the second field with NaN equality.
4599inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() {
4600 return internal::FloatingEq2Matcher<float>(true);
4601}
4602
4603// Creates a polymorphic matcher that matches a 2-tuple where
4604// DoubleEq(first field) matches the second field with NaN equality.
4605inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() {
4606 return internal::FloatingEq2Matcher<double>(true);
4607}
4608
4609// Creates a polymorphic matcher that matches a 2-tuple where
4610// FloatNear(first field, max_abs_error) matches the second field.
4611inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) {
4612 return internal::FloatingEq2Matcher<float>(max_abs_error);
4613}
4614
4615// Creates a polymorphic matcher that matches a 2-tuple where
4616// DoubleNear(first field, max_abs_error) matches the second field.
4617inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) {
4618 return internal::FloatingEq2Matcher<double>(max_abs_error);
4619}
4620
4621// Creates a polymorphic matcher that matches a 2-tuple where
4622// FloatNear(first field, max_abs_error) matches the second field with NaN
4623// equality.
4624inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear(
4625 float max_abs_error) {
4626 return internal::FloatingEq2Matcher<float>(max_abs_error, true);
4627}
4628
4629// Creates a polymorphic matcher that matches a 2-tuple where
4630// DoubleNear(first field, max_abs_error) matches the second field with NaN
4631// equality.
4632inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear(
4633 double max_abs_error) {
4634 return internal::FloatingEq2Matcher<double>(max_abs_error, true);
4635}
4636
shiqiane35fdd92008-12-10 05:08:54 +00004637// Creates a matcher that matches any value of type T that m doesn't
4638// match.
4639template <typename InnerMatcher>
4640inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4641 return internal::NotMatcher<InnerMatcher>(m);
4642}
4643
shiqiane35fdd92008-12-10 05:08:54 +00004644// Returns a matcher that matches anything that satisfies the given
4645// predicate. The predicate can be any unary function or functor
4646// whose return type can be implicitly converted to bool.
4647template <typename Predicate>
4648inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4649Truly(Predicate pred) {
4650 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4651}
4652
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004653// Returns a matcher that matches the container size. The container must
4654// support both size() and size_type which all STL-like containers provide.
4655// Note that the parameter 'size' can be a value of type size_type as well as
4656// matcher. For instance:
4657// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
4658// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
4659template <typename SizeMatcher>
4660inline internal::SizeIsMatcher<SizeMatcher>
4661SizeIs(const SizeMatcher& size_matcher) {
4662 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4663}
4664
kosakb6a34882014-03-12 21:06:46 +00004665// Returns a matcher that matches the distance between the container's begin()
4666// iterator and its end() iterator, i.e. the size of the container. This matcher
4667// can be used instead of SizeIs with containers such as std::forward_list which
4668// do not implement size(). The container must provide const_iterator (with
4669// valid iterator_traits), begin() and end().
4670template <typename DistanceMatcher>
4671inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4672BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4673 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4674}
4675
zhanyong.wan6a896b52009-01-16 01:13:50 +00004676// Returns a matcher that matches an equal container.
4677// This matcher behaves like Eq(), but in the event of mismatch lists the
4678// values that are included in one container but not the other. (Duplicate
4679// values and order differences are not explained.)
4680template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00004681inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00004682 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004683 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00004684 // This following line is for working around a bug in MSVC 8.0,
4685 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00004686 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00004687 return MakePolymorphicMatcher(
4688 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00004689}
4690
zhanyong.wan898725c2011-09-16 16:45:39 +00004691// Returns a matcher that matches a container that, when sorted using
4692// the given comparator, matches container_matcher.
4693template <typename Comparator, typename ContainerMatcher>
4694inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4695WhenSortedBy(const Comparator& comparator,
4696 const ContainerMatcher& container_matcher) {
4697 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4698 comparator, container_matcher);
4699}
4700
4701// Returns a matcher that matches a container that, when sorted using
4702// the < operator, matches container_matcher.
4703template <typename ContainerMatcher>
4704inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4705WhenSorted(const ContainerMatcher& container_matcher) {
4706 return
4707 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4708 internal::LessComparator(), container_matcher);
4709}
4710
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004711// Matches an STL-style container or a native array that contains the
4712// same number of elements as in rhs, where its i-th element and rhs's
4713// i-th element (as a pair) satisfy the given pair matcher, for all i.
4714// TupleMatcher must be able to be safely cast to Matcher<tuple<const
4715// T1&, const T2&> >, where T1 and T2 are the types of elements in the
4716// LHS container and the RHS container respectively.
4717template <typename TupleMatcher, typename Container>
4718inline internal::PointwiseMatcher<TupleMatcher,
4719 GTEST_REMOVE_CONST_(Container)>
4720Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4721 // This following line is for working around a bug in MSVC 8.0,
kosak2336e9c2014-07-28 22:57:30 +00004722 // which causes Container to be a const type sometimes (e.g. when
4723 // rhs is a const int[])..
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004724 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4725 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4726 tuple_matcher, rhs);
4727}
4728
kosak2336e9c2014-07-28 22:57:30 +00004729#if GTEST_HAS_STD_INITIALIZER_LIST_
4730
4731// Supports the Pointwise(m, {a, b, c}) syntax.
4732template <typename TupleMatcher, typename T>
4733inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4734 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4735 return Pointwise(tuple_matcher, std::vector<T>(rhs));
4736}
4737
4738#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4739
4740// UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4741// container or a native array that contains the same number of
4742// elements as in rhs, where in some permutation of the container, its
4743// i-th element and rhs's i-th element (as a pair) satisfy the given
4744// pair matcher, for all i. Tuple2Matcher must be able to be safely
4745// cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4746// the types of elements in the LHS container and the RHS container
4747// respectively.
4748//
4749// This is like Pointwise(pair_matcher, rhs), except that the element
4750// order doesn't matter.
4751template <typename Tuple2Matcher, typename RhsContainer>
4752inline internal::UnorderedElementsAreArrayMatcher<
4753 typename internal::BoundSecondMatcher<
4754 Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4755 RhsContainer)>::type::value_type> >
4756UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4757 const RhsContainer& rhs_container) {
4758 // This following line is for working around a bug in MSVC 8.0,
4759 // which causes RhsContainer to be a const type sometimes (e.g. when
4760 // rhs_container is a const int[]).
4761 typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4762
4763 // RhsView allows the same code to handle RhsContainer being a
4764 // STL-style container and it being a native C-style array.
4765 typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4766 typedef typename RhsView::type RhsStlContainer;
4767 typedef typename RhsStlContainer::value_type Second;
4768 const RhsStlContainer& rhs_stl_container =
4769 RhsView::ConstReference(rhs_container);
4770
4771 // Create a matcher for each element in rhs_container.
4772 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4773 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4774 it != rhs_stl_container.end(); ++it) {
4775 matchers.push_back(
4776 internal::MatcherBindSecond(tuple2_matcher, *it));
4777 }
4778
4779 // Delegate the work to UnorderedElementsAreArray().
4780 return UnorderedElementsAreArray(matchers);
4781}
4782
4783#if GTEST_HAS_STD_INITIALIZER_LIST_
4784
4785// Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4786template <typename Tuple2Matcher, typename T>
4787inline internal::UnorderedElementsAreArrayMatcher<
4788 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4789UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4790 std::initializer_list<T> rhs) {
4791 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4792}
4793
4794#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4795
zhanyong.wanb8243162009-06-04 05:48:20 +00004796// Matches an STL-style container or a native array that contains at
4797// least one element matching the given value or matcher.
4798//
4799// Examples:
4800// ::std::set<int> page_ids;
4801// page_ids.insert(3);
4802// page_ids.insert(1);
4803// EXPECT_THAT(page_ids, Contains(1));
4804// EXPECT_THAT(page_ids, Contains(Gt(2)));
4805// EXPECT_THAT(page_ids, Not(Contains(4)));
4806//
4807// ::std::map<int, size_t> page_lengths;
4808// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00004809// EXPECT_THAT(page_lengths,
4810// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004811//
4812// const char* user_ids[] = { "joe", "mike", "tom" };
4813// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4814template <typename M>
4815inline internal::ContainsMatcher<M> Contains(M matcher) {
4816 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004817}
4818
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004819// IsSupersetOf(iterator_first, iterator_last)
4820// IsSupersetOf(pointer, count)
4821// IsSupersetOf(array)
4822// IsSupersetOf(container)
4823// IsSupersetOf({e1, e2, ..., en})
4824//
4825// IsSupersetOf() verifies that a surjective partial mapping onto a collection
4826// of matchers exists. In other words, a container matches
4827// IsSupersetOf({e1, ..., en}) if and only if there is a permutation
4828// {y1, ..., yn} of some of the container's elements where y1 matches e1,
4829// ..., and yn matches en. Obviously, the size of the container must be >= n
4830// in order to have a match. Examples:
4831//
4832// - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and
4833// 1 matches Ne(0).
4834// - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches
4835// both Eq(1) and Lt(2). The reason is that different matchers must be used
4836// for elements in different slots of the container.
4837// - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches
4838// Eq(1) and (the second) 1 matches Lt(2).
4839// - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)
4840// Gt(1) and 3 matches (the second) Gt(1).
4841//
4842// The matchers can be specified as an array, a pointer and count, a container,
4843// an initializer list, or an STL iterator range. In each of these cases, the
4844// underlying matchers can be either values or matchers.
4845
4846template <typename Iter>
4847inline internal::UnorderedElementsAreArrayMatcher<
4848 typename ::std::iterator_traits<Iter>::value_type>
4849IsSupersetOf(Iter first, Iter last) {
4850 typedef typename ::std::iterator_traits<Iter>::value_type T;
4851 return internal::UnorderedElementsAreArrayMatcher<T>(
4852 internal::UnorderedMatcherRequire::Superset, first, last);
4853}
4854
4855template <typename T>
4856inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
4857 const T* pointer, size_t count) {
4858 return IsSupersetOf(pointer, pointer + count);
4859}
4860
4861template <typename T, size_t N>
4862inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
4863 const T (&array)[N]) {
4864 return IsSupersetOf(array, N);
4865}
4866
4867template <typename Container>
4868inline internal::UnorderedElementsAreArrayMatcher<
4869 typename Container::value_type>
4870IsSupersetOf(const Container& container) {
4871 return IsSupersetOf(container.begin(), container.end());
4872}
4873
4874#if GTEST_HAS_STD_INITIALIZER_LIST_
4875template <typename T>
4876inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
4877 ::std::initializer_list<T> xs) {
4878 return IsSupersetOf(xs.begin(), xs.end());
4879}
4880#endif
4881
4882// IsSubsetOf(iterator_first, iterator_last)
4883// IsSubsetOf(pointer, count)
4884// IsSubsetOf(array)
4885// IsSubsetOf(container)
4886// IsSubsetOf({e1, e2, ..., en})
4887//
4888// IsSubsetOf() verifies that an injective mapping onto a collection of matchers
4889// exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and
4890// only if there is a subset of matchers {m1, ..., mk} which would match the
4891// container using UnorderedElementsAre. Obviously, the size of the container
4892// must be <= n in order to have a match. Examples:
4893//
4894// - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).
4895// - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1
4896// matches Lt(0).
4897// - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both
4898// match Gt(0). The reason is that different matchers must be used for
4899// elements in different slots of the container.
4900//
4901// The matchers can be specified as an array, a pointer and count, a container,
4902// an initializer list, or an STL iterator range. In each of these cases, the
4903// underlying matchers can be either values or matchers.
4904
4905template <typename Iter>
4906inline internal::UnorderedElementsAreArrayMatcher<
4907 typename ::std::iterator_traits<Iter>::value_type>
4908IsSubsetOf(Iter first, Iter last) {
4909 typedef typename ::std::iterator_traits<Iter>::value_type T;
4910 return internal::UnorderedElementsAreArrayMatcher<T>(
4911 internal::UnorderedMatcherRequire::Subset, first, last);
4912}
4913
4914template <typename T>
4915inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
4916 const T* pointer, size_t count) {
4917 return IsSubsetOf(pointer, pointer + count);
4918}
4919
4920template <typename T, size_t N>
4921inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
4922 const T (&array)[N]) {
4923 return IsSubsetOf(array, N);
4924}
4925
4926template <typename Container>
4927inline internal::UnorderedElementsAreArrayMatcher<
4928 typename Container::value_type>
4929IsSubsetOf(const Container& container) {
4930 return IsSubsetOf(container.begin(), container.end());
4931}
4932
4933#if GTEST_HAS_STD_INITIALIZER_LIST_
4934template <typename T>
4935inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
4936 ::std::initializer_list<T> xs) {
4937 return IsSubsetOf(xs.begin(), xs.end());
4938}
4939#endif
4940
zhanyong.wan33605ba2010-04-22 23:37:47 +00004941// Matches an STL-style container or a native array that contains only
4942// elements matching the given value or matcher.
4943//
4944// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
4945// the messages are different.
4946//
4947// Examples:
4948// ::std::set<int> page_ids;
4949// // Each(m) matches an empty container, regardless of what m is.
4950// EXPECT_THAT(page_ids, Each(Eq(1)));
4951// EXPECT_THAT(page_ids, Each(Eq(77)));
4952//
4953// page_ids.insert(3);
4954// EXPECT_THAT(page_ids, Each(Gt(0)));
4955// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
4956// page_ids.insert(1);
4957// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
4958//
4959// ::std::map<int, size_t> page_lengths;
4960// page_lengths[1] = 100;
4961// page_lengths[2] = 200;
4962// page_lengths[3] = 300;
4963// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
4964// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
4965//
4966// const char* user_ids[] = { "joe", "mike", "tom" };
4967// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
4968template <typename M>
4969inline internal::EachMatcher<M> Each(M matcher) {
4970 return internal::EachMatcher<M>(matcher);
4971}
4972
zhanyong.wanb5937da2009-07-16 20:26:41 +00004973// Key(inner_matcher) matches an std::pair whose 'first' field matches
4974// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
4975// std::map that contains at least one element whose key is >= 5.
4976template <typename M>
4977inline internal::KeyMatcher<M> Key(M inner_matcher) {
4978 return internal::KeyMatcher<M>(inner_matcher);
4979}
4980
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00004981// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
4982// matches first_matcher and whose 'second' field matches second_matcher. For
4983// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
4984// to match a std::map<int, string> that contains exactly one element whose key
4985// is >= 5 and whose value equals "foo".
4986template <typename FirstMatcher, typename SecondMatcher>
4987inline internal::PairMatcher<FirstMatcher, SecondMatcher>
4988Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
4989 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
4990 first_matcher, second_matcher);
4991}
4992
shiqiane35fdd92008-12-10 05:08:54 +00004993// Returns a predicate that is satisfied by anything that matches the
4994// given matcher.
4995template <typename M>
4996inline internal::MatcherAsPredicate<M> Matches(M matcher) {
4997 return internal::MatcherAsPredicate<M>(matcher);
4998}
4999
zhanyong.wanb8243162009-06-04 05:48:20 +00005000// Returns true iff the value matches the matcher.
5001template <typename T, typename M>
5002inline bool Value(const T& value, M matcher) {
5003 return testing::Matches(matcher)(value);
5004}
5005
zhanyong.wan34b034c2010-03-05 21:23:23 +00005006// Matches the value against the given matcher and explains the match
5007// result to listener.
5008template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00005009inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00005010 M matcher, const T& value, MatchResultListener* listener) {
5011 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
5012}
5013
Gennadiy Civilb907c262018-03-23 11:42:41 -04005014// Returns a string representation of the given matcher. Useful for description
5015// strings of matchers defined using MATCHER_P* macros that accept matchers as
5016// their arguments. For example:
5017//
5018// MATCHER_P(XAndYThat, matcher,
5019// "X that " + DescribeMatcher<int>(matcher, negation) +
5020// " and Y that " + DescribeMatcher<double>(matcher, negation)) {
5021// return ExplainMatchResult(matcher, arg.x(), result_listener) &&
5022// ExplainMatchResult(matcher, arg.y(), result_listener);
5023// }
5024template <typename T, typename M>
5025std::string DescribeMatcher(const M& matcher, bool negation = false) {
5026 ::std::stringstream ss;
5027 Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher);
5028 if (negation) {
5029 monomorphic_matcher.DescribeNegationTo(&ss);
5030 } else {
5031 monomorphic_matcher.DescribeTo(&ss);
5032 }
5033 return ss.str();
5034}
5035
zhanyong.wan616180e2013-06-18 18:49:51 +00005036#if GTEST_LANG_CXX11
5037// Define variadic matcher versions. They are overloaded in
5038// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
5039template <typename... Args>
5040inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
5041 return internal::AllOfMatcher<Args...>(matchers...);
5042}
5043
5044template <typename... Args>
5045inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
5046 return internal::AnyOfMatcher<Args...>(matchers...);
5047}
5048
5049#endif // GTEST_LANG_CXX11
5050
zhanyong.wanbf550852009-06-09 06:09:53 +00005051// AllArgs(m) is a synonym of m. This is useful in
5052//
5053// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
5054//
5055// which is easier to read than
5056//
5057// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
5058template <typename InnerMatcher>
5059inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
5060
Gennadiy Civilb907c262018-03-23 11:42:41 -04005061// Returns a matcher that matches the value of an optional<> type variable.
5062// The matcher implementation only uses '!arg' and requires that the optional<>
5063// type has a 'value_type' member type and that '*arg' is of type 'value_type'
5064// and is printable using 'PrintToString'. It is compatible with
5065// std::optional/std::experimental::optional.
5066// Note that to compare an optional type variable against nullopt you should
5067// use Eq(nullopt) and not Optional(Eq(nullopt)). The latter implies that the
5068// optional value contains an optional itself.
5069template <typename ValueMatcher>
5070inline internal::OptionalMatcher<ValueMatcher> Optional(
5071 const ValueMatcher& value_matcher) {
5072 return internal::OptionalMatcher<ValueMatcher>(value_matcher);
5073}
5074
5075// Returns a matcher that matches the value of a absl::any type variable.
5076template <typename T>
5077PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T> > AnyWith(
5078 const Matcher<const T&>& matcher) {
5079 return MakePolymorphicMatcher(
5080 internal::any_cast_matcher::AnyCastMatcher<T>(matcher));
5081}
5082
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05005083// Returns a matcher that matches the value of a variant<> type variable.
5084// The matcher implementation uses ADL to find the holds_alternative and get
5085// functions.
5086// It is compatible with std::variant.
5087template <typename T>
5088PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
5089 const Matcher<const T&>& matcher) {
5090 return MakePolymorphicMatcher(
5091 internal::variant_matcher::VariantMatcher<T>(matcher));
5092}
5093
shiqiane35fdd92008-12-10 05:08:54 +00005094// These macros allow using matchers to check values in Google Test
5095// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
5096// succeed iff the value matches the matcher. If the assertion fails,
5097// the value and the description of the matcher will be printed.
5098#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
5099 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
5100#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
5101 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
5102
5103} // namespace testing
5104
kosak6702b972015-07-27 23:05:57 +00005105// Include any custom callback matchers added by the local installation.
5106// We must include this header at the end to make sure it can use the
5107// declarations from this file.
5108#include "gmock/internal/custom/gmock-matchers.h"
Gennadiy Civilb907c262018-03-23 11:42:41 -04005109
shiqiane35fdd92008-12-10 05:08:54 +00005110#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_