blob: 41bf6de3b11ff04c773faa2977e82940e829f384 [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.
326 explicit Matcher(const MatcherInterface<T>* impl)
327 : internal::MatcherBase<T>(impl) {}
328
zhanyong.wan18490652009-05-11 18:54:08 +0000329 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000330 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
331 Matcher(T value); // NOLINT
332};
333
334// The following two specializations allow the user to write str
335// instead of Eq(str) and "foo" instead of Eq("foo") when a string
336// matcher is expected.
337template <>
vladlosev587c1b32011-05-20 00:42:22 +0000338class GTEST_API_ Matcher<const internal::string&>
shiqiane35fdd92008-12-10 05:08:54 +0000339 : public internal::MatcherBase<const internal::string&> {
340 public:
341 Matcher() {}
342
343 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
344 : internal::MatcherBase<const internal::string&>(impl) {}
345
346 // Allows the user to write str instead of Eq(str) sometimes, where
347 // str is a string object.
348 Matcher(const internal::string& s); // NOLINT
349
350 // Allows the user to write "foo" instead of Eq("foo") sometimes.
351 Matcher(const char* s); // NOLINT
352};
353
354template <>
vladlosev587c1b32011-05-20 00:42:22 +0000355class GTEST_API_ Matcher<internal::string>
shiqiane35fdd92008-12-10 05:08:54 +0000356 : public internal::MatcherBase<internal::string> {
357 public:
358 Matcher() {}
359
360 explicit Matcher(const MatcherInterface<internal::string>* impl)
361 : internal::MatcherBase<internal::string>(impl) {}
362
363 // Allows the user to write str instead of Eq(str) sometimes, where
364 // str is a string object.
365 Matcher(const internal::string& s); // NOLINT
366
367 // Allows the user to write "foo" instead of Eq("foo") sometimes.
368 Matcher(const char* s); // NOLINT
369};
370
zhanyong.wan1f122a02013-03-25 16:27:03 +0000371#if GTEST_HAS_STRING_PIECE_
372// The following two specializations allow the user to write str
373// instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece
374// matcher is expected.
375template <>
376class GTEST_API_ Matcher<const StringPiece&>
377 : public internal::MatcherBase<const StringPiece&> {
378 public:
379 Matcher() {}
380
381 explicit Matcher(const MatcherInterface<const StringPiece&>* impl)
382 : internal::MatcherBase<const StringPiece&>(impl) {}
383
384 // Allows the user to write str instead of Eq(str) sometimes, where
385 // str is a string object.
386 Matcher(const internal::string& s); // NOLINT
387
388 // Allows the user to write "foo" instead of Eq("foo") sometimes.
389 Matcher(const char* s); // NOLINT
390
391 // Allows the user to pass StringPieces directly.
392 Matcher(StringPiece s); // NOLINT
393};
394
395template <>
396class GTEST_API_ Matcher<StringPiece>
397 : public internal::MatcherBase<StringPiece> {
398 public:
399 Matcher() {}
400
401 explicit Matcher(const MatcherInterface<StringPiece>* impl)
402 : internal::MatcherBase<StringPiece>(impl) {}
403
404 // Allows the user to write str instead of Eq(str) sometimes, where
405 // str is a string object.
406 Matcher(const internal::string& s); // NOLINT
407
408 // Allows the user to write "foo" instead of Eq("foo") sometimes.
409 Matcher(const char* s); // NOLINT
410
411 // Allows the user to pass StringPieces directly.
412 Matcher(StringPiece s); // NOLINT
413};
414#endif // GTEST_HAS_STRING_PIECE_
415
shiqiane35fdd92008-12-10 05:08:54 +0000416// The PolymorphicMatcher class template makes it easy to implement a
417// polymorphic matcher (i.e. a matcher that can match values of more
418// than one type, e.g. Eq(n) and NotNull()).
419//
zhanyong.wandb22c222010-01-28 21:52:29 +0000420// To define a polymorphic matcher, a user should provide an Impl
421// class that has a DescribeTo() method and a DescribeNegationTo()
422// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000423//
zhanyong.wandb22c222010-01-28 21:52:29 +0000424// bool MatchAndExplain(const Value& value,
425// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000426//
427// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000428template <class Impl>
429class PolymorphicMatcher {
430 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000431 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000432
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000433 // Returns a mutable reference to the underlying matcher
434 // implementation object.
435 Impl& mutable_impl() { return impl_; }
436
437 // Returns an immutable reference to the underlying matcher
438 // implementation object.
439 const Impl& impl() const { return impl_; }
440
shiqiane35fdd92008-12-10 05:08:54 +0000441 template <typename T>
442 operator Matcher<T>() const {
443 return Matcher<T>(new MonomorphicImpl<T>(impl_));
444 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000445
shiqiane35fdd92008-12-10 05:08:54 +0000446 private:
447 template <typename T>
448 class MonomorphicImpl : public MatcherInterface<T> {
449 public:
450 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
451
shiqiane35fdd92008-12-10 05:08:54 +0000452 virtual void DescribeTo(::std::ostream* os) const {
453 impl_.DescribeTo(os);
454 }
455
456 virtual void DescribeNegationTo(::std::ostream* os) const {
457 impl_.DescribeNegationTo(os);
458 }
459
zhanyong.wan82113312010-01-08 21:55:40 +0000460 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000461 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000462 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000463
shiqiane35fdd92008-12-10 05:08:54 +0000464 private:
465 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000466
467 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000468 };
469
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000470 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000471
472 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000473};
474
475// Creates a matcher from its implementation. This is easier to use
476// than the Matcher<T> constructor as it doesn't require you to
477// explicitly write the template argument, e.g.
478//
479// MakeMatcher(foo);
480// vs
481// Matcher<const string&>(foo);
482template <typename T>
483inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
484 return Matcher<T>(impl);
zhanyong.wan2eab17b2013-03-08 17:53:24 +0000485}
shiqiane35fdd92008-12-10 05:08:54 +0000486
487// Creates a polymorphic matcher from its implementation. This is
488// easier to use than the PolymorphicMatcher<Impl> constructor as it
489// doesn't require you to explicitly write the template argument, e.g.
490//
491// MakePolymorphicMatcher(foo);
492// vs
493// PolymorphicMatcher<TypeOfFoo>(foo);
494template <class Impl>
495inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
496 return PolymorphicMatcher<Impl>(impl);
497}
498
jgm79a367e2012-04-10 16:02:11 +0000499// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
500// and MUST NOT BE USED IN USER CODE!!!
501namespace internal {
502
503// The MatcherCastImpl class template is a helper for implementing
504// MatcherCast(). We need this helper in order to partially
505// specialize the implementation of MatcherCast() (C++ allows
506// class/struct templates to be partially specialized, but not
507// function templates.).
508
509// This general version is used when MatcherCast()'s argument is a
510// polymorphic matcher (i.e. something that can be converted to a
511// Matcher but is not one yet; for example, Eq(value)) or a value (for
512// example, "hello").
513template <typename T, typename M>
514class MatcherCastImpl {
515 public:
kosak5f2a6ca2013-12-03 01:43:07 +0000516 static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
jgm79a367e2012-04-10 16:02:11 +0000517 // M can be a polymorhic matcher, in which case we want to use
518 // its conversion operator to create Matcher<T>. Or it can be a value
519 // that should be passed to the Matcher<T>'s constructor.
520 //
521 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
522 // polymorphic matcher because it'll be ambiguous if T has an implicit
523 // constructor from M (this usually happens when T has an implicit
524 // constructor from any type).
525 //
526 // It won't work to unconditionally implict_cast
527 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
528 // a user-defined conversion from M to T if one exists (assuming M is
529 // a value).
530 return CastImpl(
531 polymorphic_matcher_or_value,
532 BooleanConstant<
533 internal::ImplicitlyConvertible<M, Matcher<T> >::value>());
534 }
535
536 private:
kosak5f2a6ca2013-12-03 01:43:07 +0000537 static Matcher<T> CastImpl(const M& value, BooleanConstant<false>) {
jgm79a367e2012-04-10 16:02:11 +0000538 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
539 // matcher. It must be a value then. Use direct initialization to create
540 // a matcher.
541 return Matcher<T>(ImplicitCast_<T>(value));
542 }
543
kosak5f2a6ca2013-12-03 01:43:07 +0000544 static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
jgm79a367e2012-04-10 16:02:11 +0000545 BooleanConstant<true>) {
546 // M is implicitly convertible to Matcher<T>, which means that either
547 // M is a polymorhpic matcher or Matcher<T> has an implicit constructor
548 // from M. In both cases using the implicit conversion will produce a
549 // matcher.
550 //
551 // Even if T has an implicit constructor from M, it won't be called because
552 // creating Matcher<T> would require a chain of two user-defined conversions
553 // (first to create T from M and then to create Matcher<T> from T).
554 return polymorphic_matcher_or_value;
555 }
556};
557
558// This more specialized version is used when MatcherCast()'s argument
559// is already a Matcher. This only compiles when type T can be
560// statically converted to type U.
561template <typename T, typename U>
562class MatcherCastImpl<T, Matcher<U> > {
563 public:
564 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
565 return Matcher<T>(new Impl(source_matcher));
566 }
567
568 private:
569 class Impl : public MatcherInterface<T> {
570 public:
571 explicit Impl(const Matcher<U>& source_matcher)
572 : source_matcher_(source_matcher) {}
573
574 // We delegate the matching logic to the source matcher.
575 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
576 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
577 }
578
579 virtual void DescribeTo(::std::ostream* os) const {
580 source_matcher_.DescribeTo(os);
581 }
582
583 virtual void DescribeNegationTo(::std::ostream* os) const {
584 source_matcher_.DescribeNegationTo(os);
585 }
586
587 private:
588 const Matcher<U> source_matcher_;
589
590 GTEST_DISALLOW_ASSIGN_(Impl);
591 };
592};
593
594// This even more specialized version is used for efficiently casting
595// a matcher to its own type.
596template <typename T>
597class MatcherCastImpl<T, Matcher<T> > {
598 public:
599 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
600};
601
602} // namespace internal
603
shiqiane35fdd92008-12-10 05:08:54 +0000604// In order to be safe and clear, casting between different matcher
605// types is done explicitly via MatcherCast<T>(m), which takes a
606// matcher m and returns a Matcher<T>. It compiles only when T can be
607// statically converted to the argument type of m.
608template <typename T, typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000609inline Matcher<T> MatcherCast(const M& matcher) {
jgm79a367e2012-04-10 16:02:11 +0000610 return internal::MatcherCastImpl<T, M>::Cast(matcher);
611}
shiqiane35fdd92008-12-10 05:08:54 +0000612
zhanyong.wan18490652009-05-11 18:54:08 +0000613// Implements SafeMatcherCast().
614//
zhanyong.wan95b12332009-09-25 18:55:50 +0000615// We use an intermediate class to do the actual safe casting as Nokia's
616// Symbian compiler cannot decide between
617// template <T, M> ... (M) and
618// template <T, U> ... (const Matcher<U>&)
619// for function templates but can for member function templates.
620template <typename T>
621class SafeMatcherCastImpl {
622 public:
jgm79a367e2012-04-10 16:02:11 +0000623 // This overload handles polymorphic matchers and values only since
624 // monomorphic matchers are handled by the next one.
zhanyong.wan95b12332009-09-25 18:55:50 +0000625 template <typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000626 static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
jgm79a367e2012-04-10 16:02:11 +0000627 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
zhanyong.wan95b12332009-09-25 18:55:50 +0000628 }
zhanyong.wan18490652009-05-11 18:54:08 +0000629
zhanyong.wan95b12332009-09-25 18:55:50 +0000630 // This overload handles monomorphic matchers.
631 //
632 // In general, if type T can be implicitly converted to type U, we can
633 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
634 // contravariant): just keep a copy of the original Matcher<U>, convert the
635 // argument from type T to U, and then pass it to the underlying Matcher<U>.
636 // The only exception is when U is a reference and T is not, as the
637 // underlying Matcher<U> may be interested in the argument's address, which
638 // is not preserved in the conversion from T to U.
639 template <typename U>
640 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
641 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000642 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000643 T_must_be_implicitly_convertible_to_U);
644 // Enforce that we are not converting a non-reference type T to a reference
645 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000646 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000647 internal::is_reference<T>::value || !internal::is_reference<U>::value,
Hector Dearman24054ff2017-06-19 18:27:33 +0100648 cannot_convert_non_reference_arg_to_reference);
zhanyong.wan95b12332009-09-25 18:55:50 +0000649 // In case both T and U are arithmetic types, enforce that the
650 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000651 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
652 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000653 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
654 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000655 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000656 kTIsOther || kUIsOther ||
657 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
658 conversion_of_arithmetic_types_must_be_lossless);
659 return MatcherCast<T>(matcher);
660 }
661};
662
663template <typename T, typename M>
664inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
665 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000666}
667
shiqiane35fdd92008-12-10 05:08:54 +0000668// A<T>() returns a matcher that matches any value of type T.
669template <typename T>
670Matcher<T> A();
671
672// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
673// and MUST NOT BE USED IN USER CODE!!!
674namespace internal {
675
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000676// If the explanation is not empty, prints it to the ostream.
Nico Weber09fd5b32017-05-15 17:07:03 -0400677inline void PrintIfNotEmpty(const std::string& explanation,
zhanyong.wanfb25d532013-07-28 08:24:00 +0000678 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000679 if (explanation != "" && os != NULL) {
680 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000681 }
682}
683
zhanyong.wan736baa82010-09-27 17:44:16 +0000684// Returns true if the given type name is easy to read by a human.
685// This is used to decide whether printing the type of a value might
686// be helpful.
Nico Weber09fd5b32017-05-15 17:07:03 -0400687inline bool IsReadableTypeName(const std::string& type_name) {
zhanyong.wan736baa82010-09-27 17:44:16 +0000688 // We consider a type name readable if it's short or doesn't contain
689 // a template or function type.
690 return (type_name.length() <= 20 ||
Nico Weber09fd5b32017-05-15 17:07:03 -0400691 type_name.find_first_of("<(") == std::string::npos);
zhanyong.wan736baa82010-09-27 17:44:16 +0000692}
693
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000694// Matches the value against the given matcher, prints the value and explains
695// the match result to the listener. Returns the match result.
696// 'listener' must not be NULL.
697// Value cannot be passed by const reference, because some matchers take a
698// non-const argument.
699template <typename Value, typename T>
700bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
701 MatchResultListener* listener) {
702 if (!listener->IsInterested()) {
703 // If the listener is not interested, we do not need to construct the
704 // inner explanation.
705 return matcher.Matches(value);
706 }
707
708 StringMatchResultListener inner_listener;
709 const bool match = matcher.MatchAndExplain(value, &inner_listener);
710
711 UniversalPrint(value, listener->stream());
zhanyong.wan736baa82010-09-27 17:44:16 +0000712#if GTEST_HAS_RTTI
Nico Weber09fd5b32017-05-15 17:07:03 -0400713 const std::string& type_name = GetTypeName<Value>();
zhanyong.wan736baa82010-09-27 17:44:16 +0000714 if (IsReadableTypeName(type_name))
715 *listener->stream() << " (of type " << type_name << ")";
716#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000717 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000718
719 return match;
720}
721
shiqiane35fdd92008-12-10 05:08:54 +0000722// An internal helper class for doing compile-time loop on a tuple's
723// fields.
724template <size_t N>
725class TuplePrefix {
726 public:
727 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
728 // iff the first N fields of matcher_tuple matches the first N
729 // fields of value_tuple, respectively.
730 template <typename MatcherTuple, typename ValueTuple>
731 static bool Matches(const MatcherTuple& matcher_tuple,
732 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000733 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
734 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
735 }
736
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000737 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000738 // describes failures in matching the first N fields of matchers
739 // against the first N fields of values. If there is no failure,
740 // nothing will be streamed to os.
741 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000742 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
743 const ValueTuple& values,
744 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000745 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000746 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000747
748 // Then describes the failure (if any) in the (N - 1)-th (0-based)
749 // field.
750 typename tuple_element<N - 1, MatcherTuple>::type matcher =
751 get<N - 1>(matchers);
752 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
753 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000754 StringMatchResultListener listener;
755 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000756 // TODO(wan): include in the message the name of the parameter
757 // as used in MOCK_METHOD*() when possible.
758 *os << " Expected arg #" << N - 1 << ": ";
759 get<N - 1>(matchers).DescribeTo(os);
760 *os << "\n Actual: ";
761 // We remove the reference in type Value to prevent the
762 // universal printer from printing the address of value, which
763 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000764 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000765 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000766 internal::UniversalPrint(value, os);
767 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000768 *os << "\n";
769 }
770 }
771};
772
773// The base case.
774template <>
775class TuplePrefix<0> {
776 public:
777 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000778 static bool Matches(const MatcherTuple& /* matcher_tuple */,
779 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000780 return true;
781 }
782
783 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000784 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
785 const ValueTuple& /* values */,
786 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000787};
788
789// TupleMatches(matcher_tuple, value_tuple) returns true iff all
790// matchers in matcher_tuple match the corresponding fields in
791// value_tuple. It is a compiler error if matcher_tuple and
792// value_tuple have different number of fields or incompatible field
793// types.
794template <typename MatcherTuple, typename ValueTuple>
795bool TupleMatches(const MatcherTuple& matcher_tuple,
796 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000797 // Makes sure that matcher_tuple and value_tuple have the same
798 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000799 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000800 tuple_size<ValueTuple>::value,
801 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000802 return TuplePrefix<tuple_size<ValueTuple>::value>::
803 Matches(matcher_tuple, value_tuple);
804}
805
806// Describes failures in matching matchers against values. If there
807// is no failure, nothing will be streamed to os.
808template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000809void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
810 const ValueTuple& values,
811 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000812 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000813 matchers, values, os);
814}
815
zhanyong.wanfb25d532013-07-28 08:24:00 +0000816// TransformTupleValues and its helper.
817//
818// TransformTupleValuesHelper hides the internal machinery that
819// TransformTupleValues uses to implement a tuple traversal.
820template <typename Tuple, typename Func, typename OutIter>
821class TransformTupleValuesHelper {
822 private:
kosakbd018832014-04-02 20:30:00 +0000823 typedef ::testing::tuple_size<Tuple> TupleSize;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000824
825 public:
826 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
827 // Returns the final value of 'out' in case the caller needs it.
828 static OutIter Run(Func f, const Tuple& t, OutIter out) {
829 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
830 }
831
832 private:
833 template <typename Tup, size_t kRemainingSize>
834 struct IterateOverTuple {
835 OutIter operator() (Func f, const Tup& t, OutIter out) const {
kosakbd018832014-04-02 20:30:00 +0000836 *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
zhanyong.wanfb25d532013-07-28 08:24:00 +0000837 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
838 }
839 };
840 template <typename Tup>
841 struct IterateOverTuple<Tup, 0> {
842 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
843 return out;
844 }
845 };
846};
847
848// Successively invokes 'f(element)' on each element of the tuple 't',
849// appending each result to the 'out' iterator. Returns the final value
850// of 'out'.
851template <typename Tuple, typename Func, typename OutIter>
852OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
853 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
854}
855
shiqiane35fdd92008-12-10 05:08:54 +0000856// Implements A<T>().
857template <typename T>
858class AnyMatcherImpl : public MatcherInterface<T> {
859 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000860 virtual bool MatchAndExplain(
861 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000862 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
863 virtual void DescribeNegationTo(::std::ostream* os) const {
864 // This is mostly for completeness' safe, as it's not very useful
865 // to write Not(A<bool>()). However we cannot completely rule out
866 // such a possibility, and it doesn't hurt to be prepared.
867 *os << "never matches";
868 }
869};
870
871// Implements _, a matcher that matches any value of any
872// type. This is a polymorphic matcher, so we need a template type
873// conversion operator to make it appearing as a Matcher<T> for any
874// type T.
875class AnythingMatcher {
876 public:
877 template <typename T>
878 operator Matcher<T>() const { return A<T>(); }
879};
880
881// Implements a matcher that compares a given value with a
882// pre-supplied value using one of the ==, <=, <, etc, operators. The
883// two values being compared don't have to have the same type.
884//
885// The matcher defined here is polymorphic (for example, Eq(5) can be
886// used to match an int, a short, a double, etc). Therefore we use
887// a template type conversion operator in the implementation.
888//
shiqiane35fdd92008-12-10 05:08:54 +0000889// The following template definition assumes that the Rhs parameter is
890// a "bare" type (i.e. neither 'const T' nor 'T&').
kosak506340a2014-11-17 01:47:54 +0000891template <typename D, typename Rhs, typename Op>
892class ComparisonBase {
893 public:
894 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
895 template <typename Lhs>
896 operator Matcher<Lhs>() const {
897 return MakeMatcher(new Impl<Lhs>(rhs_));
shiqiane35fdd92008-12-10 05:08:54 +0000898 }
899
kosak506340a2014-11-17 01:47:54 +0000900 private:
901 template <typename Lhs>
902 class Impl : public MatcherInterface<Lhs> {
903 public:
904 explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
905 virtual bool MatchAndExplain(
906 Lhs lhs, MatchResultListener* /* listener */) const {
907 return Op()(lhs, rhs_);
908 }
909 virtual void DescribeTo(::std::ostream* os) const {
910 *os << D::Desc() << " ";
911 UniversalPrint(rhs_, os);
912 }
913 virtual void DescribeNegationTo(::std::ostream* os) const {
914 *os << D::NegatedDesc() << " ";
915 UniversalPrint(rhs_, os);
916 }
917 private:
918 Rhs rhs_;
919 GTEST_DISALLOW_ASSIGN_(Impl);
920 };
921 Rhs rhs_;
922 GTEST_DISALLOW_ASSIGN_(ComparisonBase);
923};
shiqiane35fdd92008-12-10 05:08:54 +0000924
kosak506340a2014-11-17 01:47:54 +0000925template <typename Rhs>
926class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
927 public:
928 explicit EqMatcher(const Rhs& rhs)
929 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
930 static const char* Desc() { return "is equal to"; }
931 static const char* NegatedDesc() { return "isn't equal to"; }
932};
933template <typename Rhs>
934class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
935 public:
936 explicit NeMatcher(const Rhs& rhs)
937 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
938 static const char* Desc() { return "isn't equal to"; }
939 static const char* NegatedDesc() { return "is equal to"; }
940};
941template <typename Rhs>
942class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
943 public:
944 explicit LtMatcher(const Rhs& rhs)
945 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
946 static const char* Desc() { return "is <"; }
947 static const char* NegatedDesc() { return "isn't <"; }
948};
949template <typename Rhs>
950class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
951 public:
952 explicit GtMatcher(const Rhs& rhs)
953 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
954 static const char* Desc() { return "is >"; }
955 static const char* NegatedDesc() { return "isn't >"; }
956};
957template <typename Rhs>
958class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
959 public:
960 explicit LeMatcher(const Rhs& rhs)
961 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
962 static const char* Desc() { return "is <="; }
963 static const char* NegatedDesc() { return "isn't <="; }
964};
965template <typename Rhs>
966class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
967 public:
968 explicit GeMatcher(const Rhs& rhs)
969 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
970 static const char* Desc() { return "is >="; }
971 static const char* NegatedDesc() { return "isn't >="; }
972};
shiqiane35fdd92008-12-10 05:08:54 +0000973
vladlosev79b83502009-11-18 00:43:37 +0000974// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000975// pointer that is NULL.
976class IsNullMatcher {
977 public:
vladlosev79b83502009-11-18 00:43:37 +0000978 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000979 bool MatchAndExplain(const Pointer& p,
980 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +0000981#if GTEST_LANG_CXX11
982 return p == nullptr;
983#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +0000984 return GetRawPointer(p) == NULL;
kosak6305ff52015-04-28 22:36:31 +0000985#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +0000986 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000987
988 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
989 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000990 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000991 }
992};
993
vladlosev79b83502009-11-18 00:43:37 +0000994// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000995// pointer that is not NULL.
996class NotNullMatcher {
997 public:
vladlosev79b83502009-11-18 00:43:37 +0000998 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000999 bool MatchAndExplain(const Pointer& p,
1000 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001001#if GTEST_LANG_CXX11
1002 return p != nullptr;
1003#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001004 return GetRawPointer(p) != NULL;
kosak6305ff52015-04-28 22:36:31 +00001005#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001006 }
shiqiane35fdd92008-12-10 05:08:54 +00001007
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001008 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +00001009 void DescribeNegationTo(::std::ostream* os) const {
1010 *os << "is NULL";
1011 }
1012};
1013
1014// Ref(variable) matches any argument that is a reference to
1015// 'variable'. This matcher is polymorphic as it can match any
1016// super type of the type of 'variable'.
1017//
1018// The RefMatcher template class implements Ref(variable). It can
1019// only be instantiated with a reference type. This prevents a user
1020// from mistakenly using Ref(x) to match a non-reference function
1021// argument. For example, the following will righteously cause a
1022// compiler error:
1023//
1024// int n;
1025// Matcher<int> m1 = Ref(n); // This won't compile.
1026// Matcher<int&> m2 = Ref(n); // This will compile.
1027template <typename T>
1028class RefMatcher;
1029
1030template <typename T>
1031class RefMatcher<T&> {
1032 // Google Mock is a generic framework and thus needs to support
1033 // mocking any function types, including those that take non-const
1034 // reference arguments. Therefore the template parameter T (and
1035 // Super below) can be instantiated to either a const type or a
1036 // non-const type.
1037 public:
1038 // RefMatcher() takes a T& instead of const T&, as we want the
1039 // compiler to catch using Ref(const_value) as a matcher for a
1040 // non-const reference.
1041 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
1042
1043 template <typename Super>
1044 operator Matcher<Super&>() const {
1045 // By passing object_ (type T&) to Impl(), which expects a Super&,
1046 // we make sure that Super is a super type of T. In particular,
1047 // this catches using Ref(const_value) as a matcher for a
1048 // non-const reference, as you cannot implicitly convert a const
1049 // reference to a non-const reference.
1050 return MakeMatcher(new Impl<Super>(object_));
1051 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001052
shiqiane35fdd92008-12-10 05:08:54 +00001053 private:
1054 template <typename Super>
1055 class Impl : public MatcherInterface<Super&> {
1056 public:
1057 explicit Impl(Super& x) : object_(x) {} // NOLINT
1058
zhanyong.wandb22c222010-01-28 21:52:29 +00001059 // MatchAndExplain() takes a Super& (as opposed to const Super&)
1060 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +00001061 virtual bool MatchAndExplain(
1062 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001063 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +00001064 return &x == &object_;
1065 }
shiqiane35fdd92008-12-10 05:08:54 +00001066
1067 virtual void DescribeTo(::std::ostream* os) const {
1068 *os << "references the variable ";
1069 UniversalPrinter<Super&>::Print(object_, os);
1070 }
1071
1072 virtual void DescribeNegationTo(::std::ostream* os) const {
1073 *os << "does not reference the variable ";
1074 UniversalPrinter<Super&>::Print(object_, os);
1075 }
1076
shiqiane35fdd92008-12-10 05:08:54 +00001077 private:
1078 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001079
1080 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001081 };
1082
1083 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001084
1085 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001086};
1087
1088// Polymorphic helper functions for narrow and wide string matchers.
1089inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1090 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1091}
1092
1093inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1094 const wchar_t* rhs) {
1095 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1096}
1097
1098// String comparison for narrow or wide strings that can have embedded NUL
1099// characters.
1100template <typename StringType>
1101bool CaseInsensitiveStringEquals(const StringType& s1,
1102 const StringType& s2) {
1103 // Are the heads equal?
1104 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1105 return false;
1106 }
1107
1108 // Skip the equal heads.
1109 const typename StringType::value_type nul = 0;
1110 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1111
1112 // Are we at the end of either s1 or s2?
1113 if (i1 == StringType::npos || i2 == StringType::npos) {
1114 return i1 == i2;
1115 }
1116
1117 // Are the tails equal?
1118 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1119}
1120
1121// String matchers.
1122
1123// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1124template <typename StringType>
1125class StrEqualityMatcher {
1126 public:
shiqiane35fdd92008-12-10 05:08:54 +00001127 StrEqualityMatcher(const StringType& str, bool expect_eq,
1128 bool case_sensitive)
1129 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1130
jgm38513a82012-11-15 15:50:36 +00001131 // Accepts pointer types, particularly:
1132 // const char*
1133 // char*
1134 // const wchar_t*
1135 // wchar_t*
1136 template <typename CharType>
1137 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001138 if (s == NULL) {
1139 return !expect_eq_;
1140 }
zhanyong.wandb22c222010-01-28 21:52:29 +00001141 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001142 }
1143
jgm38513a82012-11-15 15:50:36 +00001144 // Matches anything that can convert to StringType.
1145 //
1146 // This is a template, not just a plain function with const StringType&,
1147 // because StringPiece has some interfering non-explicit constructors.
1148 template <typename MatcheeStringType>
1149 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001150 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001151 const StringType& s2(s);
1152 const bool eq = case_sensitive_ ? s2 == string_ :
1153 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +00001154 return expect_eq_ == eq;
1155 }
1156
1157 void DescribeTo(::std::ostream* os) const {
1158 DescribeToHelper(expect_eq_, os);
1159 }
1160
1161 void DescribeNegationTo(::std::ostream* os) const {
1162 DescribeToHelper(!expect_eq_, os);
1163 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001164
shiqiane35fdd92008-12-10 05:08:54 +00001165 private:
1166 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001167 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +00001168 *os << "equal to ";
1169 if (!case_sensitive_) {
1170 *os << "(ignoring case) ";
1171 }
vladloseve2e8ba42010-05-13 18:16:03 +00001172 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001173 }
1174
1175 const StringType string_;
1176 const bool expect_eq_;
1177 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001178
1179 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001180};
1181
1182// Implements the polymorphic HasSubstr(substring) matcher, which
1183// can be used as a Matcher<T> as long as T can be converted to a
1184// string.
1185template <typename StringType>
1186class HasSubstrMatcher {
1187 public:
shiqiane35fdd92008-12-10 05:08:54 +00001188 explicit HasSubstrMatcher(const StringType& substring)
1189 : substring_(substring) {}
1190
jgm38513a82012-11-15 15:50:36 +00001191 // Accepts pointer types, particularly:
1192 // const char*
1193 // char*
1194 // const wchar_t*
1195 // wchar_t*
1196 template <typename CharType>
1197 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001198 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001199 }
1200
jgm38513a82012-11-15 15:50:36 +00001201 // Matches anything that can convert to StringType.
1202 //
1203 // This is a template, not just a plain function with const StringType&,
1204 // because StringPiece has some interfering non-explicit constructors.
1205 template <typename MatcheeStringType>
1206 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001207 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001208 const StringType& s2(s);
1209 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001210 }
1211
1212 // Describes what this matcher matches.
1213 void DescribeTo(::std::ostream* os) const {
1214 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001215 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001216 }
1217
1218 void DescribeNegationTo(::std::ostream* os) const {
1219 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001220 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001221 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001222
shiqiane35fdd92008-12-10 05:08:54 +00001223 private:
1224 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001225
1226 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001227};
1228
1229// Implements the polymorphic StartsWith(substring) matcher, which
1230// can be used as a Matcher<T> as long as T can be converted to a
1231// string.
1232template <typename StringType>
1233class StartsWithMatcher {
1234 public:
shiqiane35fdd92008-12-10 05:08:54 +00001235 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1236 }
1237
jgm38513a82012-11-15 15:50:36 +00001238 // Accepts pointer types, particularly:
1239 // const char*
1240 // char*
1241 // const wchar_t*
1242 // wchar_t*
1243 template <typename CharType>
1244 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001245 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001246 }
1247
jgm38513a82012-11-15 15:50:36 +00001248 // Matches anything that can convert to StringType.
1249 //
1250 // This is a template, not just a plain function with const StringType&,
1251 // because StringPiece has some interfering non-explicit constructors.
1252 template <typename MatcheeStringType>
1253 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001254 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001255 const StringType& s2(s);
1256 return s2.length() >= prefix_.length() &&
1257 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001258 }
1259
1260 void DescribeTo(::std::ostream* os) const {
1261 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001262 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001263 }
1264
1265 void DescribeNegationTo(::std::ostream* os) const {
1266 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001267 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001268 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001269
shiqiane35fdd92008-12-10 05:08:54 +00001270 private:
1271 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001272
1273 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001274};
1275
1276// Implements the polymorphic EndsWith(substring) matcher, which
1277// can be used as a Matcher<T> as long as T can be converted to a
1278// string.
1279template <typename StringType>
1280class EndsWithMatcher {
1281 public:
shiqiane35fdd92008-12-10 05:08:54 +00001282 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1283
jgm38513a82012-11-15 15:50:36 +00001284 // Accepts pointer types, particularly:
1285 // const char*
1286 // char*
1287 // const wchar_t*
1288 // wchar_t*
1289 template <typename CharType>
1290 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001291 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001292 }
1293
jgm38513a82012-11-15 15:50:36 +00001294 // Matches anything that can convert to StringType.
1295 //
1296 // This is a template, not just a plain function with const StringType&,
1297 // because StringPiece has some interfering non-explicit constructors.
1298 template <typename MatcheeStringType>
1299 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001300 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001301 const StringType& s2(s);
1302 return s2.length() >= suffix_.length() &&
1303 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001304 }
1305
1306 void DescribeTo(::std::ostream* os) const {
1307 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001308 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001309 }
1310
1311 void DescribeNegationTo(::std::ostream* os) const {
1312 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001313 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001314 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001315
shiqiane35fdd92008-12-10 05:08:54 +00001316 private:
1317 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001318
1319 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001320};
1321
shiqiane35fdd92008-12-10 05:08:54 +00001322// Implements polymorphic matchers MatchesRegex(regex) and
1323// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1324// T can be converted to a string.
1325class MatchesRegexMatcher {
1326 public:
1327 MatchesRegexMatcher(const RE* regex, bool full_match)
1328 : regex_(regex), full_match_(full_match) {}
1329
jgm38513a82012-11-15 15:50:36 +00001330 // Accepts pointer types, particularly:
1331 // const char*
1332 // char*
1333 // const wchar_t*
1334 // wchar_t*
1335 template <typename CharType>
1336 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001337 return s != NULL && MatchAndExplain(std::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001338 }
1339
Nico Weber09fd5b32017-05-15 17:07:03 -04001340 // Matches anything that can convert to std::string.
jgm38513a82012-11-15 15:50:36 +00001341 //
Nico Weber09fd5b32017-05-15 17:07:03 -04001342 // This is a template, not just a plain function with const std::string&,
jgm38513a82012-11-15 15:50:36 +00001343 // because StringPiece has some interfering non-explicit constructors.
1344 template <class MatcheeStringType>
1345 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001346 MatchResultListener* /* listener */) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001347 const std::string& s2(s);
jgm38513a82012-11-15 15:50:36 +00001348 return full_match_ ? RE::FullMatch(s2, *regex_) :
1349 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001350 }
1351
1352 void DescribeTo(::std::ostream* os) const {
1353 *os << (full_match_ ? "matches" : "contains")
1354 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001355 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001356 }
1357
1358 void DescribeNegationTo(::std::ostream* os) const {
1359 *os << "doesn't " << (full_match_ ? "match" : "contain")
1360 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001361 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001362 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001363
shiqiane35fdd92008-12-10 05:08:54 +00001364 private:
1365 const internal::linked_ptr<const RE> regex_;
1366 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001367
1368 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001369};
1370
shiqiane35fdd92008-12-10 05:08:54 +00001371// Implements a matcher that compares the two fields of a 2-tuple
1372// using one of the ==, <=, <, etc, operators. The two fields being
1373// compared don't have to have the same type.
1374//
1375// The matcher defined here is polymorphic (for example, Eq() can be
1376// used to match a tuple<int, short>, a tuple<const long&, double>,
1377// etc). Therefore we use a template type conversion operator in the
1378// implementation.
kosak506340a2014-11-17 01:47:54 +00001379template <typename D, typename Op>
1380class PairMatchBase {
1381 public:
1382 template <typename T1, typename T2>
1383 operator Matcher< ::testing::tuple<T1, T2> >() const {
1384 return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >);
1385 }
1386 template <typename T1, typename T2>
1387 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
1388 return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>);
shiqiane35fdd92008-12-10 05:08:54 +00001389 }
1390
kosak506340a2014-11-17 01:47:54 +00001391 private:
1392 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
1393 return os << D::Desc();
1394 }
shiqiane35fdd92008-12-10 05:08:54 +00001395
kosak506340a2014-11-17 01:47:54 +00001396 template <typename Tuple>
1397 class Impl : public MatcherInterface<Tuple> {
1398 public:
1399 virtual bool MatchAndExplain(
1400 Tuple args,
1401 MatchResultListener* /* listener */) const {
1402 return Op()(::testing::get<0>(args), ::testing::get<1>(args));
1403 }
1404 virtual void DescribeTo(::std::ostream* os) const {
1405 *os << "are " << GetDesc;
1406 }
1407 virtual void DescribeNegationTo(::std::ostream* os) const {
1408 *os << "aren't " << GetDesc;
1409 }
1410 };
1411};
1412
1413class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
1414 public:
1415 static const char* Desc() { return "an equal pair"; }
1416};
1417class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
1418 public:
1419 static const char* Desc() { return "an unequal pair"; }
1420};
1421class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
1422 public:
1423 static const char* Desc() { return "a pair where the first < the second"; }
1424};
1425class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
1426 public:
1427 static const char* Desc() { return "a pair where the first > the second"; }
1428};
1429class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
1430 public:
1431 static const char* Desc() { return "a pair where the first <= the second"; }
1432};
1433class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
1434 public:
1435 static const char* Desc() { return "a pair where the first >= the second"; }
1436};
shiqiane35fdd92008-12-10 05:08:54 +00001437
zhanyong.wanc6a41232009-05-13 23:38:40 +00001438// Implements the Not(...) matcher for a particular argument type T.
1439// We do not nest it inside the NotMatcher class template, as that
1440// will prevent different instantiations of NotMatcher from sharing
1441// the same NotMatcherImpl<T> class.
1442template <typename T>
1443class NotMatcherImpl : public MatcherInterface<T> {
1444 public:
1445 explicit NotMatcherImpl(const Matcher<T>& matcher)
1446 : matcher_(matcher) {}
1447
zhanyong.wan82113312010-01-08 21:55:40 +00001448 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1449 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001450 }
1451
1452 virtual void DescribeTo(::std::ostream* os) const {
1453 matcher_.DescribeNegationTo(os);
1454 }
1455
1456 virtual void DescribeNegationTo(::std::ostream* os) const {
1457 matcher_.DescribeTo(os);
1458 }
1459
zhanyong.wanc6a41232009-05-13 23:38:40 +00001460 private:
1461 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001462
1463 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001464};
1465
shiqiane35fdd92008-12-10 05:08:54 +00001466// Implements the Not(m) matcher, which matches a value that doesn't
1467// match matcher m.
1468template <typename InnerMatcher>
1469class NotMatcher {
1470 public:
1471 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1472
1473 // This template type conversion operator allows Not(m) to be used
1474 // to match any type m can match.
1475 template <typename T>
1476 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001477 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001478 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001479
shiqiane35fdd92008-12-10 05:08:54 +00001480 private:
shiqiane35fdd92008-12-10 05:08:54 +00001481 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001482
1483 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001484};
1485
zhanyong.wanc6a41232009-05-13 23:38:40 +00001486// Implements the AllOf(m1, m2) matcher for a particular argument type
1487// T. We do not nest it inside the BothOfMatcher class template, as
1488// that will prevent different instantiations of BothOfMatcher from
1489// sharing the same BothOfMatcherImpl<T> class.
1490template <typename T>
1491class BothOfMatcherImpl : public MatcherInterface<T> {
1492 public:
1493 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1494 : matcher1_(matcher1), matcher2_(matcher2) {}
1495
zhanyong.wanc6a41232009-05-13 23:38:40 +00001496 virtual void DescribeTo(::std::ostream* os) const {
1497 *os << "(";
1498 matcher1_.DescribeTo(os);
1499 *os << ") and (";
1500 matcher2_.DescribeTo(os);
1501 *os << ")";
1502 }
1503
1504 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001505 *os << "(";
1506 matcher1_.DescribeNegationTo(os);
1507 *os << ") or (";
1508 matcher2_.DescribeNegationTo(os);
1509 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001510 }
1511
zhanyong.wan82113312010-01-08 21:55:40 +00001512 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1513 // If either matcher1_ or matcher2_ doesn't match x, we only need
1514 // to explain why one of them fails.
1515 StringMatchResultListener listener1;
1516 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1517 *listener << listener1.str();
1518 return false;
1519 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001520
zhanyong.wan82113312010-01-08 21:55:40 +00001521 StringMatchResultListener listener2;
1522 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1523 *listener << listener2.str();
1524 return false;
1525 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001526
zhanyong.wan82113312010-01-08 21:55:40 +00001527 // Otherwise we need to explain why *both* of them match.
Nico Weber09fd5b32017-05-15 17:07:03 -04001528 const std::string s1 = listener1.str();
1529 const std::string s2 = listener2.str();
zhanyong.wan82113312010-01-08 21:55:40 +00001530
1531 if (s1 == "") {
1532 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001533 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001534 *listener << s1;
1535 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001536 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001537 }
1538 }
zhanyong.wan82113312010-01-08 21:55:40 +00001539 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001540 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001541
zhanyong.wanc6a41232009-05-13 23:38:40 +00001542 private:
1543 const Matcher<T> matcher1_;
1544 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001545
1546 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001547};
1548
zhanyong.wan616180e2013-06-18 18:49:51 +00001549#if GTEST_LANG_CXX11
1550// MatcherList provides mechanisms for storing a variable number of matchers in
1551// a list structure (ListType) and creating a combining matcher from such a
1552// list.
1553// The template is defined recursively using the following template paramters:
1554// * kSize is the length of the MatcherList.
1555// * Head is the type of the first matcher of the list.
1556// * Tail denotes the types of the remaining matchers of the list.
1557template <int kSize, typename Head, typename... Tail>
1558struct MatcherList {
1559 typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
zhanyong.wan29897032013-06-20 18:59:15 +00001560 typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001561
1562 // BuildList stores variadic type values in a nested pair structure.
1563 // Example:
1564 // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
1565 // the corresponding result of type pair<int, pair<string, float>>.
1566 static ListType BuildList(const Head& matcher, const Tail&... tail) {
1567 return ListType(matcher, MatcherListTail::BuildList(tail...));
1568 }
1569
1570 // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
1571 // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
1572 // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
1573 // constructor taking two Matcher<T>s as input.
1574 template <typename T, template <typename /* T */> class CombiningMatcher>
1575 static Matcher<T> CreateMatcher(const ListType& matchers) {
1576 return Matcher<T>(new CombiningMatcher<T>(
1577 SafeMatcherCast<T>(matchers.first),
1578 MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
1579 matchers.second)));
1580 }
1581};
1582
1583// The following defines the base case for the recursive definition of
1584// MatcherList.
1585template <typename Matcher1, typename Matcher2>
1586struct MatcherList<2, Matcher1, Matcher2> {
zhanyong.wan29897032013-06-20 18:59:15 +00001587 typedef ::std::pair<Matcher1, Matcher2> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001588
1589 static ListType BuildList(const Matcher1& matcher1,
1590 const Matcher2& matcher2) {
zhanyong.wan29897032013-06-20 18:59:15 +00001591 return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
zhanyong.wan616180e2013-06-18 18:49:51 +00001592 }
1593
1594 template <typename T, template <typename /* T */> class CombiningMatcher>
1595 static Matcher<T> CreateMatcher(const ListType& matchers) {
1596 return Matcher<T>(new CombiningMatcher<T>(
1597 SafeMatcherCast<T>(matchers.first),
1598 SafeMatcherCast<T>(matchers.second)));
1599 }
1600};
1601
1602// VariadicMatcher is used for the variadic implementation of
1603// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1604// CombiningMatcher<T> is used to recursively combine the provided matchers
1605// (of type Args...).
1606template <template <typename T> class CombiningMatcher, typename... Args>
1607class VariadicMatcher {
1608 public:
1609 VariadicMatcher(const Args&... matchers) // NOLINT
1610 : matchers_(MatcherListType::BuildList(matchers...)) {}
1611
1612 // This template type conversion operator allows an
1613 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1614 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1615 template <typename T>
1616 operator Matcher<T>() const {
1617 return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
1618 matchers_);
1619 }
1620
1621 private:
1622 typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
1623
1624 const typename MatcherListType::ListType matchers_;
1625
1626 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1627};
1628
1629template <typename... Args>
1630using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
1631
1632#endif // GTEST_LANG_CXX11
1633
shiqiane35fdd92008-12-10 05:08:54 +00001634// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1635// matches a value that matches all of the matchers m_1, ..., and m_n.
1636template <typename Matcher1, typename Matcher2>
1637class BothOfMatcher {
1638 public:
1639 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1640 : matcher1_(matcher1), matcher2_(matcher2) {}
1641
1642 // This template type conversion operator allows a
1643 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1644 // both Matcher1 and Matcher2 can match.
1645 template <typename T>
1646 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001647 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1648 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001649 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001650
shiqiane35fdd92008-12-10 05:08:54 +00001651 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001652 Matcher1 matcher1_;
1653 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001654
1655 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001656};
shiqiane35fdd92008-12-10 05:08:54 +00001657
zhanyong.wanc6a41232009-05-13 23:38:40 +00001658// Implements the AnyOf(m1, m2) matcher for a particular argument type
1659// T. We do not nest it inside the AnyOfMatcher class template, as
1660// that will prevent different instantiations of AnyOfMatcher from
1661// sharing the same EitherOfMatcherImpl<T> class.
1662template <typename T>
1663class EitherOfMatcherImpl : public MatcherInterface<T> {
1664 public:
1665 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1666 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001667
zhanyong.wanc6a41232009-05-13 23:38:40 +00001668 virtual void DescribeTo(::std::ostream* os) const {
1669 *os << "(";
1670 matcher1_.DescribeTo(os);
1671 *os << ") or (";
1672 matcher2_.DescribeTo(os);
1673 *os << ")";
1674 }
shiqiane35fdd92008-12-10 05:08:54 +00001675
zhanyong.wanc6a41232009-05-13 23:38:40 +00001676 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001677 *os << "(";
1678 matcher1_.DescribeNegationTo(os);
1679 *os << ") and (";
1680 matcher2_.DescribeNegationTo(os);
1681 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001682 }
shiqiane35fdd92008-12-10 05:08:54 +00001683
zhanyong.wan82113312010-01-08 21:55:40 +00001684 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1685 // If either matcher1_ or matcher2_ matches x, we just need to
1686 // explain why *one* of them matches.
1687 StringMatchResultListener listener1;
1688 if (matcher1_.MatchAndExplain(x, &listener1)) {
1689 *listener << listener1.str();
1690 return true;
1691 }
1692
1693 StringMatchResultListener listener2;
1694 if (matcher2_.MatchAndExplain(x, &listener2)) {
1695 *listener << listener2.str();
1696 return true;
1697 }
1698
1699 // Otherwise we need to explain why *both* of them fail.
Nico Weber09fd5b32017-05-15 17:07:03 -04001700 const std::string s1 = listener1.str();
1701 const std::string s2 = listener2.str();
zhanyong.wan82113312010-01-08 21:55:40 +00001702
1703 if (s1 == "") {
1704 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001705 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001706 *listener << s1;
1707 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001708 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001709 }
1710 }
zhanyong.wan82113312010-01-08 21:55:40 +00001711 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001712 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001713
zhanyong.wanc6a41232009-05-13 23:38:40 +00001714 private:
1715 const Matcher<T> matcher1_;
1716 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001717
1718 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001719};
1720
zhanyong.wan616180e2013-06-18 18:49:51 +00001721#if GTEST_LANG_CXX11
1722// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1723template <typename... Args>
1724using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
1725
1726#endif // GTEST_LANG_CXX11
1727
shiqiane35fdd92008-12-10 05:08:54 +00001728// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1729// matches a value that matches at least one of the matchers m_1, ...,
1730// and m_n.
1731template <typename Matcher1, typename Matcher2>
1732class EitherOfMatcher {
1733 public:
1734 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1735 : matcher1_(matcher1), matcher2_(matcher2) {}
1736
1737 // This template type conversion operator allows a
1738 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1739 // both Matcher1 and Matcher2 can match.
1740 template <typename T>
1741 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001742 return Matcher<T>(new EitherOfMatcherImpl<T>(
1743 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001744 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001745
shiqiane35fdd92008-12-10 05:08:54 +00001746 private:
shiqiane35fdd92008-12-10 05:08:54 +00001747 Matcher1 matcher1_;
1748 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001749
1750 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001751};
1752
1753// Used for implementing Truly(pred), which turns a predicate into a
1754// matcher.
1755template <typename Predicate>
1756class TrulyMatcher {
1757 public:
1758 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1759
1760 // This method template allows Truly(pred) to be used as a matcher
1761 // for type T where T is the argument type of predicate 'pred'. The
1762 // argument is passed by reference as the predicate may be
1763 // interested in the address of the argument.
1764 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001765 bool MatchAndExplain(T& x, // NOLINT
1766 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001767 // Without the if-statement, MSVC sometimes warns about converting
1768 // a value to bool (warning 4800).
1769 //
1770 // We cannot write 'return !!predicate_(x);' as that doesn't work
1771 // when predicate_(x) returns a class convertible to bool but
1772 // having no operator!().
1773 if (predicate_(x))
1774 return true;
1775 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001776 }
1777
1778 void DescribeTo(::std::ostream* os) const {
1779 *os << "satisfies the given predicate";
1780 }
1781
1782 void DescribeNegationTo(::std::ostream* os) const {
1783 *os << "doesn't satisfy the given predicate";
1784 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001785
shiqiane35fdd92008-12-10 05:08:54 +00001786 private:
1787 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001788
1789 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001790};
1791
1792// Used for implementing Matches(matcher), which turns a matcher into
1793// a predicate.
1794template <typename M>
1795class MatcherAsPredicate {
1796 public:
1797 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1798
1799 // This template operator() allows Matches(m) to be used as a
1800 // predicate on type T where m is a matcher on type T.
1801 //
1802 // The argument x is passed by reference instead of by value, as
1803 // some matcher may be interested in its address (e.g. as in
1804 // Matches(Ref(n))(x)).
1805 template <typename T>
1806 bool operator()(const T& x) const {
1807 // We let matcher_ commit to a particular type here instead of
1808 // when the MatcherAsPredicate object was constructed. This
1809 // allows us to write Matches(m) where m is a polymorphic matcher
1810 // (e.g. Eq(5)).
1811 //
1812 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1813 // compile when matcher_ has type Matcher<const T&>; if we write
1814 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1815 // when matcher_ has type Matcher<T>; if we just write
1816 // matcher_.Matches(x), it won't compile when matcher_ is
1817 // polymorphic, e.g. Eq(5).
1818 //
1819 // MatcherCast<const T&>() is necessary for making the code work
1820 // in all of the above situations.
1821 return MatcherCast<const T&>(matcher_).Matches(x);
1822 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001823
shiqiane35fdd92008-12-10 05:08:54 +00001824 private:
1825 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001826
1827 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001828};
1829
1830// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1831// argument M must be a type that can be converted to a matcher.
1832template <typename M>
1833class PredicateFormatterFromMatcher {
1834 public:
kosak9b1a9442015-04-28 23:06:58 +00001835 explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {}
shiqiane35fdd92008-12-10 05:08:54 +00001836
1837 // This template () operator allows a PredicateFormatterFromMatcher
1838 // object to act as a predicate-formatter suitable for using with
1839 // Google Test's EXPECT_PRED_FORMAT1() macro.
1840 template <typename T>
1841 AssertionResult operator()(const char* value_text, const T& x) const {
1842 // We convert matcher_ to a Matcher<const T&> *now* instead of
1843 // when the PredicateFormatterFromMatcher object was constructed,
1844 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1845 // know which type to instantiate it to until we actually see the
1846 // type of x here.
1847 //
zhanyong.wanf4274522013-04-24 02:49:43 +00001848 // We write SafeMatcherCast<const T&>(matcher_) instead of
shiqiane35fdd92008-12-10 05:08:54 +00001849 // Matcher<const T&>(matcher_), as the latter won't compile when
1850 // matcher_ has type Matcher<T> (e.g. An<int>()).
zhanyong.wanf4274522013-04-24 02:49:43 +00001851 // We don't write MatcherCast<const T&> either, as that allows
1852 // potentially unsafe downcasting of the matcher argument.
1853 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001854 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001855 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001856 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001857
1858 ::std::stringstream ss;
1859 ss << "Value of: " << value_text << "\n"
1860 << "Expected: ";
1861 matcher.DescribeTo(&ss);
1862 ss << "\n Actual: " << listener.str();
1863 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001864 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001865
shiqiane35fdd92008-12-10 05:08:54 +00001866 private:
1867 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001868
1869 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001870};
1871
1872// A helper function for converting a matcher to a predicate-formatter
1873// without the user needing to explicitly write the type. This is
1874// used for implementing ASSERT_THAT() and EXPECT_THAT().
kosak9b1a9442015-04-28 23:06:58 +00001875// Implementation detail: 'matcher' is received by-value to force decaying.
shiqiane35fdd92008-12-10 05:08:54 +00001876template <typename M>
1877inline PredicateFormatterFromMatcher<M>
kosak9b1a9442015-04-28 23:06:58 +00001878MakePredicateFormatterFromMatcher(M matcher) {
1879 return PredicateFormatterFromMatcher<M>(internal::move(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00001880}
1881
zhanyong.wan616180e2013-06-18 18:49:51 +00001882// Implements the polymorphic floating point equality matcher, which matches
1883// two float values using ULP-based approximation or, optionally, a
1884// user-specified epsilon. The template is meant to be instantiated with
1885// FloatType being either float or double.
shiqiane35fdd92008-12-10 05:08:54 +00001886template <typename FloatType>
1887class FloatingEqMatcher {
1888 public:
1889 // Constructor for FloatingEqMatcher.
kosak6b817802015-01-08 02:38:14 +00001890 // The matcher's input will be compared with expected. The matcher treats two
shiqiane35fdd92008-12-10 05:08:54 +00001891 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
zhanyong.wan616180e2013-06-18 18:49:51 +00001892 // equality comparisons between NANs will always return false. We specify a
1893 // negative max_abs_error_ term to indicate that ULP-based approximation will
1894 // be used for comparison.
kosak6b817802015-01-08 02:38:14 +00001895 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
1896 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001897 }
1898
1899 // Constructor that supports a user-specified max_abs_error that will be used
1900 // for comparison instead of ULP-based approximation. The max absolute
1901 // should be non-negative.
kosak6b817802015-01-08 02:38:14 +00001902 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
1903 FloatType max_abs_error)
1904 : expected_(expected),
1905 nan_eq_nan_(nan_eq_nan),
1906 max_abs_error_(max_abs_error) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001907 GTEST_CHECK_(max_abs_error >= 0)
1908 << ", where max_abs_error is" << max_abs_error;
1909 }
shiqiane35fdd92008-12-10 05:08:54 +00001910
1911 // Implements floating point equality matcher as a Matcher<T>.
1912 template <typename T>
1913 class Impl : public MatcherInterface<T> {
1914 public:
kosak6b817802015-01-08 02:38:14 +00001915 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
1916 : expected_(expected),
1917 nan_eq_nan_(nan_eq_nan),
1918 max_abs_error_(max_abs_error) {}
shiqiane35fdd92008-12-10 05:08:54 +00001919
zhanyong.wan82113312010-01-08 21:55:40 +00001920 virtual bool MatchAndExplain(T value,
kosak6b817802015-01-08 02:38:14 +00001921 MatchResultListener* listener) const {
1922 const FloatingPoint<FloatType> actual(value), expected(expected_);
shiqiane35fdd92008-12-10 05:08:54 +00001923
1924 // Compares NaNs first, if nan_eq_nan_ is true.
kosak6b817802015-01-08 02:38:14 +00001925 if (actual.is_nan() || expected.is_nan()) {
1926 if (actual.is_nan() && expected.is_nan()) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001927 return nan_eq_nan_;
1928 }
1929 // One is nan; the other is not nan.
1930 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001931 }
zhanyong.wan616180e2013-06-18 18:49:51 +00001932 if (HasMaxAbsError()) {
1933 // We perform an equality check so that inf will match inf, regardless
kosak6b817802015-01-08 02:38:14 +00001934 // of error bounds. If the result of value - expected_ would result in
zhanyong.wan616180e2013-06-18 18:49:51 +00001935 // overflow or if either value is inf, the default result is infinity,
1936 // which should only match if max_abs_error_ is also infinity.
kosak6b817802015-01-08 02:38:14 +00001937 if (value == expected_) {
1938 return true;
1939 }
1940
1941 const FloatType diff = value - expected_;
1942 if (fabs(diff) <= max_abs_error_) {
1943 return true;
1944 }
1945
1946 if (listener->IsInterested()) {
1947 *listener << "which is " << diff << " from " << expected_;
1948 }
1949 return false;
zhanyong.wan616180e2013-06-18 18:49:51 +00001950 } else {
kosak6b817802015-01-08 02:38:14 +00001951 return actual.AlmostEquals(expected);
zhanyong.wan616180e2013-06-18 18:49:51 +00001952 }
shiqiane35fdd92008-12-10 05:08:54 +00001953 }
1954
1955 virtual void DescribeTo(::std::ostream* os) const {
1956 // os->precision() returns the previously set precision, which we
1957 // store to restore the ostream to its original configuration
1958 // after outputting.
1959 const ::std::streamsize old_precision = os->precision(
1960 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00001961 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00001962 if (nan_eq_nan_) {
1963 *os << "is NaN";
1964 } else {
1965 *os << "never matches";
1966 }
1967 } else {
kosak6b817802015-01-08 02:38:14 +00001968 *os << "is approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001969 if (HasMaxAbsError()) {
1970 *os << " (absolute error <= " << max_abs_error_ << ")";
1971 }
shiqiane35fdd92008-12-10 05:08:54 +00001972 }
1973 os->precision(old_precision);
1974 }
1975
1976 virtual void DescribeNegationTo(::std::ostream* os) const {
1977 // As before, get original precision.
1978 const ::std::streamsize old_precision = os->precision(
1979 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00001980 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00001981 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001982 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00001983 } else {
1984 *os << "is anything";
1985 }
1986 } else {
kosak6b817802015-01-08 02:38:14 +00001987 *os << "isn't approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001988 if (HasMaxAbsError()) {
1989 *os << " (absolute error > " << max_abs_error_ << ")";
1990 }
shiqiane35fdd92008-12-10 05:08:54 +00001991 }
1992 // Restore original precision.
1993 os->precision(old_precision);
1994 }
1995
1996 private:
zhanyong.wan616180e2013-06-18 18:49:51 +00001997 bool HasMaxAbsError() const {
1998 return max_abs_error_ >= 0;
1999 }
2000
kosak6b817802015-01-08 02:38:14 +00002001 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002002 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002003 // max_abs_error will be used for value comparison when >= 0.
2004 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002005
2006 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002007 };
2008
kosak6b817802015-01-08 02:38:14 +00002009 // The following 3 type conversion operators allow FloatEq(expected) and
2010 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
shiqiane35fdd92008-12-10 05:08:54 +00002011 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
2012 // (While Google's C++ coding style doesn't allow arguments passed
2013 // by non-const reference, we may see them in code not conforming to
2014 // the style. Therefore Google Mock needs to support them.)
2015 operator Matcher<FloatType>() const {
kosak6b817802015-01-08 02:38:14 +00002016 return MakeMatcher(
2017 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002018 }
2019
2020 operator Matcher<const FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00002021 return MakeMatcher(
kosak6b817802015-01-08 02:38:14 +00002022 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002023 }
2024
2025 operator Matcher<FloatType&>() const {
kosak6b817802015-01-08 02:38:14 +00002026 return MakeMatcher(
2027 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002028 }
jgm79a367e2012-04-10 16:02:11 +00002029
shiqiane35fdd92008-12-10 05:08:54 +00002030 private:
kosak6b817802015-01-08 02:38:14 +00002031 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002032 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002033 // max_abs_error will be used for value comparison when >= 0.
2034 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002035
2036 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002037};
2038
2039// Implements the Pointee(m) matcher for matching a pointer whose
2040// pointee matches matcher m. The pointer can be either raw or smart.
2041template <typename InnerMatcher>
2042class PointeeMatcher {
2043 public:
2044 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
2045
2046 // This type conversion operator template allows Pointee(m) to be
2047 // used as a matcher for any pointer type whose pointee type is
2048 // compatible with the inner matcher, where type Pointer can be
2049 // either a raw pointer or a smart pointer.
2050 //
2051 // The reason we do this instead of relying on
2052 // MakePolymorphicMatcher() is that the latter is not flexible
2053 // enough for implementing the DescribeTo() method of Pointee().
2054 template <typename Pointer>
2055 operator Matcher<Pointer>() const {
2056 return MakeMatcher(new Impl<Pointer>(matcher_));
2057 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002058
shiqiane35fdd92008-12-10 05:08:54 +00002059 private:
2060 // The monomorphic implementation that works for a particular pointer type.
2061 template <typename Pointer>
2062 class Impl : public MatcherInterface<Pointer> {
2063 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00002064 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
2065 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00002066
2067 explicit Impl(const InnerMatcher& matcher)
2068 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
2069
shiqiane35fdd92008-12-10 05:08:54 +00002070 virtual void DescribeTo(::std::ostream* os) const {
2071 *os << "points to a value that ";
2072 matcher_.DescribeTo(os);
2073 }
2074
2075 virtual void DescribeNegationTo(::std::ostream* os) const {
2076 *os << "does not point to a value that ";
2077 matcher_.DescribeTo(os);
2078 }
2079
zhanyong.wan82113312010-01-08 21:55:40 +00002080 virtual bool MatchAndExplain(Pointer pointer,
2081 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00002082 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00002083 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002084
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002085 *listener << "which points to ";
2086 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002087 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002088
shiqiane35fdd92008-12-10 05:08:54 +00002089 private:
2090 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002091
2092 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002093 };
2094
2095 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002096
2097 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002098};
2099
billydonahue1f5fdea2014-05-19 17:54:51 +00002100// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2101// reference that matches inner_matcher when dynamic_cast<T> is applied.
2102// The result of dynamic_cast<To> is forwarded to the inner matcher.
2103// If To is a pointer and the cast fails, the inner matcher will receive NULL.
2104// If To is a reference and the cast fails, this matcher returns false
2105// immediately.
2106template <typename To>
2107class WhenDynamicCastToMatcherBase {
2108 public:
2109 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2110 : matcher_(matcher) {}
2111
2112 void DescribeTo(::std::ostream* os) const {
2113 GetCastTypeDescription(os);
2114 matcher_.DescribeTo(os);
2115 }
2116
2117 void DescribeNegationTo(::std::ostream* os) const {
2118 GetCastTypeDescription(os);
2119 matcher_.DescribeNegationTo(os);
2120 }
2121
2122 protected:
2123 const Matcher<To> matcher_;
2124
Nico Weber09fd5b32017-05-15 17:07:03 -04002125 static std::string GetToName() {
billydonahue1f5fdea2014-05-19 17:54:51 +00002126#if GTEST_HAS_RTTI
2127 return GetTypeName<To>();
2128#else // GTEST_HAS_RTTI
2129 return "the target type";
2130#endif // GTEST_HAS_RTTI
2131 }
2132
2133 private:
2134 static void GetCastTypeDescription(::std::ostream* os) {
2135 *os << "when dynamic_cast to " << GetToName() << ", ";
2136 }
2137
2138 GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2139};
2140
2141// Primary template.
2142// To is a pointer. Cast and forward the result.
2143template <typename To>
2144class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2145 public:
2146 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2147 : WhenDynamicCastToMatcherBase<To>(matcher) {}
2148
2149 template <typename From>
2150 bool MatchAndExplain(From from, MatchResultListener* listener) const {
2151 // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail?
2152 To to = dynamic_cast<To>(from);
2153 return MatchPrintAndExplain(to, this->matcher_, listener);
2154 }
2155};
2156
2157// Specialize for references.
2158// In this case we return false if the dynamic_cast fails.
2159template <typename To>
2160class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2161 public:
2162 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2163 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2164
2165 template <typename From>
2166 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2167 // We don't want an std::bad_cast here, so do the cast with pointers.
2168 To* to = dynamic_cast<To*>(&from);
2169 if (to == NULL) {
2170 *listener << "which cannot be dynamic_cast to " << this->GetToName();
2171 return false;
2172 }
2173 return MatchPrintAndExplain(*to, this->matcher_, listener);
2174 }
2175};
2176
shiqiane35fdd92008-12-10 05:08:54 +00002177// Implements the Field() matcher for matching a field (i.e. member
2178// variable) of an object.
2179template <typename Class, typename FieldType>
2180class FieldMatcher {
2181 public:
2182 FieldMatcher(FieldType Class::*field,
2183 const Matcher<const FieldType&>& matcher)
2184 : field_(field), matcher_(matcher) {}
2185
shiqiane35fdd92008-12-10 05:08:54 +00002186 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002187 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002188 matcher_.DescribeTo(os);
2189 }
2190
2191 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002192 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002193 matcher_.DescribeNegationTo(os);
2194 }
2195
zhanyong.wandb22c222010-01-28 21:52:29 +00002196 template <typename T>
2197 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2198 return MatchAndExplainImpl(
2199 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002200 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002201 value, listener);
2202 }
2203
2204 private:
2205 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002206 // Symbian's C++ compiler choose which overload to use. Its type is
2207 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002208 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2209 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002210 *listener << "whose given field is ";
2211 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002212 }
2213
zhanyong.wandb22c222010-01-28 21:52:29 +00002214 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2215 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002216 if (p == NULL)
2217 return false;
2218
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002219 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002220 // Since *p has a field, it must be a class/struct/union type and
2221 // thus cannot be a pointer. Therefore we pass false_type() as
2222 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002223 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002224 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002225
shiqiane35fdd92008-12-10 05:08:54 +00002226 const FieldType Class::*field_;
2227 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002228
2229 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002230};
2231
shiqiane35fdd92008-12-10 05:08:54 +00002232// Implements the Property() matcher for matching a property
2233// (i.e. return value of a getter method) of an object.
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002234//
2235// Property is a const-qualified member function of Class returning
2236// PropertyType.
2237template <typename Class, typename PropertyType, typename Property>
shiqiane35fdd92008-12-10 05:08:54 +00002238class PropertyMatcher {
2239 public:
2240 // The property may have a reference type, so 'const PropertyType&'
2241 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00002242 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00002243 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00002244 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00002245
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002246 PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)
shiqiane35fdd92008-12-10 05:08:54 +00002247 : property_(property), matcher_(matcher) {}
2248
shiqiane35fdd92008-12-10 05:08:54 +00002249 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002250 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002251 matcher_.DescribeTo(os);
2252 }
2253
2254 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002255 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002256 matcher_.DescribeNegationTo(os);
2257 }
2258
zhanyong.wandb22c222010-01-28 21:52:29 +00002259 template <typename T>
2260 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2261 return MatchAndExplainImpl(
2262 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002263 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002264 value, listener);
2265 }
2266
2267 private:
2268 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002269 // Symbian's C++ compiler choose which overload to use. Its type is
2270 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002271 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2272 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002273 *listener << "whose given property is ";
2274 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2275 // which takes a non-const reference as argument.
kosak02d64792015-02-14 02:22:21 +00002276#if defined(_PREFAST_ ) && _MSC_VER == 1800
2277 // Workaround bug in VC++ 2013's /analyze parser.
2278 // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move
2279 posix::Abort(); // To make sure it is never run.
2280 return false;
2281#else
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002282 RefToConstProperty result = (obj.*property_)();
2283 return MatchPrintAndExplain(result, matcher_, listener);
kosak02d64792015-02-14 02:22:21 +00002284#endif
shiqiane35fdd92008-12-10 05:08:54 +00002285 }
2286
zhanyong.wandb22c222010-01-28 21:52:29 +00002287 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2288 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002289 if (p == NULL)
2290 return false;
2291
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002292 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002293 // Since *p has a property method, it must be a class/struct/union
2294 // type and thus cannot be a pointer. Therefore we pass
2295 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002296 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002297 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002298
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002299 Property property_;
shiqiane35fdd92008-12-10 05:08:54 +00002300 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002301
2302 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002303};
2304
shiqiane35fdd92008-12-10 05:08:54 +00002305// Type traits specifying various features of different functors for ResultOf.
2306// The default template specifies features for functor objects.
2307// Functor classes have to typedef argument_type and result_type
2308// to be compatible with ResultOf.
2309template <typename Functor>
2310struct CallableTraits {
2311 typedef typename Functor::result_type ResultType;
2312 typedef Functor StorageType;
2313
zhanyong.wan32de5f52009-12-23 00:13:23 +00002314 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00002315 template <typename T>
2316 static ResultType Invoke(Functor f, T arg) { return f(arg); }
2317};
2318
2319// Specialization for function pointers.
2320template <typename ArgType, typename ResType>
2321struct CallableTraits<ResType(*)(ArgType)> {
2322 typedef ResType ResultType;
2323 typedef ResType(*StorageType)(ArgType);
2324
2325 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002326 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00002327 << "NULL function pointer is passed into ResultOf().";
2328 }
2329 template <typename T>
2330 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2331 return (*f)(arg);
2332 }
2333};
2334
2335// Implements the ResultOf() matcher for matching a return value of a
2336// unary function of an object.
2337template <typename Callable>
2338class ResultOfMatcher {
2339 public:
2340 typedef typename CallableTraits<Callable>::ResultType ResultType;
2341
2342 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
2343 : callable_(callable), matcher_(matcher) {
2344 CallableTraits<Callable>::CheckIsValid(callable_);
2345 }
2346
2347 template <typename T>
2348 operator Matcher<T>() const {
2349 return Matcher<T>(new Impl<T>(callable_, matcher_));
2350 }
2351
2352 private:
2353 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2354
2355 template <typename T>
2356 class Impl : public MatcherInterface<T> {
2357 public:
2358 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
2359 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00002360
2361 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002362 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002363 matcher_.DescribeTo(os);
2364 }
2365
2366 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002367 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002368 matcher_.DescribeNegationTo(os);
2369 }
2370
zhanyong.wan82113312010-01-08 21:55:40 +00002371 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002372 *listener << "which is mapped by the given callable to ";
2373 // Cannot pass the return value (for example, int) to
2374 // MatchPrintAndExplain, which takes a non-const reference as argument.
2375 ResultType result =
2376 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2377 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002378 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002379
shiqiane35fdd92008-12-10 05:08:54 +00002380 private:
2381 // Functors often define operator() as non-const method even though
2382 // they are actualy stateless. But we need to use them even when
2383 // 'this' is a const pointer. It's the user's responsibility not to
2384 // use stateful callables with ResultOf(), which does't guarantee
2385 // how many times the callable will be invoked.
2386 mutable CallableStorageType callable_;
2387 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002388
2389 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002390 }; // class Impl
2391
2392 const CallableStorageType callable_;
2393 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002394
2395 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002396};
2397
zhanyong.wana31d9ce2013-03-01 01:50:17 +00002398// Implements a matcher that checks the size of an STL-style container.
2399template <typename SizeMatcher>
2400class SizeIsMatcher {
2401 public:
2402 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2403 : size_matcher_(size_matcher) {
2404 }
2405
2406 template <typename Container>
2407 operator Matcher<Container>() const {
2408 return MakeMatcher(new Impl<Container>(size_matcher_));
2409 }
2410
2411 template <typename Container>
2412 class Impl : public MatcherInterface<Container> {
2413 public:
2414 typedef internal::StlContainerView<
2415 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2416 typedef typename ContainerView::type::size_type SizeType;
2417 explicit Impl(const SizeMatcher& size_matcher)
2418 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2419
2420 virtual void DescribeTo(::std::ostream* os) const {
2421 *os << "size ";
2422 size_matcher_.DescribeTo(os);
2423 }
2424 virtual void DescribeNegationTo(::std::ostream* os) const {
2425 *os << "size ";
2426 size_matcher_.DescribeNegationTo(os);
2427 }
2428
2429 virtual bool MatchAndExplain(Container container,
2430 MatchResultListener* listener) const {
2431 SizeType size = container.size();
2432 StringMatchResultListener size_listener;
2433 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2434 *listener
2435 << "whose size " << size << (result ? " matches" : " doesn't match");
2436 PrintIfNotEmpty(size_listener.str(), listener->stream());
2437 return result;
2438 }
2439
2440 private:
2441 const Matcher<SizeType> size_matcher_;
2442 GTEST_DISALLOW_ASSIGN_(Impl);
2443 };
2444
2445 private:
2446 const SizeMatcher size_matcher_;
2447 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2448};
2449
kosakb6a34882014-03-12 21:06:46 +00002450// Implements a matcher that checks the begin()..end() distance of an STL-style
2451// container.
2452template <typename DistanceMatcher>
2453class BeginEndDistanceIsMatcher {
2454 public:
2455 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2456 : distance_matcher_(distance_matcher) {}
2457
2458 template <typename Container>
2459 operator Matcher<Container>() const {
2460 return MakeMatcher(new Impl<Container>(distance_matcher_));
2461 }
2462
2463 template <typename Container>
2464 class Impl : public MatcherInterface<Container> {
2465 public:
2466 typedef internal::StlContainerView<
2467 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2468 typedef typename std::iterator_traits<
2469 typename ContainerView::type::const_iterator>::difference_type
2470 DistanceType;
2471 explicit Impl(const DistanceMatcher& distance_matcher)
2472 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2473
2474 virtual void DescribeTo(::std::ostream* os) const {
2475 *os << "distance between begin() and end() ";
2476 distance_matcher_.DescribeTo(os);
2477 }
2478 virtual void DescribeNegationTo(::std::ostream* os) const {
2479 *os << "distance between begin() and end() ";
2480 distance_matcher_.DescribeNegationTo(os);
2481 }
2482
2483 virtual bool MatchAndExplain(Container container,
2484 MatchResultListener* listener) const {
kosak5b9cbbb2014-11-17 00:28:55 +00002485#if GTEST_HAS_STD_BEGIN_AND_END_
kosakb6a34882014-03-12 21:06:46 +00002486 using std::begin;
2487 using std::end;
2488 DistanceType distance = std::distance(begin(container), end(container));
2489#else
2490 DistanceType distance = std::distance(container.begin(), container.end());
2491#endif
2492 StringMatchResultListener distance_listener;
2493 const bool result =
2494 distance_matcher_.MatchAndExplain(distance, &distance_listener);
2495 *listener << "whose distance between begin() and end() " << distance
2496 << (result ? " matches" : " doesn't match");
2497 PrintIfNotEmpty(distance_listener.str(), listener->stream());
2498 return result;
2499 }
2500
2501 private:
2502 const Matcher<DistanceType> distance_matcher_;
2503 GTEST_DISALLOW_ASSIGN_(Impl);
2504 };
2505
2506 private:
2507 const DistanceMatcher distance_matcher_;
2508 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2509};
2510
zhanyong.wan6a896b52009-01-16 01:13:50 +00002511// Implements an equality matcher for any STL-style container whose elements
2512// support ==. This matcher is like Eq(), but its failure explanations provide
2513// more detailed information that is useful when the container is used as a set.
2514// The failure message reports elements that are in one of the operands but not
2515// the other. The failure messages do not report duplicate or out-of-order
2516// elements in the containers (which don't properly matter to sets, but can
2517// occur if the containers are vectors or lists, for example).
2518//
2519// Uses the container's const_iterator, value_type, operator ==,
2520// begin(), and end().
2521template <typename Container>
2522class ContainerEqMatcher {
2523 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002524 typedef internal::StlContainerView<Container> View;
2525 typedef typename View::type StlContainer;
2526 typedef typename View::const_reference StlContainerReference;
2527
kosak6b817802015-01-08 02:38:14 +00002528 // We make a copy of expected in case the elements in it are modified
zhanyong.wanb8243162009-06-04 05:48:20 +00002529 // after this matcher is created.
kosak6b817802015-01-08 02:38:14 +00002530 explicit ContainerEqMatcher(const Container& expected)
2531 : expected_(View::Copy(expected)) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002532 // Makes sure the user doesn't instantiate this class template
2533 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002534 (void)testing::StaticAssertTypeEq<Container,
2535 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002536 }
2537
zhanyong.wan6a896b52009-01-16 01:13:50 +00002538 void DescribeTo(::std::ostream* os) const {
2539 *os << "equals ";
kosak6b817802015-01-08 02:38:14 +00002540 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002541 }
2542 void DescribeNegationTo(::std::ostream* os) const {
2543 *os << "does not equal ";
kosak6b817802015-01-08 02:38:14 +00002544 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002545 }
2546
zhanyong.wanb8243162009-06-04 05:48:20 +00002547 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002548 bool MatchAndExplain(const LhsContainer& lhs,
2549 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002550 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002551 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002552 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002553 LhsView;
2554 typedef typename LhsView::type LhsStlContainer;
2555 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
kosak6b817802015-01-08 02:38:14 +00002556 if (lhs_stl_container == expected_)
zhanyong.wane122e452010-01-12 09:03:52 +00002557 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002558
zhanyong.wane122e452010-01-12 09:03:52 +00002559 ::std::ostream* const os = listener->stream();
2560 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002561 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002562 bool printed_header = false;
2563 for (typename LhsStlContainer::const_iterator it =
2564 lhs_stl_container.begin();
2565 it != lhs_stl_container.end(); ++it) {
kosak6b817802015-01-08 02:38:14 +00002566 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
2567 expected_.end()) {
zhanyong.wane122e452010-01-12 09:03:52 +00002568 if (printed_header) {
2569 *os << ", ";
2570 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002571 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002572 printed_header = true;
2573 }
vladloseve2e8ba42010-05-13 18:16:03 +00002574 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002575 }
zhanyong.wane122e452010-01-12 09:03:52 +00002576 }
2577
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002578 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002579 bool printed_header2 = false;
kosak6b817802015-01-08 02:38:14 +00002580 for (typename StlContainer::const_iterator it = expected_.begin();
2581 it != expected_.end(); ++it) {
zhanyong.wane122e452010-01-12 09:03:52 +00002582 if (internal::ArrayAwareFind(
2583 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2584 lhs_stl_container.end()) {
2585 if (printed_header2) {
2586 *os << ", ";
2587 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002588 *os << (printed_header ? ",\nand" : "which")
2589 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002590 printed_header2 = true;
2591 }
vladloseve2e8ba42010-05-13 18:16:03 +00002592 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002593 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002594 }
2595 }
2596
zhanyong.wane122e452010-01-12 09:03:52 +00002597 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002598 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002599
zhanyong.wan6a896b52009-01-16 01:13:50 +00002600 private:
kosak6b817802015-01-08 02:38:14 +00002601 const StlContainer expected_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002602
2603 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002604};
2605
zhanyong.wan898725c2011-09-16 16:45:39 +00002606// A comparator functor that uses the < operator to compare two values.
2607struct LessComparator {
2608 template <typename T, typename U>
2609 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2610};
2611
2612// Implements WhenSortedBy(comparator, container_matcher).
2613template <typename Comparator, typename ContainerMatcher>
2614class WhenSortedByMatcher {
2615 public:
2616 WhenSortedByMatcher(const Comparator& comparator,
2617 const ContainerMatcher& matcher)
2618 : comparator_(comparator), matcher_(matcher) {}
2619
2620 template <typename LhsContainer>
2621 operator Matcher<LhsContainer>() const {
2622 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2623 }
2624
2625 template <typename LhsContainer>
2626 class Impl : public MatcherInterface<LhsContainer> {
2627 public:
2628 typedef internal::StlContainerView<
2629 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2630 typedef typename LhsView::type LhsStlContainer;
2631 typedef typename LhsView::const_reference LhsStlContainerReference;
zhanyong.wana9a59e02013-03-27 16:14:55 +00002632 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2633 // so that we can match associative containers.
2634 typedef typename RemoveConstFromKey<
2635 typename LhsStlContainer::value_type>::type LhsValue;
zhanyong.wan898725c2011-09-16 16:45:39 +00002636
2637 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2638 : comparator_(comparator), matcher_(matcher) {}
2639
2640 virtual void DescribeTo(::std::ostream* os) const {
2641 *os << "(when sorted) ";
2642 matcher_.DescribeTo(os);
2643 }
2644
2645 virtual void DescribeNegationTo(::std::ostream* os) const {
2646 *os << "(when sorted) ";
2647 matcher_.DescribeNegationTo(os);
2648 }
2649
2650 virtual bool MatchAndExplain(LhsContainer lhs,
2651 MatchResultListener* listener) const {
2652 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wanfb25d532013-07-28 08:24:00 +00002653 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2654 lhs_stl_container.end());
2655 ::std::sort(
2656 sorted_container.begin(), sorted_container.end(), comparator_);
zhanyong.wan898725c2011-09-16 16:45:39 +00002657
2658 if (!listener->IsInterested()) {
2659 // If the listener is not interested, we do not need to
2660 // construct the inner explanation.
2661 return matcher_.Matches(sorted_container);
2662 }
2663
2664 *listener << "which is ";
2665 UniversalPrint(sorted_container, listener->stream());
2666 *listener << " when sorted";
2667
2668 StringMatchResultListener inner_listener;
2669 const bool match = matcher_.MatchAndExplain(sorted_container,
2670 &inner_listener);
2671 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2672 return match;
2673 }
2674
2675 private:
2676 const Comparator comparator_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00002677 const Matcher<const ::std::vector<LhsValue>&> matcher_;
zhanyong.wan898725c2011-09-16 16:45:39 +00002678
2679 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2680 };
2681
2682 private:
2683 const Comparator comparator_;
2684 const ContainerMatcher matcher_;
2685
2686 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2687};
2688
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002689// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2690// must be able to be safely cast to Matcher<tuple<const T1&, const
2691// T2&> >, where T1 and T2 are the types of elements in the LHS
2692// container and the RHS container respectively.
2693template <typename TupleMatcher, typename RhsContainer>
2694class PointwiseMatcher {
2695 public:
2696 typedef internal::StlContainerView<RhsContainer> RhsView;
2697 typedef typename RhsView::type RhsStlContainer;
2698 typedef typename RhsStlContainer::value_type RhsValue;
2699
2700 // Like ContainerEq, we make a copy of rhs in case the elements in
2701 // it are modified after this matcher is created.
2702 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2703 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2704 // Makes sure the user doesn't instantiate this class template
2705 // with a const or reference type.
2706 (void)testing::StaticAssertTypeEq<RhsContainer,
2707 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2708 }
2709
2710 template <typename LhsContainer>
2711 operator Matcher<LhsContainer>() const {
2712 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2713 }
2714
2715 template <typename LhsContainer>
2716 class Impl : public MatcherInterface<LhsContainer> {
2717 public:
2718 typedef internal::StlContainerView<
2719 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2720 typedef typename LhsView::type LhsStlContainer;
2721 typedef typename LhsView::const_reference LhsStlContainerReference;
2722 typedef typename LhsStlContainer::value_type LhsValue;
2723 // We pass the LHS value and the RHS value to the inner matcher by
2724 // reference, as they may be expensive to copy. We must use tuple
2725 // instead of pair here, as a pair cannot hold references (C++ 98,
2726 // 20.2.2 [lib.pairs]).
kosakbd018832014-04-02 20:30:00 +00002727 typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002728
2729 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2730 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2731 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2732 rhs_(rhs) {}
2733
2734 virtual void DescribeTo(::std::ostream* os) const {
2735 *os << "contains " << rhs_.size()
2736 << " values, where each value and its corresponding value in ";
2737 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2738 *os << " ";
2739 mono_tuple_matcher_.DescribeTo(os);
2740 }
2741 virtual void DescribeNegationTo(::std::ostream* os) const {
2742 *os << "doesn't contain exactly " << rhs_.size()
2743 << " values, or contains a value x at some index i"
2744 << " where x and the i-th value of ";
2745 UniversalPrint(rhs_, os);
2746 *os << " ";
2747 mono_tuple_matcher_.DescribeNegationTo(os);
2748 }
2749
2750 virtual bool MatchAndExplain(LhsContainer lhs,
2751 MatchResultListener* listener) const {
2752 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2753 const size_t actual_size = lhs_stl_container.size();
2754 if (actual_size != rhs_.size()) {
2755 *listener << "which contains " << actual_size << " values";
2756 return false;
2757 }
2758
2759 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2760 typename RhsStlContainer::const_iterator right = rhs_.begin();
2761 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2762 const InnerMatcherArg value_pair(*left, *right);
2763
2764 if (listener->IsInterested()) {
2765 StringMatchResultListener inner_listener;
2766 if (!mono_tuple_matcher_.MatchAndExplain(
2767 value_pair, &inner_listener)) {
2768 *listener << "where the value pair (";
2769 UniversalPrint(*left, listener->stream());
2770 *listener << ", ";
2771 UniversalPrint(*right, listener->stream());
2772 *listener << ") at index #" << i << " don't match";
2773 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2774 return false;
2775 }
2776 } else {
2777 if (!mono_tuple_matcher_.Matches(value_pair))
2778 return false;
2779 }
2780 }
2781
2782 return true;
2783 }
2784
2785 private:
2786 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2787 const RhsStlContainer rhs_;
2788
2789 GTEST_DISALLOW_ASSIGN_(Impl);
2790 };
2791
2792 private:
2793 const TupleMatcher tuple_matcher_;
2794 const RhsStlContainer rhs_;
2795
2796 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2797};
2798
zhanyong.wan33605ba2010-04-22 23:37:47 +00002799// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002800template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002801class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002802 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002803 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002804 typedef StlContainerView<RawContainer> View;
2805 typedef typename View::type StlContainer;
2806 typedef typename View::const_reference StlContainerReference;
2807 typedef typename StlContainer::value_type Element;
2808
2809 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002810 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002811 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002812 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002813
zhanyong.wan33605ba2010-04-22 23:37:47 +00002814 // Checks whether:
2815 // * All elements in the container match, if all_elements_should_match.
2816 // * Any element in the container matches, if !all_elements_should_match.
2817 bool MatchAndExplainImpl(bool all_elements_should_match,
2818 Container container,
2819 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002820 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002821 size_t i = 0;
2822 for (typename StlContainer::const_iterator it = stl_container.begin();
2823 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002824 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002825 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2826
2827 if (matches != all_elements_should_match) {
2828 *listener << "whose element #" << i
2829 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002830 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002831 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002832 }
2833 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002834 return all_elements_should_match;
2835 }
2836
2837 protected:
2838 const Matcher<const Element&> inner_matcher_;
2839
2840 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2841};
2842
2843// Implements Contains(element_matcher) for the given argument type Container.
2844// Symmetric to EachMatcherImpl.
2845template <typename Container>
2846class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2847 public:
2848 template <typename InnerMatcher>
2849 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2850 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2851
2852 // Describes what this matcher does.
2853 virtual void DescribeTo(::std::ostream* os) const {
2854 *os << "contains at least one element that ";
2855 this->inner_matcher_.DescribeTo(os);
2856 }
2857
2858 virtual void DescribeNegationTo(::std::ostream* os) const {
2859 *os << "doesn't contain any element that ";
2860 this->inner_matcher_.DescribeTo(os);
2861 }
2862
2863 virtual bool MatchAndExplain(Container container,
2864 MatchResultListener* listener) const {
2865 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002866 }
2867
2868 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002869 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002870};
2871
zhanyong.wan33605ba2010-04-22 23:37:47 +00002872// Implements Each(element_matcher) for the given argument type Container.
2873// Symmetric to ContainsMatcherImpl.
2874template <typename Container>
2875class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2876 public:
2877 template <typename InnerMatcher>
2878 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2879 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2880
2881 // Describes what this matcher does.
2882 virtual void DescribeTo(::std::ostream* os) const {
2883 *os << "only contains elements that ";
2884 this->inner_matcher_.DescribeTo(os);
2885 }
2886
2887 virtual void DescribeNegationTo(::std::ostream* os) const {
2888 *os << "contains some element that ";
2889 this->inner_matcher_.DescribeNegationTo(os);
2890 }
2891
2892 virtual bool MatchAndExplain(Container container,
2893 MatchResultListener* listener) const {
2894 return this->MatchAndExplainImpl(true, container, listener);
2895 }
2896
2897 private:
2898 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2899};
2900
zhanyong.wanb8243162009-06-04 05:48:20 +00002901// Implements polymorphic Contains(element_matcher).
2902template <typename M>
2903class ContainsMatcher {
2904 public:
2905 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2906
2907 template <typename Container>
2908 operator Matcher<Container>() const {
2909 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2910 }
2911
2912 private:
2913 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002914
2915 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002916};
2917
zhanyong.wan33605ba2010-04-22 23:37:47 +00002918// Implements polymorphic Each(element_matcher).
2919template <typename M>
2920class EachMatcher {
2921 public:
2922 explicit EachMatcher(M m) : inner_matcher_(m) {}
2923
2924 template <typename Container>
2925 operator Matcher<Container>() const {
2926 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2927 }
2928
2929 private:
2930 const M inner_matcher_;
2931
2932 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2933};
2934
zhanyong.wanb5937da2009-07-16 20:26:41 +00002935// Implements Key(inner_matcher) for the given argument pair type.
2936// Key(inner_matcher) matches an std::pair whose 'first' field matches
2937// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2938// std::map that contains at least one element whose key is >= 5.
2939template <typename PairType>
2940class KeyMatcherImpl : public MatcherInterface<PairType> {
2941 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002942 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002943 typedef typename RawPairType::first_type KeyType;
2944
2945 template <typename InnerMatcher>
2946 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2947 : inner_matcher_(
2948 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2949 }
2950
2951 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002952 virtual bool MatchAndExplain(PairType key_value,
2953 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002954 StringMatchResultListener inner_listener;
2955 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2956 &inner_listener);
Nico Weber09fd5b32017-05-15 17:07:03 -04002957 const std::string explanation = inner_listener.str();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002958 if (explanation != "") {
2959 *listener << "whose first field is a value " << explanation;
2960 }
2961 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002962 }
2963
2964 // Describes what this matcher does.
2965 virtual void DescribeTo(::std::ostream* os) const {
2966 *os << "has a key that ";
2967 inner_matcher_.DescribeTo(os);
2968 }
2969
2970 // Describes what the negation of this matcher does.
2971 virtual void DescribeNegationTo(::std::ostream* os) const {
2972 *os << "doesn't have a key that ";
2973 inner_matcher_.DescribeTo(os);
2974 }
2975
zhanyong.wanb5937da2009-07-16 20:26:41 +00002976 private:
2977 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002978
2979 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002980};
2981
2982// Implements polymorphic Key(matcher_for_key).
2983template <typename M>
2984class KeyMatcher {
2985 public:
2986 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2987
2988 template <typename PairType>
2989 operator Matcher<PairType>() const {
2990 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2991 }
2992
2993 private:
2994 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002995
2996 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002997};
2998
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002999// Implements Pair(first_matcher, second_matcher) for the given argument pair
3000// type with its two matchers. See Pair() function below.
3001template <typename PairType>
3002class PairMatcherImpl : public MatcherInterface<PairType> {
3003 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003004 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003005 typedef typename RawPairType::first_type FirstType;
3006 typedef typename RawPairType::second_type SecondType;
3007
3008 template <typename FirstMatcher, typename SecondMatcher>
3009 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
3010 : first_matcher_(
3011 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
3012 second_matcher_(
3013 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
3014 }
3015
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003016 // Describes what this matcher does.
3017 virtual void DescribeTo(::std::ostream* os) const {
3018 *os << "has a first field that ";
3019 first_matcher_.DescribeTo(os);
3020 *os << ", and has a second field that ";
3021 second_matcher_.DescribeTo(os);
3022 }
3023
3024 // Describes what the negation of this matcher does.
3025 virtual void DescribeNegationTo(::std::ostream* os) const {
3026 *os << "has a first field that ";
3027 first_matcher_.DescribeNegationTo(os);
3028 *os << ", or has a second field that ";
3029 second_matcher_.DescribeNegationTo(os);
3030 }
3031
zhanyong.wan82113312010-01-08 21:55:40 +00003032 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3033 // matches second_matcher.
3034 virtual bool MatchAndExplain(PairType a_pair,
3035 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003036 if (!listener->IsInterested()) {
3037 // If the listener is not interested, we don't need to construct the
3038 // explanation.
3039 return first_matcher_.Matches(a_pair.first) &&
3040 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00003041 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003042 StringMatchResultListener first_inner_listener;
3043 if (!first_matcher_.MatchAndExplain(a_pair.first,
3044 &first_inner_listener)) {
3045 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003046 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003047 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003048 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003049 StringMatchResultListener second_inner_listener;
3050 if (!second_matcher_.MatchAndExplain(a_pair.second,
3051 &second_inner_listener)) {
3052 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003053 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003054 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003055 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003056 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3057 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00003058 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003059 }
3060
3061 private:
Nico Weber09fd5b32017-05-15 17:07:03 -04003062 void ExplainSuccess(const std::string& first_explanation,
3063 const std::string& second_explanation,
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003064 MatchResultListener* listener) const {
3065 *listener << "whose both fields match";
3066 if (first_explanation != "") {
3067 *listener << ", where the first field is a value " << first_explanation;
3068 }
3069 if (second_explanation != "") {
3070 *listener << ", ";
3071 if (first_explanation != "") {
3072 *listener << "and ";
3073 } else {
3074 *listener << "where ";
3075 }
3076 *listener << "the second field is a value " << second_explanation;
3077 }
3078 }
3079
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003080 const Matcher<const FirstType&> first_matcher_;
3081 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003082
3083 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003084};
3085
3086// Implements polymorphic Pair(first_matcher, second_matcher).
3087template <typename FirstMatcher, typename SecondMatcher>
3088class PairMatcher {
3089 public:
3090 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3091 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3092
3093 template <typename PairType>
3094 operator Matcher<PairType> () const {
3095 return MakeMatcher(
3096 new PairMatcherImpl<PairType>(
3097 first_matcher_, second_matcher_));
3098 }
3099
3100 private:
3101 const FirstMatcher first_matcher_;
3102 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003103
3104 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003105};
3106
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003107// Implements ElementsAre() and ElementsAreArray().
3108template <typename Container>
3109class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3110 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003111 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003112 typedef internal::StlContainerView<RawContainer> View;
3113 typedef typename View::type StlContainer;
3114 typedef typename View::const_reference StlContainerReference;
3115 typedef typename StlContainer::value_type Element;
3116
3117 // Constructs the matcher from a sequence of element values or
3118 // element matchers.
3119 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00003120 ElementsAreMatcherImpl(InputIter first, InputIter last) {
3121 while (first != last) {
3122 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003123 }
3124 }
3125
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003126 // Describes what this matcher does.
3127 virtual void DescribeTo(::std::ostream* os) const {
3128 if (count() == 0) {
3129 *os << "is empty";
3130 } else if (count() == 1) {
3131 *os << "has 1 element that ";
3132 matchers_[0].DescribeTo(os);
3133 } else {
3134 *os << "has " << Elements(count()) << " where\n";
3135 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003136 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003137 matchers_[i].DescribeTo(os);
3138 if (i + 1 < count()) {
3139 *os << ",\n";
3140 }
3141 }
3142 }
3143 }
3144
3145 // Describes what the negation of this matcher does.
3146 virtual void DescribeNegationTo(::std::ostream* os) const {
3147 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003148 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003149 return;
3150 }
3151
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003152 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003153 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003154 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003155 matchers_[i].DescribeNegationTo(os);
3156 if (i + 1 < count()) {
3157 *os << ", or\n";
3158 }
3159 }
3160 }
3161
zhanyong.wan82113312010-01-08 21:55:40 +00003162 virtual bool MatchAndExplain(Container container,
3163 MatchResultListener* listener) const {
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003164 // To work with stream-like "containers", we must only walk
3165 // through the elements in one pass.
3166
3167 const bool listener_interested = listener->IsInterested();
3168
3169 // explanations[i] is the explanation of the element at index i.
Nico Weber09fd5b32017-05-15 17:07:03 -04003170 ::std::vector<std::string> explanations(count());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003171 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003172 typename StlContainer::const_iterator it = stl_container.begin();
3173 size_t exam_pos = 0;
3174 bool mismatch_found = false; // Have we found a mismatched element yet?
3175
3176 // Go through the elements and matchers in pairs, until we reach
3177 // the end of either the elements or the matchers, or until we find a
3178 // mismatch.
3179 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3180 bool match; // Does the current element match the current matcher?
3181 if (listener_interested) {
3182 StringMatchResultListener s;
3183 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3184 explanations[exam_pos] = s.str();
3185 } else {
3186 match = matchers_[exam_pos].Matches(*it);
3187 }
3188
3189 if (!match) {
3190 mismatch_found = true;
3191 break;
3192 }
3193 }
3194 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3195
3196 // Find how many elements the actual container has. We avoid
3197 // calling size() s.t. this code works for stream-like "containers"
3198 // that don't define size().
3199 size_t actual_count = exam_pos;
3200 for (; it != stl_container.end(); ++it) {
3201 ++actual_count;
3202 }
3203
zhanyong.wan82113312010-01-08 21:55:40 +00003204 if (actual_count != count()) {
3205 // The element count doesn't match. If the container is empty,
3206 // there's no need to explain anything as Google Mock already
3207 // prints the empty container. Otherwise we just need to show
3208 // how many elements there actually are.
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003209 if (listener_interested && (actual_count != 0)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003210 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003211 }
zhanyong.wan82113312010-01-08 21:55:40 +00003212 return false;
3213 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003214
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003215 if (mismatch_found) {
3216 // The element count matches, but the exam_pos-th element doesn't match.
3217 if (listener_interested) {
3218 *listener << "whose element #" << exam_pos << " doesn't match";
3219 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003220 }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003221 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003222 }
zhanyong.wan82113312010-01-08 21:55:40 +00003223
3224 // Every element matches its expectation. We need to explain why
3225 // (the obvious ones can be skipped).
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003226 if (listener_interested) {
3227 bool reason_printed = false;
3228 for (size_t i = 0; i != count(); ++i) {
Nico Weber09fd5b32017-05-15 17:07:03 -04003229 const std::string& s = explanations[i];
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003230 if (!s.empty()) {
3231 if (reason_printed) {
3232 *listener << ",\nand ";
3233 }
3234 *listener << "whose element #" << i << " matches, " << s;
3235 reason_printed = true;
zhanyong.wan82113312010-01-08 21:55:40 +00003236 }
zhanyong.wan82113312010-01-08 21:55:40 +00003237 }
3238 }
zhanyong.wan82113312010-01-08 21:55:40 +00003239 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003240 }
3241
3242 private:
3243 static Message Elements(size_t count) {
3244 return Message() << count << (count == 1 ? " element" : " elements");
3245 }
3246
3247 size_t count() const { return matchers_.size(); }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003248
3249 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003250
3251 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003252};
3253
zhanyong.wanfb25d532013-07-28 08:24:00 +00003254// Connectivity matrix of (elements X matchers), in element-major order.
3255// Initially, there are no edges.
3256// Use NextGraph() to iterate over all possible edge configurations.
3257// Use Randomize() to generate a random edge configuration.
3258class GTEST_API_ MatchMatrix {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003259 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003260 MatchMatrix(size_t num_elements, size_t num_matchers)
3261 : num_elements_(num_elements),
3262 num_matchers_(num_matchers),
3263 matched_(num_elements_* num_matchers_, 0) {
3264 }
3265
3266 size_t LhsSize() const { return num_elements_; }
3267 size_t RhsSize() const { return num_matchers_; }
3268 bool HasEdge(size_t ilhs, size_t irhs) const {
3269 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3270 }
3271 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3272 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3273 }
3274
3275 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3276 // adds 1 to that number; returns false if incrementing the graph left it
3277 // empty.
3278 bool NextGraph();
3279
3280 void Randomize();
3281
Nico Weber09fd5b32017-05-15 17:07:03 -04003282 std::string DebugString() const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003283
3284 private:
3285 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3286 return ilhs * num_matchers_ + irhs;
3287 }
3288
3289 size_t num_elements_;
3290 size_t num_matchers_;
3291
3292 // Each element is a char interpreted as bool. They are stored as a
3293 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3294 // a (ilhs, irhs) matrix coordinate into an offset.
3295 ::std::vector<char> matched_;
3296};
3297
3298typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3299typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3300
3301// Returns a maximum bipartite matching for the specified graph 'g'.
3302// The matching is represented as a vector of {element, matcher} pairs.
3303GTEST_API_ ElementMatcherPairs
3304FindMaxBipartiteMatching(const MatchMatrix& g);
3305
3306GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
3307 MatchResultListener* listener);
3308
3309// Untyped base class for implementing UnorderedElementsAre. By
3310// putting logic that's not specific to the element type here, we
3311// reduce binary bloat and increase compilation speed.
3312class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3313 protected:
3314 // A vector of matcher describers, one for each element matcher.
3315 // Does not own the describers (and thus can be used only when the
3316 // element matchers are alive).
3317 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3318
3319 // Describes this UnorderedElementsAre matcher.
3320 void DescribeToImpl(::std::ostream* os) const;
3321
3322 // Describes the negation of this UnorderedElementsAre matcher.
3323 void DescribeNegationToImpl(::std::ostream* os) const;
3324
3325 bool VerifyAllElementsAndMatchersAreMatched(
Nico Weber09fd5b32017-05-15 17:07:03 -04003326 const ::std::vector<std::string>& element_printouts,
3327 const MatchMatrix& matrix, MatchResultListener* listener) const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003328
3329 MatcherDescriberVec& matcher_describers() {
3330 return matcher_describers_;
3331 }
3332
3333 static Message Elements(size_t n) {
3334 return Message() << n << " element" << (n == 1 ? "" : "s");
3335 }
3336
3337 private:
3338 MatcherDescriberVec matcher_describers_;
3339
3340 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3341};
3342
3343// Implements unordered ElementsAre and unordered ElementsAreArray.
3344template <typename Container>
3345class UnorderedElementsAreMatcherImpl
3346 : public MatcherInterface<Container>,
3347 public UnorderedElementsAreMatcherImplBase {
3348 public:
3349 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3350 typedef internal::StlContainerView<RawContainer> View;
3351 typedef typename View::type StlContainer;
3352 typedef typename View::const_reference StlContainerReference;
3353 typedef typename StlContainer::const_iterator StlContainerConstIterator;
3354 typedef typename StlContainer::value_type Element;
3355
3356 // Constructs the matcher from a sequence of element values or
3357 // element matchers.
3358 template <typename InputIter>
3359 UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) {
3360 for (; first != last; ++first) {
3361 matchers_.push_back(MatcherCast<const Element&>(*first));
3362 matcher_describers().push_back(matchers_.back().GetDescriber());
3363 }
3364 }
3365
3366 // Describes what this matcher does.
3367 virtual void DescribeTo(::std::ostream* os) const {
3368 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3369 }
3370
3371 // Describes what the negation of this matcher does.
3372 virtual void DescribeNegationTo(::std::ostream* os) const {
3373 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3374 }
3375
3376 virtual bool MatchAndExplain(Container container,
3377 MatchResultListener* listener) const {
3378 StlContainerReference stl_container = View::ConstReference(container);
Nico Weber09fd5b32017-05-15 17:07:03 -04003379 ::std::vector<std::string> element_printouts;
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003380 MatchMatrix matrix = AnalyzeElements(stl_container.begin(),
3381 stl_container.end(),
3382 &element_printouts,
3383 listener);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003384
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003385 const size_t actual_count = matrix.LhsSize();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003386 if (actual_count == 0 && matchers_.empty()) {
3387 return true;
3388 }
3389 if (actual_count != matchers_.size()) {
3390 // The element count doesn't match. If the container is empty,
3391 // there's no need to explain anything as Google Mock already
3392 // prints the empty container. Otherwise we just need to show
3393 // how many elements there actually are.
3394 if (actual_count != 0 && listener->IsInterested()) {
3395 *listener << "which has " << Elements(actual_count);
3396 }
3397 return false;
3398 }
3399
zhanyong.wanfb25d532013-07-28 08:24:00 +00003400 return VerifyAllElementsAndMatchersAreMatched(element_printouts,
3401 matrix, listener) &&
3402 FindPairing(matrix, listener);
3403 }
3404
3405 private:
3406 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3407
3408 template <typename ElementIter>
3409 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
Nico Weber09fd5b32017-05-15 17:07:03 -04003410 ::std::vector<std::string>* element_printouts,
zhanyong.wanfb25d532013-07-28 08:24:00 +00003411 MatchResultListener* listener) const {
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003412 element_printouts->clear();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003413 ::std::vector<char> did_match;
3414 size_t num_elements = 0;
3415 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3416 if (listener->IsInterested()) {
3417 element_printouts->push_back(PrintToString(*elem_first));
3418 }
3419 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3420 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3421 }
3422 }
3423
3424 MatchMatrix matrix(num_elements, matchers_.size());
3425 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3426 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3427 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3428 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3429 }
3430 }
3431 return matrix;
3432 }
3433
3434 MatcherVec matchers_;
3435
3436 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3437};
3438
3439// Functor for use in TransformTuple.
3440// Performs MatcherCast<Target> on an input argument of any type.
3441template <typename Target>
3442struct CastAndAppendTransform {
3443 template <typename Arg>
3444 Matcher<Target> operator()(const Arg& a) const {
3445 return MatcherCast<Target>(a);
3446 }
3447};
3448
3449// Implements UnorderedElementsAre.
3450template <typename MatcherTuple>
3451class UnorderedElementsAreMatcher {
3452 public:
3453 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3454 : matchers_(args) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003455
3456 template <typename Container>
3457 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003458 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003459 typedef typename internal::StlContainerView<RawContainer>::type View;
3460 typedef typename View::value_type Element;
3461 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3462 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003463 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003464 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3465 ::std::back_inserter(matchers));
3466 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3467 matchers.begin(), matchers.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003468 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003469
3470 private:
3471 const MatcherTuple matchers_;
3472 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3473};
3474
3475// Implements ElementsAre.
3476template <typename MatcherTuple>
3477class ElementsAreMatcher {
3478 public:
3479 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3480
3481 template <typename Container>
3482 operator Matcher<Container>() const {
3483 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3484 typedef typename internal::StlContainerView<RawContainer>::type View;
3485 typedef typename View::value_type Element;
3486 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3487 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003488 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003489 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3490 ::std::back_inserter(matchers));
3491 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3492 matchers.begin(), matchers.end()));
3493 }
3494
3495 private:
3496 const MatcherTuple matchers_;
3497 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3498};
3499
3500// Implements UnorderedElementsAreArray().
3501template <typename T>
3502class UnorderedElementsAreArrayMatcher {
3503 public:
3504 UnorderedElementsAreArrayMatcher() {}
3505
3506 template <typename Iter>
3507 UnorderedElementsAreArrayMatcher(Iter first, Iter last)
3508 : matchers_(first, last) {}
3509
3510 template <typename Container>
3511 operator Matcher<Container>() const {
3512 return MakeMatcher(
3513 new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(),
3514 matchers_.end()));
3515 }
3516
3517 private:
3518 ::std::vector<T> matchers_;
3519
3520 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003521};
3522
3523// Implements ElementsAreArray().
3524template <typename T>
3525class ElementsAreArrayMatcher {
3526 public:
jgm38513a82012-11-15 15:50:36 +00003527 template <typename Iter>
3528 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003529
3530 template <typename Container>
3531 operator Matcher<Container>() const {
jgm38513a82012-11-15 15:50:36 +00003532 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3533 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003534 }
3535
3536 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003537 const ::std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003538
3539 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003540};
3541
kosak2336e9c2014-07-28 22:57:30 +00003542// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3543// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3544// second) is a polymorphic matcher that matches a value x iff tm
3545// matches tuple (x, second). Useful for implementing
3546// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3547//
3548// BoundSecondMatcher is copyable and assignable, as we need to put
3549// instances of this class in a vector when implementing
3550// UnorderedPointwise().
3551template <typename Tuple2Matcher, typename Second>
3552class BoundSecondMatcher {
3553 public:
3554 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3555 : tuple2_matcher_(tm), second_value_(second) {}
3556
3557 template <typename T>
3558 operator Matcher<T>() const {
3559 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3560 }
3561
3562 // We have to define this for UnorderedPointwise() to compile in
3563 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3564 // which requires the elements to be assignable in C++98. The
3565 // compiler cannot generate the operator= for us, as Tuple2Matcher
3566 // and Second may not be assignable.
3567 //
3568 // However, this should never be called, so the implementation just
3569 // need to assert.
3570 void operator=(const BoundSecondMatcher& /*rhs*/) {
3571 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3572 }
3573
3574 private:
3575 template <typename T>
3576 class Impl : public MatcherInterface<T> {
3577 public:
3578 typedef ::testing::tuple<T, Second> ArgTuple;
3579
3580 Impl(const Tuple2Matcher& tm, const Second& second)
3581 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3582 second_value_(second) {}
3583
3584 virtual void DescribeTo(::std::ostream* os) const {
3585 *os << "and ";
3586 UniversalPrint(second_value_, os);
3587 *os << " ";
3588 mono_tuple2_matcher_.DescribeTo(os);
3589 }
3590
3591 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3592 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3593 listener);
3594 }
3595
3596 private:
3597 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3598 const Second second_value_;
3599
3600 GTEST_DISALLOW_ASSIGN_(Impl);
3601 };
3602
3603 const Tuple2Matcher tuple2_matcher_;
3604 const Second second_value_;
3605};
3606
3607// Given a 2-tuple matcher tm and a value second,
3608// MatcherBindSecond(tm, second) returns a matcher that matches a
3609// value x iff tm matches tuple (x, second). Useful for implementing
3610// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3611template <typename Tuple2Matcher, typename Second>
3612BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
3613 const Tuple2Matcher& tm, const Second& second) {
3614 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
3615}
3616
David Benjaminb3d9be52017-02-10 19:19:54 -05003617// Joins a vector of strings as if they are fields of a tuple; returns
3618// the joined string. This function is exported for testing.
3619GTEST_API_ string JoinAsTuple(const Strings& fields);
3620
zhanyong.wanb4140802010-06-08 22:53:57 +00003621// Returns the description for a matcher defined using the MATCHER*()
3622// macro where the user-supplied description string is "", if
3623// 'negation' is false; otherwise returns the description of the
3624// negation of the matcher. 'param_values' contains a list of strings
3625// that are the print-out of the matcher's parameters.
Nico Weber09fd5b32017-05-15 17:07:03 -04003626GTEST_API_ std::string FormatMatcherDescription(bool negation,
3627 const char* matcher_name,
3628 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003629
shiqiane35fdd92008-12-10 05:08:54 +00003630} // namespace internal
3631
zhanyong.wanfb25d532013-07-28 08:24:00 +00003632// ElementsAreArray(first, last)
3633// ElementsAreArray(pointer, count)
3634// ElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00003635// ElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003636// ElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00003637//
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003638// The ElementsAreArray() functions are like ElementsAre(...), except
3639// that they are given a homogeneous sequence rather than taking each
3640// element as a function argument. The sequence can be specified as an
3641// array, a pointer and count, a vector, an initializer list, or an
3642// STL iterator range. In each of these cases, the underlying sequence
3643// can be either a sequence of values or a sequence of matchers.
zhanyong.wanfb25d532013-07-28 08:24:00 +00003644//
3645// All forms of ElementsAreArray() make a copy of the input matcher sequence.
3646
3647template <typename Iter>
3648inline internal::ElementsAreArrayMatcher<
3649 typename ::std::iterator_traits<Iter>::value_type>
3650ElementsAreArray(Iter first, Iter last) {
3651 typedef typename ::std::iterator_traits<Iter>::value_type T;
3652 return internal::ElementsAreArrayMatcher<T>(first, last);
3653}
3654
3655template <typename T>
3656inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3657 const T* pointer, size_t count) {
3658 return ElementsAreArray(pointer, pointer + count);
3659}
3660
3661template <typename T, size_t N>
3662inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3663 const T (&array)[N]) {
3664 return ElementsAreArray(array, N);
3665}
3666
kosak06678922014-07-28 20:01:28 +00003667template <typename Container>
3668inline internal::ElementsAreArrayMatcher<typename Container::value_type>
3669ElementsAreArray(const Container& container) {
3670 return ElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00003671}
3672
kosak18489fa2013-12-04 23:49:07 +00003673#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003674template <typename T>
3675inline internal::ElementsAreArrayMatcher<T>
3676ElementsAreArray(::std::initializer_list<T> xs) {
3677 return ElementsAreArray(xs.begin(), xs.end());
3678}
3679#endif
3680
zhanyong.wanfb25d532013-07-28 08:24:00 +00003681// UnorderedElementsAreArray(first, last)
3682// UnorderedElementsAreArray(pointer, count)
3683// UnorderedElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00003684// UnorderedElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003685// UnorderedElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00003686//
3687// The UnorderedElementsAreArray() functions are like
3688// ElementsAreArray(...), but allow matching the elements in any order.
3689template <typename Iter>
3690inline internal::UnorderedElementsAreArrayMatcher<
3691 typename ::std::iterator_traits<Iter>::value_type>
3692UnorderedElementsAreArray(Iter first, Iter last) {
3693 typedef typename ::std::iterator_traits<Iter>::value_type T;
3694 return internal::UnorderedElementsAreArrayMatcher<T>(first, last);
3695}
3696
3697template <typename T>
3698inline internal::UnorderedElementsAreArrayMatcher<T>
3699UnorderedElementsAreArray(const T* pointer, size_t count) {
3700 return UnorderedElementsAreArray(pointer, pointer + count);
3701}
3702
3703template <typename T, size_t N>
3704inline internal::UnorderedElementsAreArrayMatcher<T>
3705UnorderedElementsAreArray(const T (&array)[N]) {
3706 return UnorderedElementsAreArray(array, N);
3707}
3708
kosak06678922014-07-28 20:01:28 +00003709template <typename Container>
3710inline internal::UnorderedElementsAreArrayMatcher<
3711 typename Container::value_type>
3712UnorderedElementsAreArray(const Container& container) {
3713 return UnorderedElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00003714}
3715
kosak18489fa2013-12-04 23:49:07 +00003716#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003717template <typename T>
3718inline internal::UnorderedElementsAreArrayMatcher<T>
3719UnorderedElementsAreArray(::std::initializer_list<T> xs) {
3720 return UnorderedElementsAreArray(xs.begin(), xs.end());
3721}
3722#endif
zhanyong.wanfb25d532013-07-28 08:24:00 +00003723
shiqiane35fdd92008-12-10 05:08:54 +00003724// _ is a matcher that matches anything of any type.
3725//
3726// This definition is fine as:
3727//
3728// 1. The C++ standard permits using the name _ in a namespace that
3729// is not the global namespace or ::std.
3730// 2. The AnythingMatcher class has no data member or constructor,
3731// so it's OK to create global variables of this type.
3732// 3. c-style has approved of using _ in this case.
3733const internal::AnythingMatcher _ = {};
3734// Creates a matcher that matches any value of the given type T.
3735template <typename T>
3736inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
3737
3738// Creates a matcher that matches any value of the given type T.
3739template <typename T>
3740inline Matcher<T> An() { return A<T>(); }
3741
3742// Creates a polymorphic matcher that matches anything equal to x.
3743// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
3744// wouldn't compile.
3745template <typename T>
3746inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
3747
3748// Constructs a Matcher<T> from a 'value' of type T. The constructed
3749// matcher matches any value that's equal to 'value'.
3750template <typename T>
3751Matcher<T>::Matcher(T value) { *this = Eq(value); }
3752
3753// Creates a monomorphic matcher that matches anything with type Lhs
3754// and equal to rhs. A user may need to use this instead of Eq(...)
3755// in order to resolve an overloading ambiguity.
3756//
3757// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
3758// or Matcher<T>(x), but more readable than the latter.
3759//
3760// We could define similar monomorphic matchers for other comparison
3761// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
3762// it yet as those are used much less than Eq() in practice. A user
3763// can always write Matcher<T>(Lt(5)) to be explicit about the type,
3764// for example.
3765template <typename Lhs, typename Rhs>
3766inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
3767
3768// Creates a polymorphic matcher that matches anything >= x.
3769template <typename Rhs>
3770inline internal::GeMatcher<Rhs> Ge(Rhs x) {
3771 return internal::GeMatcher<Rhs>(x);
3772}
3773
3774// Creates a polymorphic matcher that matches anything > x.
3775template <typename Rhs>
3776inline internal::GtMatcher<Rhs> Gt(Rhs x) {
3777 return internal::GtMatcher<Rhs>(x);
3778}
3779
3780// Creates a polymorphic matcher that matches anything <= x.
3781template <typename Rhs>
3782inline internal::LeMatcher<Rhs> Le(Rhs x) {
3783 return internal::LeMatcher<Rhs>(x);
3784}
3785
3786// Creates a polymorphic matcher that matches anything < x.
3787template <typename Rhs>
3788inline internal::LtMatcher<Rhs> Lt(Rhs x) {
3789 return internal::LtMatcher<Rhs>(x);
3790}
3791
3792// Creates a polymorphic matcher that matches anything != x.
3793template <typename Rhs>
3794inline internal::NeMatcher<Rhs> Ne(Rhs x) {
3795 return internal::NeMatcher<Rhs>(x);
3796}
3797
zhanyong.wan2d970ee2009-09-24 21:41:36 +00003798// Creates a polymorphic matcher that matches any NULL pointer.
3799inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
3800 return MakePolymorphicMatcher(internal::IsNullMatcher());
3801}
3802
shiqiane35fdd92008-12-10 05:08:54 +00003803// Creates a polymorphic matcher that matches any non-NULL pointer.
3804// This is convenient as Not(NULL) doesn't compile (the compiler
3805// thinks that that expression is comparing a pointer with an integer).
3806inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
3807 return MakePolymorphicMatcher(internal::NotNullMatcher());
3808}
3809
3810// Creates a polymorphic matcher that matches any argument that
3811// references variable x.
3812template <typename T>
3813inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
3814 return internal::RefMatcher<T&>(x);
3815}
3816
3817// Creates a matcher that matches any double argument approximately
3818// equal to rhs, where two NANs are considered unequal.
3819inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
3820 return internal::FloatingEqMatcher<double>(rhs, false);
3821}
3822
3823// Creates a matcher that matches any double argument approximately
3824// equal to rhs, including NaN values when rhs is NaN.
3825inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
3826 return internal::FloatingEqMatcher<double>(rhs, true);
3827}
3828
zhanyong.wan616180e2013-06-18 18:49:51 +00003829// Creates a matcher that matches any double argument approximately equal to
3830// rhs, up to the specified max absolute error bound, where two NANs are
3831// considered unequal. The max absolute error bound must be non-negative.
3832inline internal::FloatingEqMatcher<double> DoubleNear(
3833 double rhs, double max_abs_error) {
3834 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
3835}
3836
3837// Creates a matcher that matches any double argument approximately equal to
3838// rhs, up to the specified max absolute error bound, including NaN values when
3839// rhs is NaN. The max absolute error bound must be non-negative.
3840inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
3841 double rhs, double max_abs_error) {
3842 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
3843}
3844
shiqiane35fdd92008-12-10 05:08:54 +00003845// Creates a matcher that matches any float argument approximately
3846// equal to rhs, where two NANs are considered unequal.
3847inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
3848 return internal::FloatingEqMatcher<float>(rhs, false);
3849}
3850
zhanyong.wan616180e2013-06-18 18:49:51 +00003851// Creates a matcher that matches any float argument approximately
shiqiane35fdd92008-12-10 05:08:54 +00003852// equal to rhs, including NaN values when rhs is NaN.
3853inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
3854 return internal::FloatingEqMatcher<float>(rhs, true);
3855}
3856
zhanyong.wan616180e2013-06-18 18:49:51 +00003857// Creates a matcher that matches any float argument approximately equal to
3858// rhs, up to the specified max absolute error bound, where two NANs are
3859// considered unequal. The max absolute error bound must be non-negative.
3860inline internal::FloatingEqMatcher<float> FloatNear(
3861 float rhs, float max_abs_error) {
3862 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
3863}
3864
3865// Creates a matcher that matches any float argument approximately equal to
3866// rhs, up to the specified max absolute error bound, including NaN values when
3867// rhs is NaN. The max absolute error bound must be non-negative.
3868inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
3869 float rhs, float max_abs_error) {
3870 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
3871}
3872
shiqiane35fdd92008-12-10 05:08:54 +00003873// Creates a matcher that matches a pointer (raw or smart) that points
3874// to a value that matches inner_matcher.
3875template <typename InnerMatcher>
3876inline internal::PointeeMatcher<InnerMatcher> Pointee(
3877 const InnerMatcher& inner_matcher) {
3878 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
3879}
3880
billydonahue1f5fdea2014-05-19 17:54:51 +00003881// Creates a matcher that matches a pointer or reference that matches
3882// inner_matcher when dynamic_cast<To> is applied.
3883// The result of dynamic_cast<To> is forwarded to the inner matcher.
3884// If To is a pointer and the cast fails, the inner matcher will receive NULL.
3885// If To is a reference and the cast fails, this matcher returns false
3886// immediately.
3887template <typename To>
3888inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
3889WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
3890 return MakePolymorphicMatcher(
3891 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
3892}
3893
shiqiane35fdd92008-12-10 05:08:54 +00003894// Creates a matcher that matches an object whose given field matches
3895// 'matcher'. For example,
3896// Field(&Foo::number, Ge(5))
3897// matches a Foo object x iff x.number >= 5.
3898template <typename Class, typename FieldType, typename FieldMatcher>
3899inline PolymorphicMatcher<
3900 internal::FieldMatcher<Class, FieldType> > Field(
3901 FieldType Class::*field, const FieldMatcher& matcher) {
3902 return MakePolymorphicMatcher(
3903 internal::FieldMatcher<Class, FieldType>(
3904 field, MatcherCast<const FieldType&>(matcher)));
3905 // The call to MatcherCast() is required for supporting inner
3906 // matchers of compatible types. For example, it allows
3907 // Field(&Foo::bar, m)
3908 // to compile where bar is an int32 and m is a matcher for int64.
3909}
3910
3911// Creates a matcher that matches an object whose given property
3912// matches 'matcher'. For example,
3913// Property(&Foo::str, StartsWith("hi"))
3914// matches a Foo object x iff x.str() starts with "hi".
3915template <typename Class, typename PropertyType, typename PropertyMatcher>
Roman Perepelitsa966b5492017-08-22 16:06:26 +02003916inline PolymorphicMatcher<internal::PropertyMatcher<
3917 Class, PropertyType, PropertyType (Class::*)() const> >
3918Property(PropertyType (Class::*property)() const,
3919 const PropertyMatcher& matcher) {
shiqiane35fdd92008-12-10 05:08:54 +00003920 return MakePolymorphicMatcher(
Roman Perepelitsa966b5492017-08-22 16:06:26 +02003921 internal::PropertyMatcher<Class, PropertyType,
3922 PropertyType (Class::*)() const>(
shiqiane35fdd92008-12-10 05:08:54 +00003923 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00003924 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00003925 // The call to MatcherCast() is required for supporting inner
3926 // matchers of compatible types. For example, it allows
3927 // Property(&Foo::bar, m)
3928 // to compile where bar() returns an int32 and m is a matcher for int64.
3929}
3930
Roman Perepelitsa966b5492017-08-22 16:06:26 +02003931#if GTEST_LANG_CXX11
3932// The same as above but for reference-qualified member functions.
3933template <typename Class, typename PropertyType, typename PropertyMatcher>
3934inline PolymorphicMatcher<internal::PropertyMatcher<
3935 Class, PropertyType, PropertyType (Class::*)() const &> >
3936Property(PropertyType (Class::*property)() const &,
3937 const PropertyMatcher& matcher) {
3938 return MakePolymorphicMatcher(
3939 internal::PropertyMatcher<Class, PropertyType,
3940 PropertyType (Class::*)() const &>(
3941 property,
3942 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
3943}
3944#endif
3945
shiqiane35fdd92008-12-10 05:08:54 +00003946// Creates a matcher that matches an object iff the result of applying
3947// a callable to x matches 'matcher'.
3948// For example,
3949// ResultOf(f, StartsWith("hi"))
3950// matches a Foo object x iff f(x) starts with "hi".
3951// callable parameter can be a function, function pointer, or a functor.
3952// Callable has to satisfy the following conditions:
3953// * It is required to keep no state affecting the results of
3954// the calls on it and make no assumptions about how many calls
3955// will be made. Any state it keeps must be protected from the
3956// concurrent access.
3957// * If it is a function object, it has to define type result_type.
3958// We recommend deriving your functor classes from std::unary_function.
3959template <typename Callable, typename ResultOfMatcher>
3960internal::ResultOfMatcher<Callable> ResultOf(
3961 Callable callable, const ResultOfMatcher& matcher) {
3962 return internal::ResultOfMatcher<Callable>(
3963 callable,
3964 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
3965 matcher));
3966 // The call to MatcherCast() is required for supporting inner
3967 // matchers of compatible types. For example, it allows
3968 // ResultOf(Function, m)
3969 // to compile where Function() returns an int32 and m is a matcher for int64.
3970}
3971
3972// String matchers.
3973
3974// Matches a string equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04003975inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
3976 const std::string& str) {
3977 return MakePolymorphicMatcher(
3978 internal::StrEqualityMatcher<std::string>(str, true, true));
shiqiane35fdd92008-12-10 05:08:54 +00003979}
3980
3981// Matches a string not equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04003982inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
3983 const std::string& str) {
3984 return MakePolymorphicMatcher(
3985 internal::StrEqualityMatcher<std::string>(str, false, true));
shiqiane35fdd92008-12-10 05:08:54 +00003986}
3987
3988// Matches a string equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04003989inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
3990 const std::string& str) {
3991 return MakePolymorphicMatcher(
3992 internal::StrEqualityMatcher<std::string>(str, true, false));
shiqiane35fdd92008-12-10 05:08:54 +00003993}
3994
3995// Matches a string not equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04003996inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
3997 const std::string& str) {
3998 return MakePolymorphicMatcher(
3999 internal::StrEqualityMatcher<std::string>(str, false, false));
shiqiane35fdd92008-12-10 05:08:54 +00004000}
4001
4002// Creates a matcher that matches any string, std::string, or C string
4003// that contains the given substring.
Nico Weber09fd5b32017-05-15 17:07:03 -04004004inline PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
4005 const std::string& substring) {
4006 return MakePolymorphicMatcher(
4007 internal::HasSubstrMatcher<std::string>(substring));
shiqiane35fdd92008-12-10 05:08:54 +00004008}
4009
4010// Matches a string that starts with 'prefix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004011inline PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
4012 const std::string& prefix) {
4013 return MakePolymorphicMatcher(
4014 internal::StartsWithMatcher<std::string>(prefix));
shiqiane35fdd92008-12-10 05:08:54 +00004015}
4016
4017// Matches a string that ends with 'suffix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004018inline PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
4019 const std::string& suffix) {
4020 return MakePolymorphicMatcher(internal::EndsWithMatcher<std::string>(suffix));
shiqiane35fdd92008-12-10 05:08:54 +00004021}
4022
shiqiane35fdd92008-12-10 05:08:54 +00004023// Matches a string that fully matches regular expression 'regex'.
4024// The matcher takes ownership of 'regex'.
4025inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4026 const internal::RE* regex) {
4027 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
4028}
4029inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004030 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004031 return MatchesRegex(new internal::RE(regex));
4032}
4033
4034// Matches a string that contains regular expression 'regex'.
4035// The matcher takes ownership of 'regex'.
4036inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4037 const internal::RE* regex) {
4038 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4039}
4040inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004041 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004042 return ContainsRegex(new internal::RE(regex));
4043}
4044
shiqiane35fdd92008-12-10 05:08:54 +00004045#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4046// Wide string matchers.
4047
4048// Matches a string equal to str.
4049inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4050 StrEq(const internal::wstring& str) {
4051 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4052 str, true, true));
4053}
4054
4055// Matches a string not equal to str.
4056inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4057 StrNe(const internal::wstring& str) {
4058 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4059 str, false, true));
4060}
4061
4062// Matches a string equal to str, ignoring case.
4063inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4064 StrCaseEq(const internal::wstring& str) {
4065 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4066 str, true, false));
4067}
4068
4069// Matches a string not equal to str, ignoring case.
4070inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4071 StrCaseNe(const internal::wstring& str) {
4072 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4073 str, false, false));
4074}
4075
4076// Creates a matcher that matches any wstring, std::wstring, or C wide string
4077// that contains the given substring.
4078inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
4079 HasSubstr(const internal::wstring& substring) {
4080 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
4081 substring));
4082}
4083
4084// Matches a string that starts with 'prefix' (case-sensitive).
4085inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
4086 StartsWith(const internal::wstring& prefix) {
4087 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
4088 prefix));
4089}
4090
4091// Matches a string that ends with 'suffix' (case-sensitive).
4092inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
4093 EndsWith(const internal::wstring& suffix) {
4094 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
4095 suffix));
4096}
4097
4098#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4099
4100// Creates a polymorphic matcher that matches a 2-tuple where the
4101// first field == the second field.
4102inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4103
4104// Creates a polymorphic matcher that matches a 2-tuple where the
4105// first field >= the second field.
4106inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4107
4108// Creates a polymorphic matcher that matches a 2-tuple where the
4109// first field > the second field.
4110inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4111
4112// Creates a polymorphic matcher that matches a 2-tuple where the
4113// first field <= the second field.
4114inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4115
4116// Creates a polymorphic matcher that matches a 2-tuple where the
4117// first field < the second field.
4118inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4119
4120// Creates a polymorphic matcher that matches a 2-tuple where the
4121// first field != the second field.
4122inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4123
4124// Creates a matcher that matches any value of type T that m doesn't
4125// match.
4126template <typename InnerMatcher>
4127inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4128 return internal::NotMatcher<InnerMatcher>(m);
4129}
4130
shiqiane35fdd92008-12-10 05:08:54 +00004131// Returns a matcher that matches anything that satisfies the given
4132// predicate. The predicate can be any unary function or functor
4133// whose return type can be implicitly converted to bool.
4134template <typename Predicate>
4135inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4136Truly(Predicate pred) {
4137 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4138}
4139
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004140// Returns a matcher that matches the container size. The container must
4141// support both size() and size_type which all STL-like containers provide.
4142// Note that the parameter 'size' can be a value of type size_type as well as
4143// matcher. For instance:
4144// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
4145// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
4146template <typename SizeMatcher>
4147inline internal::SizeIsMatcher<SizeMatcher>
4148SizeIs(const SizeMatcher& size_matcher) {
4149 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4150}
4151
kosakb6a34882014-03-12 21:06:46 +00004152// Returns a matcher that matches the distance between the container's begin()
4153// iterator and its end() iterator, i.e. the size of the container. This matcher
4154// can be used instead of SizeIs with containers such as std::forward_list which
4155// do not implement size(). The container must provide const_iterator (with
4156// valid iterator_traits), begin() and end().
4157template <typename DistanceMatcher>
4158inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4159BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4160 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4161}
4162
zhanyong.wan6a896b52009-01-16 01:13:50 +00004163// Returns a matcher that matches an equal container.
4164// This matcher behaves like Eq(), but in the event of mismatch lists the
4165// values that are included in one container but not the other. (Duplicate
4166// values and order differences are not explained.)
4167template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00004168inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00004169 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004170 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00004171 // This following line is for working around a bug in MSVC 8.0,
4172 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00004173 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00004174 return MakePolymorphicMatcher(
4175 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00004176}
4177
zhanyong.wan898725c2011-09-16 16:45:39 +00004178// Returns a matcher that matches a container that, when sorted using
4179// the given comparator, matches container_matcher.
4180template <typename Comparator, typename ContainerMatcher>
4181inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4182WhenSortedBy(const Comparator& comparator,
4183 const ContainerMatcher& container_matcher) {
4184 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4185 comparator, container_matcher);
4186}
4187
4188// Returns a matcher that matches a container that, when sorted using
4189// the < operator, matches container_matcher.
4190template <typename ContainerMatcher>
4191inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4192WhenSorted(const ContainerMatcher& container_matcher) {
4193 return
4194 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4195 internal::LessComparator(), container_matcher);
4196}
4197
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004198// Matches an STL-style container or a native array that contains the
4199// same number of elements as in rhs, where its i-th element and rhs's
4200// i-th element (as a pair) satisfy the given pair matcher, for all i.
4201// TupleMatcher must be able to be safely cast to Matcher<tuple<const
4202// T1&, const T2&> >, where T1 and T2 are the types of elements in the
4203// LHS container and the RHS container respectively.
4204template <typename TupleMatcher, typename Container>
4205inline internal::PointwiseMatcher<TupleMatcher,
4206 GTEST_REMOVE_CONST_(Container)>
4207Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4208 // This following line is for working around a bug in MSVC 8.0,
kosak2336e9c2014-07-28 22:57:30 +00004209 // which causes Container to be a const type sometimes (e.g. when
4210 // rhs is a const int[])..
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004211 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4212 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4213 tuple_matcher, rhs);
4214}
4215
kosak2336e9c2014-07-28 22:57:30 +00004216#if GTEST_HAS_STD_INITIALIZER_LIST_
4217
4218// Supports the Pointwise(m, {a, b, c}) syntax.
4219template <typename TupleMatcher, typename T>
4220inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4221 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4222 return Pointwise(tuple_matcher, std::vector<T>(rhs));
4223}
4224
4225#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4226
4227// UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4228// container or a native array that contains the same number of
4229// elements as in rhs, where in some permutation of the container, its
4230// i-th element and rhs's i-th element (as a pair) satisfy the given
4231// pair matcher, for all i. Tuple2Matcher must be able to be safely
4232// cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4233// the types of elements in the LHS container and the RHS container
4234// respectively.
4235//
4236// This is like Pointwise(pair_matcher, rhs), except that the element
4237// order doesn't matter.
4238template <typename Tuple2Matcher, typename RhsContainer>
4239inline internal::UnorderedElementsAreArrayMatcher<
4240 typename internal::BoundSecondMatcher<
4241 Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4242 RhsContainer)>::type::value_type> >
4243UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4244 const RhsContainer& rhs_container) {
4245 // This following line is for working around a bug in MSVC 8.0,
4246 // which causes RhsContainer to be a const type sometimes (e.g. when
4247 // rhs_container is a const int[]).
4248 typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4249
4250 // RhsView allows the same code to handle RhsContainer being a
4251 // STL-style container and it being a native C-style array.
4252 typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4253 typedef typename RhsView::type RhsStlContainer;
4254 typedef typename RhsStlContainer::value_type Second;
4255 const RhsStlContainer& rhs_stl_container =
4256 RhsView::ConstReference(rhs_container);
4257
4258 // Create a matcher for each element in rhs_container.
4259 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4260 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4261 it != rhs_stl_container.end(); ++it) {
4262 matchers.push_back(
4263 internal::MatcherBindSecond(tuple2_matcher, *it));
4264 }
4265
4266 // Delegate the work to UnorderedElementsAreArray().
4267 return UnorderedElementsAreArray(matchers);
4268}
4269
4270#if GTEST_HAS_STD_INITIALIZER_LIST_
4271
4272// Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4273template <typename Tuple2Matcher, typename T>
4274inline internal::UnorderedElementsAreArrayMatcher<
4275 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4276UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4277 std::initializer_list<T> rhs) {
4278 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4279}
4280
4281#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4282
zhanyong.wanb8243162009-06-04 05:48:20 +00004283// Matches an STL-style container or a native array that contains at
4284// least one element matching the given value or matcher.
4285//
4286// Examples:
4287// ::std::set<int> page_ids;
4288// page_ids.insert(3);
4289// page_ids.insert(1);
4290// EXPECT_THAT(page_ids, Contains(1));
4291// EXPECT_THAT(page_ids, Contains(Gt(2)));
4292// EXPECT_THAT(page_ids, Not(Contains(4)));
4293//
4294// ::std::map<int, size_t> page_lengths;
4295// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00004296// EXPECT_THAT(page_lengths,
4297// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004298//
4299// const char* user_ids[] = { "joe", "mike", "tom" };
4300// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4301template <typename M>
4302inline internal::ContainsMatcher<M> Contains(M matcher) {
4303 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004304}
4305
zhanyong.wan33605ba2010-04-22 23:37:47 +00004306// Matches an STL-style container or a native array that contains only
4307// elements matching the given value or matcher.
4308//
4309// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
4310// the messages are different.
4311//
4312// Examples:
4313// ::std::set<int> page_ids;
4314// // Each(m) matches an empty container, regardless of what m is.
4315// EXPECT_THAT(page_ids, Each(Eq(1)));
4316// EXPECT_THAT(page_ids, Each(Eq(77)));
4317//
4318// page_ids.insert(3);
4319// EXPECT_THAT(page_ids, Each(Gt(0)));
4320// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
4321// page_ids.insert(1);
4322// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
4323//
4324// ::std::map<int, size_t> page_lengths;
4325// page_lengths[1] = 100;
4326// page_lengths[2] = 200;
4327// page_lengths[3] = 300;
4328// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
4329// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
4330//
4331// const char* user_ids[] = { "joe", "mike", "tom" };
4332// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
4333template <typename M>
4334inline internal::EachMatcher<M> Each(M matcher) {
4335 return internal::EachMatcher<M>(matcher);
4336}
4337
zhanyong.wanb5937da2009-07-16 20:26:41 +00004338// Key(inner_matcher) matches an std::pair whose 'first' field matches
4339// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
4340// std::map that contains at least one element whose key is >= 5.
4341template <typename M>
4342inline internal::KeyMatcher<M> Key(M inner_matcher) {
4343 return internal::KeyMatcher<M>(inner_matcher);
4344}
4345
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00004346// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
4347// matches first_matcher and whose 'second' field matches second_matcher. For
4348// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
4349// to match a std::map<int, string> that contains exactly one element whose key
4350// is >= 5 and whose value equals "foo".
4351template <typename FirstMatcher, typename SecondMatcher>
4352inline internal::PairMatcher<FirstMatcher, SecondMatcher>
4353Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
4354 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
4355 first_matcher, second_matcher);
4356}
4357
shiqiane35fdd92008-12-10 05:08:54 +00004358// Returns a predicate that is satisfied by anything that matches the
4359// given matcher.
4360template <typename M>
4361inline internal::MatcherAsPredicate<M> Matches(M matcher) {
4362 return internal::MatcherAsPredicate<M>(matcher);
4363}
4364
zhanyong.wanb8243162009-06-04 05:48:20 +00004365// Returns true iff the value matches the matcher.
4366template <typename T, typename M>
4367inline bool Value(const T& value, M matcher) {
4368 return testing::Matches(matcher)(value);
4369}
4370
zhanyong.wan34b034c2010-03-05 21:23:23 +00004371// Matches the value against the given matcher and explains the match
4372// result to listener.
4373template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00004374inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00004375 M matcher, const T& value, MatchResultListener* listener) {
4376 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
4377}
4378
zhanyong.wan616180e2013-06-18 18:49:51 +00004379#if GTEST_LANG_CXX11
4380// Define variadic matcher versions. They are overloaded in
4381// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
4382template <typename... Args>
4383inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
4384 return internal::AllOfMatcher<Args...>(matchers...);
4385}
4386
4387template <typename... Args>
4388inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
4389 return internal::AnyOfMatcher<Args...>(matchers...);
4390}
4391
4392#endif // GTEST_LANG_CXX11
4393
zhanyong.wanbf550852009-06-09 06:09:53 +00004394// AllArgs(m) is a synonym of m. This is useful in
4395//
4396// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
4397//
4398// which is easier to read than
4399//
4400// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
4401template <typename InnerMatcher>
4402inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
4403
shiqiane35fdd92008-12-10 05:08:54 +00004404// These macros allow using matchers to check values in Google Test
4405// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
4406// succeed iff the value matches the matcher. If the assertion fails,
4407// the value and the description of the matcher will be printed.
4408#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
4409 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4410#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
4411 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4412
4413} // namespace testing
4414
kosak6702b972015-07-27 23:05:57 +00004415// Include any custom callback matchers added by the local installation.
4416// We must include this header at the end to make sure it can use the
4417// declarations from this file.
4418#include "gmock/internal/custom/gmock-matchers.h"
shiqiane35fdd92008-12-10 05:08:54 +00004419#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_