blob: bd90d81f6b9332e9401bea56e30893a9f8650efd [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>
50
zhanyong.wan53e08c42010-09-14 05:38:21 +000051#include "gmock/internal/gmock-internal-utils.h"
52#include "gmock/internal/gmock-port.h"
53#include "gtest/gtest.h"
shiqiane35fdd92008-12-10 05:08:54 +000054
kosak18489fa2013-12-04 23:49:07 +000055#if GTEST_HAS_STD_INITIALIZER_LIST_
56# include <initializer_list> // NOLINT -- must be after gtest.h
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +000057#endif
58
shiqiane35fdd92008-12-10 05:08:54 +000059namespace testing {
60
61// To implement a matcher Foo for type T, define:
62// 1. a class FooMatcherImpl that implements the
63// MatcherInterface<T> interface, and
64// 2. a factory function that creates a Matcher<T> object from a
65// FooMatcherImpl*.
66//
67// The two-level delegation design makes it possible to allow a user
68// to write "v" instead of "Eq(v)" where a Matcher is expected, which
69// is impossible if we pass matchers by pointers. It also eases
70// ownership management as Matcher objects can now be copied like
71// plain values.
72
zhanyong.wan82113312010-01-08 21:55:40 +000073// MatchResultListener is an abstract class. Its << operator can be
74// used by a matcher to explain why a value matches or doesn't match.
75//
76// TODO(wan@google.com): add method
77// bool InterestedInWhy(bool result) const;
78// to indicate whether the listener is interested in why the match
79// result is 'result'.
80class MatchResultListener {
81 public:
82 // Creates a listener object with the given underlying ostream. The
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +000083 // listener does not own the ostream, and does not dereference it
84 // in the constructor or destructor.
zhanyong.wan82113312010-01-08 21:55:40 +000085 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
86 virtual ~MatchResultListener() = 0; // Makes this class abstract.
87
88 // Streams x to the underlying ostream; does nothing if the ostream
89 // is NULL.
90 template <typename T>
91 MatchResultListener& operator<<(const T& x) {
92 if (stream_ != NULL)
93 *stream_ << x;
94 return *this;
95 }
96
97 // Returns the underlying ostream.
98 ::std::ostream* stream() { return stream_; }
99
zhanyong.wana862f1d2010-03-15 21:23:04 +0000100 // Returns true iff the listener is interested in an explanation of
101 // the match result. A matcher's MatchAndExplain() method can use
102 // this information to avoid generating the explanation when no one
103 // intends to hear it.
104 bool IsInterested() const { return stream_ != NULL; }
105
zhanyong.wan82113312010-01-08 21:55:40 +0000106 private:
107 ::std::ostream* const stream_;
108
109 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
110};
111
112inline MatchResultListener::~MatchResultListener() {
113}
114
zhanyong.wanfb25d532013-07-28 08:24:00 +0000115// An instance of a subclass of this knows how to describe itself as a
116// matcher.
117class MatcherDescriberInterface {
118 public:
119 virtual ~MatcherDescriberInterface() {}
120
121 // Describes this matcher to an ostream. The function should print
122 // a verb phrase that describes the property a value matching this
123 // matcher should have. The subject of the verb phrase is the value
124 // being matched. For example, the DescribeTo() method of the Gt(7)
125 // matcher prints "is greater than 7".
126 virtual void DescribeTo(::std::ostream* os) const = 0;
127
128 // Describes the negation of this matcher to an ostream. For
129 // example, if the description of this matcher is "is greater than
130 // 7", the negated description could be "is not greater than 7".
131 // You are not required to override this when implementing
132 // MatcherInterface, but it is highly advised so that your matcher
133 // can produce good error messages.
134 virtual void DescribeNegationTo(::std::ostream* os) const {
135 *os << "not (";
136 DescribeTo(os);
137 *os << ")";
138 }
139};
140
shiqiane35fdd92008-12-10 05:08:54 +0000141// The implementation of a matcher.
142template <typename T>
zhanyong.wanfb25d532013-07-28 08:24:00 +0000143class MatcherInterface : public MatcherDescriberInterface {
shiqiane35fdd92008-12-10 05:08:54 +0000144 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000145 // Returns true iff the matcher matches x; also explains the match
zhanyong.wan83f6b082013-03-01 01:47:35 +0000146 // result to 'listener' if necessary (see the next paragraph), in
147 // the form of a non-restrictive relative clause ("which ...",
148 // "whose ...", etc) that describes x. For example, the
149 // MatchAndExplain() method of the Pointee(...) matcher should
150 // generate an explanation like "which points to ...".
151 //
152 // Implementations of MatchAndExplain() should add an explanation of
153 // the match result *if and only if* they can provide additional
154 // information that's not already present (or not obvious) in the
155 // print-out of x and the matcher's description. Whether the match
156 // succeeds is not a factor in deciding whether an explanation is
157 // needed, as sometimes the caller needs to print a failure message
158 // when the match succeeds (e.g. when the matcher is used inside
159 // Not()).
160 //
161 // For example, a "has at least 10 elements" matcher should explain
162 // what the actual element count is, regardless of the match result,
163 // as it is useful information to the reader; on the other hand, an
164 // "is empty" matcher probably only needs to explain what the actual
165 // size is when the match fails, as it's redundant to say that the
166 // size is 0 when the value is already known to be empty.
zhanyong.wan82113312010-01-08 21:55:40 +0000167 //
zhanyong.wandb22c222010-01-28 21:52:29 +0000168 // You should override this method when defining a new matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000169 //
170 // It's the responsibility of the caller (Google Mock) to guarantee
171 // that 'listener' is not NULL. This helps to simplify a matcher's
172 // implementation when it doesn't care about the performance, as it
173 // can talk to 'listener' without checking its validity first.
174 // However, in order to implement dummy listeners efficiently,
175 // listener->stream() may be NULL.
zhanyong.wandb22c222010-01-28 21:52:29 +0000176 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
shiqiane35fdd92008-12-10 05:08:54 +0000177
zhanyong.wanfb25d532013-07-28 08:24:00 +0000178 // Inherits these methods from MatcherDescriberInterface:
179 // virtual void DescribeTo(::std::ostream* os) const = 0;
180 // virtual void DescribeNegationTo(::std::ostream* os) const;
shiqiane35fdd92008-12-10 05:08:54 +0000181};
182
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000183// A match result listener that stores the explanation in a string.
184class StringMatchResultListener : public MatchResultListener {
185 public:
186 StringMatchResultListener() : MatchResultListener(&ss_) {}
187
188 // Returns the explanation accumulated so far.
189 internal::string str() const { return ss_.str(); }
190
191 // Clears the explanation accumulated so far.
192 void Clear() { ss_.str(""); }
193
194 private:
195 ::std::stringstream ss_;
196
197 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
198};
199
shiqiane35fdd92008-12-10 05:08:54 +0000200namespace internal {
201
zhanyong.wan82113312010-01-08 21:55:40 +0000202// A match result listener that ignores the explanation.
203class DummyMatchResultListener : public MatchResultListener {
204 public:
205 DummyMatchResultListener() : MatchResultListener(NULL) {}
206
207 private:
208 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
209};
210
211// A match result listener that forwards the explanation to a given
212// ostream. The difference between this and MatchResultListener is
213// that the former is concrete.
214class StreamMatchResultListener : public MatchResultListener {
215 public:
216 explicit StreamMatchResultListener(::std::ostream* os)
217 : MatchResultListener(os) {}
218
219 private:
220 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
221};
222
shiqiane35fdd92008-12-10 05:08:54 +0000223// An internal class for implementing Matcher<T>, which will derive
224// from it. We put functionalities common to all Matcher<T>
225// specializations here to avoid code duplication.
226template <typename T>
227class MatcherBase {
228 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000229 // Returns true iff the matcher matches x; also explains the match
230 // result to 'listener'.
231 bool MatchAndExplain(T x, MatchResultListener* listener) const {
232 return impl_->MatchAndExplain(x, listener);
233 }
234
shiqiane35fdd92008-12-10 05:08:54 +0000235 // Returns true iff this matcher matches x.
zhanyong.wan82113312010-01-08 21:55:40 +0000236 bool Matches(T x) const {
237 DummyMatchResultListener dummy;
238 return MatchAndExplain(x, &dummy);
239 }
shiqiane35fdd92008-12-10 05:08:54 +0000240
241 // Describes this matcher to an ostream.
242 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
243
244 // Describes the negation of this matcher to an ostream.
245 void DescribeNegationTo(::std::ostream* os) const {
246 impl_->DescribeNegationTo(os);
247 }
248
249 // Explains why x matches, or doesn't match, the matcher.
250 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000251 StreamMatchResultListener listener(os);
252 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000253 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000254
zhanyong.wanfb25d532013-07-28 08:24:00 +0000255 // Returns the describer for this matcher object; retains ownership
256 // of the describer, which is only guaranteed to be alive when
257 // this matcher object is alive.
258 const MatcherDescriberInterface* GetDescriber() const {
259 return impl_.get();
260 }
261
shiqiane35fdd92008-12-10 05:08:54 +0000262 protected:
263 MatcherBase() {}
264
265 // Constructs a matcher from its implementation.
266 explicit MatcherBase(const MatcherInterface<T>* impl)
267 : impl_(impl) {}
268
269 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000270
shiqiane35fdd92008-12-10 05:08:54 +0000271 private:
272 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
273 // interfaces. The former dynamically allocates a chunk of memory
274 // to hold the reference count, while the latter tracks all
275 // references using a circular linked list without allocating
276 // memory. It has been observed that linked_ptr performs better in
277 // typical scenarios. However, shared_ptr can out-perform
278 // linked_ptr when there are many more uses of the copy constructor
279 // than the default constructor.
280 //
281 // If performance becomes a problem, we should see if using
282 // shared_ptr helps.
283 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
284};
285
shiqiane35fdd92008-12-10 05:08:54 +0000286} // namespace internal
287
288// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
289// object that can check whether a value of type T matches. The
290// implementation of Matcher<T> is just a linked_ptr to const
291// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
292// from Matcher!
293template <typename T>
294class Matcher : public internal::MatcherBase<T> {
295 public:
vladlosev88032d82010-11-17 23:29:21 +0000296 // Constructs a null matcher. Needed for storing Matcher objects in STL
297 // containers. A default-constructed matcher is not yet initialized. You
298 // cannot use it until a valid value has been assigned to it.
shiqiane35fdd92008-12-10 05:08:54 +0000299 Matcher() {}
300
301 // Constructs a matcher from its implementation.
302 explicit Matcher(const MatcherInterface<T>* impl)
303 : internal::MatcherBase<T>(impl) {}
304
zhanyong.wan18490652009-05-11 18:54:08 +0000305 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000306 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
307 Matcher(T value); // NOLINT
308};
309
310// The following two specializations allow the user to write str
311// instead of Eq(str) and "foo" instead of Eq("foo") when a string
312// matcher is expected.
313template <>
vladlosev587c1b32011-05-20 00:42:22 +0000314class GTEST_API_ Matcher<const internal::string&>
shiqiane35fdd92008-12-10 05:08:54 +0000315 : public internal::MatcherBase<const internal::string&> {
316 public:
317 Matcher() {}
318
319 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
320 : internal::MatcherBase<const internal::string&>(impl) {}
321
322 // Allows the user to write str instead of Eq(str) sometimes, where
323 // str is a string object.
324 Matcher(const internal::string& s); // NOLINT
325
326 // Allows the user to write "foo" instead of Eq("foo") sometimes.
327 Matcher(const char* s); // NOLINT
328};
329
330template <>
vladlosev587c1b32011-05-20 00:42:22 +0000331class GTEST_API_ Matcher<internal::string>
shiqiane35fdd92008-12-10 05:08:54 +0000332 : public internal::MatcherBase<internal::string> {
333 public:
334 Matcher() {}
335
336 explicit Matcher(const MatcherInterface<internal::string>* impl)
337 : internal::MatcherBase<internal::string>(impl) {}
338
339 // Allows the user to write str instead of Eq(str) sometimes, where
340 // str is a string object.
341 Matcher(const internal::string& s); // NOLINT
342
343 // Allows the user to write "foo" instead of Eq("foo") sometimes.
344 Matcher(const char* s); // NOLINT
345};
346
zhanyong.wan1f122a02013-03-25 16:27:03 +0000347#if GTEST_HAS_STRING_PIECE_
348// The following two specializations allow the user to write str
349// instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece
350// matcher is expected.
351template <>
352class GTEST_API_ Matcher<const StringPiece&>
353 : public internal::MatcherBase<const StringPiece&> {
354 public:
355 Matcher() {}
356
357 explicit Matcher(const MatcherInterface<const StringPiece&>* impl)
358 : internal::MatcherBase<const StringPiece&>(impl) {}
359
360 // Allows the user to write str instead of Eq(str) sometimes, where
361 // str is a string object.
362 Matcher(const internal::string& s); // NOLINT
363
364 // Allows the user to write "foo" instead of Eq("foo") sometimes.
365 Matcher(const char* s); // NOLINT
366
367 // Allows the user to pass StringPieces directly.
368 Matcher(StringPiece s); // NOLINT
369};
370
371template <>
372class GTEST_API_ Matcher<StringPiece>
373 : public internal::MatcherBase<StringPiece> {
374 public:
375 Matcher() {}
376
377 explicit Matcher(const MatcherInterface<StringPiece>* impl)
378 : internal::MatcherBase<StringPiece>(impl) {}
379
380 // Allows the user to write str instead of Eq(str) sometimes, where
381 // str is a string object.
382 Matcher(const internal::string& s); // NOLINT
383
384 // Allows the user to write "foo" instead of Eq("foo") sometimes.
385 Matcher(const char* s); // NOLINT
386
387 // Allows the user to pass StringPieces directly.
388 Matcher(StringPiece s); // NOLINT
389};
390#endif // GTEST_HAS_STRING_PIECE_
391
shiqiane35fdd92008-12-10 05:08:54 +0000392// The PolymorphicMatcher class template makes it easy to implement a
393// polymorphic matcher (i.e. a matcher that can match values of more
394// than one type, e.g. Eq(n) and NotNull()).
395//
zhanyong.wandb22c222010-01-28 21:52:29 +0000396// To define a polymorphic matcher, a user should provide an Impl
397// class that has a DescribeTo() method and a DescribeNegationTo()
398// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000399//
zhanyong.wandb22c222010-01-28 21:52:29 +0000400// bool MatchAndExplain(const Value& value,
401// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000402//
403// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000404template <class Impl>
405class PolymorphicMatcher {
406 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000407 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000408
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000409 // Returns a mutable reference to the underlying matcher
410 // implementation object.
411 Impl& mutable_impl() { return impl_; }
412
413 // Returns an immutable reference to the underlying matcher
414 // implementation object.
415 const Impl& impl() const { return impl_; }
416
shiqiane35fdd92008-12-10 05:08:54 +0000417 template <typename T>
418 operator Matcher<T>() const {
419 return Matcher<T>(new MonomorphicImpl<T>(impl_));
420 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000421
shiqiane35fdd92008-12-10 05:08:54 +0000422 private:
423 template <typename T>
424 class MonomorphicImpl : public MatcherInterface<T> {
425 public:
426 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
427
shiqiane35fdd92008-12-10 05:08:54 +0000428 virtual void DescribeTo(::std::ostream* os) const {
429 impl_.DescribeTo(os);
430 }
431
432 virtual void DescribeNegationTo(::std::ostream* os) const {
433 impl_.DescribeNegationTo(os);
434 }
435
zhanyong.wan82113312010-01-08 21:55:40 +0000436 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000437 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000438 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000439
shiqiane35fdd92008-12-10 05:08:54 +0000440 private:
441 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000442
443 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000444 };
445
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000446 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000447
448 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000449};
450
451// Creates a matcher from its implementation. This is easier to use
452// than the Matcher<T> constructor as it doesn't require you to
453// explicitly write the template argument, e.g.
454//
455// MakeMatcher(foo);
456// vs
457// Matcher<const string&>(foo);
458template <typename T>
459inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
460 return Matcher<T>(impl);
zhanyong.wan2eab17b2013-03-08 17:53:24 +0000461}
shiqiane35fdd92008-12-10 05:08:54 +0000462
463// Creates a polymorphic matcher from its implementation. This is
464// easier to use than the PolymorphicMatcher<Impl> constructor as it
465// doesn't require you to explicitly write the template argument, e.g.
466//
467// MakePolymorphicMatcher(foo);
468// vs
469// PolymorphicMatcher<TypeOfFoo>(foo);
470template <class Impl>
471inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
472 return PolymorphicMatcher<Impl>(impl);
473}
474
jgm79a367e2012-04-10 16:02:11 +0000475// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
476// and MUST NOT BE USED IN USER CODE!!!
477namespace internal {
478
479// The MatcherCastImpl class template is a helper for implementing
480// MatcherCast(). We need this helper in order to partially
481// specialize the implementation of MatcherCast() (C++ allows
482// class/struct templates to be partially specialized, but not
483// function templates.).
484
485// This general version is used when MatcherCast()'s argument is a
486// polymorphic matcher (i.e. something that can be converted to a
487// Matcher but is not one yet; for example, Eq(value)) or a value (for
488// example, "hello").
489template <typename T, typename M>
490class MatcherCastImpl {
491 public:
kosak5f2a6ca2013-12-03 01:43:07 +0000492 static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
jgm79a367e2012-04-10 16:02:11 +0000493 // M can be a polymorhic matcher, in which case we want to use
494 // its conversion operator to create Matcher<T>. Or it can be a value
495 // that should be passed to the Matcher<T>'s constructor.
496 //
497 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
498 // polymorphic matcher because it'll be ambiguous if T has an implicit
499 // constructor from M (this usually happens when T has an implicit
500 // constructor from any type).
501 //
502 // It won't work to unconditionally implict_cast
503 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
504 // a user-defined conversion from M to T if one exists (assuming M is
505 // a value).
506 return CastImpl(
507 polymorphic_matcher_or_value,
508 BooleanConstant<
509 internal::ImplicitlyConvertible<M, Matcher<T> >::value>());
510 }
511
512 private:
kosak5f2a6ca2013-12-03 01:43:07 +0000513 static Matcher<T> CastImpl(const M& value, BooleanConstant<false>) {
jgm79a367e2012-04-10 16:02:11 +0000514 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
515 // matcher. It must be a value then. Use direct initialization to create
516 // a matcher.
517 return Matcher<T>(ImplicitCast_<T>(value));
518 }
519
kosak5f2a6ca2013-12-03 01:43:07 +0000520 static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
jgm79a367e2012-04-10 16:02:11 +0000521 BooleanConstant<true>) {
522 // M is implicitly convertible to Matcher<T>, which means that either
523 // M is a polymorhpic matcher or Matcher<T> has an implicit constructor
524 // from M. In both cases using the implicit conversion will produce a
525 // matcher.
526 //
527 // Even if T has an implicit constructor from M, it won't be called because
528 // creating Matcher<T> would require a chain of two user-defined conversions
529 // (first to create T from M and then to create Matcher<T> from T).
530 return polymorphic_matcher_or_value;
531 }
532};
533
534// This more specialized version is used when MatcherCast()'s argument
535// is already a Matcher. This only compiles when type T can be
536// statically converted to type U.
537template <typename T, typename U>
538class MatcherCastImpl<T, Matcher<U> > {
539 public:
540 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
541 return Matcher<T>(new Impl(source_matcher));
542 }
543
544 private:
545 class Impl : public MatcherInterface<T> {
546 public:
547 explicit Impl(const Matcher<U>& source_matcher)
548 : source_matcher_(source_matcher) {}
549
550 // We delegate the matching logic to the source matcher.
551 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
552 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
553 }
554
555 virtual void DescribeTo(::std::ostream* os) const {
556 source_matcher_.DescribeTo(os);
557 }
558
559 virtual void DescribeNegationTo(::std::ostream* os) const {
560 source_matcher_.DescribeNegationTo(os);
561 }
562
563 private:
564 const Matcher<U> source_matcher_;
565
566 GTEST_DISALLOW_ASSIGN_(Impl);
567 };
568};
569
570// This even more specialized version is used for efficiently casting
571// a matcher to its own type.
572template <typename T>
573class MatcherCastImpl<T, Matcher<T> > {
574 public:
575 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
576};
577
578} // namespace internal
579
shiqiane35fdd92008-12-10 05:08:54 +0000580// In order to be safe and clear, casting between different matcher
581// types is done explicitly via MatcherCast<T>(m), which takes a
582// matcher m and returns a Matcher<T>. It compiles only when T can be
583// statically converted to the argument type of m.
584template <typename T, typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000585inline Matcher<T> MatcherCast(const M& matcher) {
jgm79a367e2012-04-10 16:02:11 +0000586 return internal::MatcherCastImpl<T, M>::Cast(matcher);
587}
shiqiane35fdd92008-12-10 05:08:54 +0000588
zhanyong.wan18490652009-05-11 18:54:08 +0000589// Implements SafeMatcherCast().
590//
zhanyong.wan95b12332009-09-25 18:55:50 +0000591// We use an intermediate class to do the actual safe casting as Nokia's
592// Symbian compiler cannot decide between
593// template <T, M> ... (M) and
594// template <T, U> ... (const Matcher<U>&)
595// for function templates but can for member function templates.
596template <typename T>
597class SafeMatcherCastImpl {
598 public:
jgm79a367e2012-04-10 16:02:11 +0000599 // This overload handles polymorphic matchers and values only since
600 // monomorphic matchers are handled by the next one.
zhanyong.wan95b12332009-09-25 18:55:50 +0000601 template <typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000602 static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
jgm79a367e2012-04-10 16:02:11 +0000603 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
zhanyong.wan95b12332009-09-25 18:55:50 +0000604 }
zhanyong.wan18490652009-05-11 18:54:08 +0000605
zhanyong.wan95b12332009-09-25 18:55:50 +0000606 // This overload handles monomorphic matchers.
607 //
608 // In general, if type T can be implicitly converted to type U, we can
609 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
610 // contravariant): just keep a copy of the original Matcher<U>, convert the
611 // argument from type T to U, and then pass it to the underlying Matcher<U>.
612 // The only exception is when U is a reference and T is not, as the
613 // underlying Matcher<U> may be interested in the argument's address, which
614 // is not preserved in the conversion from T to U.
615 template <typename U>
616 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
617 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000618 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000619 T_must_be_implicitly_convertible_to_U);
620 // Enforce that we are not converting a non-reference type T to a reference
621 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000622 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000623 internal::is_reference<T>::value || !internal::is_reference<U>::value,
624 cannot_convert_non_referentce_arg_to_reference);
625 // In case both T and U are arithmetic types, enforce that the
626 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000627 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
628 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000629 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
630 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000631 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000632 kTIsOther || kUIsOther ||
633 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
634 conversion_of_arithmetic_types_must_be_lossless);
635 return MatcherCast<T>(matcher);
636 }
637};
638
639template <typename T, typename M>
640inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
641 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000642}
643
shiqiane35fdd92008-12-10 05:08:54 +0000644// A<T>() returns a matcher that matches any value of type T.
645template <typename T>
646Matcher<T> A();
647
648// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
649// and MUST NOT BE USED IN USER CODE!!!
650namespace internal {
651
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000652// If the explanation is not empty, prints it to the ostream.
653inline void PrintIfNotEmpty(const internal::string& explanation,
zhanyong.wanfb25d532013-07-28 08:24:00 +0000654 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000655 if (explanation != "" && os != NULL) {
656 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000657 }
658}
659
zhanyong.wan736baa82010-09-27 17:44:16 +0000660// Returns true if the given type name is easy to read by a human.
661// This is used to decide whether printing the type of a value might
662// be helpful.
663inline bool IsReadableTypeName(const string& type_name) {
664 // We consider a type name readable if it's short or doesn't contain
665 // a template or function type.
666 return (type_name.length() <= 20 ||
667 type_name.find_first_of("<(") == string::npos);
668}
669
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000670// Matches the value against the given matcher, prints the value and explains
671// the match result to the listener. Returns the match result.
672// 'listener' must not be NULL.
673// Value cannot be passed by const reference, because some matchers take a
674// non-const argument.
675template <typename Value, typename T>
676bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
677 MatchResultListener* listener) {
678 if (!listener->IsInterested()) {
679 // If the listener is not interested, we do not need to construct the
680 // inner explanation.
681 return matcher.Matches(value);
682 }
683
684 StringMatchResultListener inner_listener;
685 const bool match = matcher.MatchAndExplain(value, &inner_listener);
686
687 UniversalPrint(value, listener->stream());
zhanyong.wan736baa82010-09-27 17:44:16 +0000688#if GTEST_HAS_RTTI
689 const string& type_name = GetTypeName<Value>();
690 if (IsReadableTypeName(type_name))
691 *listener->stream() << " (of type " << type_name << ")";
692#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000693 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000694
695 return match;
696}
697
shiqiane35fdd92008-12-10 05:08:54 +0000698// An internal helper class for doing compile-time loop on a tuple's
699// fields.
700template <size_t N>
701class TuplePrefix {
702 public:
703 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
704 // iff the first N fields of matcher_tuple matches the first N
705 // fields of value_tuple, respectively.
706 template <typename MatcherTuple, typename ValueTuple>
707 static bool Matches(const MatcherTuple& matcher_tuple,
708 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000709 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
710 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
711 }
712
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000713 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000714 // describes failures in matching the first N fields of matchers
715 // against the first N fields of values. If there is no failure,
716 // nothing will be streamed to os.
717 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000718 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
719 const ValueTuple& values,
720 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000721 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000722 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000723
724 // Then describes the failure (if any) in the (N - 1)-th (0-based)
725 // field.
726 typename tuple_element<N - 1, MatcherTuple>::type matcher =
727 get<N - 1>(matchers);
728 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
729 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000730 StringMatchResultListener listener;
731 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000732 // TODO(wan): include in the message the name of the parameter
733 // as used in MOCK_METHOD*() when possible.
734 *os << " Expected arg #" << N - 1 << ": ";
735 get<N - 1>(matchers).DescribeTo(os);
736 *os << "\n Actual: ";
737 // We remove the reference in type Value to prevent the
738 // universal printer from printing the address of value, which
739 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000740 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000741 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000742 internal::UniversalPrint(value, os);
743 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000744 *os << "\n";
745 }
746 }
747};
748
749// The base case.
750template <>
751class TuplePrefix<0> {
752 public:
753 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000754 static bool Matches(const MatcherTuple& /* matcher_tuple */,
755 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000756 return true;
757 }
758
759 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000760 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
761 const ValueTuple& /* values */,
762 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000763};
764
765// TupleMatches(matcher_tuple, value_tuple) returns true iff all
766// matchers in matcher_tuple match the corresponding fields in
767// value_tuple. It is a compiler error if matcher_tuple and
768// value_tuple have different number of fields or incompatible field
769// types.
770template <typename MatcherTuple, typename ValueTuple>
771bool TupleMatches(const MatcherTuple& matcher_tuple,
772 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000773 // Makes sure that matcher_tuple and value_tuple have the same
774 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000775 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000776 tuple_size<ValueTuple>::value,
777 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000778 return TuplePrefix<tuple_size<ValueTuple>::value>::
779 Matches(matcher_tuple, value_tuple);
780}
781
782// Describes failures in matching matchers against values. If there
783// is no failure, nothing will be streamed to os.
784template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000785void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
786 const ValueTuple& values,
787 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000788 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000789 matchers, values, os);
790}
791
zhanyong.wanfb25d532013-07-28 08:24:00 +0000792// TransformTupleValues and its helper.
793//
794// TransformTupleValuesHelper hides the internal machinery that
795// TransformTupleValues uses to implement a tuple traversal.
796template <typename Tuple, typename Func, typename OutIter>
797class TransformTupleValuesHelper {
798 private:
kosakbd018832014-04-02 20:30:00 +0000799 typedef ::testing::tuple_size<Tuple> TupleSize;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000800
801 public:
802 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
803 // Returns the final value of 'out' in case the caller needs it.
804 static OutIter Run(Func f, const Tuple& t, OutIter out) {
805 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
806 }
807
808 private:
809 template <typename Tup, size_t kRemainingSize>
810 struct IterateOverTuple {
811 OutIter operator() (Func f, const Tup& t, OutIter out) const {
kosakbd018832014-04-02 20:30:00 +0000812 *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
zhanyong.wanfb25d532013-07-28 08:24:00 +0000813 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
814 }
815 };
816 template <typename Tup>
817 struct IterateOverTuple<Tup, 0> {
818 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
819 return out;
820 }
821 };
822};
823
824// Successively invokes 'f(element)' on each element of the tuple 't',
825// appending each result to the 'out' iterator. Returns the final value
826// of 'out'.
827template <typename Tuple, typename Func, typename OutIter>
828OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
829 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
830}
831
shiqiane35fdd92008-12-10 05:08:54 +0000832// Implements A<T>().
833template <typename T>
834class AnyMatcherImpl : public MatcherInterface<T> {
835 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000836 virtual bool MatchAndExplain(
837 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000838 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
839 virtual void DescribeNegationTo(::std::ostream* os) const {
840 // This is mostly for completeness' safe, as it's not very useful
841 // to write Not(A<bool>()). However we cannot completely rule out
842 // such a possibility, and it doesn't hurt to be prepared.
843 *os << "never matches";
844 }
845};
846
847// Implements _, a matcher that matches any value of any
848// type. This is a polymorphic matcher, so we need a template type
849// conversion operator to make it appearing as a Matcher<T> for any
850// type T.
851class AnythingMatcher {
852 public:
853 template <typename T>
854 operator Matcher<T>() const { return A<T>(); }
855};
856
857// Implements a matcher that compares a given value with a
858// pre-supplied value using one of the ==, <=, <, etc, operators. The
859// two values being compared don't have to have the same type.
860//
861// The matcher defined here is polymorphic (for example, Eq(5) can be
862// used to match an int, a short, a double, etc). Therefore we use
863// a template type conversion operator in the implementation.
864//
865// We define this as a macro in order to eliminate duplicated source
866// code.
867//
868// The following template definition assumes that the Rhs parameter is
869// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000870#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \
871 name, op, relation, negated_relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000872 template <typename Rhs> class name##Matcher { \
873 public: \
874 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
875 template <typename Lhs> \
876 operator Matcher<Lhs>() const { \
877 return MakeMatcher(new Impl<Lhs>(rhs_)); \
878 } \
879 private: \
880 template <typename Lhs> \
881 class Impl : public MatcherInterface<Lhs> { \
882 public: \
883 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
zhanyong.wan82113312010-01-08 21:55:40 +0000884 virtual bool MatchAndExplain(\
885 Lhs lhs, MatchResultListener* /* listener */) const { \
886 return lhs op rhs_; \
887 } \
shiqiane35fdd92008-12-10 05:08:54 +0000888 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000889 *os << relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000890 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000891 } \
892 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000893 *os << negated_relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000894 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000895 } \
896 private: \
897 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000898 GTEST_DISALLOW_ASSIGN_(Impl); \
shiqiane35fdd92008-12-10 05:08:54 +0000899 }; \
900 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000901 GTEST_DISALLOW_ASSIGN_(name##Matcher); \
shiqiane35fdd92008-12-10 05:08:54 +0000902 }
903
904// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
905// respectively.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000906GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
907GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
908GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
909GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
910GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
911GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000912
zhanyong.wane0d051e2009-02-19 00:33:37 +0000913#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000914
vladlosev79b83502009-11-18 00:43:37 +0000915// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000916// pointer that is NULL.
917class IsNullMatcher {
918 public:
vladlosev79b83502009-11-18 00:43:37 +0000919 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000920 bool MatchAndExplain(const Pointer& p,
921 MatchResultListener* /* listener */) const {
922 return GetRawPointer(p) == NULL;
923 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000924
925 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
926 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000927 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000928 }
929};
930
vladlosev79b83502009-11-18 00:43:37 +0000931// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000932// pointer that is not NULL.
933class NotNullMatcher {
934 public:
vladlosev79b83502009-11-18 00:43:37 +0000935 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000936 bool MatchAndExplain(const Pointer& p,
937 MatchResultListener* /* listener */) const {
938 return GetRawPointer(p) != NULL;
939 }
shiqiane35fdd92008-12-10 05:08:54 +0000940
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000941 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +0000942 void DescribeNegationTo(::std::ostream* os) const {
943 *os << "is NULL";
944 }
945};
946
947// Ref(variable) matches any argument that is a reference to
948// 'variable'. This matcher is polymorphic as it can match any
949// super type of the type of 'variable'.
950//
951// The RefMatcher template class implements Ref(variable). It can
952// only be instantiated with a reference type. This prevents a user
953// from mistakenly using Ref(x) to match a non-reference function
954// argument. For example, the following will righteously cause a
955// compiler error:
956//
957// int n;
958// Matcher<int> m1 = Ref(n); // This won't compile.
959// Matcher<int&> m2 = Ref(n); // This will compile.
960template <typename T>
961class RefMatcher;
962
963template <typename T>
964class RefMatcher<T&> {
965 // Google Mock is a generic framework and thus needs to support
966 // mocking any function types, including those that take non-const
967 // reference arguments. Therefore the template parameter T (and
968 // Super below) can be instantiated to either a const type or a
969 // non-const type.
970 public:
971 // RefMatcher() takes a T& instead of const T&, as we want the
972 // compiler to catch using Ref(const_value) as a matcher for a
973 // non-const reference.
974 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
975
976 template <typename Super>
977 operator Matcher<Super&>() const {
978 // By passing object_ (type T&) to Impl(), which expects a Super&,
979 // we make sure that Super is a super type of T. In particular,
980 // this catches using Ref(const_value) as a matcher for a
981 // non-const reference, as you cannot implicitly convert a const
982 // reference to a non-const reference.
983 return MakeMatcher(new Impl<Super>(object_));
984 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000985
shiqiane35fdd92008-12-10 05:08:54 +0000986 private:
987 template <typename Super>
988 class Impl : public MatcherInterface<Super&> {
989 public:
990 explicit Impl(Super& x) : object_(x) {} // NOLINT
991
zhanyong.wandb22c222010-01-28 21:52:29 +0000992 // MatchAndExplain() takes a Super& (as opposed to const Super&)
993 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +0000994 virtual bool MatchAndExplain(
995 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000996 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +0000997 return &x == &object_;
998 }
shiqiane35fdd92008-12-10 05:08:54 +0000999
1000 virtual void DescribeTo(::std::ostream* os) const {
1001 *os << "references the variable ";
1002 UniversalPrinter<Super&>::Print(object_, os);
1003 }
1004
1005 virtual void DescribeNegationTo(::std::ostream* os) const {
1006 *os << "does not reference the variable ";
1007 UniversalPrinter<Super&>::Print(object_, os);
1008 }
1009
shiqiane35fdd92008-12-10 05:08:54 +00001010 private:
1011 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001012
1013 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001014 };
1015
1016 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001017
1018 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001019};
1020
1021// Polymorphic helper functions for narrow and wide string matchers.
1022inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1023 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1024}
1025
1026inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1027 const wchar_t* rhs) {
1028 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1029}
1030
1031// String comparison for narrow or wide strings that can have embedded NUL
1032// characters.
1033template <typename StringType>
1034bool CaseInsensitiveStringEquals(const StringType& s1,
1035 const StringType& s2) {
1036 // Are the heads equal?
1037 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1038 return false;
1039 }
1040
1041 // Skip the equal heads.
1042 const typename StringType::value_type nul = 0;
1043 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1044
1045 // Are we at the end of either s1 or s2?
1046 if (i1 == StringType::npos || i2 == StringType::npos) {
1047 return i1 == i2;
1048 }
1049
1050 // Are the tails equal?
1051 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1052}
1053
1054// String matchers.
1055
1056// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1057template <typename StringType>
1058class StrEqualityMatcher {
1059 public:
shiqiane35fdd92008-12-10 05:08:54 +00001060 StrEqualityMatcher(const StringType& str, bool expect_eq,
1061 bool case_sensitive)
1062 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1063
jgm38513a82012-11-15 15:50:36 +00001064 // Accepts pointer types, particularly:
1065 // const char*
1066 // char*
1067 // const wchar_t*
1068 // wchar_t*
1069 template <typename CharType>
1070 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001071 if (s == NULL) {
1072 return !expect_eq_;
1073 }
zhanyong.wandb22c222010-01-28 21:52:29 +00001074 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001075 }
1076
jgm38513a82012-11-15 15:50:36 +00001077 // Matches anything that can convert to StringType.
1078 //
1079 // This is a template, not just a plain function with const StringType&,
1080 // because StringPiece has some interfering non-explicit constructors.
1081 template <typename MatcheeStringType>
1082 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001083 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001084 const StringType& s2(s);
1085 const bool eq = case_sensitive_ ? s2 == string_ :
1086 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +00001087 return expect_eq_ == eq;
1088 }
1089
1090 void DescribeTo(::std::ostream* os) const {
1091 DescribeToHelper(expect_eq_, os);
1092 }
1093
1094 void DescribeNegationTo(::std::ostream* os) const {
1095 DescribeToHelper(!expect_eq_, os);
1096 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001097
shiqiane35fdd92008-12-10 05:08:54 +00001098 private:
1099 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001100 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +00001101 *os << "equal to ";
1102 if (!case_sensitive_) {
1103 *os << "(ignoring case) ";
1104 }
vladloseve2e8ba42010-05-13 18:16:03 +00001105 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001106 }
1107
1108 const StringType string_;
1109 const bool expect_eq_;
1110 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001111
1112 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001113};
1114
1115// Implements the polymorphic HasSubstr(substring) matcher, which
1116// can be used as a Matcher<T> as long as T can be converted to a
1117// string.
1118template <typename StringType>
1119class HasSubstrMatcher {
1120 public:
shiqiane35fdd92008-12-10 05:08:54 +00001121 explicit HasSubstrMatcher(const StringType& substring)
1122 : substring_(substring) {}
1123
jgm38513a82012-11-15 15:50:36 +00001124 // Accepts pointer types, particularly:
1125 // const char*
1126 // char*
1127 // const wchar_t*
1128 // wchar_t*
1129 template <typename CharType>
1130 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001131 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001132 }
1133
jgm38513a82012-11-15 15:50:36 +00001134 // Matches anything that can convert to StringType.
1135 //
1136 // This is a template, not just a plain function with const StringType&,
1137 // because StringPiece has some interfering non-explicit constructors.
1138 template <typename MatcheeStringType>
1139 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001140 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001141 const StringType& s2(s);
1142 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001143 }
1144
1145 // Describes what this matcher matches.
1146 void DescribeTo(::std::ostream* os) const {
1147 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001148 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001149 }
1150
1151 void DescribeNegationTo(::std::ostream* os) const {
1152 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001153 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001154 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001155
shiqiane35fdd92008-12-10 05:08:54 +00001156 private:
1157 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001158
1159 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001160};
1161
1162// Implements the polymorphic StartsWith(substring) matcher, which
1163// can be used as a Matcher<T> as long as T can be converted to a
1164// string.
1165template <typename StringType>
1166class StartsWithMatcher {
1167 public:
shiqiane35fdd92008-12-10 05:08:54 +00001168 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1169 }
1170
jgm38513a82012-11-15 15:50:36 +00001171 // Accepts pointer types, particularly:
1172 // const char*
1173 // char*
1174 // const wchar_t*
1175 // wchar_t*
1176 template <typename CharType>
1177 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001178 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001179 }
1180
jgm38513a82012-11-15 15:50:36 +00001181 // Matches anything that can convert to StringType.
1182 //
1183 // This is a template, not just a plain function with const StringType&,
1184 // because StringPiece has some interfering non-explicit constructors.
1185 template <typename MatcheeStringType>
1186 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001187 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001188 const StringType& s2(s);
1189 return s2.length() >= prefix_.length() &&
1190 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001191 }
1192
1193 void DescribeTo(::std::ostream* os) const {
1194 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001195 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001196 }
1197
1198 void DescribeNegationTo(::std::ostream* os) const {
1199 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001200 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001201 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001202
shiqiane35fdd92008-12-10 05:08:54 +00001203 private:
1204 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001205
1206 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001207};
1208
1209// Implements the polymorphic EndsWith(substring) matcher, which
1210// can be used as a Matcher<T> as long as T can be converted to a
1211// string.
1212template <typename StringType>
1213class EndsWithMatcher {
1214 public:
shiqiane35fdd92008-12-10 05:08:54 +00001215 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1216
jgm38513a82012-11-15 15:50:36 +00001217 // Accepts pointer types, particularly:
1218 // const char*
1219 // char*
1220 // const wchar_t*
1221 // wchar_t*
1222 template <typename CharType>
1223 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001224 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001225 }
1226
jgm38513a82012-11-15 15:50:36 +00001227 // Matches anything that can convert to StringType.
1228 //
1229 // This is a template, not just a plain function with const StringType&,
1230 // because StringPiece has some interfering non-explicit constructors.
1231 template <typename MatcheeStringType>
1232 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001233 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001234 const StringType& s2(s);
1235 return s2.length() >= suffix_.length() &&
1236 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001237 }
1238
1239 void DescribeTo(::std::ostream* os) const {
1240 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001241 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001242 }
1243
1244 void DescribeNegationTo(::std::ostream* os) const {
1245 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001246 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001247 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001248
shiqiane35fdd92008-12-10 05:08:54 +00001249 private:
1250 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001251
1252 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001253};
1254
shiqiane35fdd92008-12-10 05:08:54 +00001255// Implements polymorphic matchers MatchesRegex(regex) and
1256// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1257// T can be converted to a string.
1258class MatchesRegexMatcher {
1259 public:
1260 MatchesRegexMatcher(const RE* regex, bool full_match)
1261 : regex_(regex), full_match_(full_match) {}
1262
jgm38513a82012-11-15 15:50:36 +00001263 // Accepts pointer types, particularly:
1264 // const char*
1265 // char*
1266 // const wchar_t*
1267 // wchar_t*
1268 template <typename CharType>
1269 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001270 return s != NULL && MatchAndExplain(internal::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001271 }
1272
jgm38513a82012-11-15 15:50:36 +00001273 // Matches anything that can convert to internal::string.
1274 //
1275 // This is a template, not just a plain function with const internal::string&,
1276 // because StringPiece has some interfering non-explicit constructors.
1277 template <class MatcheeStringType>
1278 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001279 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001280 const internal::string& s2(s);
1281 return full_match_ ? RE::FullMatch(s2, *regex_) :
1282 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001283 }
1284
1285 void DescribeTo(::std::ostream* os) const {
1286 *os << (full_match_ ? "matches" : "contains")
1287 << " regular expression ";
1288 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1289 }
1290
1291 void DescribeNegationTo(::std::ostream* os) const {
1292 *os << "doesn't " << (full_match_ ? "match" : "contain")
1293 << " regular expression ";
1294 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1295 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001296
shiqiane35fdd92008-12-10 05:08:54 +00001297 private:
1298 const internal::linked_ptr<const RE> regex_;
1299 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001300
1301 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001302};
1303
shiqiane35fdd92008-12-10 05:08:54 +00001304// Implements a matcher that compares the two fields of a 2-tuple
1305// using one of the ==, <=, <, etc, operators. The two fields being
1306// compared don't have to have the same type.
1307//
1308// The matcher defined here is polymorphic (for example, Eq() can be
1309// used to match a tuple<int, short>, a tuple<const long&, double>,
1310// etc). Therefore we use a template type conversion operator in the
1311// implementation.
1312//
1313// We define this as a macro in order to eliminate duplicated source
1314// code.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001315#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +00001316 class name##2Matcher { \
1317 public: \
1318 template <typename T1, typename T2> \
kosakbd018832014-04-02 20:30:00 +00001319 operator Matcher< ::testing::tuple<T1, T2> >() const { \
1320 return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >); \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001321 } \
1322 template <typename T1, typename T2> \
kosakbd018832014-04-02 20:30:00 +00001323 operator Matcher<const ::testing::tuple<T1, T2>&>() const { \
1324 return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>); \
shiqiane35fdd92008-12-10 05:08:54 +00001325 } \
1326 private: \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001327 template <typename Tuple> \
1328 class Impl : public MatcherInterface<Tuple> { \
shiqiane35fdd92008-12-10 05:08:54 +00001329 public: \
zhanyong.wan82113312010-01-08 21:55:40 +00001330 virtual bool MatchAndExplain( \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001331 Tuple args, \
zhanyong.wan82113312010-01-08 21:55:40 +00001332 MatchResultListener* /* listener */) const { \
kosakbd018832014-04-02 20:30:00 +00001333 return ::testing::get<0>(args) op ::testing::get<1>(args); \
shiqiane35fdd92008-12-10 05:08:54 +00001334 } \
1335 virtual void DescribeTo(::std::ostream* os) const { \
kosakbd018832014-04-02 20:30:00 +00001336 *os << "are " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001337 } \
1338 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001339 *os << "aren't " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001340 } \
1341 }; \
1342 }
1343
1344// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001345GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "an equal pair");
1346GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1347 Ge, >=, "a pair where the first >= the second");
1348GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1349 Gt, >, "a pair where the first > the second");
1350GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1351 Le, <=, "a pair where the first <= the second");
1352GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1353 Lt, <, "a pair where the first < the second");
1354GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "an unequal pair");
shiqiane35fdd92008-12-10 05:08:54 +00001355
zhanyong.wane0d051e2009-02-19 00:33:37 +00001356#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001357
zhanyong.wanc6a41232009-05-13 23:38:40 +00001358// Implements the Not(...) matcher for a particular argument type T.
1359// We do not nest it inside the NotMatcher class template, as that
1360// will prevent different instantiations of NotMatcher from sharing
1361// the same NotMatcherImpl<T> class.
1362template <typename T>
1363class NotMatcherImpl : public MatcherInterface<T> {
1364 public:
1365 explicit NotMatcherImpl(const Matcher<T>& matcher)
1366 : matcher_(matcher) {}
1367
zhanyong.wan82113312010-01-08 21:55:40 +00001368 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1369 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001370 }
1371
1372 virtual void DescribeTo(::std::ostream* os) const {
1373 matcher_.DescribeNegationTo(os);
1374 }
1375
1376 virtual void DescribeNegationTo(::std::ostream* os) const {
1377 matcher_.DescribeTo(os);
1378 }
1379
zhanyong.wanc6a41232009-05-13 23:38:40 +00001380 private:
1381 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001382
1383 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001384};
1385
shiqiane35fdd92008-12-10 05:08:54 +00001386// Implements the Not(m) matcher, which matches a value that doesn't
1387// match matcher m.
1388template <typename InnerMatcher>
1389class NotMatcher {
1390 public:
1391 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1392
1393 // This template type conversion operator allows Not(m) to be used
1394 // to match any type m can match.
1395 template <typename T>
1396 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001397 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001398 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001399
shiqiane35fdd92008-12-10 05:08:54 +00001400 private:
shiqiane35fdd92008-12-10 05:08:54 +00001401 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001402
1403 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001404};
1405
zhanyong.wanc6a41232009-05-13 23:38:40 +00001406// Implements the AllOf(m1, m2) matcher for a particular argument type
1407// T. We do not nest it inside the BothOfMatcher class template, as
1408// that will prevent different instantiations of BothOfMatcher from
1409// sharing the same BothOfMatcherImpl<T> class.
1410template <typename T>
1411class BothOfMatcherImpl : public MatcherInterface<T> {
1412 public:
1413 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1414 : matcher1_(matcher1), matcher2_(matcher2) {}
1415
zhanyong.wanc6a41232009-05-13 23:38:40 +00001416 virtual void DescribeTo(::std::ostream* os) const {
1417 *os << "(";
1418 matcher1_.DescribeTo(os);
1419 *os << ") and (";
1420 matcher2_.DescribeTo(os);
1421 *os << ")";
1422 }
1423
1424 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001425 *os << "(";
1426 matcher1_.DescribeNegationTo(os);
1427 *os << ") or (";
1428 matcher2_.DescribeNegationTo(os);
1429 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001430 }
1431
zhanyong.wan82113312010-01-08 21:55:40 +00001432 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1433 // If either matcher1_ or matcher2_ doesn't match x, we only need
1434 // to explain why one of them fails.
1435 StringMatchResultListener listener1;
1436 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1437 *listener << listener1.str();
1438 return false;
1439 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001440
zhanyong.wan82113312010-01-08 21:55:40 +00001441 StringMatchResultListener listener2;
1442 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1443 *listener << listener2.str();
1444 return false;
1445 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001446
zhanyong.wan82113312010-01-08 21:55:40 +00001447 // Otherwise we need to explain why *both* of them match.
1448 const internal::string s1 = listener1.str();
1449 const internal::string s2 = listener2.str();
1450
1451 if (s1 == "") {
1452 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001453 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001454 *listener << s1;
1455 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001456 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001457 }
1458 }
zhanyong.wan82113312010-01-08 21:55:40 +00001459 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001460 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001461
zhanyong.wanc6a41232009-05-13 23:38:40 +00001462 private:
1463 const Matcher<T> matcher1_;
1464 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001465
1466 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001467};
1468
zhanyong.wan616180e2013-06-18 18:49:51 +00001469#if GTEST_LANG_CXX11
1470// MatcherList provides mechanisms for storing a variable number of matchers in
1471// a list structure (ListType) and creating a combining matcher from such a
1472// list.
1473// The template is defined recursively using the following template paramters:
1474// * kSize is the length of the MatcherList.
1475// * Head is the type of the first matcher of the list.
1476// * Tail denotes the types of the remaining matchers of the list.
1477template <int kSize, typename Head, typename... Tail>
1478struct MatcherList {
1479 typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
zhanyong.wan29897032013-06-20 18:59:15 +00001480 typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001481
1482 // BuildList stores variadic type values in a nested pair structure.
1483 // Example:
1484 // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
1485 // the corresponding result of type pair<int, pair<string, float>>.
1486 static ListType BuildList(const Head& matcher, const Tail&... tail) {
1487 return ListType(matcher, MatcherListTail::BuildList(tail...));
1488 }
1489
1490 // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
1491 // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
1492 // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
1493 // constructor taking two Matcher<T>s as input.
1494 template <typename T, template <typename /* T */> class CombiningMatcher>
1495 static Matcher<T> CreateMatcher(const ListType& matchers) {
1496 return Matcher<T>(new CombiningMatcher<T>(
1497 SafeMatcherCast<T>(matchers.first),
1498 MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
1499 matchers.second)));
1500 }
1501};
1502
1503// The following defines the base case for the recursive definition of
1504// MatcherList.
1505template <typename Matcher1, typename Matcher2>
1506struct MatcherList<2, Matcher1, Matcher2> {
zhanyong.wan29897032013-06-20 18:59:15 +00001507 typedef ::std::pair<Matcher1, Matcher2> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001508
1509 static ListType BuildList(const Matcher1& matcher1,
1510 const Matcher2& matcher2) {
zhanyong.wan29897032013-06-20 18:59:15 +00001511 return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
zhanyong.wan616180e2013-06-18 18:49:51 +00001512 }
1513
1514 template <typename T, template <typename /* T */> class CombiningMatcher>
1515 static Matcher<T> CreateMatcher(const ListType& matchers) {
1516 return Matcher<T>(new CombiningMatcher<T>(
1517 SafeMatcherCast<T>(matchers.first),
1518 SafeMatcherCast<T>(matchers.second)));
1519 }
1520};
1521
1522// VariadicMatcher is used for the variadic implementation of
1523// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1524// CombiningMatcher<T> is used to recursively combine the provided matchers
1525// (of type Args...).
1526template <template <typename T> class CombiningMatcher, typename... Args>
1527class VariadicMatcher {
1528 public:
1529 VariadicMatcher(const Args&... matchers) // NOLINT
1530 : matchers_(MatcherListType::BuildList(matchers...)) {}
1531
1532 // This template type conversion operator allows an
1533 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1534 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1535 template <typename T>
1536 operator Matcher<T>() const {
1537 return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
1538 matchers_);
1539 }
1540
1541 private:
1542 typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
1543
1544 const typename MatcherListType::ListType matchers_;
1545
1546 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1547};
1548
1549template <typename... Args>
1550using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
1551
1552#endif // GTEST_LANG_CXX11
1553
shiqiane35fdd92008-12-10 05:08:54 +00001554// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1555// matches a value that matches all of the matchers m_1, ..., and m_n.
1556template <typename Matcher1, typename Matcher2>
1557class BothOfMatcher {
1558 public:
1559 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1560 : matcher1_(matcher1), matcher2_(matcher2) {}
1561
1562 // This template type conversion operator allows a
1563 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1564 // both Matcher1 and Matcher2 can match.
1565 template <typename T>
1566 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001567 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1568 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001569 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001570
shiqiane35fdd92008-12-10 05:08:54 +00001571 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001572 Matcher1 matcher1_;
1573 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001574
1575 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001576};
shiqiane35fdd92008-12-10 05:08:54 +00001577
zhanyong.wanc6a41232009-05-13 23:38:40 +00001578// Implements the AnyOf(m1, m2) matcher for a particular argument type
1579// T. We do not nest it inside the AnyOfMatcher class template, as
1580// that will prevent different instantiations of AnyOfMatcher from
1581// sharing the same EitherOfMatcherImpl<T> class.
1582template <typename T>
1583class EitherOfMatcherImpl : public MatcherInterface<T> {
1584 public:
1585 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1586 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001587
zhanyong.wanc6a41232009-05-13 23:38:40 +00001588 virtual void DescribeTo(::std::ostream* os) const {
1589 *os << "(";
1590 matcher1_.DescribeTo(os);
1591 *os << ") or (";
1592 matcher2_.DescribeTo(os);
1593 *os << ")";
1594 }
shiqiane35fdd92008-12-10 05:08:54 +00001595
zhanyong.wanc6a41232009-05-13 23:38:40 +00001596 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001597 *os << "(";
1598 matcher1_.DescribeNegationTo(os);
1599 *os << ") and (";
1600 matcher2_.DescribeNegationTo(os);
1601 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001602 }
shiqiane35fdd92008-12-10 05:08:54 +00001603
zhanyong.wan82113312010-01-08 21:55:40 +00001604 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1605 // If either matcher1_ or matcher2_ matches x, we just need to
1606 // explain why *one* of them matches.
1607 StringMatchResultListener listener1;
1608 if (matcher1_.MatchAndExplain(x, &listener1)) {
1609 *listener << listener1.str();
1610 return true;
1611 }
1612
1613 StringMatchResultListener listener2;
1614 if (matcher2_.MatchAndExplain(x, &listener2)) {
1615 *listener << listener2.str();
1616 return true;
1617 }
1618
1619 // Otherwise we need to explain why *both* of them fail.
1620 const internal::string s1 = listener1.str();
1621 const internal::string s2 = listener2.str();
1622
1623 if (s1 == "") {
1624 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001625 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001626 *listener << s1;
1627 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001628 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001629 }
1630 }
zhanyong.wan82113312010-01-08 21:55:40 +00001631 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001632 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001633
zhanyong.wanc6a41232009-05-13 23:38:40 +00001634 private:
1635 const Matcher<T> matcher1_;
1636 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001637
1638 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001639};
1640
zhanyong.wan616180e2013-06-18 18:49:51 +00001641#if GTEST_LANG_CXX11
1642// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1643template <typename... Args>
1644using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
1645
1646#endif // GTEST_LANG_CXX11
1647
shiqiane35fdd92008-12-10 05:08:54 +00001648// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1649// matches a value that matches at least one of the matchers m_1, ...,
1650// and m_n.
1651template <typename Matcher1, typename Matcher2>
1652class EitherOfMatcher {
1653 public:
1654 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1655 : matcher1_(matcher1), matcher2_(matcher2) {}
1656
1657 // This template type conversion operator allows a
1658 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1659 // both Matcher1 and Matcher2 can match.
1660 template <typename T>
1661 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001662 return Matcher<T>(new EitherOfMatcherImpl<T>(
1663 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001664 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001665
shiqiane35fdd92008-12-10 05:08:54 +00001666 private:
shiqiane35fdd92008-12-10 05:08:54 +00001667 Matcher1 matcher1_;
1668 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001669
1670 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001671};
1672
1673// Used for implementing Truly(pred), which turns a predicate into a
1674// matcher.
1675template <typename Predicate>
1676class TrulyMatcher {
1677 public:
1678 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1679
1680 // This method template allows Truly(pred) to be used as a matcher
1681 // for type T where T is the argument type of predicate 'pred'. The
1682 // argument is passed by reference as the predicate may be
1683 // interested in the address of the argument.
1684 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001685 bool MatchAndExplain(T& x, // NOLINT
1686 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001687 // Without the if-statement, MSVC sometimes warns about converting
1688 // a value to bool (warning 4800).
1689 //
1690 // We cannot write 'return !!predicate_(x);' as that doesn't work
1691 // when predicate_(x) returns a class convertible to bool but
1692 // having no operator!().
1693 if (predicate_(x))
1694 return true;
1695 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001696 }
1697
1698 void DescribeTo(::std::ostream* os) const {
1699 *os << "satisfies the given predicate";
1700 }
1701
1702 void DescribeNegationTo(::std::ostream* os) const {
1703 *os << "doesn't satisfy the given predicate";
1704 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001705
shiqiane35fdd92008-12-10 05:08:54 +00001706 private:
1707 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001708
1709 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001710};
1711
1712// Used for implementing Matches(matcher), which turns a matcher into
1713// a predicate.
1714template <typename M>
1715class MatcherAsPredicate {
1716 public:
1717 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1718
1719 // This template operator() allows Matches(m) to be used as a
1720 // predicate on type T where m is a matcher on type T.
1721 //
1722 // The argument x is passed by reference instead of by value, as
1723 // some matcher may be interested in its address (e.g. as in
1724 // Matches(Ref(n))(x)).
1725 template <typename T>
1726 bool operator()(const T& x) const {
1727 // We let matcher_ commit to a particular type here instead of
1728 // when the MatcherAsPredicate object was constructed. This
1729 // allows us to write Matches(m) where m is a polymorphic matcher
1730 // (e.g. Eq(5)).
1731 //
1732 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1733 // compile when matcher_ has type Matcher<const T&>; if we write
1734 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1735 // when matcher_ has type Matcher<T>; if we just write
1736 // matcher_.Matches(x), it won't compile when matcher_ is
1737 // polymorphic, e.g. Eq(5).
1738 //
1739 // MatcherCast<const T&>() is necessary for making the code work
1740 // in all of the above situations.
1741 return MatcherCast<const T&>(matcher_).Matches(x);
1742 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001743
shiqiane35fdd92008-12-10 05:08:54 +00001744 private:
1745 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001746
1747 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001748};
1749
1750// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1751// argument M must be a type that can be converted to a matcher.
1752template <typename M>
1753class PredicateFormatterFromMatcher {
1754 public:
1755 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1756
1757 // This template () operator allows a PredicateFormatterFromMatcher
1758 // object to act as a predicate-formatter suitable for using with
1759 // Google Test's EXPECT_PRED_FORMAT1() macro.
1760 template <typename T>
1761 AssertionResult operator()(const char* value_text, const T& x) const {
1762 // We convert matcher_ to a Matcher<const T&> *now* instead of
1763 // when the PredicateFormatterFromMatcher object was constructed,
1764 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1765 // know which type to instantiate it to until we actually see the
1766 // type of x here.
1767 //
zhanyong.wanf4274522013-04-24 02:49:43 +00001768 // We write SafeMatcherCast<const T&>(matcher_) instead of
shiqiane35fdd92008-12-10 05:08:54 +00001769 // Matcher<const T&>(matcher_), as the latter won't compile when
1770 // matcher_ has type Matcher<T> (e.g. An<int>()).
zhanyong.wanf4274522013-04-24 02:49:43 +00001771 // We don't write MatcherCast<const T&> either, as that allows
1772 // potentially unsafe downcasting of the matcher argument.
1773 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001774 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001775 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001776 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001777
1778 ::std::stringstream ss;
1779 ss << "Value of: " << value_text << "\n"
1780 << "Expected: ";
1781 matcher.DescribeTo(&ss);
1782 ss << "\n Actual: " << listener.str();
1783 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001784 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001785
shiqiane35fdd92008-12-10 05:08:54 +00001786 private:
1787 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001788
1789 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001790};
1791
1792// A helper function for converting a matcher to a predicate-formatter
1793// without the user needing to explicitly write the type. This is
1794// used for implementing ASSERT_THAT() and EXPECT_THAT().
1795template <typename M>
1796inline PredicateFormatterFromMatcher<M>
1797MakePredicateFormatterFromMatcher(const M& matcher) {
1798 return PredicateFormatterFromMatcher<M>(matcher);
1799}
1800
zhanyong.wan616180e2013-06-18 18:49:51 +00001801// Implements the polymorphic floating point equality matcher, which matches
1802// two float values using ULP-based approximation or, optionally, a
1803// user-specified epsilon. The template is meant to be instantiated with
1804// FloatType being either float or double.
shiqiane35fdd92008-12-10 05:08:54 +00001805template <typename FloatType>
1806class FloatingEqMatcher {
1807 public:
1808 // Constructor for FloatingEqMatcher.
1809 // The matcher's input will be compared with rhs. The matcher treats two
1810 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
zhanyong.wan616180e2013-06-18 18:49:51 +00001811 // equality comparisons between NANs will always return false. We specify a
1812 // negative max_abs_error_ term to indicate that ULP-based approximation will
1813 // be used for comparison.
shiqiane35fdd92008-12-10 05:08:54 +00001814 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
zhanyong.wan616180e2013-06-18 18:49:51 +00001815 rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
1816 }
1817
1818 // Constructor that supports a user-specified max_abs_error that will be used
1819 // for comparison instead of ULP-based approximation. The max absolute
1820 // should be non-negative.
1821 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan, FloatType max_abs_error) :
1822 rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) {
1823 GTEST_CHECK_(max_abs_error >= 0)
1824 << ", where max_abs_error is" << max_abs_error;
1825 }
shiqiane35fdd92008-12-10 05:08:54 +00001826
1827 // Implements floating point equality matcher as a Matcher<T>.
1828 template <typename T>
1829 class Impl : public MatcherInterface<T> {
1830 public:
zhanyong.wan616180e2013-06-18 18:49:51 +00001831 Impl(FloatType rhs, bool nan_eq_nan, FloatType max_abs_error) :
1832 rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) {}
shiqiane35fdd92008-12-10 05:08:54 +00001833
zhanyong.wan82113312010-01-08 21:55:40 +00001834 virtual bool MatchAndExplain(T value,
1835 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001836 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1837
1838 // Compares NaNs first, if nan_eq_nan_ is true.
zhanyong.wan616180e2013-06-18 18:49:51 +00001839 if (lhs.is_nan() || rhs.is_nan()) {
1840 if (lhs.is_nan() && rhs.is_nan()) {
1841 return nan_eq_nan_;
1842 }
1843 // One is nan; the other is not nan.
1844 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001845 }
zhanyong.wan616180e2013-06-18 18:49:51 +00001846 if (HasMaxAbsError()) {
1847 // We perform an equality check so that inf will match inf, regardless
1848 // of error bounds. If the result of value - rhs_ would result in
1849 // overflow or if either value is inf, the default result is infinity,
1850 // which should only match if max_abs_error_ is also infinity.
1851 return value == rhs_ || fabs(value - rhs_) <= max_abs_error_;
1852 } else {
1853 return lhs.AlmostEquals(rhs);
1854 }
shiqiane35fdd92008-12-10 05:08:54 +00001855 }
1856
1857 virtual void DescribeTo(::std::ostream* os) const {
1858 // os->precision() returns the previously set precision, which we
1859 // store to restore the ostream to its original configuration
1860 // after outputting.
1861 const ::std::streamsize old_precision = os->precision(
1862 ::std::numeric_limits<FloatType>::digits10 + 2);
1863 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1864 if (nan_eq_nan_) {
1865 *os << "is NaN";
1866 } else {
1867 *os << "never matches";
1868 }
1869 } else {
1870 *os << "is approximately " << rhs_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001871 if (HasMaxAbsError()) {
1872 *os << " (absolute error <= " << max_abs_error_ << ")";
1873 }
shiqiane35fdd92008-12-10 05:08:54 +00001874 }
1875 os->precision(old_precision);
1876 }
1877
1878 virtual void DescribeNegationTo(::std::ostream* os) const {
1879 // As before, get original precision.
1880 const ::std::streamsize old_precision = os->precision(
1881 ::std::numeric_limits<FloatType>::digits10 + 2);
1882 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1883 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001884 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00001885 } else {
1886 *os << "is anything";
1887 }
1888 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001889 *os << "isn't approximately " << rhs_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001890 if (HasMaxAbsError()) {
1891 *os << " (absolute error > " << max_abs_error_ << ")";
1892 }
shiqiane35fdd92008-12-10 05:08:54 +00001893 }
1894 // Restore original precision.
1895 os->precision(old_precision);
1896 }
1897
1898 private:
zhanyong.wan616180e2013-06-18 18:49:51 +00001899 bool HasMaxAbsError() const {
1900 return max_abs_error_ >= 0;
1901 }
1902
shiqiane35fdd92008-12-10 05:08:54 +00001903 const FloatType rhs_;
1904 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001905 // max_abs_error will be used for value comparison when >= 0.
1906 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001907
1908 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001909 };
1910
1911 // The following 3 type conversion operators allow FloatEq(rhs) and
1912 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1913 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1914 // (While Google's C++ coding style doesn't allow arguments passed
1915 // by non-const reference, we may see them in code not conforming to
1916 // the style. Therefore Google Mock needs to support them.)
1917 operator Matcher<FloatType>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00001918 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00001919 }
1920
1921 operator Matcher<const FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00001922 return MakeMatcher(
1923 new Impl<const FloatType&>(rhs_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00001924 }
1925
1926 operator Matcher<FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00001927 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00001928 }
jgm79a367e2012-04-10 16:02:11 +00001929
shiqiane35fdd92008-12-10 05:08:54 +00001930 private:
1931 const FloatType rhs_;
1932 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001933 // max_abs_error will be used for value comparison when >= 0.
1934 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001935
1936 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001937};
1938
1939// Implements the Pointee(m) matcher for matching a pointer whose
1940// pointee matches matcher m. The pointer can be either raw or smart.
1941template <typename InnerMatcher>
1942class PointeeMatcher {
1943 public:
1944 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1945
1946 // This type conversion operator template allows Pointee(m) to be
1947 // used as a matcher for any pointer type whose pointee type is
1948 // compatible with the inner matcher, where type Pointer can be
1949 // either a raw pointer or a smart pointer.
1950 //
1951 // The reason we do this instead of relying on
1952 // MakePolymorphicMatcher() is that the latter is not flexible
1953 // enough for implementing the DescribeTo() method of Pointee().
1954 template <typename Pointer>
1955 operator Matcher<Pointer>() const {
1956 return MakeMatcher(new Impl<Pointer>(matcher_));
1957 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001958
shiqiane35fdd92008-12-10 05:08:54 +00001959 private:
1960 // The monomorphic implementation that works for a particular pointer type.
1961 template <typename Pointer>
1962 class Impl : public MatcherInterface<Pointer> {
1963 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00001964 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
1965 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001966
1967 explicit Impl(const InnerMatcher& matcher)
1968 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1969
shiqiane35fdd92008-12-10 05:08:54 +00001970 virtual void DescribeTo(::std::ostream* os) const {
1971 *os << "points to a value that ";
1972 matcher_.DescribeTo(os);
1973 }
1974
1975 virtual void DescribeNegationTo(::std::ostream* os) const {
1976 *os << "does not point to a value that ";
1977 matcher_.DescribeTo(os);
1978 }
1979
zhanyong.wan82113312010-01-08 21:55:40 +00001980 virtual bool MatchAndExplain(Pointer pointer,
1981 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001982 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001983 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001984
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001985 *listener << "which points to ";
1986 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001987 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001988
shiqiane35fdd92008-12-10 05:08:54 +00001989 private:
1990 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001991
1992 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001993 };
1994
1995 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001996
1997 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001998};
1999
billydonahue1f5fdea2014-05-19 17:54:51 +00002000// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2001// reference that matches inner_matcher when dynamic_cast<T> is applied.
2002// The result of dynamic_cast<To> is forwarded to the inner matcher.
2003// If To is a pointer and the cast fails, the inner matcher will receive NULL.
2004// If To is a reference and the cast fails, this matcher returns false
2005// immediately.
2006template <typename To>
2007class WhenDynamicCastToMatcherBase {
2008 public:
2009 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2010 : matcher_(matcher) {}
2011
2012 void DescribeTo(::std::ostream* os) const {
2013 GetCastTypeDescription(os);
2014 matcher_.DescribeTo(os);
2015 }
2016
2017 void DescribeNegationTo(::std::ostream* os) const {
2018 GetCastTypeDescription(os);
2019 matcher_.DescribeNegationTo(os);
2020 }
2021
2022 protected:
2023 const Matcher<To> matcher_;
2024
2025 static string GetToName() {
2026#if GTEST_HAS_RTTI
2027 return GetTypeName<To>();
2028#else // GTEST_HAS_RTTI
2029 return "the target type";
2030#endif // GTEST_HAS_RTTI
2031 }
2032
2033 private:
2034 static void GetCastTypeDescription(::std::ostream* os) {
2035 *os << "when dynamic_cast to " << GetToName() << ", ";
2036 }
2037
2038 GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2039};
2040
2041// Primary template.
2042// To is a pointer. Cast and forward the result.
2043template <typename To>
2044class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2045 public:
2046 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2047 : WhenDynamicCastToMatcherBase<To>(matcher) {}
2048
2049 template <typename From>
2050 bool MatchAndExplain(From from, MatchResultListener* listener) const {
2051 // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail?
2052 To to = dynamic_cast<To>(from);
2053 return MatchPrintAndExplain(to, this->matcher_, listener);
2054 }
2055};
2056
2057// Specialize for references.
2058// In this case we return false if the dynamic_cast fails.
2059template <typename To>
2060class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2061 public:
2062 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2063 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2064
2065 template <typename From>
2066 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2067 // We don't want an std::bad_cast here, so do the cast with pointers.
2068 To* to = dynamic_cast<To*>(&from);
2069 if (to == NULL) {
2070 *listener << "which cannot be dynamic_cast to " << this->GetToName();
2071 return false;
2072 }
2073 return MatchPrintAndExplain(*to, this->matcher_, listener);
2074 }
2075};
2076
shiqiane35fdd92008-12-10 05:08:54 +00002077// Implements the Field() matcher for matching a field (i.e. member
2078// variable) of an object.
2079template <typename Class, typename FieldType>
2080class FieldMatcher {
2081 public:
2082 FieldMatcher(FieldType Class::*field,
2083 const Matcher<const FieldType&>& matcher)
2084 : field_(field), matcher_(matcher) {}
2085
shiqiane35fdd92008-12-10 05:08:54 +00002086 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002087 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002088 matcher_.DescribeTo(os);
2089 }
2090
2091 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002092 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002093 matcher_.DescribeNegationTo(os);
2094 }
2095
zhanyong.wandb22c222010-01-28 21:52:29 +00002096 template <typename T>
2097 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2098 return MatchAndExplainImpl(
2099 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002100 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002101 value, listener);
2102 }
2103
2104 private:
2105 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002106 // Symbian's C++ compiler choose which overload to use. Its type is
2107 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002108 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2109 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002110 *listener << "whose given field is ";
2111 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002112 }
2113
zhanyong.wandb22c222010-01-28 21:52:29 +00002114 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2115 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002116 if (p == NULL)
2117 return false;
2118
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002119 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002120 // Since *p has a field, it must be a class/struct/union type and
2121 // thus cannot be a pointer. Therefore we pass false_type() as
2122 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002123 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002124 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002125
shiqiane35fdd92008-12-10 05:08:54 +00002126 const FieldType Class::*field_;
2127 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002128
2129 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002130};
2131
shiqiane35fdd92008-12-10 05:08:54 +00002132// Implements the Property() matcher for matching a property
2133// (i.e. return value of a getter method) of an object.
2134template <typename Class, typename PropertyType>
2135class PropertyMatcher {
2136 public:
2137 // The property may have a reference type, so 'const PropertyType&'
2138 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00002139 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00002140 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00002141 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00002142
2143 PropertyMatcher(PropertyType (Class::*property)() const,
2144 const Matcher<RefToConstProperty>& matcher)
2145 : property_(property), matcher_(matcher) {}
2146
shiqiane35fdd92008-12-10 05:08:54 +00002147 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002148 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002149 matcher_.DescribeTo(os);
2150 }
2151
2152 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002153 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002154 matcher_.DescribeNegationTo(os);
2155 }
2156
zhanyong.wandb22c222010-01-28 21:52:29 +00002157 template <typename T>
2158 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2159 return MatchAndExplainImpl(
2160 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002161 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002162 value, listener);
2163 }
2164
2165 private:
2166 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002167 // Symbian's C++ compiler choose which overload to use. Its type is
2168 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002169 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2170 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002171 *listener << "whose given property is ";
2172 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2173 // which takes a non-const reference as argument.
2174 RefToConstProperty result = (obj.*property_)();
2175 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002176 }
2177
zhanyong.wandb22c222010-01-28 21:52:29 +00002178 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2179 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002180 if (p == NULL)
2181 return false;
2182
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002183 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002184 // Since *p has a property method, it must be a class/struct/union
2185 // type and thus cannot be a pointer. Therefore we pass
2186 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002187 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002188 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002189
shiqiane35fdd92008-12-10 05:08:54 +00002190 PropertyType (Class::*property_)() const;
2191 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002192
2193 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002194};
2195
shiqiane35fdd92008-12-10 05:08:54 +00002196// Type traits specifying various features of different functors for ResultOf.
2197// The default template specifies features for functor objects.
2198// Functor classes have to typedef argument_type and result_type
2199// to be compatible with ResultOf.
2200template <typename Functor>
2201struct CallableTraits {
2202 typedef typename Functor::result_type ResultType;
2203 typedef Functor StorageType;
2204
zhanyong.wan32de5f52009-12-23 00:13:23 +00002205 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00002206 template <typename T>
2207 static ResultType Invoke(Functor f, T arg) { return f(arg); }
2208};
2209
2210// Specialization for function pointers.
2211template <typename ArgType, typename ResType>
2212struct CallableTraits<ResType(*)(ArgType)> {
2213 typedef ResType ResultType;
2214 typedef ResType(*StorageType)(ArgType);
2215
2216 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002217 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00002218 << "NULL function pointer is passed into ResultOf().";
2219 }
2220 template <typename T>
2221 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2222 return (*f)(arg);
2223 }
2224};
2225
2226// Implements the ResultOf() matcher for matching a return value of a
2227// unary function of an object.
2228template <typename Callable>
2229class ResultOfMatcher {
2230 public:
2231 typedef typename CallableTraits<Callable>::ResultType ResultType;
2232
2233 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
2234 : callable_(callable), matcher_(matcher) {
2235 CallableTraits<Callable>::CheckIsValid(callable_);
2236 }
2237
2238 template <typename T>
2239 operator Matcher<T>() const {
2240 return Matcher<T>(new Impl<T>(callable_, matcher_));
2241 }
2242
2243 private:
2244 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2245
2246 template <typename T>
2247 class Impl : public MatcherInterface<T> {
2248 public:
2249 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
2250 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00002251
2252 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002253 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002254 matcher_.DescribeTo(os);
2255 }
2256
2257 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002258 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002259 matcher_.DescribeNegationTo(os);
2260 }
2261
zhanyong.wan82113312010-01-08 21:55:40 +00002262 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002263 *listener << "which is mapped by the given callable to ";
2264 // Cannot pass the return value (for example, int) to
2265 // MatchPrintAndExplain, which takes a non-const reference as argument.
2266 ResultType result =
2267 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2268 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002269 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002270
shiqiane35fdd92008-12-10 05:08:54 +00002271 private:
2272 // Functors often define operator() as non-const method even though
2273 // they are actualy stateless. But we need to use them even when
2274 // 'this' is a const pointer. It's the user's responsibility not to
2275 // use stateful callables with ResultOf(), which does't guarantee
2276 // how many times the callable will be invoked.
2277 mutable CallableStorageType callable_;
2278 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002279
2280 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002281 }; // class Impl
2282
2283 const CallableStorageType callable_;
2284 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002285
2286 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002287};
2288
zhanyong.wana31d9ce2013-03-01 01:50:17 +00002289// Implements a matcher that checks the size of an STL-style container.
2290template <typename SizeMatcher>
2291class SizeIsMatcher {
2292 public:
2293 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2294 : size_matcher_(size_matcher) {
2295 }
2296
2297 template <typename Container>
2298 operator Matcher<Container>() const {
2299 return MakeMatcher(new Impl<Container>(size_matcher_));
2300 }
2301
2302 template <typename Container>
2303 class Impl : public MatcherInterface<Container> {
2304 public:
2305 typedef internal::StlContainerView<
2306 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2307 typedef typename ContainerView::type::size_type SizeType;
2308 explicit Impl(const SizeMatcher& size_matcher)
2309 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2310
2311 virtual void DescribeTo(::std::ostream* os) const {
2312 *os << "size ";
2313 size_matcher_.DescribeTo(os);
2314 }
2315 virtual void DescribeNegationTo(::std::ostream* os) const {
2316 *os << "size ";
2317 size_matcher_.DescribeNegationTo(os);
2318 }
2319
2320 virtual bool MatchAndExplain(Container container,
2321 MatchResultListener* listener) const {
2322 SizeType size = container.size();
2323 StringMatchResultListener size_listener;
2324 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2325 *listener
2326 << "whose size " << size << (result ? " matches" : " doesn't match");
2327 PrintIfNotEmpty(size_listener.str(), listener->stream());
2328 return result;
2329 }
2330
2331 private:
2332 const Matcher<SizeType> size_matcher_;
2333 GTEST_DISALLOW_ASSIGN_(Impl);
2334 };
2335
2336 private:
2337 const SizeMatcher size_matcher_;
2338 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2339};
2340
kosakb6a34882014-03-12 21:06:46 +00002341// Implements a matcher that checks the begin()..end() distance of an STL-style
2342// container.
2343template <typename DistanceMatcher>
2344class BeginEndDistanceIsMatcher {
2345 public:
2346 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2347 : distance_matcher_(distance_matcher) {}
2348
2349 template <typename Container>
2350 operator Matcher<Container>() const {
2351 return MakeMatcher(new Impl<Container>(distance_matcher_));
2352 }
2353
2354 template <typename Container>
2355 class Impl : public MatcherInterface<Container> {
2356 public:
2357 typedef internal::StlContainerView<
2358 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2359 typedef typename std::iterator_traits<
2360 typename ContainerView::type::const_iterator>::difference_type
2361 DistanceType;
2362 explicit Impl(const DistanceMatcher& distance_matcher)
2363 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2364
2365 virtual void DescribeTo(::std::ostream* os) const {
2366 *os << "distance between begin() and end() ";
2367 distance_matcher_.DescribeTo(os);
2368 }
2369 virtual void DescribeNegationTo(::std::ostream* os) const {
2370 *os << "distance between begin() and end() ";
2371 distance_matcher_.DescribeNegationTo(os);
2372 }
2373
2374 virtual bool MatchAndExplain(Container container,
2375 MatchResultListener* listener) const {
2376#if GTEST_LANG_CXX11
2377 using std::begin;
2378 using std::end;
2379 DistanceType distance = std::distance(begin(container), end(container));
2380#else
2381 DistanceType distance = std::distance(container.begin(), container.end());
2382#endif
2383 StringMatchResultListener distance_listener;
2384 const bool result =
2385 distance_matcher_.MatchAndExplain(distance, &distance_listener);
2386 *listener << "whose distance between begin() and end() " << distance
2387 << (result ? " matches" : " doesn't match");
2388 PrintIfNotEmpty(distance_listener.str(), listener->stream());
2389 return result;
2390 }
2391
2392 private:
2393 const Matcher<DistanceType> distance_matcher_;
2394 GTEST_DISALLOW_ASSIGN_(Impl);
2395 };
2396
2397 private:
2398 const DistanceMatcher distance_matcher_;
2399 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2400};
2401
zhanyong.wan6a896b52009-01-16 01:13:50 +00002402// Implements an equality matcher for any STL-style container whose elements
2403// support ==. This matcher is like Eq(), but its failure explanations provide
2404// more detailed information that is useful when the container is used as a set.
2405// The failure message reports elements that are in one of the operands but not
2406// the other. The failure messages do not report duplicate or out-of-order
2407// elements in the containers (which don't properly matter to sets, but can
2408// occur if the containers are vectors or lists, for example).
2409//
2410// Uses the container's const_iterator, value_type, operator ==,
2411// begin(), and end().
2412template <typename Container>
2413class ContainerEqMatcher {
2414 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002415 typedef internal::StlContainerView<Container> View;
2416 typedef typename View::type StlContainer;
2417 typedef typename View::const_reference StlContainerReference;
2418
2419 // We make a copy of rhs in case the elements in it are modified
2420 // after this matcher is created.
2421 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
2422 // Makes sure the user doesn't instantiate this class template
2423 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002424 (void)testing::StaticAssertTypeEq<Container,
2425 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002426 }
2427
zhanyong.wan6a896b52009-01-16 01:13:50 +00002428 void DescribeTo(::std::ostream* os) const {
2429 *os << "equals ";
vladloseve2e8ba42010-05-13 18:16:03 +00002430 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002431 }
2432 void DescribeNegationTo(::std::ostream* os) const {
2433 *os << "does not equal ";
vladloseve2e8ba42010-05-13 18:16:03 +00002434 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002435 }
2436
zhanyong.wanb8243162009-06-04 05:48:20 +00002437 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002438 bool MatchAndExplain(const LhsContainer& lhs,
2439 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002440 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002441 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002442 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002443 LhsView;
2444 typedef typename LhsView::type LhsStlContainer;
2445 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00002446 if (lhs_stl_container == rhs_)
2447 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002448
zhanyong.wane122e452010-01-12 09:03:52 +00002449 ::std::ostream* const os = listener->stream();
2450 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002451 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002452 bool printed_header = false;
2453 for (typename LhsStlContainer::const_iterator it =
2454 lhs_stl_container.begin();
2455 it != lhs_stl_container.end(); ++it) {
2456 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
2457 rhs_.end()) {
2458 if (printed_header) {
2459 *os << ", ";
2460 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002461 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002462 printed_header = true;
2463 }
vladloseve2e8ba42010-05-13 18:16:03 +00002464 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002465 }
zhanyong.wane122e452010-01-12 09:03:52 +00002466 }
2467
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002468 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002469 bool printed_header2 = false;
2470 for (typename StlContainer::const_iterator it = rhs_.begin();
2471 it != rhs_.end(); ++it) {
2472 if (internal::ArrayAwareFind(
2473 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2474 lhs_stl_container.end()) {
2475 if (printed_header2) {
2476 *os << ", ";
2477 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002478 *os << (printed_header ? ",\nand" : "which")
2479 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002480 printed_header2 = true;
2481 }
vladloseve2e8ba42010-05-13 18:16:03 +00002482 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002483 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002484 }
2485 }
2486
zhanyong.wane122e452010-01-12 09:03:52 +00002487 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002488 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002489
zhanyong.wan6a896b52009-01-16 01:13:50 +00002490 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00002491 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002492
2493 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002494};
2495
zhanyong.wan898725c2011-09-16 16:45:39 +00002496// A comparator functor that uses the < operator to compare two values.
2497struct LessComparator {
2498 template <typename T, typename U>
2499 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2500};
2501
2502// Implements WhenSortedBy(comparator, container_matcher).
2503template <typename Comparator, typename ContainerMatcher>
2504class WhenSortedByMatcher {
2505 public:
2506 WhenSortedByMatcher(const Comparator& comparator,
2507 const ContainerMatcher& matcher)
2508 : comparator_(comparator), matcher_(matcher) {}
2509
2510 template <typename LhsContainer>
2511 operator Matcher<LhsContainer>() const {
2512 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2513 }
2514
2515 template <typename LhsContainer>
2516 class Impl : public MatcherInterface<LhsContainer> {
2517 public:
2518 typedef internal::StlContainerView<
2519 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2520 typedef typename LhsView::type LhsStlContainer;
2521 typedef typename LhsView::const_reference LhsStlContainerReference;
zhanyong.wana9a59e02013-03-27 16:14:55 +00002522 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2523 // so that we can match associative containers.
2524 typedef typename RemoveConstFromKey<
2525 typename LhsStlContainer::value_type>::type LhsValue;
zhanyong.wan898725c2011-09-16 16:45:39 +00002526
2527 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2528 : comparator_(comparator), matcher_(matcher) {}
2529
2530 virtual void DescribeTo(::std::ostream* os) const {
2531 *os << "(when sorted) ";
2532 matcher_.DescribeTo(os);
2533 }
2534
2535 virtual void DescribeNegationTo(::std::ostream* os) const {
2536 *os << "(when sorted) ";
2537 matcher_.DescribeNegationTo(os);
2538 }
2539
2540 virtual bool MatchAndExplain(LhsContainer lhs,
2541 MatchResultListener* listener) const {
2542 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wanfb25d532013-07-28 08:24:00 +00002543 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2544 lhs_stl_container.end());
2545 ::std::sort(
2546 sorted_container.begin(), sorted_container.end(), comparator_);
zhanyong.wan898725c2011-09-16 16:45:39 +00002547
2548 if (!listener->IsInterested()) {
2549 // If the listener is not interested, we do not need to
2550 // construct the inner explanation.
2551 return matcher_.Matches(sorted_container);
2552 }
2553
2554 *listener << "which is ";
2555 UniversalPrint(sorted_container, listener->stream());
2556 *listener << " when sorted";
2557
2558 StringMatchResultListener inner_listener;
2559 const bool match = matcher_.MatchAndExplain(sorted_container,
2560 &inner_listener);
2561 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2562 return match;
2563 }
2564
2565 private:
2566 const Comparator comparator_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00002567 const Matcher<const ::std::vector<LhsValue>&> matcher_;
zhanyong.wan898725c2011-09-16 16:45:39 +00002568
2569 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2570 };
2571
2572 private:
2573 const Comparator comparator_;
2574 const ContainerMatcher matcher_;
2575
2576 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2577};
2578
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002579// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2580// must be able to be safely cast to Matcher<tuple<const T1&, const
2581// T2&> >, where T1 and T2 are the types of elements in the LHS
2582// container and the RHS container respectively.
2583template <typename TupleMatcher, typename RhsContainer>
2584class PointwiseMatcher {
2585 public:
2586 typedef internal::StlContainerView<RhsContainer> RhsView;
2587 typedef typename RhsView::type RhsStlContainer;
2588 typedef typename RhsStlContainer::value_type RhsValue;
2589
2590 // Like ContainerEq, we make a copy of rhs in case the elements in
2591 // it are modified after this matcher is created.
2592 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2593 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2594 // Makes sure the user doesn't instantiate this class template
2595 // with a const or reference type.
2596 (void)testing::StaticAssertTypeEq<RhsContainer,
2597 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2598 }
2599
2600 template <typename LhsContainer>
2601 operator Matcher<LhsContainer>() const {
2602 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2603 }
2604
2605 template <typename LhsContainer>
2606 class Impl : public MatcherInterface<LhsContainer> {
2607 public:
2608 typedef internal::StlContainerView<
2609 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2610 typedef typename LhsView::type LhsStlContainer;
2611 typedef typename LhsView::const_reference LhsStlContainerReference;
2612 typedef typename LhsStlContainer::value_type LhsValue;
2613 // We pass the LHS value and the RHS value to the inner matcher by
2614 // reference, as they may be expensive to copy. We must use tuple
2615 // instead of pair here, as a pair cannot hold references (C++ 98,
2616 // 20.2.2 [lib.pairs]).
kosakbd018832014-04-02 20:30:00 +00002617 typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002618
2619 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2620 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2621 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2622 rhs_(rhs) {}
2623
2624 virtual void DescribeTo(::std::ostream* os) const {
2625 *os << "contains " << rhs_.size()
2626 << " values, where each value and its corresponding value in ";
2627 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2628 *os << " ";
2629 mono_tuple_matcher_.DescribeTo(os);
2630 }
2631 virtual void DescribeNegationTo(::std::ostream* os) const {
2632 *os << "doesn't contain exactly " << rhs_.size()
2633 << " values, or contains a value x at some index i"
2634 << " where x and the i-th value of ";
2635 UniversalPrint(rhs_, os);
2636 *os << " ";
2637 mono_tuple_matcher_.DescribeNegationTo(os);
2638 }
2639
2640 virtual bool MatchAndExplain(LhsContainer lhs,
2641 MatchResultListener* listener) const {
2642 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2643 const size_t actual_size = lhs_stl_container.size();
2644 if (actual_size != rhs_.size()) {
2645 *listener << "which contains " << actual_size << " values";
2646 return false;
2647 }
2648
2649 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2650 typename RhsStlContainer::const_iterator right = rhs_.begin();
2651 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2652 const InnerMatcherArg value_pair(*left, *right);
2653
2654 if (listener->IsInterested()) {
2655 StringMatchResultListener inner_listener;
2656 if (!mono_tuple_matcher_.MatchAndExplain(
2657 value_pair, &inner_listener)) {
2658 *listener << "where the value pair (";
2659 UniversalPrint(*left, listener->stream());
2660 *listener << ", ";
2661 UniversalPrint(*right, listener->stream());
2662 *listener << ") at index #" << i << " don't match";
2663 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2664 return false;
2665 }
2666 } else {
2667 if (!mono_tuple_matcher_.Matches(value_pair))
2668 return false;
2669 }
2670 }
2671
2672 return true;
2673 }
2674
2675 private:
2676 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2677 const RhsStlContainer rhs_;
2678
2679 GTEST_DISALLOW_ASSIGN_(Impl);
2680 };
2681
2682 private:
2683 const TupleMatcher tuple_matcher_;
2684 const RhsStlContainer rhs_;
2685
2686 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2687};
2688
zhanyong.wan33605ba2010-04-22 23:37:47 +00002689// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002690template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002691class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002692 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002693 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002694 typedef StlContainerView<RawContainer> View;
2695 typedef typename View::type StlContainer;
2696 typedef typename View::const_reference StlContainerReference;
2697 typedef typename StlContainer::value_type Element;
2698
2699 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002700 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002701 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002702 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002703
zhanyong.wan33605ba2010-04-22 23:37:47 +00002704 // Checks whether:
2705 // * All elements in the container match, if all_elements_should_match.
2706 // * Any element in the container matches, if !all_elements_should_match.
2707 bool MatchAndExplainImpl(bool all_elements_should_match,
2708 Container container,
2709 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002710 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002711 size_t i = 0;
2712 for (typename StlContainer::const_iterator it = stl_container.begin();
2713 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002714 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002715 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2716
2717 if (matches != all_elements_should_match) {
2718 *listener << "whose element #" << i
2719 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002720 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002721 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002722 }
2723 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002724 return all_elements_should_match;
2725 }
2726
2727 protected:
2728 const Matcher<const Element&> inner_matcher_;
2729
2730 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2731};
2732
2733// Implements Contains(element_matcher) for the given argument type Container.
2734// Symmetric to EachMatcherImpl.
2735template <typename Container>
2736class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2737 public:
2738 template <typename InnerMatcher>
2739 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2740 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2741
2742 // Describes what this matcher does.
2743 virtual void DescribeTo(::std::ostream* os) const {
2744 *os << "contains at least one element that ";
2745 this->inner_matcher_.DescribeTo(os);
2746 }
2747
2748 virtual void DescribeNegationTo(::std::ostream* os) const {
2749 *os << "doesn't contain any element that ";
2750 this->inner_matcher_.DescribeTo(os);
2751 }
2752
2753 virtual bool MatchAndExplain(Container container,
2754 MatchResultListener* listener) const {
2755 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002756 }
2757
2758 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002759 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002760};
2761
zhanyong.wan33605ba2010-04-22 23:37:47 +00002762// Implements Each(element_matcher) for the given argument type Container.
2763// Symmetric to ContainsMatcherImpl.
2764template <typename Container>
2765class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2766 public:
2767 template <typename InnerMatcher>
2768 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2769 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2770
2771 // Describes what this matcher does.
2772 virtual void DescribeTo(::std::ostream* os) const {
2773 *os << "only contains elements that ";
2774 this->inner_matcher_.DescribeTo(os);
2775 }
2776
2777 virtual void DescribeNegationTo(::std::ostream* os) const {
2778 *os << "contains some element that ";
2779 this->inner_matcher_.DescribeNegationTo(os);
2780 }
2781
2782 virtual bool MatchAndExplain(Container container,
2783 MatchResultListener* listener) const {
2784 return this->MatchAndExplainImpl(true, container, listener);
2785 }
2786
2787 private:
2788 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2789};
2790
zhanyong.wanb8243162009-06-04 05:48:20 +00002791// Implements polymorphic Contains(element_matcher).
2792template <typename M>
2793class ContainsMatcher {
2794 public:
2795 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2796
2797 template <typename Container>
2798 operator Matcher<Container>() const {
2799 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2800 }
2801
2802 private:
2803 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002804
2805 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002806};
2807
zhanyong.wan33605ba2010-04-22 23:37:47 +00002808// Implements polymorphic Each(element_matcher).
2809template <typename M>
2810class EachMatcher {
2811 public:
2812 explicit EachMatcher(M m) : inner_matcher_(m) {}
2813
2814 template <typename Container>
2815 operator Matcher<Container>() const {
2816 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2817 }
2818
2819 private:
2820 const M inner_matcher_;
2821
2822 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2823};
2824
zhanyong.wanb5937da2009-07-16 20:26:41 +00002825// Implements Key(inner_matcher) for the given argument pair type.
2826// Key(inner_matcher) matches an std::pair whose 'first' field matches
2827// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2828// std::map that contains at least one element whose key is >= 5.
2829template <typename PairType>
2830class KeyMatcherImpl : public MatcherInterface<PairType> {
2831 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002832 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002833 typedef typename RawPairType::first_type KeyType;
2834
2835 template <typename InnerMatcher>
2836 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2837 : inner_matcher_(
2838 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2839 }
2840
2841 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002842 virtual bool MatchAndExplain(PairType key_value,
2843 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002844 StringMatchResultListener inner_listener;
2845 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2846 &inner_listener);
2847 const internal::string explanation = inner_listener.str();
2848 if (explanation != "") {
2849 *listener << "whose first field is a value " << explanation;
2850 }
2851 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002852 }
2853
2854 // Describes what this matcher does.
2855 virtual void DescribeTo(::std::ostream* os) const {
2856 *os << "has a key that ";
2857 inner_matcher_.DescribeTo(os);
2858 }
2859
2860 // Describes what the negation of this matcher does.
2861 virtual void DescribeNegationTo(::std::ostream* os) const {
2862 *os << "doesn't have a key that ";
2863 inner_matcher_.DescribeTo(os);
2864 }
2865
zhanyong.wanb5937da2009-07-16 20:26:41 +00002866 private:
2867 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002868
2869 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002870};
2871
2872// Implements polymorphic Key(matcher_for_key).
2873template <typename M>
2874class KeyMatcher {
2875 public:
2876 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2877
2878 template <typename PairType>
2879 operator Matcher<PairType>() const {
2880 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2881 }
2882
2883 private:
2884 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002885
2886 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002887};
2888
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002889// Implements Pair(first_matcher, second_matcher) for the given argument pair
2890// type with its two matchers. See Pair() function below.
2891template <typename PairType>
2892class PairMatcherImpl : public MatcherInterface<PairType> {
2893 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002894 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002895 typedef typename RawPairType::first_type FirstType;
2896 typedef typename RawPairType::second_type SecondType;
2897
2898 template <typename FirstMatcher, typename SecondMatcher>
2899 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2900 : first_matcher_(
2901 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2902 second_matcher_(
2903 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2904 }
2905
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002906 // Describes what this matcher does.
2907 virtual void DescribeTo(::std::ostream* os) const {
2908 *os << "has a first field that ";
2909 first_matcher_.DescribeTo(os);
2910 *os << ", and has a second field that ";
2911 second_matcher_.DescribeTo(os);
2912 }
2913
2914 // Describes what the negation of this matcher does.
2915 virtual void DescribeNegationTo(::std::ostream* os) const {
2916 *os << "has a first field that ";
2917 first_matcher_.DescribeNegationTo(os);
2918 *os << ", or has a second field that ";
2919 second_matcher_.DescribeNegationTo(os);
2920 }
2921
zhanyong.wan82113312010-01-08 21:55:40 +00002922 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2923 // matches second_matcher.
2924 virtual bool MatchAndExplain(PairType a_pair,
2925 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002926 if (!listener->IsInterested()) {
2927 // If the listener is not interested, we don't need to construct the
2928 // explanation.
2929 return first_matcher_.Matches(a_pair.first) &&
2930 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00002931 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002932 StringMatchResultListener first_inner_listener;
2933 if (!first_matcher_.MatchAndExplain(a_pair.first,
2934 &first_inner_listener)) {
2935 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002936 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002937 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002938 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002939 StringMatchResultListener second_inner_listener;
2940 if (!second_matcher_.MatchAndExplain(a_pair.second,
2941 &second_inner_listener)) {
2942 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002943 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002944 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002945 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002946 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2947 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002948 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002949 }
2950
2951 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002952 void ExplainSuccess(const internal::string& first_explanation,
2953 const internal::string& second_explanation,
2954 MatchResultListener* listener) const {
2955 *listener << "whose both fields match";
2956 if (first_explanation != "") {
2957 *listener << ", where the first field is a value " << first_explanation;
2958 }
2959 if (second_explanation != "") {
2960 *listener << ", ";
2961 if (first_explanation != "") {
2962 *listener << "and ";
2963 } else {
2964 *listener << "where ";
2965 }
2966 *listener << "the second field is a value " << second_explanation;
2967 }
2968 }
2969
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002970 const Matcher<const FirstType&> first_matcher_;
2971 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002972
2973 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002974};
2975
2976// Implements polymorphic Pair(first_matcher, second_matcher).
2977template <typename FirstMatcher, typename SecondMatcher>
2978class PairMatcher {
2979 public:
2980 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2981 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2982
2983 template <typename PairType>
2984 operator Matcher<PairType> () const {
2985 return MakeMatcher(
2986 new PairMatcherImpl<PairType>(
2987 first_matcher_, second_matcher_));
2988 }
2989
2990 private:
2991 const FirstMatcher first_matcher_;
2992 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002993
2994 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002995};
2996
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002997// Implements ElementsAre() and ElementsAreArray().
2998template <typename Container>
2999class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3000 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003001 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003002 typedef internal::StlContainerView<RawContainer> View;
3003 typedef typename View::type StlContainer;
3004 typedef typename View::const_reference StlContainerReference;
3005 typedef typename StlContainer::value_type Element;
3006
3007 // Constructs the matcher from a sequence of element values or
3008 // element matchers.
3009 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00003010 ElementsAreMatcherImpl(InputIter first, InputIter last) {
3011 while (first != last) {
3012 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003013 }
3014 }
3015
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003016 // Describes what this matcher does.
3017 virtual void DescribeTo(::std::ostream* os) const {
3018 if (count() == 0) {
3019 *os << "is empty";
3020 } else if (count() == 1) {
3021 *os << "has 1 element that ";
3022 matchers_[0].DescribeTo(os);
3023 } else {
3024 *os << "has " << Elements(count()) << " where\n";
3025 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003026 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003027 matchers_[i].DescribeTo(os);
3028 if (i + 1 < count()) {
3029 *os << ",\n";
3030 }
3031 }
3032 }
3033 }
3034
3035 // Describes what the negation of this matcher does.
3036 virtual void DescribeNegationTo(::std::ostream* os) const {
3037 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003038 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003039 return;
3040 }
3041
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003042 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003043 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003044 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003045 matchers_[i].DescribeNegationTo(os);
3046 if (i + 1 < count()) {
3047 *os << ", or\n";
3048 }
3049 }
3050 }
3051
zhanyong.wan82113312010-01-08 21:55:40 +00003052 virtual bool MatchAndExplain(Container container,
3053 MatchResultListener* listener) const {
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003054 // To work with stream-like "containers", we must only walk
3055 // through the elements in one pass.
3056
3057 const bool listener_interested = listener->IsInterested();
3058
3059 // explanations[i] is the explanation of the element at index i.
3060 ::std::vector<internal::string> explanations(count());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003061 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003062 typename StlContainer::const_iterator it = stl_container.begin();
3063 size_t exam_pos = 0;
3064 bool mismatch_found = false; // Have we found a mismatched element yet?
3065
3066 // Go through the elements and matchers in pairs, until we reach
3067 // the end of either the elements or the matchers, or until we find a
3068 // mismatch.
3069 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3070 bool match; // Does the current element match the current matcher?
3071 if (listener_interested) {
3072 StringMatchResultListener s;
3073 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3074 explanations[exam_pos] = s.str();
3075 } else {
3076 match = matchers_[exam_pos].Matches(*it);
3077 }
3078
3079 if (!match) {
3080 mismatch_found = true;
3081 break;
3082 }
3083 }
3084 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3085
3086 // Find how many elements the actual container has. We avoid
3087 // calling size() s.t. this code works for stream-like "containers"
3088 // that don't define size().
3089 size_t actual_count = exam_pos;
3090 for (; it != stl_container.end(); ++it) {
3091 ++actual_count;
3092 }
3093
zhanyong.wan82113312010-01-08 21:55:40 +00003094 if (actual_count != count()) {
3095 // The element count doesn't match. If the container is empty,
3096 // there's no need to explain anything as Google Mock already
3097 // prints the empty container. Otherwise we just need to show
3098 // how many elements there actually are.
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003099 if (listener_interested && (actual_count != 0)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003100 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003101 }
zhanyong.wan82113312010-01-08 21:55:40 +00003102 return false;
3103 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003104
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003105 if (mismatch_found) {
3106 // The element count matches, but the exam_pos-th element doesn't match.
3107 if (listener_interested) {
3108 *listener << "whose element #" << exam_pos << " doesn't match";
3109 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003110 }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003111 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003112 }
zhanyong.wan82113312010-01-08 21:55:40 +00003113
3114 // Every element matches its expectation. We need to explain why
3115 // (the obvious ones can be skipped).
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003116 if (listener_interested) {
3117 bool reason_printed = false;
3118 for (size_t i = 0; i != count(); ++i) {
3119 const internal::string& s = explanations[i];
3120 if (!s.empty()) {
3121 if (reason_printed) {
3122 *listener << ",\nand ";
3123 }
3124 *listener << "whose element #" << i << " matches, " << s;
3125 reason_printed = true;
zhanyong.wan82113312010-01-08 21:55:40 +00003126 }
zhanyong.wan82113312010-01-08 21:55:40 +00003127 }
3128 }
zhanyong.wan82113312010-01-08 21:55:40 +00003129 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003130 }
3131
3132 private:
3133 static Message Elements(size_t count) {
3134 return Message() << count << (count == 1 ? " element" : " elements");
3135 }
3136
3137 size_t count() const { return matchers_.size(); }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003138
3139 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003140
3141 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003142};
3143
zhanyong.wanfb25d532013-07-28 08:24:00 +00003144// Connectivity matrix of (elements X matchers), in element-major order.
3145// Initially, there are no edges.
3146// Use NextGraph() to iterate over all possible edge configurations.
3147// Use Randomize() to generate a random edge configuration.
3148class GTEST_API_ MatchMatrix {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003149 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003150 MatchMatrix(size_t num_elements, size_t num_matchers)
3151 : num_elements_(num_elements),
3152 num_matchers_(num_matchers),
3153 matched_(num_elements_* num_matchers_, 0) {
3154 }
3155
3156 size_t LhsSize() const { return num_elements_; }
3157 size_t RhsSize() const { return num_matchers_; }
3158 bool HasEdge(size_t ilhs, size_t irhs) const {
3159 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3160 }
3161 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3162 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3163 }
3164
3165 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3166 // adds 1 to that number; returns false if incrementing the graph left it
3167 // empty.
3168 bool NextGraph();
3169
3170 void Randomize();
3171
3172 string DebugString() const;
3173
3174 private:
3175 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3176 return ilhs * num_matchers_ + irhs;
3177 }
3178
3179 size_t num_elements_;
3180 size_t num_matchers_;
3181
3182 // Each element is a char interpreted as bool. They are stored as a
3183 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3184 // a (ilhs, irhs) matrix coordinate into an offset.
3185 ::std::vector<char> matched_;
3186};
3187
3188typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3189typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3190
3191// Returns a maximum bipartite matching for the specified graph 'g'.
3192// The matching is represented as a vector of {element, matcher} pairs.
3193GTEST_API_ ElementMatcherPairs
3194FindMaxBipartiteMatching(const MatchMatrix& g);
3195
3196GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
3197 MatchResultListener* listener);
3198
3199// Untyped base class for implementing UnorderedElementsAre. By
3200// putting logic that's not specific to the element type here, we
3201// reduce binary bloat and increase compilation speed.
3202class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3203 protected:
3204 // A vector of matcher describers, one for each element matcher.
3205 // Does not own the describers (and thus can be used only when the
3206 // element matchers are alive).
3207 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3208
3209 // Describes this UnorderedElementsAre matcher.
3210 void DescribeToImpl(::std::ostream* os) const;
3211
3212 // Describes the negation of this UnorderedElementsAre matcher.
3213 void DescribeNegationToImpl(::std::ostream* os) const;
3214
3215 bool VerifyAllElementsAndMatchersAreMatched(
3216 const ::std::vector<string>& element_printouts,
3217 const MatchMatrix& matrix,
3218 MatchResultListener* listener) const;
3219
3220 MatcherDescriberVec& matcher_describers() {
3221 return matcher_describers_;
3222 }
3223
3224 static Message Elements(size_t n) {
3225 return Message() << n << " element" << (n == 1 ? "" : "s");
3226 }
3227
3228 private:
3229 MatcherDescriberVec matcher_describers_;
3230
3231 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3232};
3233
3234// Implements unordered ElementsAre and unordered ElementsAreArray.
3235template <typename Container>
3236class UnorderedElementsAreMatcherImpl
3237 : public MatcherInterface<Container>,
3238 public UnorderedElementsAreMatcherImplBase {
3239 public:
3240 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3241 typedef internal::StlContainerView<RawContainer> View;
3242 typedef typename View::type StlContainer;
3243 typedef typename View::const_reference StlContainerReference;
3244 typedef typename StlContainer::const_iterator StlContainerConstIterator;
3245 typedef typename StlContainer::value_type Element;
3246
3247 // Constructs the matcher from a sequence of element values or
3248 // element matchers.
3249 template <typename InputIter>
3250 UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) {
3251 for (; first != last; ++first) {
3252 matchers_.push_back(MatcherCast<const Element&>(*first));
3253 matcher_describers().push_back(matchers_.back().GetDescriber());
3254 }
3255 }
3256
3257 // Describes what this matcher does.
3258 virtual void DescribeTo(::std::ostream* os) const {
3259 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3260 }
3261
3262 // Describes what the negation of this matcher does.
3263 virtual void DescribeNegationTo(::std::ostream* os) const {
3264 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3265 }
3266
3267 virtual bool MatchAndExplain(Container container,
3268 MatchResultListener* listener) const {
3269 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003270 ::std::vector<string> element_printouts;
3271 MatchMatrix matrix = AnalyzeElements(stl_container.begin(),
3272 stl_container.end(),
3273 &element_printouts,
3274 listener);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003275
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003276 const size_t actual_count = matrix.LhsSize();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003277 if (actual_count == 0 && matchers_.empty()) {
3278 return true;
3279 }
3280 if (actual_count != matchers_.size()) {
3281 // The element count doesn't match. If the container is empty,
3282 // there's no need to explain anything as Google Mock already
3283 // prints the empty container. Otherwise we just need to show
3284 // how many elements there actually are.
3285 if (actual_count != 0 && listener->IsInterested()) {
3286 *listener << "which has " << Elements(actual_count);
3287 }
3288 return false;
3289 }
3290
zhanyong.wanfb25d532013-07-28 08:24:00 +00003291 return VerifyAllElementsAndMatchersAreMatched(element_printouts,
3292 matrix, listener) &&
3293 FindPairing(matrix, listener);
3294 }
3295
3296 private:
3297 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3298
3299 template <typename ElementIter>
3300 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
3301 ::std::vector<string>* element_printouts,
3302 MatchResultListener* listener) const {
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003303 element_printouts->clear();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003304 ::std::vector<char> did_match;
3305 size_t num_elements = 0;
3306 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3307 if (listener->IsInterested()) {
3308 element_printouts->push_back(PrintToString(*elem_first));
3309 }
3310 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3311 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3312 }
3313 }
3314
3315 MatchMatrix matrix(num_elements, matchers_.size());
3316 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3317 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3318 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3319 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3320 }
3321 }
3322 return matrix;
3323 }
3324
3325 MatcherVec matchers_;
3326
3327 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3328};
3329
3330// Functor for use in TransformTuple.
3331// Performs MatcherCast<Target> on an input argument of any type.
3332template <typename Target>
3333struct CastAndAppendTransform {
3334 template <typename Arg>
3335 Matcher<Target> operator()(const Arg& a) const {
3336 return MatcherCast<Target>(a);
3337 }
3338};
3339
3340// Implements UnorderedElementsAre.
3341template <typename MatcherTuple>
3342class UnorderedElementsAreMatcher {
3343 public:
3344 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3345 : matchers_(args) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003346
3347 template <typename Container>
3348 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003349 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003350 typedef typename internal::StlContainerView<RawContainer>::type View;
3351 typedef typename View::value_type Element;
3352 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3353 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003354 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003355 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3356 ::std::back_inserter(matchers));
3357 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3358 matchers.begin(), matchers.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003359 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003360
3361 private:
3362 const MatcherTuple matchers_;
3363 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3364};
3365
3366// Implements ElementsAre.
3367template <typename MatcherTuple>
3368class ElementsAreMatcher {
3369 public:
3370 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3371
3372 template <typename Container>
3373 operator Matcher<Container>() const {
3374 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3375 typedef typename internal::StlContainerView<RawContainer>::type View;
3376 typedef typename View::value_type Element;
3377 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3378 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003379 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003380 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3381 ::std::back_inserter(matchers));
3382 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3383 matchers.begin(), matchers.end()));
3384 }
3385
3386 private:
3387 const MatcherTuple matchers_;
3388 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3389};
3390
3391// Implements UnorderedElementsAreArray().
3392template <typename T>
3393class UnorderedElementsAreArrayMatcher {
3394 public:
3395 UnorderedElementsAreArrayMatcher() {}
3396
3397 template <typename Iter>
3398 UnorderedElementsAreArrayMatcher(Iter first, Iter last)
3399 : matchers_(first, last) {}
3400
3401 template <typename Container>
3402 operator Matcher<Container>() const {
3403 return MakeMatcher(
3404 new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(),
3405 matchers_.end()));
3406 }
3407
3408 private:
3409 ::std::vector<T> matchers_;
3410
3411 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003412};
3413
3414// Implements ElementsAreArray().
3415template <typename T>
3416class ElementsAreArrayMatcher {
3417 public:
jgm38513a82012-11-15 15:50:36 +00003418 template <typename Iter>
3419 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003420
3421 template <typename Container>
3422 operator Matcher<Container>() const {
jgm38513a82012-11-15 15:50:36 +00003423 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3424 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003425 }
3426
3427 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003428 const ::std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003429
3430 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003431};
3432
zhanyong.wanb4140802010-06-08 22:53:57 +00003433// Returns the description for a matcher defined using the MATCHER*()
3434// macro where the user-supplied description string is "", if
3435// 'negation' is false; otherwise returns the description of the
3436// negation of the matcher. 'param_values' contains a list of strings
3437// that are the print-out of the matcher's parameters.
vladlosev587c1b32011-05-20 00:42:22 +00003438GTEST_API_ string FormatMatcherDescription(bool negation,
3439 const char* matcher_name,
3440 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003441
shiqiane35fdd92008-12-10 05:08:54 +00003442} // namespace internal
3443
zhanyong.wanfb25d532013-07-28 08:24:00 +00003444// ElementsAreArray(first, last)
3445// ElementsAreArray(pointer, count)
3446// ElementsAreArray(array)
3447// ElementsAreArray(vector)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003448// ElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00003449//
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003450// The ElementsAreArray() functions are like ElementsAre(...), except
3451// that they are given a homogeneous sequence rather than taking each
3452// element as a function argument. The sequence can be specified as an
3453// array, a pointer and count, a vector, an initializer list, or an
3454// STL iterator range. In each of these cases, the underlying sequence
3455// can be either a sequence of values or a sequence of matchers.
zhanyong.wanfb25d532013-07-28 08:24:00 +00003456//
3457// All forms of ElementsAreArray() make a copy of the input matcher sequence.
3458
3459template <typename Iter>
3460inline internal::ElementsAreArrayMatcher<
3461 typename ::std::iterator_traits<Iter>::value_type>
3462ElementsAreArray(Iter first, Iter last) {
3463 typedef typename ::std::iterator_traits<Iter>::value_type T;
3464 return internal::ElementsAreArrayMatcher<T>(first, last);
3465}
3466
3467template <typename T>
3468inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3469 const T* pointer, size_t count) {
3470 return ElementsAreArray(pointer, pointer + count);
3471}
3472
3473template <typename T, size_t N>
3474inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3475 const T (&array)[N]) {
3476 return ElementsAreArray(array, N);
3477}
3478
3479template <typename T, typename A>
3480inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3481 const ::std::vector<T, A>& vec) {
3482 return ElementsAreArray(vec.begin(), vec.end());
3483}
3484
kosak18489fa2013-12-04 23:49:07 +00003485#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003486template <typename T>
3487inline internal::ElementsAreArrayMatcher<T>
3488ElementsAreArray(::std::initializer_list<T> xs) {
3489 return ElementsAreArray(xs.begin(), xs.end());
3490}
3491#endif
3492
zhanyong.wanfb25d532013-07-28 08:24:00 +00003493// UnorderedElementsAreArray(first, last)
3494// UnorderedElementsAreArray(pointer, count)
3495// UnorderedElementsAreArray(array)
3496// UnorderedElementsAreArray(vector)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003497// UnorderedElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00003498//
3499// The UnorderedElementsAreArray() functions are like
3500// ElementsAreArray(...), but allow matching the elements in any order.
3501template <typename Iter>
3502inline internal::UnorderedElementsAreArrayMatcher<
3503 typename ::std::iterator_traits<Iter>::value_type>
3504UnorderedElementsAreArray(Iter first, Iter last) {
3505 typedef typename ::std::iterator_traits<Iter>::value_type T;
3506 return internal::UnorderedElementsAreArrayMatcher<T>(first, last);
3507}
3508
3509template <typename T>
3510inline internal::UnorderedElementsAreArrayMatcher<T>
3511UnorderedElementsAreArray(const T* pointer, size_t count) {
3512 return UnorderedElementsAreArray(pointer, pointer + count);
3513}
3514
3515template <typename T, size_t N>
3516inline internal::UnorderedElementsAreArrayMatcher<T>
3517UnorderedElementsAreArray(const T (&array)[N]) {
3518 return UnorderedElementsAreArray(array, N);
3519}
3520
3521template <typename T, typename A>
3522inline internal::UnorderedElementsAreArrayMatcher<T>
3523UnorderedElementsAreArray(const ::std::vector<T, A>& vec) {
3524 return UnorderedElementsAreArray(vec.begin(), vec.end());
3525}
3526
kosak18489fa2013-12-04 23:49:07 +00003527#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003528template <typename T>
3529inline internal::UnorderedElementsAreArrayMatcher<T>
3530UnorderedElementsAreArray(::std::initializer_list<T> xs) {
3531 return UnorderedElementsAreArray(xs.begin(), xs.end());
3532}
3533#endif
zhanyong.wanfb25d532013-07-28 08:24:00 +00003534
shiqiane35fdd92008-12-10 05:08:54 +00003535// _ is a matcher that matches anything of any type.
3536//
3537// This definition is fine as:
3538//
3539// 1. The C++ standard permits using the name _ in a namespace that
3540// is not the global namespace or ::std.
3541// 2. The AnythingMatcher class has no data member or constructor,
3542// so it's OK to create global variables of this type.
3543// 3. c-style has approved of using _ in this case.
3544const internal::AnythingMatcher _ = {};
3545// Creates a matcher that matches any value of the given type T.
3546template <typename T>
3547inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
3548
3549// Creates a matcher that matches any value of the given type T.
3550template <typename T>
3551inline Matcher<T> An() { return A<T>(); }
3552
3553// Creates a polymorphic matcher that matches anything equal to x.
3554// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
3555// wouldn't compile.
3556template <typename T>
3557inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
3558
3559// Constructs a Matcher<T> from a 'value' of type T. The constructed
3560// matcher matches any value that's equal to 'value'.
3561template <typename T>
3562Matcher<T>::Matcher(T value) { *this = Eq(value); }
3563
3564// Creates a monomorphic matcher that matches anything with type Lhs
3565// and equal to rhs. A user may need to use this instead of Eq(...)
3566// in order to resolve an overloading ambiguity.
3567//
3568// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
3569// or Matcher<T>(x), but more readable than the latter.
3570//
3571// We could define similar monomorphic matchers for other comparison
3572// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
3573// it yet as those are used much less than Eq() in practice. A user
3574// can always write Matcher<T>(Lt(5)) to be explicit about the type,
3575// for example.
3576template <typename Lhs, typename Rhs>
3577inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
3578
3579// Creates a polymorphic matcher that matches anything >= x.
3580template <typename Rhs>
3581inline internal::GeMatcher<Rhs> Ge(Rhs x) {
3582 return internal::GeMatcher<Rhs>(x);
3583}
3584
3585// Creates a polymorphic matcher that matches anything > x.
3586template <typename Rhs>
3587inline internal::GtMatcher<Rhs> Gt(Rhs x) {
3588 return internal::GtMatcher<Rhs>(x);
3589}
3590
3591// Creates a polymorphic matcher that matches anything <= x.
3592template <typename Rhs>
3593inline internal::LeMatcher<Rhs> Le(Rhs x) {
3594 return internal::LeMatcher<Rhs>(x);
3595}
3596
3597// Creates a polymorphic matcher that matches anything < x.
3598template <typename Rhs>
3599inline internal::LtMatcher<Rhs> Lt(Rhs x) {
3600 return internal::LtMatcher<Rhs>(x);
3601}
3602
3603// Creates a polymorphic matcher that matches anything != x.
3604template <typename Rhs>
3605inline internal::NeMatcher<Rhs> Ne(Rhs x) {
3606 return internal::NeMatcher<Rhs>(x);
3607}
3608
zhanyong.wan2d970ee2009-09-24 21:41:36 +00003609// Creates a polymorphic matcher that matches any NULL pointer.
3610inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
3611 return MakePolymorphicMatcher(internal::IsNullMatcher());
3612}
3613
shiqiane35fdd92008-12-10 05:08:54 +00003614// Creates a polymorphic matcher that matches any non-NULL pointer.
3615// This is convenient as Not(NULL) doesn't compile (the compiler
3616// thinks that that expression is comparing a pointer with an integer).
3617inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
3618 return MakePolymorphicMatcher(internal::NotNullMatcher());
3619}
3620
3621// Creates a polymorphic matcher that matches any argument that
3622// references variable x.
3623template <typename T>
3624inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
3625 return internal::RefMatcher<T&>(x);
3626}
3627
3628// Creates a matcher that matches any double argument approximately
3629// equal to rhs, where two NANs are considered unequal.
3630inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
3631 return internal::FloatingEqMatcher<double>(rhs, false);
3632}
3633
3634// Creates a matcher that matches any double argument approximately
3635// equal to rhs, including NaN values when rhs is NaN.
3636inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
3637 return internal::FloatingEqMatcher<double>(rhs, true);
3638}
3639
zhanyong.wan616180e2013-06-18 18:49:51 +00003640// Creates a matcher that matches any double argument approximately equal to
3641// rhs, up to the specified max absolute error bound, where two NANs are
3642// considered unequal. The max absolute error bound must be non-negative.
3643inline internal::FloatingEqMatcher<double> DoubleNear(
3644 double rhs, double max_abs_error) {
3645 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
3646}
3647
3648// Creates a matcher that matches any double argument approximately equal to
3649// rhs, up to the specified max absolute error bound, including NaN values when
3650// rhs is NaN. The max absolute error bound must be non-negative.
3651inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
3652 double rhs, double max_abs_error) {
3653 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
3654}
3655
shiqiane35fdd92008-12-10 05:08:54 +00003656// Creates a matcher that matches any float argument approximately
3657// equal to rhs, where two NANs are considered unequal.
3658inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
3659 return internal::FloatingEqMatcher<float>(rhs, false);
3660}
3661
zhanyong.wan616180e2013-06-18 18:49:51 +00003662// Creates a matcher that matches any float argument approximately
shiqiane35fdd92008-12-10 05:08:54 +00003663// equal to rhs, including NaN values when rhs is NaN.
3664inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
3665 return internal::FloatingEqMatcher<float>(rhs, true);
3666}
3667
zhanyong.wan616180e2013-06-18 18:49:51 +00003668// Creates a matcher that matches any float argument approximately equal to
3669// rhs, up to the specified max absolute error bound, where two NANs are
3670// considered unequal. The max absolute error bound must be non-negative.
3671inline internal::FloatingEqMatcher<float> FloatNear(
3672 float rhs, float max_abs_error) {
3673 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
3674}
3675
3676// Creates a matcher that matches any float argument approximately equal to
3677// rhs, up to the specified max absolute error bound, including NaN values when
3678// rhs is NaN. The max absolute error bound must be non-negative.
3679inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
3680 float rhs, float max_abs_error) {
3681 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
3682}
3683
shiqiane35fdd92008-12-10 05:08:54 +00003684// Creates a matcher that matches a pointer (raw or smart) that points
3685// to a value that matches inner_matcher.
3686template <typename InnerMatcher>
3687inline internal::PointeeMatcher<InnerMatcher> Pointee(
3688 const InnerMatcher& inner_matcher) {
3689 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
3690}
3691
billydonahue1f5fdea2014-05-19 17:54:51 +00003692// Creates a matcher that matches a pointer or reference that matches
3693// inner_matcher when dynamic_cast<To> is applied.
3694// The result of dynamic_cast<To> is forwarded to the inner matcher.
3695// If To is a pointer and the cast fails, the inner matcher will receive NULL.
3696// If To is a reference and the cast fails, this matcher returns false
3697// immediately.
3698template <typename To>
3699inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
3700WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
3701 return MakePolymorphicMatcher(
3702 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
3703}
3704
shiqiane35fdd92008-12-10 05:08:54 +00003705// Creates a matcher that matches an object whose given field matches
3706// 'matcher'. For example,
3707// Field(&Foo::number, Ge(5))
3708// matches a Foo object x iff x.number >= 5.
3709template <typename Class, typename FieldType, typename FieldMatcher>
3710inline PolymorphicMatcher<
3711 internal::FieldMatcher<Class, FieldType> > Field(
3712 FieldType Class::*field, const FieldMatcher& matcher) {
3713 return MakePolymorphicMatcher(
3714 internal::FieldMatcher<Class, FieldType>(
3715 field, MatcherCast<const FieldType&>(matcher)));
3716 // The call to MatcherCast() is required for supporting inner
3717 // matchers of compatible types. For example, it allows
3718 // Field(&Foo::bar, m)
3719 // to compile where bar is an int32 and m is a matcher for int64.
3720}
3721
3722// Creates a matcher that matches an object whose given property
3723// matches 'matcher'. For example,
3724// Property(&Foo::str, StartsWith("hi"))
3725// matches a Foo object x iff x.str() starts with "hi".
3726template <typename Class, typename PropertyType, typename PropertyMatcher>
3727inline PolymorphicMatcher<
3728 internal::PropertyMatcher<Class, PropertyType> > Property(
3729 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
3730 return MakePolymorphicMatcher(
3731 internal::PropertyMatcher<Class, PropertyType>(
3732 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00003733 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00003734 // The call to MatcherCast() is required for supporting inner
3735 // matchers of compatible types. For example, it allows
3736 // Property(&Foo::bar, m)
3737 // to compile where bar() returns an int32 and m is a matcher for int64.
3738}
3739
3740// Creates a matcher that matches an object iff the result of applying
3741// a callable to x matches 'matcher'.
3742// For example,
3743// ResultOf(f, StartsWith("hi"))
3744// matches a Foo object x iff f(x) starts with "hi".
3745// callable parameter can be a function, function pointer, or a functor.
3746// Callable has to satisfy the following conditions:
3747// * It is required to keep no state affecting the results of
3748// the calls on it and make no assumptions about how many calls
3749// will be made. Any state it keeps must be protected from the
3750// concurrent access.
3751// * If it is a function object, it has to define type result_type.
3752// We recommend deriving your functor classes from std::unary_function.
3753template <typename Callable, typename ResultOfMatcher>
3754internal::ResultOfMatcher<Callable> ResultOf(
3755 Callable callable, const ResultOfMatcher& matcher) {
3756 return internal::ResultOfMatcher<Callable>(
3757 callable,
3758 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
3759 matcher));
3760 // The call to MatcherCast() is required for supporting inner
3761 // matchers of compatible types. For example, it allows
3762 // ResultOf(Function, m)
3763 // to compile where Function() returns an int32 and m is a matcher for int64.
3764}
3765
3766// String matchers.
3767
3768// Matches a string equal to str.
3769inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3770 StrEq(const internal::string& str) {
3771 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3772 str, true, true));
3773}
3774
3775// Matches a string not equal to str.
3776inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3777 StrNe(const internal::string& str) {
3778 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3779 str, false, true));
3780}
3781
3782// Matches a string equal to str, ignoring case.
3783inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3784 StrCaseEq(const internal::string& str) {
3785 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3786 str, true, false));
3787}
3788
3789// Matches a string not equal to str, ignoring case.
3790inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3791 StrCaseNe(const internal::string& str) {
3792 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3793 str, false, false));
3794}
3795
3796// Creates a matcher that matches any string, std::string, or C string
3797// that contains the given substring.
3798inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
3799 HasSubstr(const internal::string& substring) {
3800 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
3801 substring));
3802}
3803
3804// Matches a string that starts with 'prefix' (case-sensitive).
3805inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
3806 StartsWith(const internal::string& prefix) {
3807 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
3808 prefix));
3809}
3810
3811// Matches a string that ends with 'suffix' (case-sensitive).
3812inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
3813 EndsWith(const internal::string& suffix) {
3814 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
3815 suffix));
3816}
3817
shiqiane35fdd92008-12-10 05:08:54 +00003818// Matches a string that fully matches regular expression 'regex'.
3819// The matcher takes ownership of 'regex'.
3820inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3821 const internal::RE* regex) {
3822 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
3823}
3824inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3825 const internal::string& regex) {
3826 return MatchesRegex(new internal::RE(regex));
3827}
3828
3829// Matches a string that contains regular expression 'regex'.
3830// The matcher takes ownership of 'regex'.
3831inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3832 const internal::RE* regex) {
3833 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
3834}
3835inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3836 const internal::string& regex) {
3837 return ContainsRegex(new internal::RE(regex));
3838}
3839
shiqiane35fdd92008-12-10 05:08:54 +00003840#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3841// Wide string matchers.
3842
3843// Matches a string equal to str.
3844inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3845 StrEq(const internal::wstring& str) {
3846 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3847 str, true, true));
3848}
3849
3850// Matches a string not equal to str.
3851inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3852 StrNe(const internal::wstring& str) {
3853 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3854 str, false, true));
3855}
3856
3857// Matches a string equal to str, ignoring case.
3858inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3859 StrCaseEq(const internal::wstring& str) {
3860 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3861 str, true, false));
3862}
3863
3864// Matches a string not equal to str, ignoring case.
3865inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3866 StrCaseNe(const internal::wstring& str) {
3867 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3868 str, false, false));
3869}
3870
3871// Creates a matcher that matches any wstring, std::wstring, or C wide string
3872// that contains the given substring.
3873inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
3874 HasSubstr(const internal::wstring& substring) {
3875 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
3876 substring));
3877}
3878
3879// Matches a string that starts with 'prefix' (case-sensitive).
3880inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
3881 StartsWith(const internal::wstring& prefix) {
3882 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
3883 prefix));
3884}
3885
3886// Matches a string that ends with 'suffix' (case-sensitive).
3887inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
3888 EndsWith(const internal::wstring& suffix) {
3889 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
3890 suffix));
3891}
3892
3893#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3894
3895// Creates a polymorphic matcher that matches a 2-tuple where the
3896// first field == the second field.
3897inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
3898
3899// Creates a polymorphic matcher that matches a 2-tuple where the
3900// first field >= the second field.
3901inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
3902
3903// Creates a polymorphic matcher that matches a 2-tuple where the
3904// first field > the second field.
3905inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
3906
3907// Creates a polymorphic matcher that matches a 2-tuple where the
3908// first field <= the second field.
3909inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
3910
3911// Creates a polymorphic matcher that matches a 2-tuple where the
3912// first field < the second field.
3913inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
3914
3915// Creates a polymorphic matcher that matches a 2-tuple where the
3916// first field != the second field.
3917inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
3918
3919// Creates a matcher that matches any value of type T that m doesn't
3920// match.
3921template <typename InnerMatcher>
3922inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
3923 return internal::NotMatcher<InnerMatcher>(m);
3924}
3925
shiqiane35fdd92008-12-10 05:08:54 +00003926// Returns a matcher that matches anything that satisfies the given
3927// predicate. The predicate can be any unary function or functor
3928// whose return type can be implicitly converted to bool.
3929template <typename Predicate>
3930inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
3931Truly(Predicate pred) {
3932 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
3933}
3934
zhanyong.wana31d9ce2013-03-01 01:50:17 +00003935// Returns a matcher that matches the container size. The container must
3936// support both size() and size_type which all STL-like containers provide.
3937// Note that the parameter 'size' can be a value of type size_type as well as
3938// matcher. For instance:
3939// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
3940// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
3941template <typename SizeMatcher>
3942inline internal::SizeIsMatcher<SizeMatcher>
3943SizeIs(const SizeMatcher& size_matcher) {
3944 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
3945}
3946
kosakb6a34882014-03-12 21:06:46 +00003947// Returns a matcher that matches the distance between the container's begin()
3948// iterator and its end() iterator, i.e. the size of the container. This matcher
3949// can be used instead of SizeIs with containers such as std::forward_list which
3950// do not implement size(). The container must provide const_iterator (with
3951// valid iterator_traits), begin() and end().
3952template <typename DistanceMatcher>
3953inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
3954BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
3955 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
3956}
3957
zhanyong.wan6a896b52009-01-16 01:13:50 +00003958// Returns a matcher that matches an equal container.
3959// This matcher behaves like Eq(), but in the event of mismatch lists the
3960// values that are included in one container but not the other. (Duplicate
3961// values and order differences are not explained.)
3962template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00003963inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00003964 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00003965 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00003966 // This following line is for working around a bug in MSVC 8.0,
3967 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00003968 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00003969 return MakePolymorphicMatcher(
3970 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00003971}
3972
zhanyong.wan898725c2011-09-16 16:45:39 +00003973// Returns a matcher that matches a container that, when sorted using
3974// the given comparator, matches container_matcher.
3975template <typename Comparator, typename ContainerMatcher>
3976inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
3977WhenSortedBy(const Comparator& comparator,
3978 const ContainerMatcher& container_matcher) {
3979 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
3980 comparator, container_matcher);
3981}
3982
3983// Returns a matcher that matches a container that, when sorted using
3984// the < operator, matches container_matcher.
3985template <typename ContainerMatcher>
3986inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
3987WhenSorted(const ContainerMatcher& container_matcher) {
3988 return
3989 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
3990 internal::LessComparator(), container_matcher);
3991}
3992
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003993// Matches an STL-style container or a native array that contains the
3994// same number of elements as in rhs, where its i-th element and rhs's
3995// i-th element (as a pair) satisfy the given pair matcher, for all i.
3996// TupleMatcher must be able to be safely cast to Matcher<tuple<const
3997// T1&, const T2&> >, where T1 and T2 are the types of elements in the
3998// LHS container and the RHS container respectively.
3999template <typename TupleMatcher, typename Container>
4000inline internal::PointwiseMatcher<TupleMatcher,
4001 GTEST_REMOVE_CONST_(Container)>
4002Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4003 // This following line is for working around a bug in MSVC 8.0,
4004 // which causes Container to be a const type sometimes.
4005 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4006 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4007 tuple_matcher, rhs);
4008}
4009
zhanyong.wanb8243162009-06-04 05:48:20 +00004010// Matches an STL-style container or a native array that contains at
4011// least one element matching the given value or matcher.
4012//
4013// Examples:
4014// ::std::set<int> page_ids;
4015// page_ids.insert(3);
4016// page_ids.insert(1);
4017// EXPECT_THAT(page_ids, Contains(1));
4018// EXPECT_THAT(page_ids, Contains(Gt(2)));
4019// EXPECT_THAT(page_ids, Not(Contains(4)));
4020//
4021// ::std::map<int, size_t> page_lengths;
4022// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00004023// EXPECT_THAT(page_lengths,
4024// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004025//
4026// const char* user_ids[] = { "joe", "mike", "tom" };
4027// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4028template <typename M>
4029inline internal::ContainsMatcher<M> Contains(M matcher) {
4030 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004031}
4032
zhanyong.wan33605ba2010-04-22 23:37:47 +00004033// Matches an STL-style container or a native array that contains only
4034// elements matching the given value or matcher.
4035//
4036// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
4037// the messages are different.
4038//
4039// Examples:
4040// ::std::set<int> page_ids;
4041// // Each(m) matches an empty container, regardless of what m is.
4042// EXPECT_THAT(page_ids, Each(Eq(1)));
4043// EXPECT_THAT(page_ids, Each(Eq(77)));
4044//
4045// page_ids.insert(3);
4046// EXPECT_THAT(page_ids, Each(Gt(0)));
4047// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
4048// page_ids.insert(1);
4049// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
4050//
4051// ::std::map<int, size_t> page_lengths;
4052// page_lengths[1] = 100;
4053// page_lengths[2] = 200;
4054// page_lengths[3] = 300;
4055// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
4056// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
4057//
4058// const char* user_ids[] = { "joe", "mike", "tom" };
4059// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
4060template <typename M>
4061inline internal::EachMatcher<M> Each(M matcher) {
4062 return internal::EachMatcher<M>(matcher);
4063}
4064
zhanyong.wanb5937da2009-07-16 20:26:41 +00004065// Key(inner_matcher) matches an std::pair whose 'first' field matches
4066// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
4067// std::map that contains at least one element whose key is >= 5.
4068template <typename M>
4069inline internal::KeyMatcher<M> Key(M inner_matcher) {
4070 return internal::KeyMatcher<M>(inner_matcher);
4071}
4072
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00004073// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
4074// matches first_matcher and whose 'second' field matches second_matcher. For
4075// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
4076// to match a std::map<int, string> that contains exactly one element whose key
4077// is >= 5 and whose value equals "foo".
4078template <typename FirstMatcher, typename SecondMatcher>
4079inline internal::PairMatcher<FirstMatcher, SecondMatcher>
4080Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
4081 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
4082 first_matcher, second_matcher);
4083}
4084
shiqiane35fdd92008-12-10 05:08:54 +00004085// Returns a predicate that is satisfied by anything that matches the
4086// given matcher.
4087template <typename M>
4088inline internal::MatcherAsPredicate<M> Matches(M matcher) {
4089 return internal::MatcherAsPredicate<M>(matcher);
4090}
4091
zhanyong.wanb8243162009-06-04 05:48:20 +00004092// Returns true iff the value matches the matcher.
4093template <typename T, typename M>
4094inline bool Value(const T& value, M matcher) {
4095 return testing::Matches(matcher)(value);
4096}
4097
zhanyong.wan34b034c2010-03-05 21:23:23 +00004098// Matches the value against the given matcher and explains the match
4099// result to listener.
4100template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00004101inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00004102 M matcher, const T& value, MatchResultListener* listener) {
4103 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
4104}
4105
zhanyong.wan616180e2013-06-18 18:49:51 +00004106#if GTEST_LANG_CXX11
4107// Define variadic matcher versions. They are overloaded in
4108// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
4109template <typename... Args>
4110inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
4111 return internal::AllOfMatcher<Args...>(matchers...);
4112}
4113
4114template <typename... Args>
4115inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
4116 return internal::AnyOfMatcher<Args...>(matchers...);
4117}
4118
4119#endif // GTEST_LANG_CXX11
4120
zhanyong.wanbf550852009-06-09 06:09:53 +00004121// AllArgs(m) is a synonym of m. This is useful in
4122//
4123// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
4124//
4125// which is easier to read than
4126//
4127// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
4128template <typename InnerMatcher>
4129inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
4130
shiqiane35fdd92008-12-10 05:08:54 +00004131// These macros allow using matchers to check values in Google Test
4132// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
4133// succeed iff the value matches the matcher. If the assertion fails,
4134// the value and the description of the matcher will be printed.
4135#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
4136 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4137#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
4138 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4139
4140} // namespace testing
4141
4142#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
billydonahue1f5fdea2014-05-19 17:54:51 +00004143