blob: 044a323e768ab469dd13e55c43c8d36b610324fc [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
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000182// A match result listener that stores the explanation in a string.
183class StringMatchResultListener : public MatchResultListener {
184 public:
185 StringMatchResultListener() : MatchResultListener(&ss_) {}
186
187 // Returns the explanation accumulated so far.
Nico Weber09fd5b32017-05-15 17:07:03 -0400188 std::string str() const { return ss_.str(); }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000189
190 // Clears the explanation accumulated so far.
191 void Clear() { ss_.str(""); }
192
193 private:
194 ::std::stringstream ss_;
195
196 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
197};
198
shiqiane35fdd92008-12-10 05:08:54 +0000199namespace internal {
200
kosak506340a2014-11-17 01:47:54 +0000201struct AnyEq {
202 template <typename A, typename B>
203 bool operator()(const A& a, const B& b) const { return a == b; }
204};
205struct AnyNe {
206 template <typename A, typename B>
207 bool operator()(const A& a, const B& b) const { return a != b; }
208};
209struct AnyLt {
210 template <typename A, typename B>
211 bool operator()(const A& a, const B& b) const { return a < b; }
212};
213struct AnyGt {
214 template <typename A, typename B>
215 bool operator()(const A& a, const B& b) const { return a > b; }
216};
217struct AnyLe {
218 template <typename A, typename B>
219 bool operator()(const A& a, const B& b) const { return a <= b; }
220};
221struct AnyGe {
222 template <typename A, typename B>
223 bool operator()(const A& a, const B& b) const { return a >= b; }
224};
225
zhanyong.wan82113312010-01-08 21:55:40 +0000226// A match result listener that ignores the explanation.
227class DummyMatchResultListener : public MatchResultListener {
228 public:
229 DummyMatchResultListener() : MatchResultListener(NULL) {}
230
231 private:
232 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
233};
234
235// A match result listener that forwards the explanation to a given
236// ostream. The difference between this and MatchResultListener is
237// that the former is concrete.
238class StreamMatchResultListener : public MatchResultListener {
239 public:
240 explicit StreamMatchResultListener(::std::ostream* os)
241 : MatchResultListener(os) {}
242
243 private:
244 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
245};
246
shiqiane35fdd92008-12-10 05:08:54 +0000247// An internal class for implementing Matcher<T>, which will derive
248// from it. We put functionalities common to all Matcher<T>
249// specializations here to avoid code duplication.
250template <typename T>
251class MatcherBase {
252 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000253 // Returns true iff the matcher matches x; also explains the match
254 // result to 'listener'.
255 bool MatchAndExplain(T x, MatchResultListener* listener) const {
256 return impl_->MatchAndExplain(x, listener);
257 }
258
shiqiane35fdd92008-12-10 05:08:54 +0000259 // Returns true iff this matcher matches x.
zhanyong.wan82113312010-01-08 21:55:40 +0000260 bool Matches(T x) const {
261 DummyMatchResultListener dummy;
262 return MatchAndExplain(x, &dummy);
263 }
shiqiane35fdd92008-12-10 05:08:54 +0000264
265 // Describes this matcher to an ostream.
266 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
267
268 // Describes the negation of this matcher to an ostream.
269 void DescribeNegationTo(::std::ostream* os) const {
270 impl_->DescribeNegationTo(os);
271 }
272
273 // Explains why x matches, or doesn't match, the matcher.
274 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000275 StreamMatchResultListener listener(os);
276 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000277 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000278
zhanyong.wanfb25d532013-07-28 08:24:00 +0000279 // Returns the describer for this matcher object; retains ownership
280 // of the describer, which is only guaranteed to be alive when
281 // this matcher object is alive.
282 const MatcherDescriberInterface* GetDescriber() const {
283 return impl_.get();
284 }
285
shiqiane35fdd92008-12-10 05:08:54 +0000286 protected:
287 MatcherBase() {}
288
289 // Constructs a matcher from its implementation.
290 explicit MatcherBase(const MatcherInterface<T>* impl)
291 : impl_(impl) {}
292
293 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000294
shiqiane35fdd92008-12-10 05:08:54 +0000295 private:
296 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
297 // interfaces. The former dynamically allocates a chunk of memory
298 // to hold the reference count, while the latter tracks all
299 // references using a circular linked list without allocating
300 // memory. It has been observed that linked_ptr performs better in
301 // typical scenarios. However, shared_ptr can out-perform
302 // linked_ptr when there are many more uses of the copy constructor
303 // than the default constructor.
304 //
305 // If performance becomes a problem, we should see if using
306 // shared_ptr helps.
307 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
308};
309
shiqiane35fdd92008-12-10 05:08:54 +0000310} // namespace internal
311
312// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
313// object that can check whether a value of type T matches. The
314// implementation of Matcher<T> is just a linked_ptr to const
315// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
316// from Matcher!
317template <typename T>
318class Matcher : public internal::MatcherBase<T> {
319 public:
vladlosev88032d82010-11-17 23:29:21 +0000320 // Constructs a null matcher. Needed for storing Matcher objects in STL
321 // containers. A default-constructed matcher is not yet initialized. You
322 // cannot use it until a valid value has been assigned to it.
kosakd86a7232015-07-13 21:19:43 +0000323 explicit Matcher() {} // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000324
325 // Constructs a matcher from its implementation.
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400326 explicit Matcher(const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)>* impl)
327 : internal::MatcherBase<T>(impl) {}
328
329 template <typename U>
330 explicit Matcher(const MatcherInterface<U>* impl,
331 typename internal::EnableIf<!internal::IsSame<
332 U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* = NULL)
shiqiane35fdd92008-12-10 05:08:54 +0000333 : internal::MatcherBase<T>(impl) {}
334
zhanyong.wan18490652009-05-11 18:54:08 +0000335 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000336 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
337 Matcher(T value); // NOLINT
338};
339
340// The following two specializations allow the user to write str
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400341// instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
shiqiane35fdd92008-12-10 05:08:54 +0000342// matcher is expected.
343template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400344class GTEST_API_ Matcher<const std::string&>
345 : public internal::MatcherBase<const std::string&> {
shiqiane35fdd92008-12-10 05:08:54 +0000346 public:
347 Matcher() {}
348
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400349 explicit Matcher(const MatcherInterface<const std::string&>* impl)
350 : internal::MatcherBase<const std::string&>(impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000351
352 // Allows the user to write str instead of Eq(str) sometimes, where
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400353 // str is a std::string object.
354 Matcher(const std::string& s); // NOLINT
355
356#if GTEST_HAS_GLOBAL_STRING
357 // Allows the user to write str instead of Eq(str) sometimes, where
358 // str is a ::string object.
359 Matcher(const ::string& s); // NOLINT
360#endif // GTEST_HAS_GLOBAL_STRING
shiqiane35fdd92008-12-10 05:08:54 +0000361
362 // Allows the user to write "foo" instead of Eq("foo") sometimes.
363 Matcher(const char* s); // NOLINT
364};
365
366template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400367class GTEST_API_ Matcher<std::string>
368 : public internal::MatcherBase<std::string> {
shiqiane35fdd92008-12-10 05:08:54 +0000369 public:
370 Matcher() {}
371
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400372 explicit Matcher(const MatcherInterface<std::string>* impl)
373 : internal::MatcherBase<std::string>(impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000374
375 // Allows the user to write str instead of Eq(str) sometimes, where
376 // str is a string object.
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400377 Matcher(const std::string& s); // NOLINT
378
379#if GTEST_HAS_GLOBAL_STRING
380 // Allows the user to write str instead of Eq(str) sometimes, where
381 // str is a ::string object.
382 Matcher(const ::string& s); // NOLINT
383#endif // GTEST_HAS_GLOBAL_STRING
shiqiane35fdd92008-12-10 05:08:54 +0000384
385 // Allows the user to write "foo" instead of Eq("foo") sometimes.
386 Matcher(const char* s); // NOLINT
387};
388
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400389#if GTEST_HAS_GLOBAL_STRING
zhanyong.wan1f122a02013-03-25 16:27:03 +0000390// The following two specializations allow the user to write str
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400391// instead of Eq(str) and "foo" instead of Eq("foo") when a ::string
zhanyong.wan1f122a02013-03-25 16:27:03 +0000392// matcher is expected.
393template <>
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400394class GTEST_API_ Matcher<const ::string&>
395 : public internal::MatcherBase<const ::string&> {
zhanyong.wan1f122a02013-03-25 16:27:03 +0000396 public:
397 Matcher() {}
398
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400399 explicit Matcher(const MatcherInterface<const ::string&>* impl)
400 : internal::MatcherBase<const ::string&>(impl) {}
zhanyong.wan1f122a02013-03-25 16:27:03 +0000401
402 // Allows the user to write str instead of Eq(str) sometimes, where
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400403 // str is a std::string object.
404 Matcher(const std::string& s); // NOLINT
405
406 // Allows the user to write str instead of Eq(str) sometimes, where
407 // str is a ::string object.
408 Matcher(const ::string& s); // NOLINT
zhanyong.wan1f122a02013-03-25 16:27:03 +0000409
410 // Allows the user to write "foo" instead of Eq("foo") sometimes.
411 Matcher(const char* s); // NOLINT
Gennadiy Civilb7c56832018-03-22 15:35:37 -0400412};
zhanyong.wan1f122a02013-03-25 16:27:03 +0000413
zhanyong.wan1f122a02013-03-25 16:27:03 +0000414};
415
416template <>
417class GTEST_API_ Matcher<StringPiece>
418 : public internal::MatcherBase<StringPiece> {
419 public:
420 Matcher() {}
421
422 explicit Matcher(const MatcherInterface<StringPiece>* impl)
423 : internal::MatcherBase<StringPiece>(impl) {}
424
425 // Allows the user to write str instead of Eq(str) sometimes, where
426 // str is a string object.
427 Matcher(const internal::string& s); // NOLINT
428
429 // Allows the user to write "foo" instead of Eq("foo") sometimes.
430 Matcher(const char* s); // NOLINT
431
432 // Allows the user to pass StringPieces directly.
433 Matcher(StringPiece s); // NOLINT
434};
435#endif // GTEST_HAS_STRING_PIECE_
436
shiqiane35fdd92008-12-10 05:08:54 +0000437// The PolymorphicMatcher class template makes it easy to implement a
438// polymorphic matcher (i.e. a matcher that can match values of more
439// than one type, e.g. Eq(n) and NotNull()).
440//
zhanyong.wandb22c222010-01-28 21:52:29 +0000441// To define a polymorphic matcher, a user should provide an Impl
442// class that has a DescribeTo() method and a DescribeNegationTo()
443// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000444//
zhanyong.wandb22c222010-01-28 21:52:29 +0000445// bool MatchAndExplain(const Value& value,
446// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000447//
448// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000449template <class Impl>
450class PolymorphicMatcher {
451 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000452 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000453
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000454 // Returns a mutable reference to the underlying matcher
455 // implementation object.
456 Impl& mutable_impl() { return impl_; }
457
458 // Returns an immutable reference to the underlying matcher
459 // implementation object.
460 const Impl& impl() const { return impl_; }
461
shiqiane35fdd92008-12-10 05:08:54 +0000462 template <typename T>
463 operator Matcher<T>() const {
464 return Matcher<T>(new MonomorphicImpl<T>(impl_));
465 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000466
shiqiane35fdd92008-12-10 05:08:54 +0000467 private:
468 template <typename T>
469 class MonomorphicImpl : public MatcherInterface<T> {
470 public:
471 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
472
shiqiane35fdd92008-12-10 05:08:54 +0000473 virtual void DescribeTo(::std::ostream* os) const {
474 impl_.DescribeTo(os);
475 }
476
477 virtual void DescribeNegationTo(::std::ostream* os) const {
478 impl_.DescribeNegationTo(os);
479 }
480
zhanyong.wan82113312010-01-08 21:55:40 +0000481 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000482 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000483 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000484
shiqiane35fdd92008-12-10 05:08:54 +0000485 private:
486 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000487
488 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000489 };
490
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000491 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000492
493 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000494};
495
496// Creates a matcher from its implementation. This is easier to use
497// than the Matcher<T> constructor as it doesn't require you to
498// explicitly write the template argument, e.g.
499//
500// MakeMatcher(foo);
501// vs
502// Matcher<const string&>(foo);
503template <typename T>
504inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
505 return Matcher<T>(impl);
zhanyong.wan2eab17b2013-03-08 17:53:24 +0000506}
shiqiane35fdd92008-12-10 05:08:54 +0000507
508// Creates a polymorphic matcher from its implementation. This is
509// easier to use than the PolymorphicMatcher<Impl> constructor as it
510// doesn't require you to explicitly write the template argument, e.g.
511//
512// MakePolymorphicMatcher(foo);
513// vs
514// PolymorphicMatcher<TypeOfFoo>(foo);
515template <class Impl>
516inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
517 return PolymorphicMatcher<Impl>(impl);
518}
519
jgm79a367e2012-04-10 16:02:11 +0000520// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
521// and MUST NOT BE USED IN USER CODE!!!
522namespace internal {
523
524// The MatcherCastImpl class template is a helper for implementing
525// MatcherCast(). We need this helper in order to partially
526// specialize the implementation of MatcherCast() (C++ allows
527// class/struct templates to be partially specialized, but not
528// function templates.).
529
530// This general version is used when MatcherCast()'s argument is a
531// polymorphic matcher (i.e. something that can be converted to a
532// Matcher but is not one yet; for example, Eq(value)) or a value (for
533// example, "hello").
534template <typename T, typename M>
535class MatcherCastImpl {
536 public:
kosak5f2a6ca2013-12-03 01:43:07 +0000537 static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
Gennadiy Civil2bd17502018-02-27 13:51:09 -0500538 // M can be a polymorphic matcher, in which case we want to use
jgm79a367e2012-04-10 16:02:11 +0000539 // its conversion operator to create Matcher<T>. Or it can be a value
540 // that should be passed to the Matcher<T>'s constructor.
541 //
542 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
543 // polymorphic matcher because it'll be ambiguous if T has an implicit
544 // constructor from M (this usually happens when T has an implicit
545 // constructor from any type).
546 //
547 // It won't work to unconditionally implict_cast
548 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
549 // a user-defined conversion from M to T if one exists (assuming M is
550 // a value).
551 return CastImpl(
552 polymorphic_matcher_or_value,
553 BooleanConstant<
554 internal::ImplicitlyConvertible<M, Matcher<T> >::value>());
555 }
556
557 private:
kosak5f2a6ca2013-12-03 01:43:07 +0000558 static Matcher<T> CastImpl(const M& value, BooleanConstant<false>) {
jgm79a367e2012-04-10 16:02:11 +0000559 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
560 // matcher. It must be a value then. Use direct initialization to create
561 // a matcher.
562 return Matcher<T>(ImplicitCast_<T>(value));
563 }
564
kosak5f2a6ca2013-12-03 01:43:07 +0000565 static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
jgm79a367e2012-04-10 16:02:11 +0000566 BooleanConstant<true>) {
567 // M is implicitly convertible to Matcher<T>, which means that either
568 // M is a polymorhpic matcher or Matcher<T> has an implicit constructor
569 // from M. In both cases using the implicit conversion will produce a
570 // matcher.
571 //
572 // Even if T has an implicit constructor from M, it won't be called because
573 // creating Matcher<T> would require a chain of two user-defined conversions
574 // (first to create T from M and then to create Matcher<T> from T).
575 return polymorphic_matcher_or_value;
576 }
577};
578
579// This more specialized version is used when MatcherCast()'s argument
580// is already a Matcher. This only compiles when type T can be
581// statically converted to type U.
582template <typename T, typename U>
583class MatcherCastImpl<T, Matcher<U> > {
584 public:
585 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
586 return Matcher<T>(new Impl(source_matcher));
587 }
588
589 private:
590 class Impl : public MatcherInterface<T> {
591 public:
592 explicit Impl(const Matcher<U>& source_matcher)
593 : source_matcher_(source_matcher) {}
594
595 // We delegate the matching logic to the source matcher.
596 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
597 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
598 }
599
600 virtual void DescribeTo(::std::ostream* os) const {
601 source_matcher_.DescribeTo(os);
602 }
603
604 virtual void DescribeNegationTo(::std::ostream* os) const {
605 source_matcher_.DescribeNegationTo(os);
606 }
607
608 private:
609 const Matcher<U> source_matcher_;
610
611 GTEST_DISALLOW_ASSIGN_(Impl);
612 };
613};
614
615// This even more specialized version is used for efficiently casting
616// a matcher to its own type.
617template <typename T>
618class MatcherCastImpl<T, Matcher<T> > {
619 public:
620 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
621};
622
623} // namespace internal
624
shiqiane35fdd92008-12-10 05:08:54 +0000625// In order to be safe and clear, casting between different matcher
626// types is done explicitly via MatcherCast<T>(m), which takes a
627// matcher m and returns a Matcher<T>. It compiles only when T can be
628// statically converted to the argument type of m.
629template <typename T, typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000630inline Matcher<T> MatcherCast(const M& matcher) {
jgm79a367e2012-04-10 16:02:11 +0000631 return internal::MatcherCastImpl<T, M>::Cast(matcher);
632}
shiqiane35fdd92008-12-10 05:08:54 +0000633
zhanyong.wan18490652009-05-11 18:54:08 +0000634// Implements SafeMatcherCast().
635//
zhanyong.wan95b12332009-09-25 18:55:50 +0000636// We use an intermediate class to do the actual safe casting as Nokia's
637// Symbian compiler cannot decide between
638// template <T, M> ... (M) and
639// template <T, U> ... (const Matcher<U>&)
640// for function templates but can for member function templates.
641template <typename T>
642class SafeMatcherCastImpl {
643 public:
jgm79a367e2012-04-10 16:02:11 +0000644 // This overload handles polymorphic matchers and values only since
645 // monomorphic matchers are handled by the next one.
zhanyong.wan95b12332009-09-25 18:55:50 +0000646 template <typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000647 static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
jgm79a367e2012-04-10 16:02:11 +0000648 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
zhanyong.wan95b12332009-09-25 18:55:50 +0000649 }
zhanyong.wan18490652009-05-11 18:54:08 +0000650
zhanyong.wan95b12332009-09-25 18:55:50 +0000651 // This overload handles monomorphic matchers.
652 //
653 // In general, if type T can be implicitly converted to type U, we can
654 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
655 // contravariant): just keep a copy of the original Matcher<U>, convert the
656 // argument from type T to U, and then pass it to the underlying Matcher<U>.
657 // The only exception is when U is a reference and T is not, as the
658 // underlying Matcher<U> may be interested in the argument's address, which
659 // is not preserved in the conversion from T to U.
660 template <typename U>
661 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
662 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000663 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000664 T_must_be_implicitly_convertible_to_U);
665 // Enforce that we are not converting a non-reference type T to a reference
666 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000667 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000668 internal::is_reference<T>::value || !internal::is_reference<U>::value,
Hector Dearman24054ff2017-06-19 18:27:33 +0100669 cannot_convert_non_reference_arg_to_reference);
zhanyong.wan95b12332009-09-25 18:55:50 +0000670 // In case both T and U are arithmetic types, enforce that the
671 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000672 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
673 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000674 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
675 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000676 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000677 kTIsOther || kUIsOther ||
678 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
679 conversion_of_arithmetic_types_must_be_lossless);
680 return MatcherCast<T>(matcher);
681 }
682};
683
684template <typename T, typename M>
685inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
686 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000687}
688
shiqiane35fdd92008-12-10 05:08:54 +0000689// A<T>() returns a matcher that matches any value of type T.
690template <typename T>
691Matcher<T> A();
692
693// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
694// and MUST NOT BE USED IN USER CODE!!!
695namespace internal {
696
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000697// If the explanation is not empty, prints it to the ostream.
Nico Weber09fd5b32017-05-15 17:07:03 -0400698inline void PrintIfNotEmpty(const std::string& explanation,
zhanyong.wanfb25d532013-07-28 08:24:00 +0000699 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000700 if (explanation != "" && os != NULL) {
701 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000702 }
703}
704
zhanyong.wan736baa82010-09-27 17:44:16 +0000705// Returns true if the given type name is easy to read by a human.
706// This is used to decide whether printing the type of a value might
707// be helpful.
Nico Weber09fd5b32017-05-15 17:07:03 -0400708inline bool IsReadableTypeName(const std::string& type_name) {
zhanyong.wan736baa82010-09-27 17:44:16 +0000709 // We consider a type name readable if it's short or doesn't contain
710 // a template or function type.
711 return (type_name.length() <= 20 ||
Nico Weber09fd5b32017-05-15 17:07:03 -0400712 type_name.find_first_of("<(") == std::string::npos);
zhanyong.wan736baa82010-09-27 17:44:16 +0000713}
714
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000715// Matches the value against the given matcher, prints the value and explains
716// the match result to the listener. Returns the match result.
717// 'listener' must not be NULL.
718// Value cannot be passed by const reference, because some matchers take a
719// non-const argument.
720template <typename Value, typename T>
721bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
722 MatchResultListener* listener) {
723 if (!listener->IsInterested()) {
724 // If the listener is not interested, we do not need to construct the
725 // inner explanation.
726 return matcher.Matches(value);
727 }
728
729 StringMatchResultListener inner_listener;
730 const bool match = matcher.MatchAndExplain(value, &inner_listener);
731
732 UniversalPrint(value, listener->stream());
zhanyong.wan736baa82010-09-27 17:44:16 +0000733#if GTEST_HAS_RTTI
Nico Weber09fd5b32017-05-15 17:07:03 -0400734 const std::string& type_name = GetTypeName<Value>();
zhanyong.wan736baa82010-09-27 17:44:16 +0000735 if (IsReadableTypeName(type_name))
736 *listener->stream() << " (of type " << type_name << ")";
737#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000738 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000739
740 return match;
741}
742
shiqiane35fdd92008-12-10 05:08:54 +0000743// An internal helper class for doing compile-time loop on a tuple's
744// fields.
745template <size_t N>
746class TuplePrefix {
747 public:
748 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
749 // iff the first N fields of matcher_tuple matches the first N
750 // fields of value_tuple, respectively.
751 template <typename MatcherTuple, typename ValueTuple>
752 static bool Matches(const MatcherTuple& matcher_tuple,
753 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000754 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
755 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
756 }
757
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000758 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000759 // describes failures in matching the first N fields of matchers
760 // against the first N fields of values. If there is no failure,
761 // nothing will be streamed to os.
762 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000763 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
764 const ValueTuple& values,
765 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000766 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000767 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000768
769 // Then describes the failure (if any) in the (N - 1)-th (0-based)
770 // field.
771 typename tuple_element<N - 1, MatcherTuple>::type matcher =
772 get<N - 1>(matchers);
773 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
774 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000775 StringMatchResultListener listener;
776 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000777 // TODO(wan): include in the message the name of the parameter
778 // as used in MOCK_METHOD*() when possible.
779 *os << " Expected arg #" << N - 1 << ": ";
780 get<N - 1>(matchers).DescribeTo(os);
781 *os << "\n Actual: ";
782 // We remove the reference in type Value to prevent the
783 // universal printer from printing the address of value, which
784 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000785 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000786 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000787 internal::UniversalPrint(value, os);
788 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000789 *os << "\n";
790 }
791 }
792};
793
794// The base case.
795template <>
796class TuplePrefix<0> {
797 public:
798 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000799 static bool Matches(const MatcherTuple& /* matcher_tuple */,
800 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000801 return true;
802 }
803
804 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000805 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
806 const ValueTuple& /* values */,
807 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000808};
809
810// TupleMatches(matcher_tuple, value_tuple) returns true iff all
811// matchers in matcher_tuple match the corresponding fields in
812// value_tuple. It is a compiler error if matcher_tuple and
813// value_tuple have different number of fields or incompatible field
814// types.
815template <typename MatcherTuple, typename ValueTuple>
816bool TupleMatches(const MatcherTuple& matcher_tuple,
817 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000818 // Makes sure that matcher_tuple and value_tuple have the same
819 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000820 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000821 tuple_size<ValueTuple>::value,
822 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000823 return TuplePrefix<tuple_size<ValueTuple>::value>::
824 Matches(matcher_tuple, value_tuple);
825}
826
827// Describes failures in matching matchers against values. If there
828// is no failure, nothing will be streamed to os.
829template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000830void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
831 const ValueTuple& values,
832 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000833 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000834 matchers, values, os);
835}
836
zhanyong.wanfb25d532013-07-28 08:24:00 +0000837// TransformTupleValues and its helper.
838//
839// TransformTupleValuesHelper hides the internal machinery that
840// TransformTupleValues uses to implement a tuple traversal.
841template <typename Tuple, typename Func, typename OutIter>
842class TransformTupleValuesHelper {
843 private:
kosakbd018832014-04-02 20:30:00 +0000844 typedef ::testing::tuple_size<Tuple> TupleSize;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000845
846 public:
847 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
848 // Returns the final value of 'out' in case the caller needs it.
849 static OutIter Run(Func f, const Tuple& t, OutIter out) {
850 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
851 }
852
853 private:
854 template <typename Tup, size_t kRemainingSize>
855 struct IterateOverTuple {
856 OutIter operator() (Func f, const Tup& t, OutIter out) const {
kosakbd018832014-04-02 20:30:00 +0000857 *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
zhanyong.wanfb25d532013-07-28 08:24:00 +0000858 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
859 }
860 };
861 template <typename Tup>
862 struct IterateOverTuple<Tup, 0> {
863 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
864 return out;
865 }
866 };
867};
868
869// Successively invokes 'f(element)' on each element of the tuple 't',
870// appending each result to the 'out' iterator. Returns the final value
871// of 'out'.
872template <typename Tuple, typename Func, typename OutIter>
873OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
874 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
875}
876
shiqiane35fdd92008-12-10 05:08:54 +0000877// Implements A<T>().
878template <typename T>
879class AnyMatcherImpl : public MatcherInterface<T> {
880 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000881 virtual bool MatchAndExplain(
882 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000883 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
884 virtual void DescribeNegationTo(::std::ostream* os) const {
885 // This is mostly for completeness' safe, as it's not very useful
886 // to write Not(A<bool>()). However we cannot completely rule out
887 // such a possibility, and it doesn't hurt to be prepared.
888 *os << "never matches";
889 }
890};
891
892// Implements _, a matcher that matches any value of any
893// type. This is a polymorphic matcher, so we need a template type
894// conversion operator to make it appearing as a Matcher<T> for any
895// type T.
896class AnythingMatcher {
897 public:
898 template <typename T>
899 operator Matcher<T>() const { return A<T>(); }
900};
901
902// Implements a matcher that compares a given value with a
903// pre-supplied value using one of the ==, <=, <, etc, operators. The
904// two values being compared don't have to have the same type.
905//
906// The matcher defined here is polymorphic (for example, Eq(5) can be
907// used to match an int, a short, a double, etc). Therefore we use
908// a template type conversion operator in the implementation.
909//
shiqiane35fdd92008-12-10 05:08:54 +0000910// The following template definition assumes that the Rhs parameter is
911// a "bare" type (i.e. neither 'const T' nor 'T&').
kosak506340a2014-11-17 01:47:54 +0000912template <typename D, typename Rhs, typename Op>
913class ComparisonBase {
914 public:
915 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
916 template <typename Lhs>
917 operator Matcher<Lhs>() const {
918 return MakeMatcher(new Impl<Lhs>(rhs_));
shiqiane35fdd92008-12-10 05:08:54 +0000919 }
920
kosak506340a2014-11-17 01:47:54 +0000921 private:
922 template <typename Lhs>
923 class Impl : public MatcherInterface<Lhs> {
924 public:
925 explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
926 virtual bool MatchAndExplain(
927 Lhs lhs, MatchResultListener* /* listener */) const {
928 return Op()(lhs, rhs_);
929 }
930 virtual void DescribeTo(::std::ostream* os) const {
931 *os << D::Desc() << " ";
932 UniversalPrint(rhs_, os);
933 }
934 virtual void DescribeNegationTo(::std::ostream* os) const {
935 *os << D::NegatedDesc() << " ";
936 UniversalPrint(rhs_, os);
937 }
938 private:
939 Rhs rhs_;
940 GTEST_DISALLOW_ASSIGN_(Impl);
941 };
942 Rhs rhs_;
943 GTEST_DISALLOW_ASSIGN_(ComparisonBase);
944};
shiqiane35fdd92008-12-10 05:08:54 +0000945
kosak506340a2014-11-17 01:47:54 +0000946template <typename Rhs>
947class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
948 public:
949 explicit EqMatcher(const Rhs& rhs)
950 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
951 static const char* Desc() { return "is equal to"; }
952 static const char* NegatedDesc() { return "isn't equal to"; }
953};
954template <typename Rhs>
955class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
956 public:
957 explicit NeMatcher(const Rhs& rhs)
958 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
959 static const char* Desc() { return "isn't equal to"; }
960 static const char* NegatedDesc() { return "is equal to"; }
961};
962template <typename Rhs>
963class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
964 public:
965 explicit LtMatcher(const Rhs& rhs)
966 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
967 static const char* Desc() { return "is <"; }
968 static const char* NegatedDesc() { return "isn't <"; }
969};
970template <typename Rhs>
971class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
972 public:
973 explicit GtMatcher(const Rhs& rhs)
974 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
975 static const char* Desc() { return "is >"; }
976 static const char* NegatedDesc() { return "isn't >"; }
977};
978template <typename Rhs>
979class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
980 public:
981 explicit LeMatcher(const Rhs& rhs)
982 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
983 static const char* Desc() { return "is <="; }
984 static const char* NegatedDesc() { return "isn't <="; }
985};
986template <typename Rhs>
987class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
988 public:
989 explicit GeMatcher(const Rhs& rhs)
990 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
991 static const char* Desc() { return "is >="; }
992 static const char* NegatedDesc() { return "isn't >="; }
993};
shiqiane35fdd92008-12-10 05:08:54 +0000994
vladlosev79b83502009-11-18 00:43:37 +0000995// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000996// pointer that is NULL.
997class IsNullMatcher {
998 public:
vladlosev79b83502009-11-18 00:43:37 +0000999 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +00001000 bool MatchAndExplain(const Pointer& p,
1001 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001002#if GTEST_LANG_CXX11
1003 return p == nullptr;
1004#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001005 return GetRawPointer(p) == NULL;
kosak6305ff52015-04-28 22:36:31 +00001006#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001007 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001008
1009 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
1010 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001011 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001012 }
1013};
1014
vladlosev79b83502009-11-18 00:43:37 +00001015// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +00001016// pointer that is not NULL.
1017class NotNullMatcher {
1018 public:
vladlosev79b83502009-11-18 00:43:37 +00001019 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +00001020 bool MatchAndExplain(const Pointer& p,
1021 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001022#if GTEST_LANG_CXX11
1023 return p != nullptr;
1024#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001025 return GetRawPointer(p) != NULL;
kosak6305ff52015-04-28 22:36:31 +00001026#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001027 }
shiqiane35fdd92008-12-10 05:08:54 +00001028
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001029 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +00001030 void DescribeNegationTo(::std::ostream* os) const {
1031 *os << "is NULL";
1032 }
1033};
1034
1035// Ref(variable) matches any argument that is a reference to
1036// 'variable'. This matcher is polymorphic as it can match any
1037// super type of the type of 'variable'.
1038//
1039// The RefMatcher template class implements Ref(variable). It can
1040// only be instantiated with a reference type. This prevents a user
1041// from mistakenly using Ref(x) to match a non-reference function
1042// argument. For example, the following will righteously cause a
1043// compiler error:
1044//
1045// int n;
1046// Matcher<int> m1 = Ref(n); // This won't compile.
1047// Matcher<int&> m2 = Ref(n); // This will compile.
1048template <typename T>
1049class RefMatcher;
1050
1051template <typename T>
1052class RefMatcher<T&> {
1053 // Google Mock is a generic framework and thus needs to support
1054 // mocking any function types, including those that take non-const
1055 // reference arguments. Therefore the template parameter T (and
1056 // Super below) can be instantiated to either a const type or a
1057 // non-const type.
1058 public:
1059 // RefMatcher() takes a T& instead of const T&, as we want the
1060 // compiler to catch using Ref(const_value) as a matcher for a
1061 // non-const reference.
1062 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
1063
1064 template <typename Super>
1065 operator Matcher<Super&>() const {
1066 // By passing object_ (type T&) to Impl(), which expects a Super&,
1067 // we make sure that Super is a super type of T. In particular,
1068 // this catches using Ref(const_value) as a matcher for a
1069 // non-const reference, as you cannot implicitly convert a const
1070 // reference to a non-const reference.
1071 return MakeMatcher(new Impl<Super>(object_));
1072 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001073
shiqiane35fdd92008-12-10 05:08:54 +00001074 private:
1075 template <typename Super>
1076 class Impl : public MatcherInterface<Super&> {
1077 public:
1078 explicit Impl(Super& x) : object_(x) {} // NOLINT
1079
zhanyong.wandb22c222010-01-28 21:52:29 +00001080 // MatchAndExplain() takes a Super& (as opposed to const Super&)
1081 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +00001082 virtual bool MatchAndExplain(
1083 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001084 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +00001085 return &x == &object_;
1086 }
shiqiane35fdd92008-12-10 05:08:54 +00001087
1088 virtual void DescribeTo(::std::ostream* os) const {
1089 *os << "references the variable ";
1090 UniversalPrinter<Super&>::Print(object_, os);
1091 }
1092
1093 virtual void DescribeNegationTo(::std::ostream* os) const {
1094 *os << "does not reference the variable ";
1095 UniversalPrinter<Super&>::Print(object_, os);
1096 }
1097
shiqiane35fdd92008-12-10 05:08:54 +00001098 private:
1099 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001100
1101 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001102 };
1103
1104 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001105
1106 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001107};
1108
1109// Polymorphic helper functions for narrow and wide string matchers.
1110inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1111 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1112}
1113
1114inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1115 const wchar_t* rhs) {
1116 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1117}
1118
1119// String comparison for narrow or wide strings that can have embedded NUL
1120// characters.
1121template <typename StringType>
1122bool CaseInsensitiveStringEquals(const StringType& s1,
1123 const StringType& s2) {
1124 // Are the heads equal?
1125 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1126 return false;
1127 }
1128
1129 // Skip the equal heads.
1130 const typename StringType::value_type nul = 0;
1131 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1132
1133 // Are we at the end of either s1 or s2?
1134 if (i1 == StringType::npos || i2 == StringType::npos) {
1135 return i1 == i2;
1136 }
1137
1138 // Are the tails equal?
1139 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1140}
1141
1142// String matchers.
1143
1144// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1145template <typename StringType>
1146class StrEqualityMatcher {
1147 public:
shiqiane35fdd92008-12-10 05:08:54 +00001148 StrEqualityMatcher(const StringType& str, bool expect_eq,
1149 bool case_sensitive)
1150 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1151
jgm38513a82012-11-15 15:50:36 +00001152 // Accepts pointer types, particularly:
1153 // const char*
1154 // char*
1155 // const wchar_t*
1156 // wchar_t*
1157 template <typename CharType>
1158 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001159 if (s == NULL) {
1160 return !expect_eq_;
1161 }
zhanyong.wandb22c222010-01-28 21:52:29 +00001162 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001163 }
1164
jgm38513a82012-11-15 15:50:36 +00001165 // Matches anything that can convert to StringType.
1166 //
1167 // This is a template, not just a plain function with const StringType&,
1168 // because StringPiece has some interfering non-explicit constructors.
1169 template <typename MatcheeStringType>
1170 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001171 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001172 const StringType& s2(s);
1173 const bool eq = case_sensitive_ ? s2 == string_ :
1174 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +00001175 return expect_eq_ == eq;
1176 }
1177
1178 void DescribeTo(::std::ostream* os) const {
1179 DescribeToHelper(expect_eq_, os);
1180 }
1181
1182 void DescribeNegationTo(::std::ostream* os) const {
1183 DescribeToHelper(!expect_eq_, os);
1184 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001185
shiqiane35fdd92008-12-10 05:08:54 +00001186 private:
1187 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001188 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +00001189 *os << "equal to ";
1190 if (!case_sensitive_) {
1191 *os << "(ignoring case) ";
1192 }
vladloseve2e8ba42010-05-13 18:16:03 +00001193 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001194 }
1195
1196 const StringType string_;
1197 const bool expect_eq_;
1198 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001199
1200 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001201};
1202
1203// Implements the polymorphic HasSubstr(substring) matcher, which
1204// can be used as a Matcher<T> as long as T can be converted to a
1205// string.
1206template <typename StringType>
1207class HasSubstrMatcher {
1208 public:
shiqiane35fdd92008-12-10 05:08:54 +00001209 explicit HasSubstrMatcher(const StringType& substring)
1210 : substring_(substring) {}
1211
jgm38513a82012-11-15 15:50:36 +00001212 // Accepts pointer types, particularly:
1213 // const char*
1214 // char*
1215 // const wchar_t*
1216 // wchar_t*
1217 template <typename CharType>
1218 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001219 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001220 }
1221
jgm38513a82012-11-15 15:50:36 +00001222 // Matches anything that can convert to StringType.
1223 //
1224 // This is a template, not just a plain function with const StringType&,
1225 // because StringPiece has some interfering non-explicit constructors.
1226 template <typename MatcheeStringType>
1227 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001228 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001229 const StringType& s2(s);
1230 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001231 }
1232
1233 // Describes what this matcher matches.
1234 void DescribeTo(::std::ostream* os) const {
1235 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001236 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001237 }
1238
1239 void DescribeNegationTo(::std::ostream* os) const {
1240 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001241 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001242 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001243
shiqiane35fdd92008-12-10 05:08:54 +00001244 private:
1245 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001246
1247 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001248};
1249
1250// Implements the polymorphic StartsWith(substring) matcher, which
1251// can be used as a Matcher<T> as long as T can be converted to a
1252// string.
1253template <typename StringType>
1254class StartsWithMatcher {
1255 public:
shiqiane35fdd92008-12-10 05:08:54 +00001256 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1257 }
1258
jgm38513a82012-11-15 15:50:36 +00001259 // Accepts pointer types, particularly:
1260 // const char*
1261 // char*
1262 // const wchar_t*
1263 // wchar_t*
1264 template <typename CharType>
1265 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001266 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001267 }
1268
jgm38513a82012-11-15 15:50:36 +00001269 // Matches anything that can convert to StringType.
1270 //
1271 // This is a template, not just a plain function with const StringType&,
1272 // because StringPiece has some interfering non-explicit constructors.
1273 template <typename MatcheeStringType>
1274 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001275 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001276 const StringType& s2(s);
1277 return s2.length() >= prefix_.length() &&
1278 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001279 }
1280
1281 void DescribeTo(::std::ostream* os) const {
1282 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001283 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001284 }
1285
1286 void DescribeNegationTo(::std::ostream* os) const {
1287 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001288 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001289 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001290
shiqiane35fdd92008-12-10 05:08:54 +00001291 private:
1292 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001293
1294 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001295};
1296
1297// Implements the polymorphic EndsWith(substring) matcher, which
1298// can be used as a Matcher<T> as long as T can be converted to a
1299// string.
1300template <typename StringType>
1301class EndsWithMatcher {
1302 public:
shiqiane35fdd92008-12-10 05:08:54 +00001303 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1304
jgm38513a82012-11-15 15:50:36 +00001305 // Accepts pointer types, particularly:
1306 // const char*
1307 // char*
1308 // const wchar_t*
1309 // wchar_t*
1310 template <typename CharType>
1311 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001312 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001313 }
1314
jgm38513a82012-11-15 15:50:36 +00001315 // Matches anything that can convert to StringType.
1316 //
1317 // This is a template, not just a plain function with const StringType&,
1318 // because StringPiece has some interfering non-explicit constructors.
1319 template <typename MatcheeStringType>
1320 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001321 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001322 const StringType& s2(s);
1323 return s2.length() >= suffix_.length() &&
1324 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001325 }
1326
1327 void DescribeTo(::std::ostream* os) const {
1328 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001329 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001330 }
1331
1332 void DescribeNegationTo(::std::ostream* os) const {
1333 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001334 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001335 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001336
shiqiane35fdd92008-12-10 05:08:54 +00001337 private:
1338 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001339
1340 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001341};
1342
shiqiane35fdd92008-12-10 05:08:54 +00001343// Implements polymorphic matchers MatchesRegex(regex) and
1344// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1345// T can be converted to a string.
1346class MatchesRegexMatcher {
1347 public:
1348 MatchesRegexMatcher(const RE* regex, bool full_match)
1349 : regex_(regex), full_match_(full_match) {}
1350
jgm38513a82012-11-15 15:50:36 +00001351 // Accepts pointer types, particularly:
1352 // const char*
1353 // char*
1354 // const wchar_t*
1355 // wchar_t*
1356 template <typename CharType>
1357 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001358 return s != NULL && MatchAndExplain(std::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001359 }
1360
Nico Weber09fd5b32017-05-15 17:07:03 -04001361 // Matches anything that can convert to std::string.
jgm38513a82012-11-15 15:50:36 +00001362 //
Nico Weber09fd5b32017-05-15 17:07:03 -04001363 // This is a template, not just a plain function with const std::string&,
Gennadiy Civilb7c56832018-03-22 15:35:37 -04001364 // because absl::string_view has some interfering non-explicit constructors.
jgm38513a82012-11-15 15:50:36 +00001365 template <class MatcheeStringType>
1366 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001367 MatchResultListener* /* listener */) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001368 const std::string& s2(s);
jgm38513a82012-11-15 15:50:36 +00001369 return full_match_ ? RE::FullMatch(s2, *regex_) :
1370 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001371 }
1372
1373 void DescribeTo(::std::ostream* os) const {
1374 *os << (full_match_ ? "matches" : "contains")
1375 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001376 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001377 }
1378
1379 void DescribeNegationTo(::std::ostream* os) const {
1380 *os << "doesn't " << (full_match_ ? "match" : "contain")
1381 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001382 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001383 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001384
shiqiane35fdd92008-12-10 05:08:54 +00001385 private:
1386 const internal::linked_ptr<const RE> regex_;
1387 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001388
1389 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001390};
1391
shiqiane35fdd92008-12-10 05:08:54 +00001392// Implements a matcher that compares the two fields of a 2-tuple
1393// using one of the ==, <=, <, etc, operators. The two fields being
1394// compared don't have to have the same type.
1395//
1396// The matcher defined here is polymorphic (for example, Eq() can be
1397// used to match a tuple<int, short>, a tuple<const long&, double>,
1398// etc). Therefore we use a template type conversion operator in the
1399// implementation.
kosak506340a2014-11-17 01:47:54 +00001400template <typename D, typename Op>
1401class PairMatchBase {
1402 public:
1403 template <typename T1, typename T2>
1404 operator Matcher< ::testing::tuple<T1, T2> >() const {
1405 return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >);
1406 }
1407 template <typename T1, typename T2>
1408 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
1409 return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>);
shiqiane35fdd92008-12-10 05:08:54 +00001410 }
1411
kosak506340a2014-11-17 01:47:54 +00001412 private:
1413 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
1414 return os << D::Desc();
1415 }
shiqiane35fdd92008-12-10 05:08:54 +00001416
kosak506340a2014-11-17 01:47:54 +00001417 template <typename Tuple>
1418 class Impl : public MatcherInterface<Tuple> {
1419 public:
1420 virtual bool MatchAndExplain(
1421 Tuple args,
1422 MatchResultListener* /* listener */) const {
1423 return Op()(::testing::get<0>(args), ::testing::get<1>(args));
1424 }
1425 virtual void DescribeTo(::std::ostream* os) const {
1426 *os << "are " << GetDesc;
1427 }
1428 virtual void DescribeNegationTo(::std::ostream* os) const {
1429 *os << "aren't " << GetDesc;
1430 }
1431 };
1432};
1433
1434class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
1435 public:
1436 static const char* Desc() { return "an equal pair"; }
1437};
1438class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
1439 public:
1440 static const char* Desc() { return "an unequal pair"; }
1441};
1442class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
1443 public:
1444 static const char* Desc() { return "a pair where the first < the second"; }
1445};
1446class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
1447 public:
1448 static const char* Desc() { return "a pair where the first > the second"; }
1449};
1450class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
1451 public:
1452 static const char* Desc() { return "a pair where the first <= the second"; }
1453};
1454class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
1455 public:
1456 static const char* Desc() { return "a pair where the first >= the second"; }
1457};
shiqiane35fdd92008-12-10 05:08:54 +00001458
zhanyong.wanc6a41232009-05-13 23:38:40 +00001459// Implements the Not(...) matcher for a particular argument type T.
1460// We do not nest it inside the NotMatcher class template, as that
1461// will prevent different instantiations of NotMatcher from sharing
1462// the same NotMatcherImpl<T> class.
1463template <typename T>
1464class NotMatcherImpl : public MatcherInterface<T> {
1465 public:
1466 explicit NotMatcherImpl(const Matcher<T>& matcher)
1467 : matcher_(matcher) {}
1468
zhanyong.wan82113312010-01-08 21:55:40 +00001469 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1470 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001471 }
1472
1473 virtual void DescribeTo(::std::ostream* os) const {
1474 matcher_.DescribeNegationTo(os);
1475 }
1476
1477 virtual void DescribeNegationTo(::std::ostream* os) const {
1478 matcher_.DescribeTo(os);
1479 }
1480
zhanyong.wanc6a41232009-05-13 23:38:40 +00001481 private:
1482 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001483
1484 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001485};
1486
shiqiane35fdd92008-12-10 05:08:54 +00001487// Implements the Not(m) matcher, which matches a value that doesn't
1488// match matcher m.
1489template <typename InnerMatcher>
1490class NotMatcher {
1491 public:
1492 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1493
1494 // This template type conversion operator allows Not(m) to be used
1495 // to match any type m can match.
1496 template <typename T>
1497 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001498 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001499 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001500
shiqiane35fdd92008-12-10 05:08:54 +00001501 private:
shiqiane35fdd92008-12-10 05:08:54 +00001502 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001503
1504 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001505};
1506
zhanyong.wanc6a41232009-05-13 23:38:40 +00001507// Implements the AllOf(m1, m2) matcher for a particular argument type
1508// T. We do not nest it inside the BothOfMatcher class template, as
1509// that will prevent different instantiations of BothOfMatcher from
1510// sharing the same BothOfMatcherImpl<T> class.
1511template <typename T>
1512class BothOfMatcherImpl : public MatcherInterface<T> {
1513 public:
1514 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1515 : matcher1_(matcher1), matcher2_(matcher2) {}
1516
zhanyong.wanc6a41232009-05-13 23:38:40 +00001517 virtual void DescribeTo(::std::ostream* os) const {
1518 *os << "(";
1519 matcher1_.DescribeTo(os);
1520 *os << ") and (";
1521 matcher2_.DescribeTo(os);
1522 *os << ")";
1523 }
1524
1525 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001526 *os << "(";
1527 matcher1_.DescribeNegationTo(os);
1528 *os << ") or (";
1529 matcher2_.DescribeNegationTo(os);
1530 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001531 }
1532
zhanyong.wan82113312010-01-08 21:55:40 +00001533 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1534 // If either matcher1_ or matcher2_ doesn't match x, we only need
1535 // to explain why one of them fails.
1536 StringMatchResultListener listener1;
1537 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1538 *listener << listener1.str();
1539 return false;
1540 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001541
zhanyong.wan82113312010-01-08 21:55:40 +00001542 StringMatchResultListener listener2;
1543 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1544 *listener << listener2.str();
1545 return false;
1546 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001547
zhanyong.wan82113312010-01-08 21:55:40 +00001548 // Otherwise we need to explain why *both* of them match.
Nico Weber09fd5b32017-05-15 17:07:03 -04001549 const std::string s1 = listener1.str();
1550 const std::string s2 = listener2.str();
zhanyong.wan82113312010-01-08 21:55:40 +00001551
1552 if (s1 == "") {
1553 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001554 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001555 *listener << s1;
1556 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001557 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001558 }
1559 }
zhanyong.wan82113312010-01-08 21:55:40 +00001560 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001561 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001562
zhanyong.wanc6a41232009-05-13 23:38:40 +00001563 private:
1564 const Matcher<T> matcher1_;
1565 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001566
1567 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001568};
1569
zhanyong.wan616180e2013-06-18 18:49:51 +00001570#if GTEST_LANG_CXX11
1571// MatcherList provides mechanisms for storing a variable number of matchers in
1572// a list structure (ListType) and creating a combining matcher from such a
1573// list.
Troy Holsapplec8510502018-02-07 22:06:00 -08001574// The template is defined recursively using the following template parameters:
zhanyong.wan616180e2013-06-18 18:49:51 +00001575// * kSize is the length of the MatcherList.
1576// * Head is the type of the first matcher of the list.
1577// * Tail denotes the types of the remaining matchers of the list.
1578template <int kSize, typename Head, typename... Tail>
1579struct MatcherList {
1580 typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
zhanyong.wan29897032013-06-20 18:59:15 +00001581 typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001582
1583 // BuildList stores variadic type values in a nested pair structure.
1584 // Example:
1585 // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
1586 // the corresponding result of type pair<int, pair<string, float>>.
1587 static ListType BuildList(const Head& matcher, const Tail&... tail) {
1588 return ListType(matcher, MatcherListTail::BuildList(tail...));
1589 }
1590
1591 // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
1592 // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
1593 // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
1594 // constructor taking two Matcher<T>s as input.
1595 template <typename T, template <typename /* T */> class CombiningMatcher>
1596 static Matcher<T> CreateMatcher(const ListType& matchers) {
1597 return Matcher<T>(new CombiningMatcher<T>(
1598 SafeMatcherCast<T>(matchers.first),
1599 MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
1600 matchers.second)));
1601 }
1602};
1603
1604// The following defines the base case for the recursive definition of
1605// MatcherList.
1606template <typename Matcher1, typename Matcher2>
1607struct MatcherList<2, Matcher1, Matcher2> {
zhanyong.wan29897032013-06-20 18:59:15 +00001608 typedef ::std::pair<Matcher1, Matcher2> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001609
1610 static ListType BuildList(const Matcher1& matcher1,
1611 const Matcher2& matcher2) {
zhanyong.wan29897032013-06-20 18:59:15 +00001612 return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
zhanyong.wan616180e2013-06-18 18:49:51 +00001613 }
1614
1615 template <typename T, template <typename /* T */> class CombiningMatcher>
1616 static Matcher<T> CreateMatcher(const ListType& matchers) {
1617 return Matcher<T>(new CombiningMatcher<T>(
1618 SafeMatcherCast<T>(matchers.first),
1619 SafeMatcherCast<T>(matchers.second)));
1620 }
1621};
1622
1623// VariadicMatcher is used for the variadic implementation of
1624// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1625// CombiningMatcher<T> is used to recursively combine the provided matchers
1626// (of type Args...).
1627template <template <typename T> class CombiningMatcher, typename... Args>
1628class VariadicMatcher {
1629 public:
1630 VariadicMatcher(const Args&... matchers) // NOLINT
1631 : matchers_(MatcherListType::BuildList(matchers...)) {}
1632
1633 // This template type conversion operator allows an
1634 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1635 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1636 template <typename T>
1637 operator Matcher<T>() const {
1638 return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
1639 matchers_);
1640 }
1641
1642 private:
1643 typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
1644
1645 const typename MatcherListType::ListType matchers_;
1646
1647 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1648};
1649
1650template <typename... Args>
1651using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
1652
1653#endif // GTEST_LANG_CXX11
1654
shiqiane35fdd92008-12-10 05:08:54 +00001655// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1656// matches a value that matches all of the matchers m_1, ..., and m_n.
1657template <typename Matcher1, typename Matcher2>
1658class BothOfMatcher {
1659 public:
1660 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1661 : matcher1_(matcher1), matcher2_(matcher2) {}
1662
1663 // This template type conversion operator allows a
1664 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1665 // both Matcher1 and Matcher2 can match.
1666 template <typename T>
1667 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001668 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1669 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001670 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001671
shiqiane35fdd92008-12-10 05:08:54 +00001672 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001673 Matcher1 matcher1_;
1674 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001675
1676 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001677};
shiqiane35fdd92008-12-10 05:08:54 +00001678
zhanyong.wanc6a41232009-05-13 23:38:40 +00001679// Implements the AnyOf(m1, m2) matcher for a particular argument type
1680// T. We do not nest it inside the AnyOfMatcher class template, as
1681// that will prevent different instantiations of AnyOfMatcher from
1682// sharing the same EitherOfMatcherImpl<T> class.
1683template <typename T>
1684class EitherOfMatcherImpl : public MatcherInterface<T> {
1685 public:
1686 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1687 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001688
zhanyong.wanc6a41232009-05-13 23:38:40 +00001689 virtual void DescribeTo(::std::ostream* os) const {
1690 *os << "(";
1691 matcher1_.DescribeTo(os);
1692 *os << ") or (";
1693 matcher2_.DescribeTo(os);
1694 *os << ")";
1695 }
shiqiane35fdd92008-12-10 05:08:54 +00001696
zhanyong.wanc6a41232009-05-13 23:38:40 +00001697 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001698 *os << "(";
1699 matcher1_.DescribeNegationTo(os);
1700 *os << ") and (";
1701 matcher2_.DescribeNegationTo(os);
1702 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001703 }
shiqiane35fdd92008-12-10 05:08:54 +00001704
zhanyong.wan82113312010-01-08 21:55:40 +00001705 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1706 // If either matcher1_ or matcher2_ matches x, we just need to
1707 // explain why *one* of them matches.
1708 StringMatchResultListener listener1;
1709 if (matcher1_.MatchAndExplain(x, &listener1)) {
1710 *listener << listener1.str();
1711 return true;
1712 }
1713
1714 StringMatchResultListener listener2;
1715 if (matcher2_.MatchAndExplain(x, &listener2)) {
1716 *listener << listener2.str();
1717 return true;
1718 }
1719
1720 // Otherwise we need to explain why *both* of them fail.
Nico Weber09fd5b32017-05-15 17:07:03 -04001721 const std::string s1 = listener1.str();
1722 const std::string s2 = listener2.str();
zhanyong.wan82113312010-01-08 21:55:40 +00001723
1724 if (s1 == "") {
1725 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001726 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001727 *listener << s1;
1728 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001729 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001730 }
1731 }
zhanyong.wan82113312010-01-08 21:55:40 +00001732 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001733 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001734
zhanyong.wanc6a41232009-05-13 23:38:40 +00001735 private:
1736 const Matcher<T> matcher1_;
1737 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001738
1739 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001740};
1741
zhanyong.wan616180e2013-06-18 18:49:51 +00001742#if GTEST_LANG_CXX11
1743// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1744template <typename... Args>
1745using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
1746
1747#endif // GTEST_LANG_CXX11
1748
shiqiane35fdd92008-12-10 05:08:54 +00001749// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1750// matches a value that matches at least one of the matchers m_1, ...,
1751// and m_n.
1752template <typename Matcher1, typename Matcher2>
1753class EitherOfMatcher {
1754 public:
1755 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1756 : matcher1_(matcher1), matcher2_(matcher2) {}
1757
1758 // This template type conversion operator allows a
1759 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1760 // both Matcher1 and Matcher2 can match.
1761 template <typename T>
1762 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001763 return Matcher<T>(new EitherOfMatcherImpl<T>(
1764 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001765 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001766
shiqiane35fdd92008-12-10 05:08:54 +00001767 private:
shiqiane35fdd92008-12-10 05:08:54 +00001768 Matcher1 matcher1_;
1769 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001770
1771 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001772};
1773
1774// Used for implementing Truly(pred), which turns a predicate into a
1775// matcher.
1776template <typename Predicate>
1777class TrulyMatcher {
1778 public:
1779 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1780
1781 // This method template allows Truly(pred) to be used as a matcher
1782 // for type T where T is the argument type of predicate 'pred'. The
1783 // argument is passed by reference as the predicate may be
1784 // interested in the address of the argument.
1785 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001786 bool MatchAndExplain(T& x, // NOLINT
1787 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001788 // Without the if-statement, MSVC sometimes warns about converting
1789 // a value to bool (warning 4800).
1790 //
1791 // We cannot write 'return !!predicate_(x);' as that doesn't work
1792 // when predicate_(x) returns a class convertible to bool but
1793 // having no operator!().
1794 if (predicate_(x))
1795 return true;
1796 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001797 }
1798
1799 void DescribeTo(::std::ostream* os) const {
1800 *os << "satisfies the given predicate";
1801 }
1802
1803 void DescribeNegationTo(::std::ostream* os) const {
1804 *os << "doesn't satisfy the given predicate";
1805 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001806
shiqiane35fdd92008-12-10 05:08:54 +00001807 private:
1808 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001809
1810 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001811};
1812
1813// Used for implementing Matches(matcher), which turns a matcher into
1814// a predicate.
1815template <typename M>
1816class MatcherAsPredicate {
1817 public:
1818 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1819
1820 // This template operator() allows Matches(m) to be used as a
1821 // predicate on type T where m is a matcher on type T.
1822 //
1823 // The argument x is passed by reference instead of by value, as
1824 // some matcher may be interested in its address (e.g. as in
1825 // Matches(Ref(n))(x)).
1826 template <typename T>
1827 bool operator()(const T& x) const {
1828 // We let matcher_ commit to a particular type here instead of
1829 // when the MatcherAsPredicate object was constructed. This
1830 // allows us to write Matches(m) where m is a polymorphic matcher
1831 // (e.g. Eq(5)).
1832 //
1833 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1834 // compile when matcher_ has type Matcher<const T&>; if we write
1835 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1836 // when matcher_ has type Matcher<T>; if we just write
1837 // matcher_.Matches(x), it won't compile when matcher_ is
1838 // polymorphic, e.g. Eq(5).
1839 //
1840 // MatcherCast<const T&>() is necessary for making the code work
1841 // in all of the above situations.
1842 return MatcherCast<const T&>(matcher_).Matches(x);
1843 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001844
shiqiane35fdd92008-12-10 05:08:54 +00001845 private:
1846 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001847
1848 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001849};
1850
1851// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1852// argument M must be a type that can be converted to a matcher.
1853template <typename M>
1854class PredicateFormatterFromMatcher {
1855 public:
kosak9b1a9442015-04-28 23:06:58 +00001856 explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {}
shiqiane35fdd92008-12-10 05:08:54 +00001857
1858 // This template () operator allows a PredicateFormatterFromMatcher
1859 // object to act as a predicate-formatter suitable for using with
1860 // Google Test's EXPECT_PRED_FORMAT1() macro.
1861 template <typename T>
1862 AssertionResult operator()(const char* value_text, const T& x) const {
1863 // We convert matcher_ to a Matcher<const T&> *now* instead of
1864 // when the PredicateFormatterFromMatcher object was constructed,
1865 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1866 // know which type to instantiate it to until we actually see the
1867 // type of x here.
1868 //
zhanyong.wanf4274522013-04-24 02:49:43 +00001869 // We write SafeMatcherCast<const T&>(matcher_) instead of
shiqiane35fdd92008-12-10 05:08:54 +00001870 // Matcher<const T&>(matcher_), as the latter won't compile when
1871 // matcher_ has type Matcher<T> (e.g. An<int>()).
zhanyong.wanf4274522013-04-24 02:49:43 +00001872 // We don't write MatcherCast<const T&> either, as that allows
1873 // potentially unsafe downcasting of the matcher argument.
1874 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001875 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001876 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001877 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001878
1879 ::std::stringstream ss;
1880 ss << "Value of: " << value_text << "\n"
1881 << "Expected: ";
1882 matcher.DescribeTo(&ss);
1883 ss << "\n Actual: " << listener.str();
1884 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001885 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001886
shiqiane35fdd92008-12-10 05:08:54 +00001887 private:
1888 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001889
1890 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001891};
1892
1893// A helper function for converting a matcher to a predicate-formatter
1894// without the user needing to explicitly write the type. This is
1895// used for implementing ASSERT_THAT() and EXPECT_THAT().
kosak9b1a9442015-04-28 23:06:58 +00001896// Implementation detail: 'matcher' is received by-value to force decaying.
shiqiane35fdd92008-12-10 05:08:54 +00001897template <typename M>
1898inline PredicateFormatterFromMatcher<M>
kosak9b1a9442015-04-28 23:06:58 +00001899MakePredicateFormatterFromMatcher(M matcher) {
1900 return PredicateFormatterFromMatcher<M>(internal::move(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00001901}
1902
zhanyong.wan616180e2013-06-18 18:49:51 +00001903// Implements the polymorphic floating point equality matcher, which matches
1904// two float values using ULP-based approximation or, optionally, a
1905// user-specified epsilon. The template is meant to be instantiated with
1906// FloatType being either float or double.
shiqiane35fdd92008-12-10 05:08:54 +00001907template <typename FloatType>
1908class FloatingEqMatcher {
1909 public:
1910 // Constructor for FloatingEqMatcher.
kosak6b817802015-01-08 02:38:14 +00001911 // The matcher's input will be compared with expected. The matcher treats two
shiqiane35fdd92008-12-10 05:08:54 +00001912 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
zhanyong.wan616180e2013-06-18 18:49:51 +00001913 // equality comparisons between NANs will always return false. We specify a
1914 // negative max_abs_error_ term to indicate that ULP-based approximation will
1915 // be used for comparison.
kosak6b817802015-01-08 02:38:14 +00001916 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
1917 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001918 }
1919
1920 // Constructor that supports a user-specified max_abs_error that will be used
1921 // for comparison instead of ULP-based approximation. The max absolute
1922 // should be non-negative.
kosak6b817802015-01-08 02:38:14 +00001923 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
1924 FloatType max_abs_error)
1925 : expected_(expected),
1926 nan_eq_nan_(nan_eq_nan),
1927 max_abs_error_(max_abs_error) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001928 GTEST_CHECK_(max_abs_error >= 0)
1929 << ", where max_abs_error is" << max_abs_error;
1930 }
shiqiane35fdd92008-12-10 05:08:54 +00001931
1932 // Implements floating point equality matcher as a Matcher<T>.
1933 template <typename T>
1934 class Impl : public MatcherInterface<T> {
1935 public:
kosak6b817802015-01-08 02:38:14 +00001936 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
1937 : expected_(expected),
1938 nan_eq_nan_(nan_eq_nan),
1939 max_abs_error_(max_abs_error) {}
shiqiane35fdd92008-12-10 05:08:54 +00001940
zhanyong.wan82113312010-01-08 21:55:40 +00001941 virtual bool MatchAndExplain(T value,
kosak6b817802015-01-08 02:38:14 +00001942 MatchResultListener* listener) const {
1943 const FloatingPoint<FloatType> actual(value), expected(expected_);
shiqiane35fdd92008-12-10 05:08:54 +00001944
1945 // Compares NaNs first, if nan_eq_nan_ is true.
kosak6b817802015-01-08 02:38:14 +00001946 if (actual.is_nan() || expected.is_nan()) {
1947 if (actual.is_nan() && expected.is_nan()) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001948 return nan_eq_nan_;
1949 }
1950 // One is nan; the other is not nan.
1951 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001952 }
zhanyong.wan616180e2013-06-18 18:49:51 +00001953 if (HasMaxAbsError()) {
1954 // We perform an equality check so that inf will match inf, regardless
kosak6b817802015-01-08 02:38:14 +00001955 // of error bounds. If the result of value - expected_ would result in
zhanyong.wan616180e2013-06-18 18:49:51 +00001956 // overflow or if either value is inf, the default result is infinity,
1957 // which should only match if max_abs_error_ is also infinity.
kosak6b817802015-01-08 02:38:14 +00001958 if (value == expected_) {
1959 return true;
1960 }
1961
1962 const FloatType diff = value - expected_;
1963 if (fabs(diff) <= max_abs_error_) {
1964 return true;
1965 }
1966
1967 if (listener->IsInterested()) {
1968 *listener << "which is " << diff << " from " << expected_;
1969 }
1970 return false;
zhanyong.wan616180e2013-06-18 18:49:51 +00001971 } else {
kosak6b817802015-01-08 02:38:14 +00001972 return actual.AlmostEquals(expected);
zhanyong.wan616180e2013-06-18 18:49:51 +00001973 }
shiqiane35fdd92008-12-10 05:08:54 +00001974 }
1975
1976 virtual void DescribeTo(::std::ostream* os) const {
1977 // os->precision() returns the previously set precision, which we
1978 // store to restore the ostream to its original configuration
1979 // after outputting.
1980 const ::std::streamsize old_precision = os->precision(
1981 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00001982 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00001983 if (nan_eq_nan_) {
1984 *os << "is NaN";
1985 } else {
1986 *os << "never matches";
1987 }
1988 } else {
kosak6b817802015-01-08 02:38:14 +00001989 *os << "is approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001990 if (HasMaxAbsError()) {
1991 *os << " (absolute error <= " << max_abs_error_ << ")";
1992 }
shiqiane35fdd92008-12-10 05:08:54 +00001993 }
1994 os->precision(old_precision);
1995 }
1996
1997 virtual void DescribeNegationTo(::std::ostream* os) const {
1998 // As before, get original precision.
1999 const ::std::streamsize old_precision = os->precision(
2000 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00002001 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00002002 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002003 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00002004 } else {
2005 *os << "is anything";
2006 }
2007 } else {
kosak6b817802015-01-08 02:38:14 +00002008 *os << "isn't approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002009 if (HasMaxAbsError()) {
2010 *os << " (absolute error > " << max_abs_error_ << ")";
2011 }
shiqiane35fdd92008-12-10 05:08:54 +00002012 }
2013 // Restore original precision.
2014 os->precision(old_precision);
2015 }
2016
2017 private:
zhanyong.wan616180e2013-06-18 18:49:51 +00002018 bool HasMaxAbsError() const {
2019 return max_abs_error_ >= 0;
2020 }
2021
kosak6b817802015-01-08 02:38:14 +00002022 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002023 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002024 // max_abs_error will be used for value comparison when >= 0.
2025 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002026
2027 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002028 };
2029
kosak6b817802015-01-08 02:38:14 +00002030 // The following 3 type conversion operators allow FloatEq(expected) and
2031 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
shiqiane35fdd92008-12-10 05:08:54 +00002032 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
2033 // (While Google's C++ coding style doesn't allow arguments passed
2034 // by non-const reference, we may see them in code not conforming to
2035 // the style. Therefore Google Mock needs to support them.)
2036 operator Matcher<FloatType>() const {
kosak6b817802015-01-08 02:38:14 +00002037 return MakeMatcher(
2038 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002039 }
2040
2041 operator Matcher<const FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00002042 return MakeMatcher(
kosak6b817802015-01-08 02:38:14 +00002043 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002044 }
2045
2046 operator Matcher<FloatType&>() const {
kosak6b817802015-01-08 02:38:14 +00002047 return MakeMatcher(
2048 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002049 }
jgm79a367e2012-04-10 16:02:11 +00002050
shiqiane35fdd92008-12-10 05:08:54 +00002051 private:
kosak6b817802015-01-08 02:38:14 +00002052 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002053 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002054 // max_abs_error will be used for value comparison when >= 0.
2055 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002056
2057 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002058};
2059
2060// Implements the Pointee(m) matcher for matching a pointer whose
2061// pointee matches matcher m. The pointer can be either raw or smart.
2062template <typename InnerMatcher>
2063class PointeeMatcher {
2064 public:
2065 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
2066
2067 // This type conversion operator template allows Pointee(m) to be
2068 // used as a matcher for any pointer type whose pointee type is
2069 // compatible with the inner matcher, where type Pointer can be
2070 // either a raw pointer or a smart pointer.
2071 //
2072 // The reason we do this instead of relying on
2073 // MakePolymorphicMatcher() is that the latter is not flexible
2074 // enough for implementing the DescribeTo() method of Pointee().
2075 template <typename Pointer>
2076 operator Matcher<Pointer>() const {
2077 return MakeMatcher(new Impl<Pointer>(matcher_));
2078 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002079
shiqiane35fdd92008-12-10 05:08:54 +00002080 private:
2081 // The monomorphic implementation that works for a particular pointer type.
2082 template <typename Pointer>
2083 class Impl : public MatcherInterface<Pointer> {
2084 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00002085 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
2086 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00002087
2088 explicit Impl(const InnerMatcher& matcher)
2089 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
2090
shiqiane35fdd92008-12-10 05:08:54 +00002091 virtual void DescribeTo(::std::ostream* os) const {
2092 *os << "points to a value that ";
2093 matcher_.DescribeTo(os);
2094 }
2095
2096 virtual void DescribeNegationTo(::std::ostream* os) const {
2097 *os << "does not point to a value that ";
2098 matcher_.DescribeTo(os);
2099 }
2100
zhanyong.wan82113312010-01-08 21:55:40 +00002101 virtual bool MatchAndExplain(Pointer pointer,
2102 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00002103 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00002104 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002105
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002106 *listener << "which points to ";
2107 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002108 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002109
shiqiane35fdd92008-12-10 05:08:54 +00002110 private:
2111 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002112
2113 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002114 };
2115
2116 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002117
2118 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002119};
2120
billydonahue1f5fdea2014-05-19 17:54:51 +00002121// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2122// reference that matches inner_matcher when dynamic_cast<T> is applied.
2123// The result of dynamic_cast<To> is forwarded to the inner matcher.
2124// If To is a pointer and the cast fails, the inner matcher will receive NULL.
2125// If To is a reference and the cast fails, this matcher returns false
2126// immediately.
2127template <typename To>
2128class WhenDynamicCastToMatcherBase {
2129 public:
2130 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2131 : matcher_(matcher) {}
2132
2133 void DescribeTo(::std::ostream* os) const {
2134 GetCastTypeDescription(os);
2135 matcher_.DescribeTo(os);
2136 }
2137
2138 void DescribeNegationTo(::std::ostream* os) const {
2139 GetCastTypeDescription(os);
2140 matcher_.DescribeNegationTo(os);
2141 }
2142
2143 protected:
2144 const Matcher<To> matcher_;
2145
Nico Weber09fd5b32017-05-15 17:07:03 -04002146 static std::string GetToName() {
billydonahue1f5fdea2014-05-19 17:54:51 +00002147#if GTEST_HAS_RTTI
2148 return GetTypeName<To>();
2149#else // GTEST_HAS_RTTI
2150 return "the target type";
2151#endif // GTEST_HAS_RTTI
2152 }
2153
2154 private:
2155 static void GetCastTypeDescription(::std::ostream* os) {
2156 *os << "when dynamic_cast to " << GetToName() << ", ";
2157 }
2158
2159 GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2160};
2161
2162// Primary template.
2163// To is a pointer. Cast and forward the result.
2164template <typename To>
2165class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2166 public:
2167 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2168 : WhenDynamicCastToMatcherBase<To>(matcher) {}
2169
2170 template <typename From>
2171 bool MatchAndExplain(From from, MatchResultListener* listener) const {
2172 // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail?
2173 To to = dynamic_cast<To>(from);
2174 return MatchPrintAndExplain(to, this->matcher_, listener);
2175 }
2176};
2177
2178// Specialize for references.
2179// In this case we return false if the dynamic_cast fails.
2180template <typename To>
2181class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2182 public:
2183 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2184 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2185
2186 template <typename From>
2187 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2188 // We don't want an std::bad_cast here, so do the cast with pointers.
2189 To* to = dynamic_cast<To*>(&from);
2190 if (to == NULL) {
2191 *listener << "which cannot be dynamic_cast to " << this->GetToName();
2192 return false;
2193 }
2194 return MatchPrintAndExplain(*to, this->matcher_, listener);
2195 }
2196};
2197
shiqiane35fdd92008-12-10 05:08:54 +00002198// Implements the Field() matcher for matching a field (i.e. member
2199// variable) of an object.
2200template <typename Class, typename FieldType>
2201class FieldMatcher {
2202 public:
2203 FieldMatcher(FieldType Class::*field,
2204 const Matcher<const FieldType&>& matcher)
2205 : field_(field), matcher_(matcher) {}
2206
shiqiane35fdd92008-12-10 05:08:54 +00002207 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002208 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002209 matcher_.DescribeTo(os);
2210 }
2211
2212 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002213 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002214 matcher_.DescribeNegationTo(os);
2215 }
2216
zhanyong.wandb22c222010-01-28 21:52:29 +00002217 template <typename T>
2218 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2219 return MatchAndExplainImpl(
2220 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002221 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002222 value, listener);
2223 }
2224
2225 private:
2226 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002227 // Symbian's C++ compiler choose which overload to use. Its type is
2228 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002229 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2230 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002231 *listener << "whose given field is ";
2232 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002233 }
2234
zhanyong.wandb22c222010-01-28 21:52:29 +00002235 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2236 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002237 if (p == NULL)
2238 return false;
2239
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002240 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002241 // Since *p has a field, it must be a class/struct/union type and
2242 // thus cannot be a pointer. Therefore we pass false_type() as
2243 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002244 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002245 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002246
shiqiane35fdd92008-12-10 05:08:54 +00002247 const FieldType Class::*field_;
2248 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002249
2250 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002251};
2252
shiqiane35fdd92008-12-10 05:08:54 +00002253// Implements the Property() matcher for matching a property
2254// (i.e. return value of a getter method) of an object.
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002255//
2256// Property is a const-qualified member function of Class returning
2257// PropertyType.
2258template <typename Class, typename PropertyType, typename Property>
shiqiane35fdd92008-12-10 05:08:54 +00002259class PropertyMatcher {
2260 public:
2261 // The property may have a reference type, so 'const PropertyType&'
2262 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00002263 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00002264 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00002265 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00002266
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002267 PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)
shiqiane35fdd92008-12-10 05:08:54 +00002268 : property_(property), matcher_(matcher) {}
2269
shiqiane35fdd92008-12-10 05:08:54 +00002270 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002271 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002272 matcher_.DescribeTo(os);
2273 }
2274
2275 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002276 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002277 matcher_.DescribeNegationTo(os);
2278 }
2279
zhanyong.wandb22c222010-01-28 21:52:29 +00002280 template <typename T>
2281 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2282 return MatchAndExplainImpl(
2283 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002284 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002285 value, listener);
2286 }
2287
2288 private:
2289 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002290 // Symbian's C++ compiler choose which overload to use. Its type is
2291 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002292 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2293 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002294 *listener << "whose given property is ";
2295 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2296 // which takes a non-const reference as argument.
kosak02d64792015-02-14 02:22:21 +00002297#if defined(_PREFAST_ ) && _MSC_VER == 1800
2298 // Workaround bug in VC++ 2013's /analyze parser.
2299 // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move
2300 posix::Abort(); // To make sure it is never run.
2301 return false;
2302#else
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002303 RefToConstProperty result = (obj.*property_)();
2304 return MatchPrintAndExplain(result, matcher_, listener);
kosak02d64792015-02-14 02:22:21 +00002305#endif
shiqiane35fdd92008-12-10 05:08:54 +00002306 }
2307
zhanyong.wandb22c222010-01-28 21:52:29 +00002308 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2309 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002310 if (p == NULL)
2311 return false;
2312
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002313 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002314 // Since *p has a property method, it must be a class/struct/union
2315 // type and thus cannot be a pointer. Therefore we pass
2316 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002317 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002318 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002319
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002320 Property property_;
shiqiane35fdd92008-12-10 05:08:54 +00002321 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002322
2323 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002324};
2325
shiqiane35fdd92008-12-10 05:08:54 +00002326// Type traits specifying various features of different functors for ResultOf.
2327// The default template specifies features for functor objects.
2328// Functor classes have to typedef argument_type and result_type
2329// to be compatible with ResultOf.
2330template <typename Functor>
2331struct CallableTraits {
2332 typedef typename Functor::result_type ResultType;
2333 typedef Functor StorageType;
2334
zhanyong.wan32de5f52009-12-23 00:13:23 +00002335 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00002336 template <typename T>
2337 static ResultType Invoke(Functor f, T arg) { return f(arg); }
2338};
2339
2340// Specialization for function pointers.
2341template <typename ArgType, typename ResType>
2342struct CallableTraits<ResType(*)(ArgType)> {
2343 typedef ResType ResultType;
2344 typedef ResType(*StorageType)(ArgType);
2345
2346 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002347 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00002348 << "NULL function pointer is passed into ResultOf().";
2349 }
2350 template <typename T>
2351 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2352 return (*f)(arg);
2353 }
2354};
2355
2356// Implements the ResultOf() matcher for matching a return value of a
2357// unary function of an object.
2358template <typename Callable>
2359class ResultOfMatcher {
2360 public:
2361 typedef typename CallableTraits<Callable>::ResultType ResultType;
2362
2363 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
2364 : callable_(callable), matcher_(matcher) {
2365 CallableTraits<Callable>::CheckIsValid(callable_);
2366 }
2367
2368 template <typename T>
2369 operator Matcher<T>() const {
2370 return Matcher<T>(new Impl<T>(callable_, matcher_));
2371 }
2372
2373 private:
2374 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2375
2376 template <typename T>
2377 class Impl : public MatcherInterface<T> {
2378 public:
2379 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
2380 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00002381
2382 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002383 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002384 matcher_.DescribeTo(os);
2385 }
2386
2387 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002388 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002389 matcher_.DescribeNegationTo(os);
2390 }
2391
zhanyong.wan82113312010-01-08 21:55:40 +00002392 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002393 *listener << "which is mapped by the given callable to ";
2394 // Cannot pass the return value (for example, int) to
2395 // MatchPrintAndExplain, which takes a non-const reference as argument.
2396 ResultType result =
2397 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2398 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002399 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002400
shiqiane35fdd92008-12-10 05:08:54 +00002401 private:
2402 // Functors often define operator() as non-const method even though
Troy Holsapplec8510502018-02-07 22:06:00 -08002403 // they are actually stateless. But we need to use them even when
shiqiane35fdd92008-12-10 05:08:54 +00002404 // 'this' is a const pointer. It's the user's responsibility not to
2405 // use stateful callables with ResultOf(), which does't guarantee
2406 // how many times the callable will be invoked.
2407 mutable CallableStorageType callable_;
2408 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002409
2410 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002411 }; // class Impl
2412
2413 const CallableStorageType callable_;
2414 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002415
2416 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002417};
2418
zhanyong.wana31d9ce2013-03-01 01:50:17 +00002419// Implements a matcher that checks the size of an STL-style container.
2420template <typename SizeMatcher>
2421class SizeIsMatcher {
2422 public:
2423 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2424 : size_matcher_(size_matcher) {
2425 }
2426
2427 template <typename Container>
2428 operator Matcher<Container>() const {
2429 return MakeMatcher(new Impl<Container>(size_matcher_));
2430 }
2431
2432 template <typename Container>
2433 class Impl : public MatcherInterface<Container> {
2434 public:
2435 typedef internal::StlContainerView<
2436 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2437 typedef typename ContainerView::type::size_type SizeType;
2438 explicit Impl(const SizeMatcher& size_matcher)
2439 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2440
2441 virtual void DescribeTo(::std::ostream* os) const {
2442 *os << "size ";
2443 size_matcher_.DescribeTo(os);
2444 }
2445 virtual void DescribeNegationTo(::std::ostream* os) const {
2446 *os << "size ";
2447 size_matcher_.DescribeNegationTo(os);
2448 }
2449
2450 virtual bool MatchAndExplain(Container container,
2451 MatchResultListener* listener) const {
2452 SizeType size = container.size();
2453 StringMatchResultListener size_listener;
2454 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2455 *listener
2456 << "whose size " << size << (result ? " matches" : " doesn't match");
2457 PrintIfNotEmpty(size_listener.str(), listener->stream());
2458 return result;
2459 }
2460
2461 private:
2462 const Matcher<SizeType> size_matcher_;
2463 GTEST_DISALLOW_ASSIGN_(Impl);
2464 };
2465
2466 private:
2467 const SizeMatcher size_matcher_;
2468 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2469};
2470
kosakb6a34882014-03-12 21:06:46 +00002471// Implements a matcher that checks the begin()..end() distance of an STL-style
2472// container.
2473template <typename DistanceMatcher>
2474class BeginEndDistanceIsMatcher {
2475 public:
2476 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2477 : distance_matcher_(distance_matcher) {}
2478
2479 template <typename Container>
2480 operator Matcher<Container>() const {
2481 return MakeMatcher(new Impl<Container>(distance_matcher_));
2482 }
2483
2484 template <typename Container>
2485 class Impl : public MatcherInterface<Container> {
2486 public:
2487 typedef internal::StlContainerView<
2488 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2489 typedef typename std::iterator_traits<
2490 typename ContainerView::type::const_iterator>::difference_type
2491 DistanceType;
2492 explicit Impl(const DistanceMatcher& distance_matcher)
2493 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2494
2495 virtual void DescribeTo(::std::ostream* os) const {
2496 *os << "distance between begin() and end() ";
2497 distance_matcher_.DescribeTo(os);
2498 }
2499 virtual void DescribeNegationTo(::std::ostream* os) const {
2500 *os << "distance between begin() and end() ";
2501 distance_matcher_.DescribeNegationTo(os);
2502 }
2503
2504 virtual bool MatchAndExplain(Container container,
2505 MatchResultListener* listener) const {
kosak5b9cbbb2014-11-17 00:28:55 +00002506#if GTEST_HAS_STD_BEGIN_AND_END_
kosakb6a34882014-03-12 21:06:46 +00002507 using std::begin;
2508 using std::end;
2509 DistanceType distance = std::distance(begin(container), end(container));
2510#else
2511 DistanceType distance = std::distance(container.begin(), container.end());
2512#endif
2513 StringMatchResultListener distance_listener;
2514 const bool result =
2515 distance_matcher_.MatchAndExplain(distance, &distance_listener);
2516 *listener << "whose distance between begin() and end() " << distance
2517 << (result ? " matches" : " doesn't match");
2518 PrintIfNotEmpty(distance_listener.str(), listener->stream());
2519 return result;
2520 }
2521
2522 private:
2523 const Matcher<DistanceType> distance_matcher_;
2524 GTEST_DISALLOW_ASSIGN_(Impl);
2525 };
2526
2527 private:
2528 const DistanceMatcher distance_matcher_;
2529 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2530};
2531
zhanyong.wan6a896b52009-01-16 01:13:50 +00002532// Implements an equality matcher for any STL-style container whose elements
2533// support ==. This matcher is like Eq(), but its failure explanations provide
2534// more detailed information that is useful when the container is used as a set.
2535// The failure message reports elements that are in one of the operands but not
2536// the other. The failure messages do not report duplicate or out-of-order
2537// elements in the containers (which don't properly matter to sets, but can
2538// occur if the containers are vectors or lists, for example).
2539//
2540// Uses the container's const_iterator, value_type, operator ==,
2541// begin(), and end().
2542template <typename Container>
2543class ContainerEqMatcher {
2544 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002545 typedef internal::StlContainerView<Container> View;
2546 typedef typename View::type StlContainer;
2547 typedef typename View::const_reference StlContainerReference;
2548
kosak6b817802015-01-08 02:38:14 +00002549 // We make a copy of expected in case the elements in it are modified
zhanyong.wanb8243162009-06-04 05:48:20 +00002550 // after this matcher is created.
kosak6b817802015-01-08 02:38:14 +00002551 explicit ContainerEqMatcher(const Container& expected)
2552 : expected_(View::Copy(expected)) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002553 // Makes sure the user doesn't instantiate this class template
2554 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002555 (void)testing::StaticAssertTypeEq<Container,
2556 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002557 }
2558
zhanyong.wan6a896b52009-01-16 01:13:50 +00002559 void DescribeTo(::std::ostream* os) const {
2560 *os << "equals ";
kosak6b817802015-01-08 02:38:14 +00002561 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002562 }
2563 void DescribeNegationTo(::std::ostream* os) const {
2564 *os << "does not equal ";
kosak6b817802015-01-08 02:38:14 +00002565 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002566 }
2567
zhanyong.wanb8243162009-06-04 05:48:20 +00002568 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002569 bool MatchAndExplain(const LhsContainer& lhs,
2570 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002571 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002572 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002573 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002574 LhsView;
2575 typedef typename LhsView::type LhsStlContainer;
2576 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
kosak6b817802015-01-08 02:38:14 +00002577 if (lhs_stl_container == expected_)
zhanyong.wane122e452010-01-12 09:03:52 +00002578 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002579
zhanyong.wane122e452010-01-12 09:03:52 +00002580 ::std::ostream* const os = listener->stream();
2581 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002582 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002583 bool printed_header = false;
2584 for (typename LhsStlContainer::const_iterator it =
2585 lhs_stl_container.begin();
2586 it != lhs_stl_container.end(); ++it) {
kosak6b817802015-01-08 02:38:14 +00002587 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
2588 expected_.end()) {
zhanyong.wane122e452010-01-12 09:03:52 +00002589 if (printed_header) {
2590 *os << ", ";
2591 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002592 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002593 printed_header = true;
2594 }
vladloseve2e8ba42010-05-13 18:16:03 +00002595 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002596 }
zhanyong.wane122e452010-01-12 09:03:52 +00002597 }
2598
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002599 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002600 bool printed_header2 = false;
kosak6b817802015-01-08 02:38:14 +00002601 for (typename StlContainer::const_iterator it = expected_.begin();
2602 it != expected_.end(); ++it) {
zhanyong.wane122e452010-01-12 09:03:52 +00002603 if (internal::ArrayAwareFind(
2604 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2605 lhs_stl_container.end()) {
2606 if (printed_header2) {
2607 *os << ", ";
2608 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002609 *os << (printed_header ? ",\nand" : "which")
2610 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002611 printed_header2 = true;
2612 }
vladloseve2e8ba42010-05-13 18:16:03 +00002613 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002614 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002615 }
2616 }
2617
zhanyong.wane122e452010-01-12 09:03:52 +00002618 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002619 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002620
zhanyong.wan6a896b52009-01-16 01:13:50 +00002621 private:
kosak6b817802015-01-08 02:38:14 +00002622 const StlContainer expected_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002623
2624 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002625};
2626
zhanyong.wan898725c2011-09-16 16:45:39 +00002627// A comparator functor that uses the < operator to compare two values.
2628struct LessComparator {
2629 template <typename T, typename U>
2630 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2631};
2632
2633// Implements WhenSortedBy(comparator, container_matcher).
2634template <typename Comparator, typename ContainerMatcher>
2635class WhenSortedByMatcher {
2636 public:
2637 WhenSortedByMatcher(const Comparator& comparator,
2638 const ContainerMatcher& matcher)
2639 : comparator_(comparator), matcher_(matcher) {}
2640
2641 template <typename LhsContainer>
2642 operator Matcher<LhsContainer>() const {
2643 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2644 }
2645
2646 template <typename LhsContainer>
2647 class Impl : public MatcherInterface<LhsContainer> {
2648 public:
2649 typedef internal::StlContainerView<
2650 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2651 typedef typename LhsView::type LhsStlContainer;
2652 typedef typename LhsView::const_reference LhsStlContainerReference;
zhanyong.wana9a59e02013-03-27 16:14:55 +00002653 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2654 // so that we can match associative containers.
2655 typedef typename RemoveConstFromKey<
2656 typename LhsStlContainer::value_type>::type LhsValue;
zhanyong.wan898725c2011-09-16 16:45:39 +00002657
2658 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2659 : comparator_(comparator), matcher_(matcher) {}
2660
2661 virtual void DescribeTo(::std::ostream* os) const {
2662 *os << "(when sorted) ";
2663 matcher_.DescribeTo(os);
2664 }
2665
2666 virtual void DescribeNegationTo(::std::ostream* os) const {
2667 *os << "(when sorted) ";
2668 matcher_.DescribeNegationTo(os);
2669 }
2670
2671 virtual bool MatchAndExplain(LhsContainer lhs,
2672 MatchResultListener* listener) const {
2673 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wanfb25d532013-07-28 08:24:00 +00002674 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2675 lhs_stl_container.end());
2676 ::std::sort(
2677 sorted_container.begin(), sorted_container.end(), comparator_);
zhanyong.wan898725c2011-09-16 16:45:39 +00002678
2679 if (!listener->IsInterested()) {
2680 // If the listener is not interested, we do not need to
2681 // construct the inner explanation.
2682 return matcher_.Matches(sorted_container);
2683 }
2684
2685 *listener << "which is ";
2686 UniversalPrint(sorted_container, listener->stream());
2687 *listener << " when sorted";
2688
2689 StringMatchResultListener inner_listener;
2690 const bool match = matcher_.MatchAndExplain(sorted_container,
2691 &inner_listener);
2692 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2693 return match;
2694 }
2695
2696 private:
2697 const Comparator comparator_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00002698 const Matcher<const ::std::vector<LhsValue>&> matcher_;
zhanyong.wan898725c2011-09-16 16:45:39 +00002699
2700 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2701 };
2702
2703 private:
2704 const Comparator comparator_;
2705 const ContainerMatcher matcher_;
2706
2707 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2708};
2709
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002710// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2711// must be able to be safely cast to Matcher<tuple<const T1&, const
2712// T2&> >, where T1 and T2 are the types of elements in the LHS
2713// container and the RHS container respectively.
2714template <typename TupleMatcher, typename RhsContainer>
2715class PointwiseMatcher {
2716 public:
2717 typedef internal::StlContainerView<RhsContainer> RhsView;
2718 typedef typename RhsView::type RhsStlContainer;
2719 typedef typename RhsStlContainer::value_type RhsValue;
2720
2721 // Like ContainerEq, we make a copy of rhs in case the elements in
2722 // it are modified after this matcher is created.
2723 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2724 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2725 // Makes sure the user doesn't instantiate this class template
2726 // with a const or reference type.
2727 (void)testing::StaticAssertTypeEq<RhsContainer,
2728 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2729 }
2730
2731 template <typename LhsContainer>
2732 operator Matcher<LhsContainer>() const {
2733 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2734 }
2735
2736 template <typename LhsContainer>
2737 class Impl : public MatcherInterface<LhsContainer> {
2738 public:
2739 typedef internal::StlContainerView<
2740 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2741 typedef typename LhsView::type LhsStlContainer;
2742 typedef typename LhsView::const_reference LhsStlContainerReference;
2743 typedef typename LhsStlContainer::value_type LhsValue;
2744 // We pass the LHS value and the RHS value to the inner matcher by
2745 // reference, as they may be expensive to copy. We must use tuple
2746 // instead of pair here, as a pair cannot hold references (C++ 98,
2747 // 20.2.2 [lib.pairs]).
kosakbd018832014-04-02 20:30:00 +00002748 typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002749
2750 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2751 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2752 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2753 rhs_(rhs) {}
2754
2755 virtual void DescribeTo(::std::ostream* os) const {
2756 *os << "contains " << rhs_.size()
2757 << " values, where each value and its corresponding value in ";
2758 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2759 *os << " ";
2760 mono_tuple_matcher_.DescribeTo(os);
2761 }
2762 virtual void DescribeNegationTo(::std::ostream* os) const {
2763 *os << "doesn't contain exactly " << rhs_.size()
2764 << " values, or contains a value x at some index i"
2765 << " where x and the i-th value of ";
2766 UniversalPrint(rhs_, os);
2767 *os << " ";
2768 mono_tuple_matcher_.DescribeNegationTo(os);
2769 }
2770
2771 virtual bool MatchAndExplain(LhsContainer lhs,
2772 MatchResultListener* listener) const {
2773 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2774 const size_t actual_size = lhs_stl_container.size();
2775 if (actual_size != rhs_.size()) {
2776 *listener << "which contains " << actual_size << " values";
2777 return false;
2778 }
2779
2780 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2781 typename RhsStlContainer::const_iterator right = rhs_.begin();
2782 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2783 const InnerMatcherArg value_pair(*left, *right);
2784
2785 if (listener->IsInterested()) {
2786 StringMatchResultListener inner_listener;
2787 if (!mono_tuple_matcher_.MatchAndExplain(
2788 value_pair, &inner_listener)) {
2789 *listener << "where the value pair (";
2790 UniversalPrint(*left, listener->stream());
2791 *listener << ", ";
2792 UniversalPrint(*right, listener->stream());
2793 *listener << ") at index #" << i << " don't match";
2794 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2795 return false;
2796 }
2797 } else {
2798 if (!mono_tuple_matcher_.Matches(value_pair))
2799 return false;
2800 }
2801 }
2802
2803 return true;
2804 }
2805
2806 private:
2807 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2808 const RhsStlContainer rhs_;
2809
2810 GTEST_DISALLOW_ASSIGN_(Impl);
2811 };
2812
2813 private:
2814 const TupleMatcher tuple_matcher_;
2815 const RhsStlContainer rhs_;
2816
2817 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2818};
2819
zhanyong.wan33605ba2010-04-22 23:37:47 +00002820// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002821template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002822class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002823 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002824 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002825 typedef StlContainerView<RawContainer> View;
2826 typedef typename View::type StlContainer;
2827 typedef typename View::const_reference StlContainerReference;
2828 typedef typename StlContainer::value_type Element;
2829
2830 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002831 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002832 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002833 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002834
zhanyong.wan33605ba2010-04-22 23:37:47 +00002835 // Checks whether:
2836 // * All elements in the container match, if all_elements_should_match.
2837 // * Any element in the container matches, if !all_elements_should_match.
2838 bool MatchAndExplainImpl(bool all_elements_should_match,
2839 Container container,
2840 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002841 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002842 size_t i = 0;
2843 for (typename StlContainer::const_iterator it = stl_container.begin();
2844 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002845 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002846 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2847
2848 if (matches != all_elements_should_match) {
2849 *listener << "whose element #" << i
2850 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002851 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002852 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002853 }
2854 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002855 return all_elements_should_match;
2856 }
2857
2858 protected:
2859 const Matcher<const Element&> inner_matcher_;
2860
2861 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2862};
2863
2864// Implements Contains(element_matcher) for the given argument type Container.
2865// Symmetric to EachMatcherImpl.
2866template <typename Container>
2867class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2868 public:
2869 template <typename InnerMatcher>
2870 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2871 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2872
2873 // Describes what this matcher does.
2874 virtual void DescribeTo(::std::ostream* os) const {
2875 *os << "contains at least one element that ";
2876 this->inner_matcher_.DescribeTo(os);
2877 }
2878
2879 virtual void DescribeNegationTo(::std::ostream* os) const {
2880 *os << "doesn't contain any element that ";
2881 this->inner_matcher_.DescribeTo(os);
2882 }
2883
2884 virtual bool MatchAndExplain(Container container,
2885 MatchResultListener* listener) const {
2886 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002887 }
2888
2889 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002890 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002891};
2892
zhanyong.wan33605ba2010-04-22 23:37:47 +00002893// Implements Each(element_matcher) for the given argument type Container.
2894// Symmetric to ContainsMatcherImpl.
2895template <typename Container>
2896class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2897 public:
2898 template <typename InnerMatcher>
2899 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2900 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2901
2902 // Describes what this matcher does.
2903 virtual void DescribeTo(::std::ostream* os) const {
2904 *os << "only contains elements that ";
2905 this->inner_matcher_.DescribeTo(os);
2906 }
2907
2908 virtual void DescribeNegationTo(::std::ostream* os) const {
2909 *os << "contains some element that ";
2910 this->inner_matcher_.DescribeNegationTo(os);
2911 }
2912
2913 virtual bool MatchAndExplain(Container container,
2914 MatchResultListener* listener) const {
2915 return this->MatchAndExplainImpl(true, container, listener);
2916 }
2917
2918 private:
2919 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2920};
2921
zhanyong.wanb8243162009-06-04 05:48:20 +00002922// Implements polymorphic Contains(element_matcher).
2923template <typename M>
2924class ContainsMatcher {
2925 public:
2926 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2927
2928 template <typename Container>
2929 operator Matcher<Container>() const {
2930 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2931 }
2932
2933 private:
2934 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002935
2936 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002937};
2938
zhanyong.wan33605ba2010-04-22 23:37:47 +00002939// Implements polymorphic Each(element_matcher).
2940template <typename M>
2941class EachMatcher {
2942 public:
2943 explicit EachMatcher(M m) : inner_matcher_(m) {}
2944
2945 template <typename Container>
2946 operator Matcher<Container>() const {
2947 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2948 }
2949
2950 private:
2951 const M inner_matcher_;
2952
2953 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2954};
2955
zhanyong.wanb5937da2009-07-16 20:26:41 +00002956// Implements Key(inner_matcher) for the given argument pair type.
2957// Key(inner_matcher) matches an std::pair whose 'first' field matches
2958// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2959// std::map that contains at least one element whose key is >= 5.
2960template <typename PairType>
2961class KeyMatcherImpl : public MatcherInterface<PairType> {
2962 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002963 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002964 typedef typename RawPairType::first_type KeyType;
2965
2966 template <typename InnerMatcher>
2967 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2968 : inner_matcher_(
2969 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2970 }
2971
2972 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002973 virtual bool MatchAndExplain(PairType key_value,
2974 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002975 StringMatchResultListener inner_listener;
2976 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2977 &inner_listener);
Nico Weber09fd5b32017-05-15 17:07:03 -04002978 const std::string explanation = inner_listener.str();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002979 if (explanation != "") {
2980 *listener << "whose first field is a value " << explanation;
2981 }
2982 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002983 }
2984
2985 // Describes what this matcher does.
2986 virtual void DescribeTo(::std::ostream* os) const {
2987 *os << "has a key that ";
2988 inner_matcher_.DescribeTo(os);
2989 }
2990
2991 // Describes what the negation of this matcher does.
2992 virtual void DescribeNegationTo(::std::ostream* os) const {
2993 *os << "doesn't have a key that ";
2994 inner_matcher_.DescribeTo(os);
2995 }
2996
zhanyong.wanb5937da2009-07-16 20:26:41 +00002997 private:
2998 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002999
3000 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00003001};
3002
3003// Implements polymorphic Key(matcher_for_key).
3004template <typename M>
3005class KeyMatcher {
3006 public:
3007 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
3008
3009 template <typename PairType>
3010 operator Matcher<PairType>() const {
3011 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
3012 }
3013
3014 private:
3015 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003016
3017 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00003018};
3019
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003020// Implements Pair(first_matcher, second_matcher) for the given argument pair
3021// type with its two matchers. See Pair() function below.
3022template <typename PairType>
3023class PairMatcherImpl : public MatcherInterface<PairType> {
3024 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003025 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003026 typedef typename RawPairType::first_type FirstType;
3027 typedef typename RawPairType::second_type SecondType;
3028
3029 template <typename FirstMatcher, typename SecondMatcher>
3030 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
3031 : first_matcher_(
3032 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
3033 second_matcher_(
3034 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
3035 }
3036
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003037 // Describes what this matcher does.
3038 virtual void DescribeTo(::std::ostream* os) const {
3039 *os << "has a first field that ";
3040 first_matcher_.DescribeTo(os);
3041 *os << ", and has a second field that ";
3042 second_matcher_.DescribeTo(os);
3043 }
3044
3045 // Describes what the negation of this matcher does.
3046 virtual void DescribeNegationTo(::std::ostream* os) const {
3047 *os << "has a first field that ";
3048 first_matcher_.DescribeNegationTo(os);
3049 *os << ", or has a second field that ";
3050 second_matcher_.DescribeNegationTo(os);
3051 }
3052
zhanyong.wan82113312010-01-08 21:55:40 +00003053 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3054 // matches second_matcher.
3055 virtual bool MatchAndExplain(PairType a_pair,
3056 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003057 if (!listener->IsInterested()) {
3058 // If the listener is not interested, we don't need to construct the
3059 // explanation.
3060 return first_matcher_.Matches(a_pair.first) &&
3061 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00003062 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003063 StringMatchResultListener first_inner_listener;
3064 if (!first_matcher_.MatchAndExplain(a_pair.first,
3065 &first_inner_listener)) {
3066 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003067 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003068 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003069 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003070 StringMatchResultListener second_inner_listener;
3071 if (!second_matcher_.MatchAndExplain(a_pair.second,
3072 &second_inner_listener)) {
3073 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003074 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003075 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003076 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003077 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3078 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00003079 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003080 }
3081
3082 private:
Nico Weber09fd5b32017-05-15 17:07:03 -04003083 void ExplainSuccess(const std::string& first_explanation,
3084 const std::string& second_explanation,
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003085 MatchResultListener* listener) const {
3086 *listener << "whose both fields match";
3087 if (first_explanation != "") {
3088 *listener << ", where the first field is a value " << first_explanation;
3089 }
3090 if (second_explanation != "") {
3091 *listener << ", ";
3092 if (first_explanation != "") {
3093 *listener << "and ";
3094 } else {
3095 *listener << "where ";
3096 }
3097 *listener << "the second field is a value " << second_explanation;
3098 }
3099 }
3100
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003101 const Matcher<const FirstType&> first_matcher_;
3102 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003103
3104 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003105};
3106
3107// Implements polymorphic Pair(first_matcher, second_matcher).
3108template <typename FirstMatcher, typename SecondMatcher>
3109class PairMatcher {
3110 public:
3111 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3112 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3113
3114 template <typename PairType>
3115 operator Matcher<PairType> () const {
3116 return MakeMatcher(
3117 new PairMatcherImpl<PairType>(
3118 first_matcher_, second_matcher_));
3119 }
3120
3121 private:
3122 const FirstMatcher first_matcher_;
3123 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003124
3125 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003126};
3127
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003128// Implements ElementsAre() and ElementsAreArray().
3129template <typename Container>
3130class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3131 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003132 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003133 typedef internal::StlContainerView<RawContainer> View;
3134 typedef typename View::type StlContainer;
3135 typedef typename View::const_reference StlContainerReference;
3136 typedef typename StlContainer::value_type Element;
3137
3138 // Constructs the matcher from a sequence of element values or
3139 // element matchers.
3140 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00003141 ElementsAreMatcherImpl(InputIter first, InputIter last) {
3142 while (first != last) {
3143 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003144 }
3145 }
3146
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003147 // Describes what this matcher does.
3148 virtual void DescribeTo(::std::ostream* os) const {
3149 if (count() == 0) {
3150 *os << "is empty";
3151 } else if (count() == 1) {
3152 *os << "has 1 element that ";
3153 matchers_[0].DescribeTo(os);
3154 } else {
3155 *os << "has " << Elements(count()) << " where\n";
3156 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003157 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003158 matchers_[i].DescribeTo(os);
3159 if (i + 1 < count()) {
3160 *os << ",\n";
3161 }
3162 }
3163 }
3164 }
3165
3166 // Describes what the negation of this matcher does.
3167 virtual void DescribeNegationTo(::std::ostream* os) const {
3168 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003169 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003170 return;
3171 }
3172
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003173 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003174 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003175 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003176 matchers_[i].DescribeNegationTo(os);
3177 if (i + 1 < count()) {
3178 *os << ", or\n";
3179 }
3180 }
3181 }
3182
zhanyong.wan82113312010-01-08 21:55:40 +00003183 virtual bool MatchAndExplain(Container container,
3184 MatchResultListener* listener) const {
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003185 // To work with stream-like "containers", we must only walk
3186 // through the elements in one pass.
3187
3188 const bool listener_interested = listener->IsInterested();
3189
3190 // explanations[i] is the explanation of the element at index i.
Nico Weber09fd5b32017-05-15 17:07:03 -04003191 ::std::vector<std::string> explanations(count());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003192 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003193 typename StlContainer::const_iterator it = stl_container.begin();
3194 size_t exam_pos = 0;
3195 bool mismatch_found = false; // Have we found a mismatched element yet?
3196
3197 // Go through the elements and matchers in pairs, until we reach
3198 // the end of either the elements or the matchers, or until we find a
3199 // mismatch.
3200 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3201 bool match; // Does the current element match the current matcher?
3202 if (listener_interested) {
3203 StringMatchResultListener s;
3204 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3205 explanations[exam_pos] = s.str();
3206 } else {
3207 match = matchers_[exam_pos].Matches(*it);
3208 }
3209
3210 if (!match) {
3211 mismatch_found = true;
3212 break;
3213 }
3214 }
3215 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3216
3217 // Find how many elements the actual container has. We avoid
3218 // calling size() s.t. this code works for stream-like "containers"
3219 // that don't define size().
3220 size_t actual_count = exam_pos;
3221 for (; it != stl_container.end(); ++it) {
3222 ++actual_count;
3223 }
3224
zhanyong.wan82113312010-01-08 21:55:40 +00003225 if (actual_count != count()) {
3226 // The element count doesn't match. If the container is empty,
3227 // there's no need to explain anything as Google Mock already
3228 // prints the empty container. Otherwise we just need to show
3229 // how many elements there actually are.
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003230 if (listener_interested && (actual_count != 0)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003231 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003232 }
zhanyong.wan82113312010-01-08 21:55:40 +00003233 return false;
3234 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003235
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003236 if (mismatch_found) {
3237 // The element count matches, but the exam_pos-th element doesn't match.
3238 if (listener_interested) {
3239 *listener << "whose element #" << exam_pos << " doesn't match";
3240 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003241 }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003242 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003243 }
zhanyong.wan82113312010-01-08 21:55:40 +00003244
3245 // Every element matches its expectation. We need to explain why
3246 // (the obvious ones can be skipped).
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003247 if (listener_interested) {
3248 bool reason_printed = false;
3249 for (size_t i = 0; i != count(); ++i) {
Nico Weber09fd5b32017-05-15 17:07:03 -04003250 const std::string& s = explanations[i];
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003251 if (!s.empty()) {
3252 if (reason_printed) {
3253 *listener << ",\nand ";
3254 }
3255 *listener << "whose element #" << i << " matches, " << s;
3256 reason_printed = true;
zhanyong.wan82113312010-01-08 21:55:40 +00003257 }
zhanyong.wan82113312010-01-08 21:55:40 +00003258 }
3259 }
zhanyong.wan82113312010-01-08 21:55:40 +00003260 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003261 }
3262
3263 private:
3264 static Message Elements(size_t count) {
3265 return Message() << count << (count == 1 ? " element" : " elements");
3266 }
3267
3268 size_t count() const { return matchers_.size(); }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003269
3270 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003271
3272 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003273};
3274
zhanyong.wanfb25d532013-07-28 08:24:00 +00003275// Connectivity matrix of (elements X matchers), in element-major order.
3276// Initially, there are no edges.
3277// Use NextGraph() to iterate over all possible edge configurations.
3278// Use Randomize() to generate a random edge configuration.
3279class GTEST_API_ MatchMatrix {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003280 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003281 MatchMatrix(size_t num_elements, size_t num_matchers)
3282 : num_elements_(num_elements),
3283 num_matchers_(num_matchers),
3284 matched_(num_elements_* num_matchers_, 0) {
3285 }
3286
3287 size_t LhsSize() const { return num_elements_; }
3288 size_t RhsSize() const { return num_matchers_; }
3289 bool HasEdge(size_t ilhs, size_t irhs) const {
3290 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3291 }
3292 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3293 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3294 }
3295
3296 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3297 // adds 1 to that number; returns false if incrementing the graph left it
3298 // empty.
3299 bool NextGraph();
3300
3301 void Randomize();
3302
Nico Weber09fd5b32017-05-15 17:07:03 -04003303 std::string DebugString() const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003304
3305 private:
3306 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3307 return ilhs * num_matchers_ + irhs;
3308 }
3309
3310 size_t num_elements_;
3311 size_t num_matchers_;
3312
3313 // Each element is a char interpreted as bool. They are stored as a
3314 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3315 // a (ilhs, irhs) matrix coordinate into an offset.
3316 ::std::vector<char> matched_;
3317};
3318
3319typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3320typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3321
3322// Returns a maximum bipartite matching for the specified graph 'g'.
3323// The matching is represented as a vector of {element, matcher} pairs.
3324GTEST_API_ ElementMatcherPairs
3325FindMaxBipartiteMatching(const MatchMatrix& g);
3326
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003327struct UnorderedMatcherRequire {
3328 enum Flags {
3329 Superset = 1 << 0,
3330 Subset = 1 << 1,
3331 ExactMatch = Superset | Subset,
3332 };
3333};
zhanyong.wanfb25d532013-07-28 08:24:00 +00003334
3335// Untyped base class for implementing UnorderedElementsAre. By
3336// putting logic that's not specific to the element type here, we
3337// reduce binary bloat and increase compilation speed.
3338class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3339 protected:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003340 explicit UnorderedElementsAreMatcherImplBase(
3341 UnorderedMatcherRequire::Flags matcher_flags)
3342 : match_flags_(matcher_flags) {}
3343
zhanyong.wanfb25d532013-07-28 08:24:00 +00003344 // A vector of matcher describers, one for each element matcher.
3345 // Does not own the describers (and thus can be used only when the
3346 // element matchers are alive).
3347 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3348
3349 // Describes this UnorderedElementsAre matcher.
3350 void DescribeToImpl(::std::ostream* os) const;
3351
3352 // Describes the negation of this UnorderedElementsAre matcher.
3353 void DescribeNegationToImpl(::std::ostream* os) const;
3354
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003355 bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,
3356 const MatchMatrix& matrix,
3357 MatchResultListener* listener) const;
3358
3359 bool FindPairing(const MatchMatrix& matrix,
3360 MatchResultListener* listener) const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003361
3362 MatcherDescriberVec& matcher_describers() {
3363 return matcher_describers_;
3364 }
3365
3366 static Message Elements(size_t n) {
3367 return Message() << n << " element" << (n == 1 ? "" : "s");
3368 }
3369
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003370 UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }
3371
zhanyong.wanfb25d532013-07-28 08:24:00 +00003372 private:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003373 UnorderedMatcherRequire::Flags match_flags_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003374 MatcherDescriberVec matcher_describers_;
3375
3376 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3377};
3378
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003379// Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
3380// IsSupersetOf.
zhanyong.wanfb25d532013-07-28 08:24:00 +00003381template <typename Container>
3382class UnorderedElementsAreMatcherImpl
3383 : public MatcherInterface<Container>,
3384 public UnorderedElementsAreMatcherImplBase {
3385 public:
3386 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3387 typedef internal::StlContainerView<RawContainer> View;
3388 typedef typename View::type StlContainer;
3389 typedef typename View::const_reference StlContainerReference;
3390 typedef typename StlContainer::const_iterator StlContainerConstIterator;
3391 typedef typename StlContainer::value_type Element;
3392
zhanyong.wanfb25d532013-07-28 08:24:00 +00003393 template <typename InputIter>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003394 UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,
3395 InputIter first, InputIter last)
3396 : UnorderedElementsAreMatcherImplBase(matcher_flags) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00003397 for (; first != last; ++first) {
3398 matchers_.push_back(MatcherCast<const Element&>(*first));
3399 matcher_describers().push_back(matchers_.back().GetDescriber());
3400 }
3401 }
3402
3403 // Describes what this matcher does.
3404 virtual void DescribeTo(::std::ostream* os) const {
3405 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3406 }
3407
3408 // Describes what the negation of this matcher does.
3409 virtual void DescribeNegationTo(::std::ostream* os) const {
3410 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3411 }
3412
3413 virtual bool MatchAndExplain(Container container,
3414 MatchResultListener* listener) const {
3415 StlContainerReference stl_container = View::ConstReference(container);
Nico Weber09fd5b32017-05-15 17:07:03 -04003416 ::std::vector<std::string> element_printouts;
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003417 MatchMatrix matrix =
3418 AnalyzeElements(stl_container.begin(), stl_container.end(),
3419 &element_printouts, listener);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003420
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003421 if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00003422 return true;
3423 }
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003424
3425 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
3426 if (matrix.LhsSize() != matrix.RhsSize()) {
3427 // The element count doesn't match. If the container is empty,
3428 // there's no need to explain anything as Google Mock already
3429 // prints the empty container. Otherwise we just need to show
3430 // how many elements there actually are.
3431 if (matrix.LhsSize() != 0 && listener->IsInterested()) {
3432 *listener << "which has " << Elements(matrix.LhsSize());
3433 }
3434 return false;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003435 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003436 }
3437
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003438 return VerifyMatchMatrix(element_printouts, matrix, listener) &&
zhanyong.wanfb25d532013-07-28 08:24:00 +00003439 FindPairing(matrix, listener);
3440 }
3441
3442 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003443 template <typename ElementIter>
3444 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
Nico Weber09fd5b32017-05-15 17:07:03 -04003445 ::std::vector<std::string>* element_printouts,
zhanyong.wanfb25d532013-07-28 08:24:00 +00003446 MatchResultListener* listener) const {
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003447 element_printouts->clear();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003448 ::std::vector<char> did_match;
3449 size_t num_elements = 0;
3450 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3451 if (listener->IsInterested()) {
3452 element_printouts->push_back(PrintToString(*elem_first));
3453 }
3454 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3455 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3456 }
3457 }
3458
3459 MatchMatrix matrix(num_elements, matchers_.size());
3460 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3461 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3462 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3463 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3464 }
3465 }
3466 return matrix;
3467 }
3468
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003469 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003470
3471 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3472};
3473
3474// Functor for use in TransformTuple.
3475// Performs MatcherCast<Target> on an input argument of any type.
3476template <typename Target>
3477struct CastAndAppendTransform {
3478 template <typename Arg>
3479 Matcher<Target> operator()(const Arg& a) const {
3480 return MatcherCast<Target>(a);
3481 }
3482};
3483
3484// Implements UnorderedElementsAre.
3485template <typename MatcherTuple>
3486class UnorderedElementsAreMatcher {
3487 public:
3488 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3489 : matchers_(args) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003490
3491 template <typename Container>
3492 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003493 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003494 typedef typename internal::StlContainerView<RawContainer>::type View;
3495 typedef typename View::value_type Element;
3496 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3497 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003498 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003499 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3500 ::std::back_inserter(matchers));
3501 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003502 UnorderedMatcherRequire::ExactMatch, matchers.begin(), matchers.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003503 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003504
3505 private:
3506 const MatcherTuple matchers_;
3507 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3508};
3509
3510// Implements ElementsAre.
3511template <typename MatcherTuple>
3512class ElementsAreMatcher {
3513 public:
3514 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3515
3516 template <typename Container>
3517 operator Matcher<Container>() const {
3518 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3519 typedef typename internal::StlContainerView<RawContainer>::type View;
3520 typedef typename View::value_type Element;
3521 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3522 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003523 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003524 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3525 ::std::back_inserter(matchers));
3526 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3527 matchers.begin(), matchers.end()));
3528 }
3529
3530 private:
3531 const MatcherTuple matchers_;
3532 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3533};
3534
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003535// Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
zhanyong.wanfb25d532013-07-28 08:24:00 +00003536template <typename T>
3537class UnorderedElementsAreArrayMatcher {
3538 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003539 template <typename Iter>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003540 UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,
3541 Iter first, Iter last)
3542 : match_flags_(match_flags), matchers_(first, last) {}
zhanyong.wanfb25d532013-07-28 08:24:00 +00003543
3544 template <typename Container>
3545 operator Matcher<Container>() const {
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003546 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3547 match_flags_, matchers_.begin(), matchers_.end()));
zhanyong.wanfb25d532013-07-28 08:24:00 +00003548 }
3549
3550 private:
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003551 UnorderedMatcherRequire::Flags match_flags_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003552 ::std::vector<T> matchers_;
3553
3554 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003555};
3556
3557// Implements ElementsAreArray().
3558template <typename T>
3559class ElementsAreArrayMatcher {
3560 public:
jgm38513a82012-11-15 15:50:36 +00003561 template <typename Iter>
3562 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003563
3564 template <typename Container>
3565 operator Matcher<Container>() const {
jgm38513a82012-11-15 15:50:36 +00003566 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3567 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003568 }
3569
3570 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003571 const ::std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003572
3573 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003574};
3575
kosak2336e9c2014-07-28 22:57:30 +00003576// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3577// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3578// second) is a polymorphic matcher that matches a value x iff tm
3579// matches tuple (x, second). Useful for implementing
3580// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3581//
3582// BoundSecondMatcher is copyable and assignable, as we need to put
3583// instances of this class in a vector when implementing
3584// UnorderedPointwise().
3585template <typename Tuple2Matcher, typename Second>
3586class BoundSecondMatcher {
3587 public:
3588 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3589 : tuple2_matcher_(tm), second_value_(second) {}
3590
3591 template <typename T>
3592 operator Matcher<T>() const {
3593 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3594 }
3595
3596 // We have to define this for UnorderedPointwise() to compile in
3597 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3598 // which requires the elements to be assignable in C++98. The
3599 // compiler cannot generate the operator= for us, as Tuple2Matcher
3600 // and Second may not be assignable.
3601 //
3602 // However, this should never be called, so the implementation just
3603 // need to assert.
3604 void operator=(const BoundSecondMatcher& /*rhs*/) {
3605 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3606 }
3607
3608 private:
3609 template <typename T>
3610 class Impl : public MatcherInterface<T> {
3611 public:
3612 typedef ::testing::tuple<T, Second> ArgTuple;
3613
3614 Impl(const Tuple2Matcher& tm, const Second& second)
3615 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3616 second_value_(second) {}
3617
3618 virtual void DescribeTo(::std::ostream* os) const {
3619 *os << "and ";
3620 UniversalPrint(second_value_, os);
3621 *os << " ";
3622 mono_tuple2_matcher_.DescribeTo(os);
3623 }
3624
3625 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3626 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3627 listener);
3628 }
3629
3630 private:
3631 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3632 const Second second_value_;
3633
3634 GTEST_DISALLOW_ASSIGN_(Impl);
3635 };
3636
3637 const Tuple2Matcher tuple2_matcher_;
3638 const Second second_value_;
3639};
3640
3641// Given a 2-tuple matcher tm and a value second,
3642// MatcherBindSecond(tm, second) returns a matcher that matches a
3643// value x iff tm matches tuple (x, second). Useful for implementing
3644// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3645template <typename Tuple2Matcher, typename Second>
3646BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
3647 const Tuple2Matcher& tm, const Second& second) {
3648 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
3649}
3650
zhanyong.wanb4140802010-06-08 22:53:57 +00003651// Returns the description for a matcher defined using the MATCHER*()
3652// macro where the user-supplied description string is "", if
3653// 'negation' is false; otherwise returns the description of the
3654// negation of the matcher. 'param_values' contains a list of strings
3655// that are the print-out of the matcher's parameters.
Nico Weber09fd5b32017-05-15 17:07:03 -04003656GTEST_API_ std::string FormatMatcherDescription(bool negation,
3657 const char* matcher_name,
3658 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003659
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05003660namespace variant_matcher {
3661// Overloads to allow VariantMatcher to do proper ADL lookup.
3662template <typename T>
3663void holds_alternative() {}
3664template <typename T>
3665void get() {}
3666
3667// Implements a matcher that checks the value of a variant<> type variable.
3668template <typename T>
3669class VariantMatcher {
3670 public:
3671 explicit VariantMatcher(::testing::Matcher<const T&> matcher)
3672 : matcher_(internal::move(matcher)) {}
3673
3674 template <typename Variant>
3675 bool MatchAndExplain(const Variant& value,
3676 ::testing::MatchResultListener* listener) const {
3677 if (!listener->IsInterested()) {
3678 return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));
3679 }
3680
3681 if (!holds_alternative<T>(value)) {
3682 *listener << "whose value is not of type '" << GetTypeName() << "'";
3683 return false;
3684 }
3685
3686 const T& elem = get<T>(value);
3687 StringMatchResultListener elem_listener;
3688 const bool match = matcher_.MatchAndExplain(elem, &elem_listener);
3689 *listener << "whose value " << PrintToString(elem)
3690 << (match ? " matches" : " doesn't match");
3691 PrintIfNotEmpty(elem_listener.str(), listener->stream());
3692 return match;
3693 }
3694
3695 void DescribeTo(std::ostream* os) const {
3696 *os << "is a variant<> with value of type '" << GetTypeName()
3697 << "' and the value ";
3698 matcher_.DescribeTo(os);
3699 }
3700
3701 void DescribeNegationTo(std::ostream* os) const {
3702 *os << "is a variant<> with value of type other than '" << GetTypeName()
3703 << "' or the value ";
3704 matcher_.DescribeNegationTo(os);
3705 }
3706
3707 private:
3708 static string GetTypeName() {
3709#if GTEST_HAS_RTTI
3710 return internal::GetTypeName<T>();
3711#endif
3712 return "the element type";
3713 }
3714
3715 const ::testing::Matcher<const T&> matcher_;
3716};
3717
3718} // namespace variant_matcher
3719
shiqiane35fdd92008-12-10 05:08:54 +00003720} // namespace internal
3721
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003722// ElementsAreArray(iterator_first, iterator_last)
zhanyong.wanfb25d532013-07-28 08:24:00 +00003723// ElementsAreArray(pointer, count)
3724// ElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00003725// ElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003726// ElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00003727//
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003728// The ElementsAreArray() functions are like ElementsAre(...), except
3729// that they are given a homogeneous sequence rather than taking each
3730// element as a function argument. The sequence can be specified as an
3731// array, a pointer and count, a vector, an initializer list, or an
3732// STL iterator range. In each of these cases, the underlying sequence
3733// can be either a sequence of values or a sequence of matchers.
zhanyong.wanfb25d532013-07-28 08:24:00 +00003734//
3735// All forms of ElementsAreArray() make a copy of the input matcher sequence.
3736
3737template <typename Iter>
3738inline internal::ElementsAreArrayMatcher<
3739 typename ::std::iterator_traits<Iter>::value_type>
3740ElementsAreArray(Iter first, Iter last) {
3741 typedef typename ::std::iterator_traits<Iter>::value_type T;
3742 return internal::ElementsAreArrayMatcher<T>(first, last);
3743}
3744
3745template <typename T>
3746inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3747 const T* pointer, size_t count) {
3748 return ElementsAreArray(pointer, pointer + count);
3749}
3750
3751template <typename T, size_t N>
3752inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3753 const T (&array)[N]) {
3754 return ElementsAreArray(array, N);
3755}
3756
kosak06678922014-07-28 20:01:28 +00003757template <typename Container>
3758inline internal::ElementsAreArrayMatcher<typename Container::value_type>
3759ElementsAreArray(const Container& container) {
3760 return ElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00003761}
3762
kosak18489fa2013-12-04 23:49:07 +00003763#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003764template <typename T>
3765inline internal::ElementsAreArrayMatcher<T>
3766ElementsAreArray(::std::initializer_list<T> xs) {
3767 return ElementsAreArray(xs.begin(), xs.end());
3768}
3769#endif
3770
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003771// UnorderedElementsAreArray(iterator_first, iterator_last)
zhanyong.wanfb25d532013-07-28 08:24:00 +00003772// UnorderedElementsAreArray(pointer, count)
3773// UnorderedElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00003774// UnorderedElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003775// UnorderedElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00003776//
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003777// UnorderedElementsAreArray() verifies that a bijective mapping onto a
3778// collection of matchers exists.
3779//
3780// The matchers can be specified as an array, a pointer and count, a container,
3781// an initializer list, or an STL iterator range. In each of these cases, the
3782// underlying matchers can be either values or matchers.
3783
zhanyong.wanfb25d532013-07-28 08:24:00 +00003784template <typename Iter>
3785inline internal::UnorderedElementsAreArrayMatcher<
3786 typename ::std::iterator_traits<Iter>::value_type>
3787UnorderedElementsAreArray(Iter first, Iter last) {
3788 typedef typename ::std::iterator_traits<Iter>::value_type T;
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003789 return internal::UnorderedElementsAreArrayMatcher<T>(
3790 internal::UnorderedMatcherRequire::ExactMatch, first, last);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003791}
3792
3793template <typename T>
3794inline internal::UnorderedElementsAreArrayMatcher<T>
3795UnorderedElementsAreArray(const T* pointer, size_t count) {
3796 return UnorderedElementsAreArray(pointer, pointer + count);
3797}
3798
3799template <typename T, size_t N>
3800inline internal::UnorderedElementsAreArrayMatcher<T>
3801UnorderedElementsAreArray(const T (&array)[N]) {
3802 return UnorderedElementsAreArray(array, N);
3803}
3804
kosak06678922014-07-28 20:01:28 +00003805template <typename Container>
3806inline internal::UnorderedElementsAreArrayMatcher<
3807 typename Container::value_type>
3808UnorderedElementsAreArray(const Container& container) {
3809 return UnorderedElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00003810}
3811
kosak18489fa2013-12-04 23:49:07 +00003812#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003813template <typename T>
3814inline internal::UnorderedElementsAreArrayMatcher<T>
3815UnorderedElementsAreArray(::std::initializer_list<T> xs) {
3816 return UnorderedElementsAreArray(xs.begin(), xs.end());
3817}
3818#endif
zhanyong.wanfb25d532013-07-28 08:24:00 +00003819
shiqiane35fdd92008-12-10 05:08:54 +00003820// _ is a matcher that matches anything of any type.
3821//
3822// This definition is fine as:
3823//
3824// 1. The C++ standard permits using the name _ in a namespace that
3825// is not the global namespace or ::std.
3826// 2. The AnythingMatcher class has no data member or constructor,
3827// so it's OK to create global variables of this type.
3828// 3. c-style has approved of using _ in this case.
3829const internal::AnythingMatcher _ = {};
3830// Creates a matcher that matches any value of the given type T.
3831template <typename T>
Gennadiy Civil2bd17502018-02-27 13:51:09 -05003832inline Matcher<T> A() {
3833 return Matcher<T>(new internal::AnyMatcherImpl<T>());
3834}
shiqiane35fdd92008-12-10 05:08:54 +00003835
3836// Creates a matcher that matches any value of the given type T.
3837template <typename T>
3838inline Matcher<T> An() { return A<T>(); }
3839
3840// Creates a polymorphic matcher that matches anything equal to x.
3841// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
3842// wouldn't compile.
3843template <typename T>
3844inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
3845
3846// Constructs a Matcher<T> from a 'value' of type T. The constructed
3847// matcher matches any value that's equal to 'value'.
3848template <typename T>
3849Matcher<T>::Matcher(T value) { *this = Eq(value); }
3850
3851// Creates a monomorphic matcher that matches anything with type Lhs
3852// and equal to rhs. A user may need to use this instead of Eq(...)
3853// in order to resolve an overloading ambiguity.
3854//
3855// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
3856// or Matcher<T>(x), but more readable than the latter.
3857//
3858// We could define similar monomorphic matchers for other comparison
3859// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
3860// it yet as those are used much less than Eq() in practice. A user
3861// can always write Matcher<T>(Lt(5)) to be explicit about the type,
3862// for example.
3863template <typename Lhs, typename Rhs>
3864inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
3865
3866// Creates a polymorphic matcher that matches anything >= x.
3867template <typename Rhs>
3868inline internal::GeMatcher<Rhs> Ge(Rhs x) {
3869 return internal::GeMatcher<Rhs>(x);
3870}
3871
3872// Creates a polymorphic matcher that matches anything > x.
3873template <typename Rhs>
3874inline internal::GtMatcher<Rhs> Gt(Rhs x) {
3875 return internal::GtMatcher<Rhs>(x);
3876}
3877
3878// Creates a polymorphic matcher that matches anything <= x.
3879template <typename Rhs>
3880inline internal::LeMatcher<Rhs> Le(Rhs x) {
3881 return internal::LeMatcher<Rhs>(x);
3882}
3883
3884// Creates a polymorphic matcher that matches anything < x.
3885template <typename Rhs>
3886inline internal::LtMatcher<Rhs> Lt(Rhs x) {
3887 return internal::LtMatcher<Rhs>(x);
3888}
3889
3890// Creates a polymorphic matcher that matches anything != x.
3891template <typename Rhs>
3892inline internal::NeMatcher<Rhs> Ne(Rhs x) {
3893 return internal::NeMatcher<Rhs>(x);
3894}
3895
zhanyong.wan2d970ee2009-09-24 21:41:36 +00003896// Creates a polymorphic matcher that matches any NULL pointer.
3897inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
3898 return MakePolymorphicMatcher(internal::IsNullMatcher());
3899}
3900
shiqiane35fdd92008-12-10 05:08:54 +00003901// Creates a polymorphic matcher that matches any non-NULL pointer.
3902// This is convenient as Not(NULL) doesn't compile (the compiler
3903// thinks that that expression is comparing a pointer with an integer).
3904inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
3905 return MakePolymorphicMatcher(internal::NotNullMatcher());
3906}
3907
3908// Creates a polymorphic matcher that matches any argument that
3909// references variable x.
3910template <typename T>
3911inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
3912 return internal::RefMatcher<T&>(x);
3913}
3914
3915// Creates a matcher that matches any double argument approximately
3916// equal to rhs, where two NANs are considered unequal.
3917inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
3918 return internal::FloatingEqMatcher<double>(rhs, false);
3919}
3920
3921// Creates a matcher that matches any double argument approximately
3922// equal to rhs, including NaN values when rhs is NaN.
3923inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
3924 return internal::FloatingEqMatcher<double>(rhs, true);
3925}
3926
zhanyong.wan616180e2013-06-18 18:49:51 +00003927// Creates a matcher that matches any double argument approximately equal to
3928// rhs, up to the specified max absolute error bound, where two NANs are
3929// considered unequal. The max absolute error bound must be non-negative.
3930inline internal::FloatingEqMatcher<double> DoubleNear(
3931 double rhs, double max_abs_error) {
3932 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
3933}
3934
3935// Creates a matcher that matches any double argument approximately equal to
3936// rhs, up to the specified max absolute error bound, including NaN values when
3937// rhs is NaN. The max absolute error bound must be non-negative.
3938inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
3939 double rhs, double max_abs_error) {
3940 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
3941}
3942
shiqiane35fdd92008-12-10 05:08:54 +00003943// Creates a matcher that matches any float argument approximately
3944// equal to rhs, where two NANs are considered unequal.
3945inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
3946 return internal::FloatingEqMatcher<float>(rhs, false);
3947}
3948
zhanyong.wan616180e2013-06-18 18:49:51 +00003949// Creates a matcher that matches any float argument approximately
shiqiane35fdd92008-12-10 05:08:54 +00003950// equal to rhs, including NaN values when rhs is NaN.
3951inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
3952 return internal::FloatingEqMatcher<float>(rhs, true);
3953}
3954
zhanyong.wan616180e2013-06-18 18:49:51 +00003955// Creates a matcher that matches any float argument approximately equal to
3956// rhs, up to the specified max absolute error bound, where two NANs are
3957// considered unequal. The max absolute error bound must be non-negative.
3958inline internal::FloatingEqMatcher<float> FloatNear(
3959 float rhs, float max_abs_error) {
3960 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
3961}
3962
3963// Creates a matcher that matches any float argument approximately equal to
3964// rhs, up to the specified max absolute error bound, including NaN values when
3965// rhs is NaN. The max absolute error bound must be non-negative.
3966inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
3967 float rhs, float max_abs_error) {
3968 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
3969}
3970
shiqiane35fdd92008-12-10 05:08:54 +00003971// Creates a matcher that matches a pointer (raw or smart) that points
3972// to a value that matches inner_matcher.
3973template <typename InnerMatcher>
3974inline internal::PointeeMatcher<InnerMatcher> Pointee(
3975 const InnerMatcher& inner_matcher) {
3976 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
3977}
3978
billydonahue1f5fdea2014-05-19 17:54:51 +00003979// Creates a matcher that matches a pointer or reference that matches
3980// inner_matcher when dynamic_cast<To> is applied.
3981// The result of dynamic_cast<To> is forwarded to the inner matcher.
3982// If To is a pointer and the cast fails, the inner matcher will receive NULL.
3983// If To is a reference and the cast fails, this matcher returns false
3984// immediately.
3985template <typename To>
3986inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
3987WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
3988 return MakePolymorphicMatcher(
3989 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
3990}
3991
shiqiane35fdd92008-12-10 05:08:54 +00003992// Creates a matcher that matches an object whose given field matches
3993// 'matcher'. For example,
3994// Field(&Foo::number, Ge(5))
3995// matches a Foo object x iff x.number >= 5.
3996template <typename Class, typename FieldType, typename FieldMatcher>
3997inline PolymorphicMatcher<
3998 internal::FieldMatcher<Class, FieldType> > Field(
3999 FieldType Class::*field, const FieldMatcher& matcher) {
4000 return MakePolymorphicMatcher(
4001 internal::FieldMatcher<Class, FieldType>(
4002 field, MatcherCast<const FieldType&>(matcher)));
4003 // The call to MatcherCast() is required for supporting inner
4004 // matchers of compatible types. For example, it allows
4005 // Field(&Foo::bar, m)
4006 // to compile where bar is an int32 and m is a matcher for int64.
4007}
4008
4009// Creates a matcher that matches an object whose given property
4010// matches 'matcher'. For example,
4011// Property(&Foo::str, StartsWith("hi"))
4012// matches a Foo object x iff x.str() starts with "hi".
4013template <typename Class, typename PropertyType, typename PropertyMatcher>
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004014inline PolymorphicMatcher<internal::PropertyMatcher<
4015 Class, PropertyType, PropertyType (Class::*)() const> >
4016Property(PropertyType (Class::*property)() const,
4017 const PropertyMatcher& matcher) {
shiqiane35fdd92008-12-10 05:08:54 +00004018 return MakePolymorphicMatcher(
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004019 internal::PropertyMatcher<Class, PropertyType,
4020 PropertyType (Class::*)() const>(
shiqiane35fdd92008-12-10 05:08:54 +00004021 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00004022 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00004023 // The call to MatcherCast() is required for supporting inner
4024 // matchers of compatible types. For example, it allows
4025 // Property(&Foo::bar, m)
4026 // to compile where bar() returns an int32 and m is a matcher for int64.
4027}
4028
Roman Perepelitsa966b5492017-08-22 16:06:26 +02004029#if GTEST_LANG_CXX11
4030// The same as above but for reference-qualified member functions.
4031template <typename Class, typename PropertyType, typename PropertyMatcher>
4032inline PolymorphicMatcher<internal::PropertyMatcher<
4033 Class, PropertyType, PropertyType (Class::*)() const &> >
4034Property(PropertyType (Class::*property)() const &,
4035 const PropertyMatcher& matcher) {
4036 return MakePolymorphicMatcher(
4037 internal::PropertyMatcher<Class, PropertyType,
4038 PropertyType (Class::*)() const &>(
4039 property,
4040 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4041}
4042#endif
4043
shiqiane35fdd92008-12-10 05:08:54 +00004044// Creates a matcher that matches an object iff the result of applying
4045// a callable to x matches 'matcher'.
4046// For example,
4047// ResultOf(f, StartsWith("hi"))
4048// matches a Foo object x iff f(x) starts with "hi".
4049// callable parameter can be a function, function pointer, or a functor.
4050// Callable has to satisfy the following conditions:
4051// * It is required to keep no state affecting the results of
4052// the calls on it and make no assumptions about how many calls
4053// will be made. Any state it keeps must be protected from the
4054// concurrent access.
4055// * If it is a function object, it has to define type result_type.
4056// We recommend deriving your functor classes from std::unary_function.
4057template <typename Callable, typename ResultOfMatcher>
4058internal::ResultOfMatcher<Callable> ResultOf(
4059 Callable callable, const ResultOfMatcher& matcher) {
4060 return internal::ResultOfMatcher<Callable>(
4061 callable,
4062 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
4063 matcher));
4064 // The call to MatcherCast() is required for supporting inner
4065 // matchers of compatible types. For example, it allows
4066 // ResultOf(Function, m)
4067 // to compile where Function() returns an int32 and m is a matcher for int64.
4068}
4069
4070// String matchers.
4071
4072// Matches a string equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04004073inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
4074 const std::string& str) {
4075 return MakePolymorphicMatcher(
4076 internal::StrEqualityMatcher<std::string>(str, true, true));
shiqiane35fdd92008-12-10 05:08:54 +00004077}
4078
4079// Matches a string not equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04004080inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
4081 const std::string& str) {
4082 return MakePolymorphicMatcher(
4083 internal::StrEqualityMatcher<std::string>(str, false, true));
shiqiane35fdd92008-12-10 05:08:54 +00004084}
4085
4086// Matches a string equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04004087inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
4088 const std::string& str) {
4089 return MakePolymorphicMatcher(
4090 internal::StrEqualityMatcher<std::string>(str, true, false));
shiqiane35fdd92008-12-10 05:08:54 +00004091}
4092
4093// Matches a string not equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04004094inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
4095 const std::string& str) {
4096 return MakePolymorphicMatcher(
4097 internal::StrEqualityMatcher<std::string>(str, false, false));
shiqiane35fdd92008-12-10 05:08:54 +00004098}
4099
4100// Creates a matcher that matches any string, std::string, or C string
4101// that contains the given substring.
Nico Weber09fd5b32017-05-15 17:07:03 -04004102inline PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
4103 const std::string& substring) {
4104 return MakePolymorphicMatcher(
4105 internal::HasSubstrMatcher<std::string>(substring));
shiqiane35fdd92008-12-10 05:08:54 +00004106}
4107
4108// Matches a string that starts with 'prefix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004109inline PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
4110 const std::string& prefix) {
4111 return MakePolymorphicMatcher(
4112 internal::StartsWithMatcher<std::string>(prefix));
shiqiane35fdd92008-12-10 05:08:54 +00004113}
4114
4115// Matches a string that ends with 'suffix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004116inline PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
4117 const std::string& suffix) {
4118 return MakePolymorphicMatcher(internal::EndsWithMatcher<std::string>(suffix));
shiqiane35fdd92008-12-10 05:08:54 +00004119}
4120
shiqiane35fdd92008-12-10 05:08:54 +00004121// Matches a string that fully matches regular expression 'regex'.
4122// The matcher takes ownership of 'regex'.
4123inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4124 const internal::RE* regex) {
4125 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
4126}
4127inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004128 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004129 return MatchesRegex(new internal::RE(regex));
4130}
4131
4132// Matches a string that contains regular expression 'regex'.
4133// The matcher takes ownership of 'regex'.
4134inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4135 const internal::RE* regex) {
4136 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4137}
4138inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004139 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004140 return ContainsRegex(new internal::RE(regex));
4141}
4142
shiqiane35fdd92008-12-10 05:08:54 +00004143#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4144// Wide string matchers.
4145
4146// Matches a string equal to str.
4147inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4148 StrEq(const internal::wstring& str) {
4149 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4150 str, true, true));
4151}
4152
4153// Matches a string not equal to str.
4154inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4155 StrNe(const internal::wstring& str) {
4156 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4157 str, false, true));
4158}
4159
4160// Matches a string equal to str, ignoring case.
4161inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4162 StrCaseEq(const internal::wstring& str) {
4163 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4164 str, true, false));
4165}
4166
4167// Matches a string not equal to str, ignoring case.
4168inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4169 StrCaseNe(const internal::wstring& str) {
4170 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4171 str, false, false));
4172}
4173
4174// Creates a matcher that matches any wstring, std::wstring, or C wide string
4175// that contains the given substring.
4176inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
4177 HasSubstr(const internal::wstring& substring) {
4178 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
4179 substring));
4180}
4181
4182// Matches a string that starts with 'prefix' (case-sensitive).
4183inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
4184 StartsWith(const internal::wstring& prefix) {
4185 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
4186 prefix));
4187}
4188
4189// Matches a string that ends with 'suffix' (case-sensitive).
4190inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
4191 EndsWith(const internal::wstring& suffix) {
4192 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
4193 suffix));
4194}
4195
4196#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4197
4198// Creates a polymorphic matcher that matches a 2-tuple where the
4199// first field == the second field.
4200inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4201
4202// Creates a polymorphic matcher that matches a 2-tuple where the
4203// first field >= the second field.
4204inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4205
4206// Creates a polymorphic matcher that matches a 2-tuple where the
4207// first field > the second field.
4208inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4209
4210// Creates a polymorphic matcher that matches a 2-tuple where the
4211// first field <= the second field.
4212inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4213
4214// Creates a polymorphic matcher that matches a 2-tuple where the
4215// first field < the second field.
4216inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4217
4218// Creates a polymorphic matcher that matches a 2-tuple where the
4219// first field != the second field.
4220inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4221
4222// Creates a matcher that matches any value of type T that m doesn't
4223// match.
4224template <typename InnerMatcher>
4225inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4226 return internal::NotMatcher<InnerMatcher>(m);
4227}
4228
shiqiane35fdd92008-12-10 05:08:54 +00004229// Returns a matcher that matches anything that satisfies the given
4230// predicate. The predicate can be any unary function or functor
4231// whose return type can be implicitly converted to bool.
4232template <typename Predicate>
4233inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4234Truly(Predicate pred) {
4235 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4236}
4237
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004238// Returns a matcher that matches the container size. The container must
4239// support both size() and size_type which all STL-like containers provide.
4240// Note that the parameter 'size' can be a value of type size_type as well as
4241// matcher. For instance:
4242// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
4243// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
4244template <typename SizeMatcher>
4245inline internal::SizeIsMatcher<SizeMatcher>
4246SizeIs(const SizeMatcher& size_matcher) {
4247 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4248}
4249
kosakb6a34882014-03-12 21:06:46 +00004250// Returns a matcher that matches the distance between the container's begin()
4251// iterator and its end() iterator, i.e. the size of the container. This matcher
4252// can be used instead of SizeIs with containers such as std::forward_list which
4253// do not implement size(). The container must provide const_iterator (with
4254// valid iterator_traits), begin() and end().
4255template <typename DistanceMatcher>
4256inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4257BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4258 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4259}
4260
zhanyong.wan6a896b52009-01-16 01:13:50 +00004261// Returns a matcher that matches an equal container.
4262// This matcher behaves like Eq(), but in the event of mismatch lists the
4263// values that are included in one container but not the other. (Duplicate
4264// values and order differences are not explained.)
4265template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00004266inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00004267 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004268 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00004269 // This following line is for working around a bug in MSVC 8.0,
4270 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00004271 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00004272 return MakePolymorphicMatcher(
4273 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00004274}
4275
zhanyong.wan898725c2011-09-16 16:45:39 +00004276// Returns a matcher that matches a container that, when sorted using
4277// the given comparator, matches container_matcher.
4278template <typename Comparator, typename ContainerMatcher>
4279inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4280WhenSortedBy(const Comparator& comparator,
4281 const ContainerMatcher& container_matcher) {
4282 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4283 comparator, container_matcher);
4284}
4285
4286// Returns a matcher that matches a container that, when sorted using
4287// the < operator, matches container_matcher.
4288template <typename ContainerMatcher>
4289inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4290WhenSorted(const ContainerMatcher& container_matcher) {
4291 return
4292 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4293 internal::LessComparator(), container_matcher);
4294}
4295
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004296// Matches an STL-style container or a native array that contains the
4297// same number of elements as in rhs, where its i-th element and rhs's
4298// i-th element (as a pair) satisfy the given pair matcher, for all i.
4299// TupleMatcher must be able to be safely cast to Matcher<tuple<const
4300// T1&, const T2&> >, where T1 and T2 are the types of elements in the
4301// LHS container and the RHS container respectively.
4302template <typename TupleMatcher, typename Container>
4303inline internal::PointwiseMatcher<TupleMatcher,
4304 GTEST_REMOVE_CONST_(Container)>
4305Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4306 // This following line is for working around a bug in MSVC 8.0,
kosak2336e9c2014-07-28 22:57:30 +00004307 // which causes Container to be a const type sometimes (e.g. when
4308 // rhs is a const int[])..
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004309 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4310 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4311 tuple_matcher, rhs);
4312}
4313
kosak2336e9c2014-07-28 22:57:30 +00004314#if GTEST_HAS_STD_INITIALIZER_LIST_
4315
4316// Supports the Pointwise(m, {a, b, c}) syntax.
4317template <typename TupleMatcher, typename T>
4318inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4319 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4320 return Pointwise(tuple_matcher, std::vector<T>(rhs));
4321}
4322
4323#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4324
4325// UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4326// container or a native array that contains the same number of
4327// elements as in rhs, where in some permutation of the container, its
4328// i-th element and rhs's i-th element (as a pair) satisfy the given
4329// pair matcher, for all i. Tuple2Matcher must be able to be safely
4330// cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4331// the types of elements in the LHS container and the RHS container
4332// respectively.
4333//
4334// This is like Pointwise(pair_matcher, rhs), except that the element
4335// order doesn't matter.
4336template <typename Tuple2Matcher, typename RhsContainer>
4337inline internal::UnorderedElementsAreArrayMatcher<
4338 typename internal::BoundSecondMatcher<
4339 Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4340 RhsContainer)>::type::value_type> >
4341UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4342 const RhsContainer& rhs_container) {
4343 // This following line is for working around a bug in MSVC 8.0,
4344 // which causes RhsContainer to be a const type sometimes (e.g. when
4345 // rhs_container is a const int[]).
4346 typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4347
4348 // RhsView allows the same code to handle RhsContainer being a
4349 // STL-style container and it being a native C-style array.
4350 typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4351 typedef typename RhsView::type RhsStlContainer;
4352 typedef typename RhsStlContainer::value_type Second;
4353 const RhsStlContainer& rhs_stl_container =
4354 RhsView::ConstReference(rhs_container);
4355
4356 // Create a matcher for each element in rhs_container.
4357 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4358 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4359 it != rhs_stl_container.end(); ++it) {
4360 matchers.push_back(
4361 internal::MatcherBindSecond(tuple2_matcher, *it));
4362 }
4363
4364 // Delegate the work to UnorderedElementsAreArray().
4365 return UnorderedElementsAreArray(matchers);
4366}
4367
4368#if GTEST_HAS_STD_INITIALIZER_LIST_
4369
4370// Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4371template <typename Tuple2Matcher, typename T>
4372inline internal::UnorderedElementsAreArrayMatcher<
4373 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4374UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4375 std::initializer_list<T> rhs) {
4376 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4377}
4378
4379#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4380
zhanyong.wanb8243162009-06-04 05:48:20 +00004381// Matches an STL-style container or a native array that contains at
4382// least one element matching the given value or matcher.
4383//
4384// Examples:
4385// ::std::set<int> page_ids;
4386// page_ids.insert(3);
4387// page_ids.insert(1);
4388// EXPECT_THAT(page_ids, Contains(1));
4389// EXPECT_THAT(page_ids, Contains(Gt(2)));
4390// EXPECT_THAT(page_ids, Not(Contains(4)));
4391//
4392// ::std::map<int, size_t> page_lengths;
4393// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00004394// EXPECT_THAT(page_lengths,
4395// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004396//
4397// const char* user_ids[] = { "joe", "mike", "tom" };
4398// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4399template <typename M>
4400inline internal::ContainsMatcher<M> Contains(M matcher) {
4401 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004402}
4403
Gennadiy Civil2bd17502018-02-27 13:51:09 -05004404// IsSupersetOf(iterator_first, iterator_last)
4405// IsSupersetOf(pointer, count)
4406// IsSupersetOf(array)
4407// IsSupersetOf(container)
4408// IsSupersetOf({e1, e2, ..., en})
4409//
4410// IsSupersetOf() verifies that a surjective partial mapping onto a collection
4411// of matchers exists. In other words, a container matches
4412// IsSupersetOf({e1, ..., en}) if and only if there is a permutation
4413// {y1, ..., yn} of some of the container's elements where y1 matches e1,
4414// ..., and yn matches en. Obviously, the size of the container must be >= n
4415// in order to have a match. Examples:
4416//
4417// - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and
4418// 1 matches Ne(0).
4419// - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches
4420// both Eq(1) and Lt(2). The reason is that different matchers must be used
4421// for elements in different slots of the container.
4422// - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches
4423// Eq(1) and (the second) 1 matches Lt(2).
4424// - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)
4425// Gt(1) and 3 matches (the second) Gt(1).
4426//
4427// The matchers can be specified as an array, a pointer and count, a container,
4428// an initializer list, or an STL iterator range. In each of these cases, the
4429// underlying matchers can be either values or matchers.
4430
4431template <typename Iter>
4432inline internal::UnorderedElementsAreArrayMatcher<
4433 typename ::std::iterator_traits<Iter>::value_type>
4434IsSupersetOf(Iter first, Iter last) {
4435 typedef typename ::std::iterator_traits<Iter>::value_type T;
4436 return internal::UnorderedElementsAreArrayMatcher<T>(
4437 internal::UnorderedMatcherRequire::Superset, first, last);
4438}
4439
4440template <typename T>
4441inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
4442 const T* pointer, size_t count) {
4443 return IsSupersetOf(pointer, pointer + count);
4444}
4445
4446template <typename T, size_t N>
4447inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
4448 const T (&array)[N]) {
4449 return IsSupersetOf(array, N);
4450}
4451
4452template <typename Container>
4453inline internal::UnorderedElementsAreArrayMatcher<
4454 typename Container::value_type>
4455IsSupersetOf(const Container& container) {
4456 return IsSupersetOf(container.begin(), container.end());
4457}
4458
4459#if GTEST_HAS_STD_INITIALIZER_LIST_
4460template <typename T>
4461inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
4462 ::std::initializer_list<T> xs) {
4463 return IsSupersetOf(xs.begin(), xs.end());
4464}
4465#endif
4466
4467// IsSubsetOf(iterator_first, iterator_last)
4468// IsSubsetOf(pointer, count)
4469// IsSubsetOf(array)
4470// IsSubsetOf(container)
4471// IsSubsetOf({e1, e2, ..., en})
4472//
4473// IsSubsetOf() verifies that an injective mapping onto a collection of matchers
4474// exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and
4475// only if there is a subset of matchers {m1, ..., mk} which would match the
4476// container using UnorderedElementsAre. Obviously, the size of the container
4477// must be <= n in order to have a match. Examples:
4478//
4479// - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).
4480// - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1
4481// matches Lt(0).
4482// - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both
4483// match Gt(0). The reason is that different matchers must be used for
4484// elements in different slots of the container.
4485//
4486// The matchers can be specified as an array, a pointer and count, a container,
4487// an initializer list, or an STL iterator range. In each of these cases, the
4488// underlying matchers can be either values or matchers.
4489
4490template <typename Iter>
4491inline internal::UnorderedElementsAreArrayMatcher<
4492 typename ::std::iterator_traits<Iter>::value_type>
4493IsSubsetOf(Iter first, Iter last) {
4494 typedef typename ::std::iterator_traits<Iter>::value_type T;
4495 return internal::UnorderedElementsAreArrayMatcher<T>(
4496 internal::UnorderedMatcherRequire::Subset, first, last);
4497}
4498
4499template <typename T>
4500inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
4501 const T* pointer, size_t count) {
4502 return IsSubsetOf(pointer, pointer + count);
4503}
4504
4505template <typename T, size_t N>
4506inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
4507 const T (&array)[N]) {
4508 return IsSubsetOf(array, N);
4509}
4510
4511template <typename Container>
4512inline internal::UnorderedElementsAreArrayMatcher<
4513 typename Container::value_type>
4514IsSubsetOf(const Container& container) {
4515 return IsSubsetOf(container.begin(), container.end());
4516}
4517
4518#if GTEST_HAS_STD_INITIALIZER_LIST_
4519template <typename T>
4520inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
4521 ::std::initializer_list<T> xs) {
4522 return IsSubsetOf(xs.begin(), xs.end());
4523}
4524#endif
4525
zhanyong.wan33605ba2010-04-22 23:37:47 +00004526// Matches an STL-style container or a native array that contains only
4527// elements matching the given value or matcher.
4528//
4529// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
4530// the messages are different.
4531//
4532// Examples:
4533// ::std::set<int> page_ids;
4534// // Each(m) matches an empty container, regardless of what m is.
4535// EXPECT_THAT(page_ids, Each(Eq(1)));
4536// EXPECT_THAT(page_ids, Each(Eq(77)));
4537//
4538// page_ids.insert(3);
4539// EXPECT_THAT(page_ids, Each(Gt(0)));
4540// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
4541// page_ids.insert(1);
4542// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
4543//
4544// ::std::map<int, size_t> page_lengths;
4545// page_lengths[1] = 100;
4546// page_lengths[2] = 200;
4547// page_lengths[3] = 300;
4548// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
4549// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
4550//
4551// const char* user_ids[] = { "joe", "mike", "tom" };
4552// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
4553template <typename M>
4554inline internal::EachMatcher<M> Each(M matcher) {
4555 return internal::EachMatcher<M>(matcher);
4556}
4557
zhanyong.wanb5937da2009-07-16 20:26:41 +00004558// Key(inner_matcher) matches an std::pair whose 'first' field matches
4559// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
4560// std::map that contains at least one element whose key is >= 5.
4561template <typename M>
4562inline internal::KeyMatcher<M> Key(M inner_matcher) {
4563 return internal::KeyMatcher<M>(inner_matcher);
4564}
4565
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00004566// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
4567// matches first_matcher and whose 'second' field matches second_matcher. For
4568// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
4569// to match a std::map<int, string> that contains exactly one element whose key
4570// is >= 5 and whose value equals "foo".
4571template <typename FirstMatcher, typename SecondMatcher>
4572inline internal::PairMatcher<FirstMatcher, SecondMatcher>
4573Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
4574 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
4575 first_matcher, second_matcher);
4576}
4577
shiqiane35fdd92008-12-10 05:08:54 +00004578// Returns a predicate that is satisfied by anything that matches the
4579// given matcher.
4580template <typename M>
4581inline internal::MatcherAsPredicate<M> Matches(M matcher) {
4582 return internal::MatcherAsPredicate<M>(matcher);
4583}
4584
zhanyong.wanb8243162009-06-04 05:48:20 +00004585// Returns true iff the value matches the matcher.
4586template <typename T, typename M>
4587inline bool Value(const T& value, M matcher) {
4588 return testing::Matches(matcher)(value);
4589}
4590
zhanyong.wan34b034c2010-03-05 21:23:23 +00004591// Matches the value against the given matcher and explains the match
4592// result to listener.
4593template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00004594inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00004595 M matcher, const T& value, MatchResultListener* listener) {
4596 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
4597}
4598
zhanyong.wan616180e2013-06-18 18:49:51 +00004599#if GTEST_LANG_CXX11
4600// Define variadic matcher versions. They are overloaded in
4601// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
4602template <typename... Args>
4603inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
4604 return internal::AllOfMatcher<Args...>(matchers...);
4605}
4606
4607template <typename... Args>
4608inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
4609 return internal::AnyOfMatcher<Args...>(matchers...);
4610}
4611
4612#endif // GTEST_LANG_CXX11
4613
zhanyong.wanbf550852009-06-09 06:09:53 +00004614// AllArgs(m) is a synonym of m. This is useful in
4615//
4616// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
4617//
4618// which is easier to read than
4619//
4620// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
4621template <typename InnerMatcher>
4622inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
4623
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05004624// Returns a matcher that matches the value of a variant<> type variable.
4625// The matcher implementation uses ADL to find the holds_alternative and get
4626// functions.
4627// It is compatible with std::variant.
4628template <typename T>
4629PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
4630 const Matcher<const T&>& matcher) {
4631 return MakePolymorphicMatcher(
4632 internal::variant_matcher::VariantMatcher<T>(matcher));
4633}
4634
shiqiane35fdd92008-12-10 05:08:54 +00004635// These macros allow using matchers to check values in Google Test
4636// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
4637// succeed iff the value matches the matcher. If the assertion fails,
4638// the value and the description of the matcher will be printed.
4639#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
4640 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4641#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
4642 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4643
4644} // namespace testing
4645
kosak6702b972015-07-27 23:05:57 +00004646// Include any custom callback matchers added by the local installation.
4647// We must include this header at the end to make sure it can use the
4648// declarations from this file.
4649#include "gmock/internal/custom/gmock-matchers.h"
shiqiane35fdd92008-12-10 05:08:54 +00004650#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_