blob: de966a7a41dacd434e99aef37d6912686d62135e [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) {
709 using ::std::tr1::get;
710 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
711 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
712 }
713
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000714 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000715 // describes failures in matching the first N fields of matchers
716 // against the first N fields of values. If there is no failure,
717 // nothing will be streamed to os.
718 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000719 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
720 const ValueTuple& values,
721 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000722 using ::std::tr1::tuple_element;
723 using ::std::tr1::get;
724
725 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000726 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000727
728 // Then describes the failure (if any) in the (N - 1)-th (0-based)
729 // field.
730 typename tuple_element<N - 1, MatcherTuple>::type matcher =
731 get<N - 1>(matchers);
732 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
733 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000734 StringMatchResultListener listener;
735 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000736 // TODO(wan): include in the message the name of the parameter
737 // as used in MOCK_METHOD*() when possible.
738 *os << " Expected arg #" << N - 1 << ": ";
739 get<N - 1>(matchers).DescribeTo(os);
740 *os << "\n Actual: ";
741 // We remove the reference in type Value to prevent the
742 // universal printer from printing the address of value, which
743 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000744 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000745 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000746 internal::UniversalPrint(value, os);
747 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000748 *os << "\n";
749 }
750 }
751};
752
753// The base case.
754template <>
755class TuplePrefix<0> {
756 public:
757 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000758 static bool Matches(const MatcherTuple& /* matcher_tuple */,
759 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000760 return true;
761 }
762
763 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000764 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
765 const ValueTuple& /* values */,
766 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000767};
768
769// TupleMatches(matcher_tuple, value_tuple) returns true iff all
770// matchers in matcher_tuple match the corresponding fields in
771// value_tuple. It is a compiler error if matcher_tuple and
772// value_tuple have different number of fields or incompatible field
773// types.
774template <typename MatcherTuple, typename ValueTuple>
775bool TupleMatches(const MatcherTuple& matcher_tuple,
776 const ValueTuple& value_tuple) {
777 using ::std::tr1::tuple_size;
778 // Makes sure that matcher_tuple and value_tuple have the same
779 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000780 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000781 tuple_size<ValueTuple>::value,
782 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000783 return TuplePrefix<tuple_size<ValueTuple>::value>::
784 Matches(matcher_tuple, value_tuple);
785}
786
787// Describes failures in matching matchers against values. If there
788// is no failure, nothing will be streamed to os.
789template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000790void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
791 const ValueTuple& values,
792 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000793 using ::std::tr1::tuple_size;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000794 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000795 matchers, values, os);
796}
797
zhanyong.wanfb25d532013-07-28 08:24:00 +0000798// TransformTupleValues and its helper.
799//
800// TransformTupleValuesHelper hides the internal machinery that
801// TransformTupleValues uses to implement a tuple traversal.
802template <typename Tuple, typename Func, typename OutIter>
803class TransformTupleValuesHelper {
804 private:
805 typedef typename ::std::tr1::tuple_size<Tuple> TupleSize;
806
807 public:
808 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
809 // Returns the final value of 'out' in case the caller needs it.
810 static OutIter Run(Func f, const Tuple& t, OutIter out) {
811 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
812 }
813
814 private:
815 template <typename Tup, size_t kRemainingSize>
816 struct IterateOverTuple {
817 OutIter operator() (Func f, const Tup& t, OutIter out) const {
818 *out++ = f(::std::tr1::get<TupleSize::value - kRemainingSize>(t));
819 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
820 }
821 };
822 template <typename Tup>
823 struct IterateOverTuple<Tup, 0> {
824 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
825 return out;
826 }
827 };
828};
829
830// Successively invokes 'f(element)' on each element of the tuple 't',
831// appending each result to the 'out' iterator. Returns the final value
832// of 'out'.
833template <typename Tuple, typename Func, typename OutIter>
834OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
835 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
836}
837
shiqiane35fdd92008-12-10 05:08:54 +0000838// Implements A<T>().
839template <typename T>
840class AnyMatcherImpl : public MatcherInterface<T> {
841 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000842 virtual bool MatchAndExplain(
843 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000844 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
845 virtual void DescribeNegationTo(::std::ostream* os) const {
846 // This is mostly for completeness' safe, as it's not very useful
847 // to write Not(A<bool>()). However we cannot completely rule out
848 // such a possibility, and it doesn't hurt to be prepared.
849 *os << "never matches";
850 }
851};
852
853// Implements _, a matcher that matches any value of any
854// type. This is a polymorphic matcher, so we need a template type
855// conversion operator to make it appearing as a Matcher<T> for any
856// type T.
857class AnythingMatcher {
858 public:
859 template <typename T>
860 operator Matcher<T>() const { return A<T>(); }
861};
862
863// Implements a matcher that compares a given value with a
864// pre-supplied value using one of the ==, <=, <, etc, operators. The
865// two values being compared don't have to have the same type.
866//
867// The matcher defined here is polymorphic (for example, Eq(5) can be
868// used to match an int, a short, a double, etc). Therefore we use
869// a template type conversion operator in the implementation.
870//
871// We define this as a macro in order to eliminate duplicated source
872// code.
873//
874// The following template definition assumes that the Rhs parameter is
875// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000876#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \
877 name, op, relation, negated_relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000878 template <typename Rhs> class name##Matcher { \
879 public: \
880 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
881 template <typename Lhs> \
882 operator Matcher<Lhs>() const { \
883 return MakeMatcher(new Impl<Lhs>(rhs_)); \
884 } \
885 private: \
886 template <typename Lhs> \
887 class Impl : public MatcherInterface<Lhs> { \
888 public: \
889 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
zhanyong.wan82113312010-01-08 21:55:40 +0000890 virtual bool MatchAndExplain(\
891 Lhs lhs, MatchResultListener* /* listener */) const { \
892 return lhs op rhs_; \
893 } \
shiqiane35fdd92008-12-10 05:08:54 +0000894 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000895 *os << relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000896 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000897 } \
898 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000899 *os << negated_relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000900 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000901 } \
902 private: \
903 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000904 GTEST_DISALLOW_ASSIGN_(Impl); \
shiqiane35fdd92008-12-10 05:08:54 +0000905 }; \
906 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000907 GTEST_DISALLOW_ASSIGN_(name##Matcher); \
shiqiane35fdd92008-12-10 05:08:54 +0000908 }
909
910// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
911// respectively.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000912GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
913GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
914GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
915GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
916GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
917GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000918
zhanyong.wane0d051e2009-02-19 00:33:37 +0000919#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000920
vladlosev79b83502009-11-18 00:43:37 +0000921// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000922// pointer that is NULL.
923class IsNullMatcher {
924 public:
vladlosev79b83502009-11-18 00:43:37 +0000925 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000926 bool MatchAndExplain(const Pointer& p,
927 MatchResultListener* /* listener */) const {
928 return GetRawPointer(p) == NULL;
929 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000930
931 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
932 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000933 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000934 }
935};
936
vladlosev79b83502009-11-18 00:43:37 +0000937// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000938// pointer that is not NULL.
939class NotNullMatcher {
940 public:
vladlosev79b83502009-11-18 00:43:37 +0000941 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000942 bool MatchAndExplain(const Pointer& p,
943 MatchResultListener* /* listener */) const {
944 return GetRawPointer(p) != NULL;
945 }
shiqiane35fdd92008-12-10 05:08:54 +0000946
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000947 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +0000948 void DescribeNegationTo(::std::ostream* os) const {
949 *os << "is NULL";
950 }
951};
952
953// Ref(variable) matches any argument that is a reference to
954// 'variable'. This matcher is polymorphic as it can match any
955// super type of the type of 'variable'.
956//
957// The RefMatcher template class implements Ref(variable). It can
958// only be instantiated with a reference type. This prevents a user
959// from mistakenly using Ref(x) to match a non-reference function
960// argument. For example, the following will righteously cause a
961// compiler error:
962//
963// int n;
964// Matcher<int> m1 = Ref(n); // This won't compile.
965// Matcher<int&> m2 = Ref(n); // This will compile.
966template <typename T>
967class RefMatcher;
968
969template <typename T>
970class RefMatcher<T&> {
971 // Google Mock is a generic framework and thus needs to support
972 // mocking any function types, including those that take non-const
973 // reference arguments. Therefore the template parameter T (and
974 // Super below) can be instantiated to either a const type or a
975 // non-const type.
976 public:
977 // RefMatcher() takes a T& instead of const T&, as we want the
978 // compiler to catch using Ref(const_value) as a matcher for a
979 // non-const reference.
980 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
981
982 template <typename Super>
983 operator Matcher<Super&>() const {
984 // By passing object_ (type T&) to Impl(), which expects a Super&,
985 // we make sure that Super is a super type of T. In particular,
986 // this catches using Ref(const_value) as a matcher for a
987 // non-const reference, as you cannot implicitly convert a const
988 // reference to a non-const reference.
989 return MakeMatcher(new Impl<Super>(object_));
990 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000991
shiqiane35fdd92008-12-10 05:08:54 +0000992 private:
993 template <typename Super>
994 class Impl : public MatcherInterface<Super&> {
995 public:
996 explicit Impl(Super& x) : object_(x) {} // NOLINT
997
zhanyong.wandb22c222010-01-28 21:52:29 +0000998 // MatchAndExplain() takes a Super& (as opposed to const Super&)
999 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +00001000 virtual bool MatchAndExplain(
1001 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001002 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +00001003 return &x == &object_;
1004 }
shiqiane35fdd92008-12-10 05:08:54 +00001005
1006 virtual void DescribeTo(::std::ostream* os) const {
1007 *os << "references the variable ";
1008 UniversalPrinter<Super&>::Print(object_, os);
1009 }
1010
1011 virtual void DescribeNegationTo(::std::ostream* os) const {
1012 *os << "does not reference the variable ";
1013 UniversalPrinter<Super&>::Print(object_, os);
1014 }
1015
shiqiane35fdd92008-12-10 05:08:54 +00001016 private:
1017 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001018
1019 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001020 };
1021
1022 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001023
1024 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001025};
1026
1027// Polymorphic helper functions for narrow and wide string matchers.
1028inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1029 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1030}
1031
1032inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1033 const wchar_t* rhs) {
1034 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1035}
1036
1037// String comparison for narrow or wide strings that can have embedded NUL
1038// characters.
1039template <typename StringType>
1040bool CaseInsensitiveStringEquals(const StringType& s1,
1041 const StringType& s2) {
1042 // Are the heads equal?
1043 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1044 return false;
1045 }
1046
1047 // Skip the equal heads.
1048 const typename StringType::value_type nul = 0;
1049 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1050
1051 // Are we at the end of either s1 or s2?
1052 if (i1 == StringType::npos || i2 == StringType::npos) {
1053 return i1 == i2;
1054 }
1055
1056 // Are the tails equal?
1057 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1058}
1059
1060// String matchers.
1061
1062// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1063template <typename StringType>
1064class StrEqualityMatcher {
1065 public:
shiqiane35fdd92008-12-10 05:08:54 +00001066 StrEqualityMatcher(const StringType& str, bool expect_eq,
1067 bool case_sensitive)
1068 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1069
jgm38513a82012-11-15 15:50:36 +00001070 // Accepts pointer types, particularly:
1071 // const char*
1072 // char*
1073 // const wchar_t*
1074 // wchar_t*
1075 template <typename CharType>
1076 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001077 if (s == NULL) {
1078 return !expect_eq_;
1079 }
zhanyong.wandb22c222010-01-28 21:52:29 +00001080 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001081 }
1082
jgm38513a82012-11-15 15:50:36 +00001083 // Matches anything that can convert to StringType.
1084 //
1085 // This is a template, not just a plain function with const StringType&,
1086 // because StringPiece has some interfering non-explicit constructors.
1087 template <typename MatcheeStringType>
1088 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001089 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001090 const StringType& s2(s);
1091 const bool eq = case_sensitive_ ? s2 == string_ :
1092 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +00001093 return expect_eq_ == eq;
1094 }
1095
1096 void DescribeTo(::std::ostream* os) const {
1097 DescribeToHelper(expect_eq_, os);
1098 }
1099
1100 void DescribeNegationTo(::std::ostream* os) const {
1101 DescribeToHelper(!expect_eq_, os);
1102 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001103
shiqiane35fdd92008-12-10 05:08:54 +00001104 private:
1105 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001106 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +00001107 *os << "equal to ";
1108 if (!case_sensitive_) {
1109 *os << "(ignoring case) ";
1110 }
vladloseve2e8ba42010-05-13 18:16:03 +00001111 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001112 }
1113
1114 const StringType string_;
1115 const bool expect_eq_;
1116 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001117
1118 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001119};
1120
1121// Implements the polymorphic HasSubstr(substring) matcher, which
1122// can be used as a Matcher<T> as long as T can be converted to a
1123// string.
1124template <typename StringType>
1125class HasSubstrMatcher {
1126 public:
shiqiane35fdd92008-12-10 05:08:54 +00001127 explicit HasSubstrMatcher(const StringType& substring)
1128 : substring_(substring) {}
1129
jgm38513a82012-11-15 15:50:36 +00001130 // Accepts pointer types, particularly:
1131 // const char*
1132 // char*
1133 // const wchar_t*
1134 // wchar_t*
1135 template <typename CharType>
1136 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001137 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001138 }
1139
jgm38513a82012-11-15 15:50:36 +00001140 // Matches anything that can convert to StringType.
1141 //
1142 // This is a template, not just a plain function with const StringType&,
1143 // because StringPiece has some interfering non-explicit constructors.
1144 template <typename MatcheeStringType>
1145 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001146 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001147 const StringType& s2(s);
1148 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001149 }
1150
1151 // Describes what this matcher matches.
1152 void DescribeTo(::std::ostream* os) const {
1153 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001154 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001155 }
1156
1157 void DescribeNegationTo(::std::ostream* os) const {
1158 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001159 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001160 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001161
shiqiane35fdd92008-12-10 05:08:54 +00001162 private:
1163 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001164
1165 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001166};
1167
1168// Implements the polymorphic StartsWith(substring) matcher, which
1169// can be used as a Matcher<T> as long as T can be converted to a
1170// string.
1171template <typename StringType>
1172class StartsWithMatcher {
1173 public:
shiqiane35fdd92008-12-10 05:08:54 +00001174 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1175 }
1176
jgm38513a82012-11-15 15:50:36 +00001177 // Accepts pointer types, particularly:
1178 // const char*
1179 // char*
1180 // const wchar_t*
1181 // wchar_t*
1182 template <typename CharType>
1183 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001184 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001185 }
1186
jgm38513a82012-11-15 15:50:36 +00001187 // Matches anything that can convert to StringType.
1188 //
1189 // This is a template, not just a plain function with const StringType&,
1190 // because StringPiece has some interfering non-explicit constructors.
1191 template <typename MatcheeStringType>
1192 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001193 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001194 const StringType& s2(s);
1195 return s2.length() >= prefix_.length() &&
1196 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001197 }
1198
1199 void DescribeTo(::std::ostream* os) const {
1200 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001201 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001202 }
1203
1204 void DescribeNegationTo(::std::ostream* os) const {
1205 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001206 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001207 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001208
shiqiane35fdd92008-12-10 05:08:54 +00001209 private:
1210 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001211
1212 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001213};
1214
1215// Implements the polymorphic EndsWith(substring) matcher, which
1216// can be used as a Matcher<T> as long as T can be converted to a
1217// string.
1218template <typename StringType>
1219class EndsWithMatcher {
1220 public:
shiqiane35fdd92008-12-10 05:08:54 +00001221 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1222
jgm38513a82012-11-15 15:50:36 +00001223 // Accepts pointer types, particularly:
1224 // const char*
1225 // char*
1226 // const wchar_t*
1227 // wchar_t*
1228 template <typename CharType>
1229 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001230 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001231 }
1232
jgm38513a82012-11-15 15:50:36 +00001233 // Matches anything that can convert to StringType.
1234 //
1235 // This is a template, not just a plain function with const StringType&,
1236 // because StringPiece has some interfering non-explicit constructors.
1237 template <typename MatcheeStringType>
1238 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001239 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001240 const StringType& s2(s);
1241 return s2.length() >= suffix_.length() &&
1242 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001243 }
1244
1245 void DescribeTo(::std::ostream* os) const {
1246 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001247 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001248 }
1249
1250 void DescribeNegationTo(::std::ostream* os) const {
1251 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001252 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001253 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001254
shiqiane35fdd92008-12-10 05:08:54 +00001255 private:
1256 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001257
1258 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001259};
1260
shiqiane35fdd92008-12-10 05:08:54 +00001261// Implements polymorphic matchers MatchesRegex(regex) and
1262// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1263// T can be converted to a string.
1264class MatchesRegexMatcher {
1265 public:
1266 MatchesRegexMatcher(const RE* regex, bool full_match)
1267 : regex_(regex), full_match_(full_match) {}
1268
jgm38513a82012-11-15 15:50:36 +00001269 // Accepts pointer types, particularly:
1270 // const char*
1271 // char*
1272 // const wchar_t*
1273 // wchar_t*
1274 template <typename CharType>
1275 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001276 return s != NULL && MatchAndExplain(internal::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001277 }
1278
jgm38513a82012-11-15 15:50:36 +00001279 // Matches anything that can convert to internal::string.
1280 //
1281 // This is a template, not just a plain function with const internal::string&,
1282 // because StringPiece has some interfering non-explicit constructors.
1283 template <class MatcheeStringType>
1284 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001285 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001286 const internal::string& s2(s);
1287 return full_match_ ? RE::FullMatch(s2, *regex_) :
1288 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001289 }
1290
1291 void DescribeTo(::std::ostream* os) const {
1292 *os << (full_match_ ? "matches" : "contains")
1293 << " regular expression ";
1294 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1295 }
1296
1297 void DescribeNegationTo(::std::ostream* os) const {
1298 *os << "doesn't " << (full_match_ ? "match" : "contain")
1299 << " regular expression ";
1300 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1301 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001302
shiqiane35fdd92008-12-10 05:08:54 +00001303 private:
1304 const internal::linked_ptr<const RE> regex_;
1305 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001306
1307 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001308};
1309
shiqiane35fdd92008-12-10 05:08:54 +00001310// Implements a matcher that compares the two fields of a 2-tuple
1311// using one of the ==, <=, <, etc, operators. The two fields being
1312// compared don't have to have the same type.
1313//
1314// The matcher defined here is polymorphic (for example, Eq() can be
1315// used to match a tuple<int, short>, a tuple<const long&, double>,
1316// etc). Therefore we use a template type conversion operator in the
1317// implementation.
1318//
1319// We define this as a macro in order to eliminate duplicated source
1320// code.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001321#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +00001322 class name##2Matcher { \
1323 public: \
1324 template <typename T1, typename T2> \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001325 operator Matcher< ::std::tr1::tuple<T1, T2> >() const { \
1326 return MakeMatcher(new Impl< ::std::tr1::tuple<T1, T2> >); \
1327 } \
1328 template <typename T1, typename T2> \
shiqiane35fdd92008-12-10 05:08:54 +00001329 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001330 return MakeMatcher(new Impl<const ::std::tr1::tuple<T1, T2>&>); \
shiqiane35fdd92008-12-10 05:08:54 +00001331 } \
1332 private: \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001333 template <typename Tuple> \
1334 class Impl : public MatcherInterface<Tuple> { \
shiqiane35fdd92008-12-10 05:08:54 +00001335 public: \
zhanyong.wan82113312010-01-08 21:55:40 +00001336 virtual bool MatchAndExplain( \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001337 Tuple args, \
zhanyong.wan82113312010-01-08 21:55:40 +00001338 MatchResultListener* /* listener */) const { \
shiqiane35fdd92008-12-10 05:08:54 +00001339 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1340 } \
1341 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001342 *os << "are " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001343 } \
1344 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001345 *os << "aren't " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001346 } \
1347 }; \
1348 }
1349
1350// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001351GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "an equal pair");
1352GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1353 Ge, >=, "a pair where the first >= the second");
1354GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1355 Gt, >, "a pair where the first > the second");
1356GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1357 Le, <=, "a pair where the first <= the second");
1358GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1359 Lt, <, "a pair where the first < the second");
1360GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "an unequal pair");
shiqiane35fdd92008-12-10 05:08:54 +00001361
zhanyong.wane0d051e2009-02-19 00:33:37 +00001362#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001363
zhanyong.wanc6a41232009-05-13 23:38:40 +00001364// Implements the Not(...) matcher for a particular argument type T.
1365// We do not nest it inside the NotMatcher class template, as that
1366// will prevent different instantiations of NotMatcher from sharing
1367// the same NotMatcherImpl<T> class.
1368template <typename T>
1369class NotMatcherImpl : public MatcherInterface<T> {
1370 public:
1371 explicit NotMatcherImpl(const Matcher<T>& matcher)
1372 : matcher_(matcher) {}
1373
zhanyong.wan82113312010-01-08 21:55:40 +00001374 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1375 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001376 }
1377
1378 virtual void DescribeTo(::std::ostream* os) const {
1379 matcher_.DescribeNegationTo(os);
1380 }
1381
1382 virtual void DescribeNegationTo(::std::ostream* os) const {
1383 matcher_.DescribeTo(os);
1384 }
1385
zhanyong.wanc6a41232009-05-13 23:38:40 +00001386 private:
1387 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001388
1389 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001390};
1391
shiqiane35fdd92008-12-10 05:08:54 +00001392// Implements the Not(m) matcher, which matches a value that doesn't
1393// match matcher m.
1394template <typename InnerMatcher>
1395class NotMatcher {
1396 public:
1397 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1398
1399 // This template type conversion operator allows Not(m) to be used
1400 // to match any type m can match.
1401 template <typename T>
1402 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001403 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001404 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001405
shiqiane35fdd92008-12-10 05:08:54 +00001406 private:
shiqiane35fdd92008-12-10 05:08:54 +00001407 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001408
1409 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001410};
1411
zhanyong.wanc6a41232009-05-13 23:38:40 +00001412// Implements the AllOf(m1, m2) matcher for a particular argument type
1413// T. We do not nest it inside the BothOfMatcher class template, as
1414// that will prevent different instantiations of BothOfMatcher from
1415// sharing the same BothOfMatcherImpl<T> class.
1416template <typename T>
1417class BothOfMatcherImpl : public MatcherInterface<T> {
1418 public:
1419 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1420 : matcher1_(matcher1), matcher2_(matcher2) {}
1421
zhanyong.wanc6a41232009-05-13 23:38:40 +00001422 virtual void DescribeTo(::std::ostream* os) const {
1423 *os << "(";
1424 matcher1_.DescribeTo(os);
1425 *os << ") and (";
1426 matcher2_.DescribeTo(os);
1427 *os << ")";
1428 }
1429
1430 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001431 *os << "(";
1432 matcher1_.DescribeNegationTo(os);
1433 *os << ") or (";
1434 matcher2_.DescribeNegationTo(os);
1435 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001436 }
1437
zhanyong.wan82113312010-01-08 21:55:40 +00001438 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1439 // If either matcher1_ or matcher2_ doesn't match x, we only need
1440 // to explain why one of them fails.
1441 StringMatchResultListener listener1;
1442 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1443 *listener << listener1.str();
1444 return false;
1445 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001446
zhanyong.wan82113312010-01-08 21:55:40 +00001447 StringMatchResultListener listener2;
1448 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1449 *listener << listener2.str();
1450 return false;
1451 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001452
zhanyong.wan82113312010-01-08 21:55:40 +00001453 // Otherwise we need to explain why *both* of them match.
1454 const internal::string s1 = listener1.str();
1455 const internal::string s2 = listener2.str();
1456
1457 if (s1 == "") {
1458 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001459 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001460 *listener << s1;
1461 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001462 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001463 }
1464 }
zhanyong.wan82113312010-01-08 21:55:40 +00001465 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001466 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001467
zhanyong.wanc6a41232009-05-13 23:38:40 +00001468 private:
1469 const Matcher<T> matcher1_;
1470 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001471
1472 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001473};
1474
zhanyong.wan616180e2013-06-18 18:49:51 +00001475#if GTEST_LANG_CXX11
1476// MatcherList provides mechanisms for storing a variable number of matchers in
1477// a list structure (ListType) and creating a combining matcher from such a
1478// list.
1479// The template is defined recursively using the following template paramters:
1480// * kSize is the length of the MatcherList.
1481// * Head is the type of the first matcher of the list.
1482// * Tail denotes the types of the remaining matchers of the list.
1483template <int kSize, typename Head, typename... Tail>
1484struct MatcherList {
1485 typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
zhanyong.wan29897032013-06-20 18:59:15 +00001486 typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001487
1488 // BuildList stores variadic type values in a nested pair structure.
1489 // Example:
1490 // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
1491 // the corresponding result of type pair<int, pair<string, float>>.
1492 static ListType BuildList(const Head& matcher, const Tail&... tail) {
1493 return ListType(matcher, MatcherListTail::BuildList(tail...));
1494 }
1495
1496 // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
1497 // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
1498 // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
1499 // constructor taking two Matcher<T>s as input.
1500 template <typename T, template <typename /* T */> class CombiningMatcher>
1501 static Matcher<T> CreateMatcher(const ListType& matchers) {
1502 return Matcher<T>(new CombiningMatcher<T>(
1503 SafeMatcherCast<T>(matchers.first),
1504 MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
1505 matchers.second)));
1506 }
1507};
1508
1509// The following defines the base case for the recursive definition of
1510// MatcherList.
1511template <typename Matcher1, typename Matcher2>
1512struct MatcherList<2, Matcher1, Matcher2> {
zhanyong.wan29897032013-06-20 18:59:15 +00001513 typedef ::std::pair<Matcher1, Matcher2> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001514
1515 static ListType BuildList(const Matcher1& matcher1,
1516 const Matcher2& matcher2) {
zhanyong.wan29897032013-06-20 18:59:15 +00001517 return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
zhanyong.wan616180e2013-06-18 18:49:51 +00001518 }
1519
1520 template <typename T, template <typename /* T */> class CombiningMatcher>
1521 static Matcher<T> CreateMatcher(const ListType& matchers) {
1522 return Matcher<T>(new CombiningMatcher<T>(
1523 SafeMatcherCast<T>(matchers.first),
1524 SafeMatcherCast<T>(matchers.second)));
1525 }
1526};
1527
1528// VariadicMatcher is used for the variadic implementation of
1529// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1530// CombiningMatcher<T> is used to recursively combine the provided matchers
1531// (of type Args...).
1532template <template <typename T> class CombiningMatcher, typename... Args>
1533class VariadicMatcher {
1534 public:
1535 VariadicMatcher(const Args&... matchers) // NOLINT
1536 : matchers_(MatcherListType::BuildList(matchers...)) {}
1537
1538 // This template type conversion operator allows an
1539 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1540 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1541 template <typename T>
1542 operator Matcher<T>() const {
1543 return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
1544 matchers_);
1545 }
1546
1547 private:
1548 typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
1549
1550 const typename MatcherListType::ListType matchers_;
1551
1552 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1553};
1554
1555template <typename... Args>
1556using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
1557
1558#endif // GTEST_LANG_CXX11
1559
shiqiane35fdd92008-12-10 05:08:54 +00001560// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1561// matches a value that matches all of the matchers m_1, ..., and m_n.
1562template <typename Matcher1, typename Matcher2>
1563class BothOfMatcher {
1564 public:
1565 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1566 : matcher1_(matcher1), matcher2_(matcher2) {}
1567
1568 // This template type conversion operator allows a
1569 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1570 // both Matcher1 and Matcher2 can match.
1571 template <typename T>
1572 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001573 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1574 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001575 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001576
shiqiane35fdd92008-12-10 05:08:54 +00001577 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001578 Matcher1 matcher1_;
1579 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001580
1581 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001582};
shiqiane35fdd92008-12-10 05:08:54 +00001583
zhanyong.wanc6a41232009-05-13 23:38:40 +00001584// Implements the AnyOf(m1, m2) matcher for a particular argument type
1585// T. We do not nest it inside the AnyOfMatcher class template, as
1586// that will prevent different instantiations of AnyOfMatcher from
1587// sharing the same EitherOfMatcherImpl<T> class.
1588template <typename T>
1589class EitherOfMatcherImpl : public MatcherInterface<T> {
1590 public:
1591 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1592 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001593
zhanyong.wanc6a41232009-05-13 23:38:40 +00001594 virtual void DescribeTo(::std::ostream* os) const {
1595 *os << "(";
1596 matcher1_.DescribeTo(os);
1597 *os << ") or (";
1598 matcher2_.DescribeTo(os);
1599 *os << ")";
1600 }
shiqiane35fdd92008-12-10 05:08:54 +00001601
zhanyong.wanc6a41232009-05-13 23:38:40 +00001602 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001603 *os << "(";
1604 matcher1_.DescribeNegationTo(os);
1605 *os << ") and (";
1606 matcher2_.DescribeNegationTo(os);
1607 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001608 }
shiqiane35fdd92008-12-10 05:08:54 +00001609
zhanyong.wan82113312010-01-08 21:55:40 +00001610 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1611 // If either matcher1_ or matcher2_ matches x, we just need to
1612 // explain why *one* of them matches.
1613 StringMatchResultListener listener1;
1614 if (matcher1_.MatchAndExplain(x, &listener1)) {
1615 *listener << listener1.str();
1616 return true;
1617 }
1618
1619 StringMatchResultListener listener2;
1620 if (matcher2_.MatchAndExplain(x, &listener2)) {
1621 *listener << listener2.str();
1622 return true;
1623 }
1624
1625 // Otherwise we need to explain why *both* of them fail.
1626 const internal::string s1 = listener1.str();
1627 const internal::string s2 = listener2.str();
1628
1629 if (s1 == "") {
1630 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001631 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001632 *listener << s1;
1633 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001634 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001635 }
1636 }
zhanyong.wan82113312010-01-08 21:55:40 +00001637 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001638 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001639
zhanyong.wanc6a41232009-05-13 23:38:40 +00001640 private:
1641 const Matcher<T> matcher1_;
1642 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001643
1644 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001645};
1646
zhanyong.wan616180e2013-06-18 18:49:51 +00001647#if GTEST_LANG_CXX11
1648// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1649template <typename... Args>
1650using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
1651
1652#endif // GTEST_LANG_CXX11
1653
shiqiane35fdd92008-12-10 05:08:54 +00001654// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1655// matches a value that matches at least one of the matchers m_1, ...,
1656// and m_n.
1657template <typename Matcher1, typename Matcher2>
1658class EitherOfMatcher {
1659 public:
1660 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1661 : matcher1_(matcher1), matcher2_(matcher2) {}
1662
1663 // This template type conversion operator allows a
1664 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1665 // both Matcher1 and Matcher2 can match.
1666 template <typename T>
1667 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001668 return Matcher<T>(new EitherOfMatcherImpl<T>(
1669 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001670 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001671
shiqiane35fdd92008-12-10 05:08:54 +00001672 private:
shiqiane35fdd92008-12-10 05:08:54 +00001673 Matcher1 matcher1_;
1674 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001675
1676 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001677};
1678
1679// Used for implementing Truly(pred), which turns a predicate into a
1680// matcher.
1681template <typename Predicate>
1682class TrulyMatcher {
1683 public:
1684 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1685
1686 // This method template allows Truly(pred) to be used as a matcher
1687 // for type T where T is the argument type of predicate 'pred'. The
1688 // argument is passed by reference as the predicate may be
1689 // interested in the address of the argument.
1690 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001691 bool MatchAndExplain(T& x, // NOLINT
1692 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001693 // Without the if-statement, MSVC sometimes warns about converting
1694 // a value to bool (warning 4800).
1695 //
1696 // We cannot write 'return !!predicate_(x);' as that doesn't work
1697 // when predicate_(x) returns a class convertible to bool but
1698 // having no operator!().
1699 if (predicate_(x))
1700 return true;
1701 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001702 }
1703
1704 void DescribeTo(::std::ostream* os) const {
1705 *os << "satisfies the given predicate";
1706 }
1707
1708 void DescribeNegationTo(::std::ostream* os) const {
1709 *os << "doesn't satisfy the given predicate";
1710 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001711
shiqiane35fdd92008-12-10 05:08:54 +00001712 private:
1713 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001714
1715 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001716};
1717
1718// Used for implementing Matches(matcher), which turns a matcher into
1719// a predicate.
1720template <typename M>
1721class MatcherAsPredicate {
1722 public:
1723 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1724
1725 // This template operator() allows Matches(m) to be used as a
1726 // predicate on type T where m is a matcher on type T.
1727 //
1728 // The argument x is passed by reference instead of by value, as
1729 // some matcher may be interested in its address (e.g. as in
1730 // Matches(Ref(n))(x)).
1731 template <typename T>
1732 bool operator()(const T& x) const {
1733 // We let matcher_ commit to a particular type here instead of
1734 // when the MatcherAsPredicate object was constructed. This
1735 // allows us to write Matches(m) where m is a polymorphic matcher
1736 // (e.g. Eq(5)).
1737 //
1738 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1739 // compile when matcher_ has type Matcher<const T&>; if we write
1740 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1741 // when matcher_ has type Matcher<T>; if we just write
1742 // matcher_.Matches(x), it won't compile when matcher_ is
1743 // polymorphic, e.g. Eq(5).
1744 //
1745 // MatcherCast<const T&>() is necessary for making the code work
1746 // in all of the above situations.
1747 return MatcherCast<const T&>(matcher_).Matches(x);
1748 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001749
shiqiane35fdd92008-12-10 05:08:54 +00001750 private:
1751 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001752
1753 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001754};
1755
1756// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1757// argument M must be a type that can be converted to a matcher.
1758template <typename M>
1759class PredicateFormatterFromMatcher {
1760 public:
1761 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1762
1763 // This template () operator allows a PredicateFormatterFromMatcher
1764 // object to act as a predicate-formatter suitable for using with
1765 // Google Test's EXPECT_PRED_FORMAT1() macro.
1766 template <typename T>
1767 AssertionResult operator()(const char* value_text, const T& x) const {
1768 // We convert matcher_ to a Matcher<const T&> *now* instead of
1769 // when the PredicateFormatterFromMatcher object was constructed,
1770 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1771 // know which type to instantiate it to until we actually see the
1772 // type of x here.
1773 //
zhanyong.wanf4274522013-04-24 02:49:43 +00001774 // We write SafeMatcherCast<const T&>(matcher_) instead of
shiqiane35fdd92008-12-10 05:08:54 +00001775 // Matcher<const T&>(matcher_), as the latter won't compile when
1776 // matcher_ has type Matcher<T> (e.g. An<int>()).
zhanyong.wanf4274522013-04-24 02:49:43 +00001777 // We don't write MatcherCast<const T&> either, as that allows
1778 // potentially unsafe downcasting of the matcher argument.
1779 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001780 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001781 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001782 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001783
1784 ::std::stringstream ss;
1785 ss << "Value of: " << value_text << "\n"
1786 << "Expected: ";
1787 matcher.DescribeTo(&ss);
1788 ss << "\n Actual: " << listener.str();
1789 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001790 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001791
shiqiane35fdd92008-12-10 05:08:54 +00001792 private:
1793 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001794
1795 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001796};
1797
1798// A helper function for converting a matcher to a predicate-formatter
1799// without the user needing to explicitly write the type. This is
1800// used for implementing ASSERT_THAT() and EXPECT_THAT().
1801template <typename M>
1802inline PredicateFormatterFromMatcher<M>
1803MakePredicateFormatterFromMatcher(const M& matcher) {
1804 return PredicateFormatterFromMatcher<M>(matcher);
1805}
1806
zhanyong.wan616180e2013-06-18 18:49:51 +00001807// Implements the polymorphic floating point equality matcher, which matches
1808// two float values using ULP-based approximation or, optionally, a
1809// user-specified epsilon. The template is meant to be instantiated with
1810// FloatType being either float or double.
shiqiane35fdd92008-12-10 05:08:54 +00001811template <typename FloatType>
1812class FloatingEqMatcher {
1813 public:
1814 // Constructor for FloatingEqMatcher.
1815 // The matcher's input will be compared with rhs. The matcher treats two
1816 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
zhanyong.wan616180e2013-06-18 18:49:51 +00001817 // equality comparisons between NANs will always return false. We specify a
1818 // negative max_abs_error_ term to indicate that ULP-based approximation will
1819 // be used for comparison.
shiqiane35fdd92008-12-10 05:08:54 +00001820 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
zhanyong.wan616180e2013-06-18 18:49:51 +00001821 rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
1822 }
1823
1824 // Constructor that supports a user-specified max_abs_error that will be used
1825 // for comparison instead of ULP-based approximation. The max absolute
1826 // should be non-negative.
1827 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan, FloatType max_abs_error) :
1828 rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) {
1829 GTEST_CHECK_(max_abs_error >= 0)
1830 << ", where max_abs_error is" << max_abs_error;
1831 }
shiqiane35fdd92008-12-10 05:08:54 +00001832
1833 // Implements floating point equality matcher as a Matcher<T>.
1834 template <typename T>
1835 class Impl : public MatcherInterface<T> {
1836 public:
zhanyong.wan616180e2013-06-18 18:49:51 +00001837 Impl(FloatType rhs, bool nan_eq_nan, FloatType max_abs_error) :
1838 rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) {}
shiqiane35fdd92008-12-10 05:08:54 +00001839
zhanyong.wan82113312010-01-08 21:55:40 +00001840 virtual bool MatchAndExplain(T value,
1841 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001842 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1843
1844 // Compares NaNs first, if nan_eq_nan_ is true.
zhanyong.wan616180e2013-06-18 18:49:51 +00001845 if (lhs.is_nan() || rhs.is_nan()) {
1846 if (lhs.is_nan() && rhs.is_nan()) {
1847 return nan_eq_nan_;
1848 }
1849 // One is nan; the other is not nan.
1850 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001851 }
zhanyong.wan616180e2013-06-18 18:49:51 +00001852 if (HasMaxAbsError()) {
1853 // We perform an equality check so that inf will match inf, regardless
1854 // of error bounds. If the result of value - rhs_ would result in
1855 // overflow or if either value is inf, the default result is infinity,
1856 // which should only match if max_abs_error_ is also infinity.
1857 return value == rhs_ || fabs(value - rhs_) <= max_abs_error_;
1858 } else {
1859 return lhs.AlmostEquals(rhs);
1860 }
shiqiane35fdd92008-12-10 05:08:54 +00001861 }
1862
1863 virtual void DescribeTo(::std::ostream* os) const {
1864 // os->precision() returns the previously set precision, which we
1865 // store to restore the ostream to its original configuration
1866 // after outputting.
1867 const ::std::streamsize old_precision = os->precision(
1868 ::std::numeric_limits<FloatType>::digits10 + 2);
1869 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1870 if (nan_eq_nan_) {
1871 *os << "is NaN";
1872 } else {
1873 *os << "never matches";
1874 }
1875 } else {
1876 *os << "is approximately " << rhs_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001877 if (HasMaxAbsError()) {
1878 *os << " (absolute error <= " << max_abs_error_ << ")";
1879 }
shiqiane35fdd92008-12-10 05:08:54 +00001880 }
1881 os->precision(old_precision);
1882 }
1883
1884 virtual void DescribeNegationTo(::std::ostream* os) const {
1885 // As before, get original precision.
1886 const ::std::streamsize old_precision = os->precision(
1887 ::std::numeric_limits<FloatType>::digits10 + 2);
1888 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1889 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001890 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00001891 } else {
1892 *os << "is anything";
1893 }
1894 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001895 *os << "isn't approximately " << rhs_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001896 if (HasMaxAbsError()) {
1897 *os << " (absolute error > " << max_abs_error_ << ")";
1898 }
shiqiane35fdd92008-12-10 05:08:54 +00001899 }
1900 // Restore original precision.
1901 os->precision(old_precision);
1902 }
1903
1904 private:
zhanyong.wan616180e2013-06-18 18:49:51 +00001905 bool HasMaxAbsError() const {
1906 return max_abs_error_ >= 0;
1907 }
1908
shiqiane35fdd92008-12-10 05:08:54 +00001909 const FloatType rhs_;
1910 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001911 // max_abs_error will be used for value comparison when >= 0.
1912 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001913
1914 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001915 };
1916
1917 // The following 3 type conversion operators allow FloatEq(rhs) and
1918 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1919 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1920 // (While Google's C++ coding style doesn't allow arguments passed
1921 // by non-const reference, we may see them in code not conforming to
1922 // the style. Therefore Google Mock needs to support them.)
1923 operator Matcher<FloatType>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00001924 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00001925 }
1926
1927 operator Matcher<const FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00001928 return MakeMatcher(
1929 new Impl<const FloatType&>(rhs_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00001930 }
1931
1932 operator Matcher<FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00001933 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00001934 }
jgm79a367e2012-04-10 16:02:11 +00001935
shiqiane35fdd92008-12-10 05:08:54 +00001936 private:
1937 const FloatType rhs_;
1938 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001939 // max_abs_error will be used for value comparison when >= 0.
1940 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001941
1942 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001943};
1944
1945// Implements the Pointee(m) matcher for matching a pointer whose
1946// pointee matches matcher m. The pointer can be either raw or smart.
1947template <typename InnerMatcher>
1948class PointeeMatcher {
1949 public:
1950 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1951
1952 // This type conversion operator template allows Pointee(m) to be
1953 // used as a matcher for any pointer type whose pointee type is
1954 // compatible with the inner matcher, where type Pointer can be
1955 // either a raw pointer or a smart pointer.
1956 //
1957 // The reason we do this instead of relying on
1958 // MakePolymorphicMatcher() is that the latter is not flexible
1959 // enough for implementing the DescribeTo() method of Pointee().
1960 template <typename Pointer>
1961 operator Matcher<Pointer>() const {
1962 return MakeMatcher(new Impl<Pointer>(matcher_));
1963 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001964
shiqiane35fdd92008-12-10 05:08:54 +00001965 private:
1966 // The monomorphic implementation that works for a particular pointer type.
1967 template <typename Pointer>
1968 class Impl : public MatcherInterface<Pointer> {
1969 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00001970 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
1971 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001972
1973 explicit Impl(const InnerMatcher& matcher)
1974 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1975
shiqiane35fdd92008-12-10 05:08:54 +00001976 virtual void DescribeTo(::std::ostream* os) const {
1977 *os << "points to a value that ";
1978 matcher_.DescribeTo(os);
1979 }
1980
1981 virtual void DescribeNegationTo(::std::ostream* os) const {
1982 *os << "does not point to a value that ";
1983 matcher_.DescribeTo(os);
1984 }
1985
zhanyong.wan82113312010-01-08 21:55:40 +00001986 virtual bool MatchAndExplain(Pointer pointer,
1987 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001988 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001989 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001990
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001991 *listener << "which points to ";
1992 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001993 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001994
shiqiane35fdd92008-12-10 05:08:54 +00001995 private:
1996 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001997
1998 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001999 };
2000
2001 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002002
2003 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002004};
2005
2006// Implements the Field() matcher for matching a field (i.e. member
2007// variable) of an object.
2008template <typename Class, typename FieldType>
2009class FieldMatcher {
2010 public:
2011 FieldMatcher(FieldType Class::*field,
2012 const Matcher<const FieldType&>& matcher)
2013 : field_(field), matcher_(matcher) {}
2014
shiqiane35fdd92008-12-10 05:08:54 +00002015 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002016 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002017 matcher_.DescribeTo(os);
2018 }
2019
2020 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002021 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002022 matcher_.DescribeNegationTo(os);
2023 }
2024
zhanyong.wandb22c222010-01-28 21:52:29 +00002025 template <typename T>
2026 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2027 return MatchAndExplainImpl(
2028 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002029 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002030 value, listener);
2031 }
2032
2033 private:
2034 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002035 // Symbian's C++ compiler choose which overload to use. Its type is
2036 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002037 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2038 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002039 *listener << "whose given field is ";
2040 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002041 }
2042
zhanyong.wandb22c222010-01-28 21:52:29 +00002043 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2044 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002045 if (p == NULL)
2046 return false;
2047
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002048 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002049 // Since *p has a field, it must be a class/struct/union type and
2050 // thus cannot be a pointer. Therefore we pass false_type() as
2051 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002052 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002053 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002054
shiqiane35fdd92008-12-10 05:08:54 +00002055 const FieldType Class::*field_;
2056 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002057
2058 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002059};
2060
shiqiane35fdd92008-12-10 05:08:54 +00002061// Implements the Property() matcher for matching a property
2062// (i.e. return value of a getter method) of an object.
2063template <typename Class, typename PropertyType>
2064class PropertyMatcher {
2065 public:
2066 // The property may have a reference type, so 'const PropertyType&'
2067 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00002068 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00002069 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00002070 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00002071
2072 PropertyMatcher(PropertyType (Class::*property)() const,
2073 const Matcher<RefToConstProperty>& matcher)
2074 : property_(property), matcher_(matcher) {}
2075
shiqiane35fdd92008-12-10 05:08:54 +00002076 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002077 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002078 matcher_.DescribeTo(os);
2079 }
2080
2081 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002082 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002083 matcher_.DescribeNegationTo(os);
2084 }
2085
zhanyong.wandb22c222010-01-28 21:52:29 +00002086 template <typename T>
2087 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2088 return MatchAndExplainImpl(
2089 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002090 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002091 value, listener);
2092 }
2093
2094 private:
2095 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002096 // Symbian's C++ compiler choose which overload to use. Its type is
2097 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002098 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2099 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002100 *listener << "whose given property is ";
2101 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2102 // which takes a non-const reference as argument.
2103 RefToConstProperty result = (obj.*property_)();
2104 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002105 }
2106
zhanyong.wandb22c222010-01-28 21:52:29 +00002107 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2108 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002109 if (p == NULL)
2110 return false;
2111
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002112 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002113 // Since *p has a property method, it must be a class/struct/union
2114 // type and thus cannot be a pointer. Therefore we pass
2115 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002116 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002117 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002118
shiqiane35fdd92008-12-10 05:08:54 +00002119 PropertyType (Class::*property_)() const;
2120 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002121
2122 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002123};
2124
shiqiane35fdd92008-12-10 05:08:54 +00002125// Type traits specifying various features of different functors for ResultOf.
2126// The default template specifies features for functor objects.
2127// Functor classes have to typedef argument_type and result_type
2128// to be compatible with ResultOf.
2129template <typename Functor>
2130struct CallableTraits {
2131 typedef typename Functor::result_type ResultType;
2132 typedef Functor StorageType;
2133
zhanyong.wan32de5f52009-12-23 00:13:23 +00002134 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00002135 template <typename T>
2136 static ResultType Invoke(Functor f, T arg) { return f(arg); }
2137};
2138
2139// Specialization for function pointers.
2140template <typename ArgType, typename ResType>
2141struct CallableTraits<ResType(*)(ArgType)> {
2142 typedef ResType ResultType;
2143 typedef ResType(*StorageType)(ArgType);
2144
2145 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002146 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00002147 << "NULL function pointer is passed into ResultOf().";
2148 }
2149 template <typename T>
2150 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2151 return (*f)(arg);
2152 }
2153};
2154
2155// Implements the ResultOf() matcher for matching a return value of a
2156// unary function of an object.
2157template <typename Callable>
2158class ResultOfMatcher {
2159 public:
2160 typedef typename CallableTraits<Callable>::ResultType ResultType;
2161
2162 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
2163 : callable_(callable), matcher_(matcher) {
2164 CallableTraits<Callable>::CheckIsValid(callable_);
2165 }
2166
2167 template <typename T>
2168 operator Matcher<T>() const {
2169 return Matcher<T>(new Impl<T>(callable_, matcher_));
2170 }
2171
2172 private:
2173 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2174
2175 template <typename T>
2176 class Impl : public MatcherInterface<T> {
2177 public:
2178 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
2179 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00002180
2181 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002182 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002183 matcher_.DescribeTo(os);
2184 }
2185
2186 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002187 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002188 matcher_.DescribeNegationTo(os);
2189 }
2190
zhanyong.wan82113312010-01-08 21:55:40 +00002191 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002192 *listener << "which is mapped by the given callable to ";
2193 // Cannot pass the return value (for example, int) to
2194 // MatchPrintAndExplain, which takes a non-const reference as argument.
2195 ResultType result =
2196 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2197 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002198 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002199
shiqiane35fdd92008-12-10 05:08:54 +00002200 private:
2201 // Functors often define operator() as non-const method even though
2202 // they are actualy stateless. But we need to use them even when
2203 // 'this' is a const pointer. It's the user's responsibility not to
2204 // use stateful callables with ResultOf(), which does't guarantee
2205 // how many times the callable will be invoked.
2206 mutable CallableStorageType callable_;
2207 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002208
2209 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002210 }; // class Impl
2211
2212 const CallableStorageType callable_;
2213 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002214
2215 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002216};
2217
zhanyong.wana31d9ce2013-03-01 01:50:17 +00002218// Implements a matcher that checks the size of an STL-style container.
2219template <typename SizeMatcher>
2220class SizeIsMatcher {
2221 public:
2222 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2223 : size_matcher_(size_matcher) {
2224 }
2225
2226 template <typename Container>
2227 operator Matcher<Container>() const {
2228 return MakeMatcher(new Impl<Container>(size_matcher_));
2229 }
2230
2231 template <typename Container>
2232 class Impl : public MatcherInterface<Container> {
2233 public:
2234 typedef internal::StlContainerView<
2235 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2236 typedef typename ContainerView::type::size_type SizeType;
2237 explicit Impl(const SizeMatcher& size_matcher)
2238 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2239
2240 virtual void DescribeTo(::std::ostream* os) const {
2241 *os << "size ";
2242 size_matcher_.DescribeTo(os);
2243 }
2244 virtual void DescribeNegationTo(::std::ostream* os) const {
2245 *os << "size ";
2246 size_matcher_.DescribeNegationTo(os);
2247 }
2248
2249 virtual bool MatchAndExplain(Container container,
2250 MatchResultListener* listener) const {
2251 SizeType size = container.size();
2252 StringMatchResultListener size_listener;
2253 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2254 *listener
2255 << "whose size " << size << (result ? " matches" : " doesn't match");
2256 PrintIfNotEmpty(size_listener.str(), listener->stream());
2257 return result;
2258 }
2259
2260 private:
2261 const Matcher<SizeType> size_matcher_;
2262 GTEST_DISALLOW_ASSIGN_(Impl);
2263 };
2264
2265 private:
2266 const SizeMatcher size_matcher_;
2267 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2268};
2269
kosakb6a34882014-03-12 21:06:46 +00002270// Implements a matcher that checks the begin()..end() distance of an STL-style
2271// container.
2272template <typename DistanceMatcher>
2273class BeginEndDistanceIsMatcher {
2274 public:
2275 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2276 : distance_matcher_(distance_matcher) {}
2277
2278 template <typename Container>
2279 operator Matcher<Container>() const {
2280 return MakeMatcher(new Impl<Container>(distance_matcher_));
2281 }
2282
2283 template <typename Container>
2284 class Impl : public MatcherInterface<Container> {
2285 public:
2286 typedef internal::StlContainerView<
2287 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2288 typedef typename std::iterator_traits<
2289 typename ContainerView::type::const_iterator>::difference_type
2290 DistanceType;
2291 explicit Impl(const DistanceMatcher& distance_matcher)
2292 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2293
2294 virtual void DescribeTo(::std::ostream* os) const {
2295 *os << "distance between begin() and end() ";
2296 distance_matcher_.DescribeTo(os);
2297 }
2298 virtual void DescribeNegationTo(::std::ostream* os) const {
2299 *os << "distance between begin() and end() ";
2300 distance_matcher_.DescribeNegationTo(os);
2301 }
2302
2303 virtual bool MatchAndExplain(Container container,
2304 MatchResultListener* listener) const {
2305#if GTEST_LANG_CXX11
2306 using std::begin;
2307 using std::end;
2308 DistanceType distance = std::distance(begin(container), end(container));
2309#else
2310 DistanceType distance = std::distance(container.begin(), container.end());
2311#endif
2312 StringMatchResultListener distance_listener;
2313 const bool result =
2314 distance_matcher_.MatchAndExplain(distance, &distance_listener);
2315 *listener << "whose distance between begin() and end() " << distance
2316 << (result ? " matches" : " doesn't match");
2317 PrintIfNotEmpty(distance_listener.str(), listener->stream());
2318 return result;
2319 }
2320
2321 private:
2322 const Matcher<DistanceType> distance_matcher_;
2323 GTEST_DISALLOW_ASSIGN_(Impl);
2324 };
2325
2326 private:
2327 const DistanceMatcher distance_matcher_;
2328 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2329};
2330
zhanyong.wan6a896b52009-01-16 01:13:50 +00002331// Implements an equality matcher for any STL-style container whose elements
2332// support ==. This matcher is like Eq(), but its failure explanations provide
2333// more detailed information that is useful when the container is used as a set.
2334// The failure message reports elements that are in one of the operands but not
2335// the other. The failure messages do not report duplicate or out-of-order
2336// elements in the containers (which don't properly matter to sets, but can
2337// occur if the containers are vectors or lists, for example).
2338//
2339// Uses the container's const_iterator, value_type, operator ==,
2340// begin(), and end().
2341template <typename Container>
2342class ContainerEqMatcher {
2343 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002344 typedef internal::StlContainerView<Container> View;
2345 typedef typename View::type StlContainer;
2346 typedef typename View::const_reference StlContainerReference;
2347
2348 // We make a copy of rhs in case the elements in it are modified
2349 // after this matcher is created.
2350 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
2351 // Makes sure the user doesn't instantiate this class template
2352 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002353 (void)testing::StaticAssertTypeEq<Container,
2354 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002355 }
2356
zhanyong.wan6a896b52009-01-16 01:13:50 +00002357 void DescribeTo(::std::ostream* os) const {
2358 *os << "equals ";
vladloseve2e8ba42010-05-13 18:16:03 +00002359 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002360 }
2361 void DescribeNegationTo(::std::ostream* os) const {
2362 *os << "does not equal ";
vladloseve2e8ba42010-05-13 18:16:03 +00002363 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002364 }
2365
zhanyong.wanb8243162009-06-04 05:48:20 +00002366 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002367 bool MatchAndExplain(const LhsContainer& lhs,
2368 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002369 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002370 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002371 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002372 LhsView;
2373 typedef typename LhsView::type LhsStlContainer;
2374 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00002375 if (lhs_stl_container == rhs_)
2376 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002377
zhanyong.wane122e452010-01-12 09:03:52 +00002378 ::std::ostream* const os = listener->stream();
2379 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002380 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002381 bool printed_header = false;
2382 for (typename LhsStlContainer::const_iterator it =
2383 lhs_stl_container.begin();
2384 it != lhs_stl_container.end(); ++it) {
2385 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
2386 rhs_.end()) {
2387 if (printed_header) {
2388 *os << ", ";
2389 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002390 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002391 printed_header = true;
2392 }
vladloseve2e8ba42010-05-13 18:16:03 +00002393 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002394 }
zhanyong.wane122e452010-01-12 09:03:52 +00002395 }
2396
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002397 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002398 bool printed_header2 = false;
2399 for (typename StlContainer::const_iterator it = rhs_.begin();
2400 it != rhs_.end(); ++it) {
2401 if (internal::ArrayAwareFind(
2402 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2403 lhs_stl_container.end()) {
2404 if (printed_header2) {
2405 *os << ", ";
2406 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002407 *os << (printed_header ? ",\nand" : "which")
2408 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002409 printed_header2 = true;
2410 }
vladloseve2e8ba42010-05-13 18:16:03 +00002411 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002412 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002413 }
2414 }
2415
zhanyong.wane122e452010-01-12 09:03:52 +00002416 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002417 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002418
zhanyong.wan6a896b52009-01-16 01:13:50 +00002419 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00002420 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002421
2422 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002423};
2424
zhanyong.wan898725c2011-09-16 16:45:39 +00002425// A comparator functor that uses the < operator to compare two values.
2426struct LessComparator {
2427 template <typename T, typename U>
2428 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2429};
2430
2431// Implements WhenSortedBy(comparator, container_matcher).
2432template <typename Comparator, typename ContainerMatcher>
2433class WhenSortedByMatcher {
2434 public:
2435 WhenSortedByMatcher(const Comparator& comparator,
2436 const ContainerMatcher& matcher)
2437 : comparator_(comparator), matcher_(matcher) {}
2438
2439 template <typename LhsContainer>
2440 operator Matcher<LhsContainer>() const {
2441 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2442 }
2443
2444 template <typename LhsContainer>
2445 class Impl : public MatcherInterface<LhsContainer> {
2446 public:
2447 typedef internal::StlContainerView<
2448 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2449 typedef typename LhsView::type LhsStlContainer;
2450 typedef typename LhsView::const_reference LhsStlContainerReference;
zhanyong.wana9a59e02013-03-27 16:14:55 +00002451 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2452 // so that we can match associative containers.
2453 typedef typename RemoveConstFromKey<
2454 typename LhsStlContainer::value_type>::type LhsValue;
zhanyong.wan898725c2011-09-16 16:45:39 +00002455
2456 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2457 : comparator_(comparator), matcher_(matcher) {}
2458
2459 virtual void DescribeTo(::std::ostream* os) const {
2460 *os << "(when sorted) ";
2461 matcher_.DescribeTo(os);
2462 }
2463
2464 virtual void DescribeNegationTo(::std::ostream* os) const {
2465 *os << "(when sorted) ";
2466 matcher_.DescribeNegationTo(os);
2467 }
2468
2469 virtual bool MatchAndExplain(LhsContainer lhs,
2470 MatchResultListener* listener) const {
2471 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wanfb25d532013-07-28 08:24:00 +00002472 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2473 lhs_stl_container.end());
2474 ::std::sort(
2475 sorted_container.begin(), sorted_container.end(), comparator_);
zhanyong.wan898725c2011-09-16 16:45:39 +00002476
2477 if (!listener->IsInterested()) {
2478 // If the listener is not interested, we do not need to
2479 // construct the inner explanation.
2480 return matcher_.Matches(sorted_container);
2481 }
2482
2483 *listener << "which is ";
2484 UniversalPrint(sorted_container, listener->stream());
2485 *listener << " when sorted";
2486
2487 StringMatchResultListener inner_listener;
2488 const bool match = matcher_.MatchAndExplain(sorted_container,
2489 &inner_listener);
2490 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2491 return match;
2492 }
2493
2494 private:
2495 const Comparator comparator_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00002496 const Matcher<const ::std::vector<LhsValue>&> matcher_;
zhanyong.wan898725c2011-09-16 16:45:39 +00002497
2498 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2499 };
2500
2501 private:
2502 const Comparator comparator_;
2503 const ContainerMatcher matcher_;
2504
2505 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2506};
2507
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002508// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2509// must be able to be safely cast to Matcher<tuple<const T1&, const
2510// T2&> >, where T1 and T2 are the types of elements in the LHS
2511// container and the RHS container respectively.
2512template <typename TupleMatcher, typename RhsContainer>
2513class PointwiseMatcher {
2514 public:
2515 typedef internal::StlContainerView<RhsContainer> RhsView;
2516 typedef typename RhsView::type RhsStlContainer;
2517 typedef typename RhsStlContainer::value_type RhsValue;
2518
2519 // Like ContainerEq, we make a copy of rhs in case the elements in
2520 // it are modified after this matcher is created.
2521 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2522 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2523 // Makes sure the user doesn't instantiate this class template
2524 // with a const or reference type.
2525 (void)testing::StaticAssertTypeEq<RhsContainer,
2526 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2527 }
2528
2529 template <typename LhsContainer>
2530 operator Matcher<LhsContainer>() const {
2531 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2532 }
2533
2534 template <typename LhsContainer>
2535 class Impl : public MatcherInterface<LhsContainer> {
2536 public:
2537 typedef internal::StlContainerView<
2538 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2539 typedef typename LhsView::type LhsStlContainer;
2540 typedef typename LhsView::const_reference LhsStlContainerReference;
2541 typedef typename LhsStlContainer::value_type LhsValue;
2542 // We pass the LHS value and the RHS value to the inner matcher by
2543 // reference, as they may be expensive to copy. We must use tuple
2544 // instead of pair here, as a pair cannot hold references (C++ 98,
2545 // 20.2.2 [lib.pairs]).
zhanyong.wanfb25d532013-07-28 08:24:00 +00002546 typedef ::std::tr1::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002547
2548 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2549 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2550 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2551 rhs_(rhs) {}
2552
2553 virtual void DescribeTo(::std::ostream* os) const {
2554 *os << "contains " << rhs_.size()
2555 << " values, where each value and its corresponding value in ";
2556 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2557 *os << " ";
2558 mono_tuple_matcher_.DescribeTo(os);
2559 }
2560 virtual void DescribeNegationTo(::std::ostream* os) const {
2561 *os << "doesn't contain exactly " << rhs_.size()
2562 << " values, or contains a value x at some index i"
2563 << " where x and the i-th value of ";
2564 UniversalPrint(rhs_, os);
2565 *os << " ";
2566 mono_tuple_matcher_.DescribeNegationTo(os);
2567 }
2568
2569 virtual bool MatchAndExplain(LhsContainer lhs,
2570 MatchResultListener* listener) const {
2571 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2572 const size_t actual_size = lhs_stl_container.size();
2573 if (actual_size != rhs_.size()) {
2574 *listener << "which contains " << actual_size << " values";
2575 return false;
2576 }
2577
2578 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2579 typename RhsStlContainer::const_iterator right = rhs_.begin();
2580 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2581 const InnerMatcherArg value_pair(*left, *right);
2582
2583 if (listener->IsInterested()) {
2584 StringMatchResultListener inner_listener;
2585 if (!mono_tuple_matcher_.MatchAndExplain(
2586 value_pair, &inner_listener)) {
2587 *listener << "where the value pair (";
2588 UniversalPrint(*left, listener->stream());
2589 *listener << ", ";
2590 UniversalPrint(*right, listener->stream());
2591 *listener << ") at index #" << i << " don't match";
2592 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2593 return false;
2594 }
2595 } else {
2596 if (!mono_tuple_matcher_.Matches(value_pair))
2597 return false;
2598 }
2599 }
2600
2601 return true;
2602 }
2603
2604 private:
2605 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2606 const RhsStlContainer rhs_;
2607
2608 GTEST_DISALLOW_ASSIGN_(Impl);
2609 };
2610
2611 private:
2612 const TupleMatcher tuple_matcher_;
2613 const RhsStlContainer rhs_;
2614
2615 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2616};
2617
zhanyong.wan33605ba2010-04-22 23:37:47 +00002618// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002619template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002620class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002621 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002622 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002623 typedef StlContainerView<RawContainer> View;
2624 typedef typename View::type StlContainer;
2625 typedef typename View::const_reference StlContainerReference;
2626 typedef typename StlContainer::value_type Element;
2627
2628 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002629 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002630 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002631 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002632
zhanyong.wan33605ba2010-04-22 23:37:47 +00002633 // Checks whether:
2634 // * All elements in the container match, if all_elements_should_match.
2635 // * Any element in the container matches, if !all_elements_should_match.
2636 bool MatchAndExplainImpl(bool all_elements_should_match,
2637 Container container,
2638 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002639 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002640 size_t i = 0;
2641 for (typename StlContainer::const_iterator it = stl_container.begin();
2642 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002643 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002644 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2645
2646 if (matches != all_elements_should_match) {
2647 *listener << "whose element #" << i
2648 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002649 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002650 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002651 }
2652 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002653 return all_elements_should_match;
2654 }
2655
2656 protected:
2657 const Matcher<const Element&> inner_matcher_;
2658
2659 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2660};
2661
2662// Implements Contains(element_matcher) for the given argument type Container.
2663// Symmetric to EachMatcherImpl.
2664template <typename Container>
2665class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2666 public:
2667 template <typename InnerMatcher>
2668 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2669 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2670
2671 // Describes what this matcher does.
2672 virtual void DescribeTo(::std::ostream* os) const {
2673 *os << "contains at least one element that ";
2674 this->inner_matcher_.DescribeTo(os);
2675 }
2676
2677 virtual void DescribeNegationTo(::std::ostream* os) const {
2678 *os << "doesn't contain any element that ";
2679 this->inner_matcher_.DescribeTo(os);
2680 }
2681
2682 virtual bool MatchAndExplain(Container container,
2683 MatchResultListener* listener) const {
2684 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002685 }
2686
2687 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002688 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002689};
2690
zhanyong.wan33605ba2010-04-22 23:37:47 +00002691// Implements Each(element_matcher) for the given argument type Container.
2692// Symmetric to ContainsMatcherImpl.
2693template <typename Container>
2694class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2695 public:
2696 template <typename InnerMatcher>
2697 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2698 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2699
2700 // Describes what this matcher does.
2701 virtual void DescribeTo(::std::ostream* os) const {
2702 *os << "only contains elements that ";
2703 this->inner_matcher_.DescribeTo(os);
2704 }
2705
2706 virtual void DescribeNegationTo(::std::ostream* os) const {
2707 *os << "contains some element that ";
2708 this->inner_matcher_.DescribeNegationTo(os);
2709 }
2710
2711 virtual bool MatchAndExplain(Container container,
2712 MatchResultListener* listener) const {
2713 return this->MatchAndExplainImpl(true, container, listener);
2714 }
2715
2716 private:
2717 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2718};
2719
zhanyong.wanb8243162009-06-04 05:48:20 +00002720// Implements polymorphic Contains(element_matcher).
2721template <typename M>
2722class ContainsMatcher {
2723 public:
2724 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2725
2726 template <typename Container>
2727 operator Matcher<Container>() const {
2728 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2729 }
2730
2731 private:
2732 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002733
2734 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002735};
2736
zhanyong.wan33605ba2010-04-22 23:37:47 +00002737// Implements polymorphic Each(element_matcher).
2738template <typename M>
2739class EachMatcher {
2740 public:
2741 explicit EachMatcher(M m) : inner_matcher_(m) {}
2742
2743 template <typename Container>
2744 operator Matcher<Container>() const {
2745 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2746 }
2747
2748 private:
2749 const M inner_matcher_;
2750
2751 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2752};
2753
zhanyong.wanb5937da2009-07-16 20:26:41 +00002754// Implements Key(inner_matcher) for the given argument pair type.
2755// Key(inner_matcher) matches an std::pair whose 'first' field matches
2756// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2757// std::map that contains at least one element whose key is >= 5.
2758template <typename PairType>
2759class KeyMatcherImpl : public MatcherInterface<PairType> {
2760 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002761 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002762 typedef typename RawPairType::first_type KeyType;
2763
2764 template <typename InnerMatcher>
2765 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2766 : inner_matcher_(
2767 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2768 }
2769
2770 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002771 virtual bool MatchAndExplain(PairType key_value,
2772 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002773 StringMatchResultListener inner_listener;
2774 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2775 &inner_listener);
2776 const internal::string explanation = inner_listener.str();
2777 if (explanation != "") {
2778 *listener << "whose first field is a value " << explanation;
2779 }
2780 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002781 }
2782
2783 // Describes what this matcher does.
2784 virtual void DescribeTo(::std::ostream* os) const {
2785 *os << "has a key that ";
2786 inner_matcher_.DescribeTo(os);
2787 }
2788
2789 // Describes what the negation of this matcher does.
2790 virtual void DescribeNegationTo(::std::ostream* os) const {
2791 *os << "doesn't have a key that ";
2792 inner_matcher_.DescribeTo(os);
2793 }
2794
zhanyong.wanb5937da2009-07-16 20:26:41 +00002795 private:
2796 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002797
2798 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002799};
2800
2801// Implements polymorphic Key(matcher_for_key).
2802template <typename M>
2803class KeyMatcher {
2804 public:
2805 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2806
2807 template <typename PairType>
2808 operator Matcher<PairType>() const {
2809 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2810 }
2811
2812 private:
2813 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002814
2815 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002816};
2817
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002818// Implements Pair(first_matcher, second_matcher) for the given argument pair
2819// type with its two matchers. See Pair() function below.
2820template <typename PairType>
2821class PairMatcherImpl : public MatcherInterface<PairType> {
2822 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002823 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002824 typedef typename RawPairType::first_type FirstType;
2825 typedef typename RawPairType::second_type SecondType;
2826
2827 template <typename FirstMatcher, typename SecondMatcher>
2828 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2829 : first_matcher_(
2830 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2831 second_matcher_(
2832 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2833 }
2834
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002835 // Describes what this matcher does.
2836 virtual void DescribeTo(::std::ostream* os) const {
2837 *os << "has a first field that ";
2838 first_matcher_.DescribeTo(os);
2839 *os << ", and has a second field that ";
2840 second_matcher_.DescribeTo(os);
2841 }
2842
2843 // Describes what the negation of this matcher does.
2844 virtual void DescribeNegationTo(::std::ostream* os) const {
2845 *os << "has a first field that ";
2846 first_matcher_.DescribeNegationTo(os);
2847 *os << ", or has a second field that ";
2848 second_matcher_.DescribeNegationTo(os);
2849 }
2850
zhanyong.wan82113312010-01-08 21:55:40 +00002851 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2852 // matches second_matcher.
2853 virtual bool MatchAndExplain(PairType a_pair,
2854 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002855 if (!listener->IsInterested()) {
2856 // If the listener is not interested, we don't need to construct the
2857 // explanation.
2858 return first_matcher_.Matches(a_pair.first) &&
2859 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00002860 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002861 StringMatchResultListener first_inner_listener;
2862 if (!first_matcher_.MatchAndExplain(a_pair.first,
2863 &first_inner_listener)) {
2864 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002865 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002866 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002867 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002868 StringMatchResultListener second_inner_listener;
2869 if (!second_matcher_.MatchAndExplain(a_pair.second,
2870 &second_inner_listener)) {
2871 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002872 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002873 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002874 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002875 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2876 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002877 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002878 }
2879
2880 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002881 void ExplainSuccess(const internal::string& first_explanation,
2882 const internal::string& second_explanation,
2883 MatchResultListener* listener) const {
2884 *listener << "whose both fields match";
2885 if (first_explanation != "") {
2886 *listener << ", where the first field is a value " << first_explanation;
2887 }
2888 if (second_explanation != "") {
2889 *listener << ", ";
2890 if (first_explanation != "") {
2891 *listener << "and ";
2892 } else {
2893 *listener << "where ";
2894 }
2895 *listener << "the second field is a value " << second_explanation;
2896 }
2897 }
2898
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002899 const Matcher<const FirstType&> first_matcher_;
2900 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002901
2902 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002903};
2904
2905// Implements polymorphic Pair(first_matcher, second_matcher).
2906template <typename FirstMatcher, typename SecondMatcher>
2907class PairMatcher {
2908 public:
2909 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2910 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2911
2912 template <typename PairType>
2913 operator Matcher<PairType> () const {
2914 return MakeMatcher(
2915 new PairMatcherImpl<PairType>(
2916 first_matcher_, second_matcher_));
2917 }
2918
2919 private:
2920 const FirstMatcher first_matcher_;
2921 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002922
2923 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002924};
2925
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002926// Implements ElementsAre() and ElementsAreArray().
2927template <typename Container>
2928class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2929 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002930 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002931 typedef internal::StlContainerView<RawContainer> View;
2932 typedef typename View::type StlContainer;
2933 typedef typename View::const_reference StlContainerReference;
2934 typedef typename StlContainer::value_type Element;
2935
2936 // Constructs the matcher from a sequence of element values or
2937 // element matchers.
2938 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00002939 ElementsAreMatcherImpl(InputIter first, InputIter last) {
2940 while (first != last) {
2941 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002942 }
2943 }
2944
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002945 // Describes what this matcher does.
2946 virtual void DescribeTo(::std::ostream* os) const {
2947 if (count() == 0) {
2948 *os << "is empty";
2949 } else if (count() == 1) {
2950 *os << "has 1 element that ";
2951 matchers_[0].DescribeTo(os);
2952 } else {
2953 *os << "has " << Elements(count()) << " where\n";
2954 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002955 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002956 matchers_[i].DescribeTo(os);
2957 if (i + 1 < count()) {
2958 *os << ",\n";
2959 }
2960 }
2961 }
2962 }
2963
2964 // Describes what the negation of this matcher does.
2965 virtual void DescribeNegationTo(::std::ostream* os) const {
2966 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002967 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002968 return;
2969 }
2970
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002971 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002972 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002973 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002974 matchers_[i].DescribeNegationTo(os);
2975 if (i + 1 < count()) {
2976 *os << ", or\n";
2977 }
2978 }
2979 }
2980
zhanyong.wan82113312010-01-08 21:55:40 +00002981 virtual bool MatchAndExplain(Container container,
2982 MatchResultListener* listener) const {
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00002983 // To work with stream-like "containers", we must only walk
2984 // through the elements in one pass.
2985
2986 const bool listener_interested = listener->IsInterested();
2987
2988 // explanations[i] is the explanation of the element at index i.
2989 ::std::vector<internal::string> explanations(count());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002990 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00002991 typename StlContainer::const_iterator it = stl_container.begin();
2992 size_t exam_pos = 0;
2993 bool mismatch_found = false; // Have we found a mismatched element yet?
2994
2995 // Go through the elements and matchers in pairs, until we reach
2996 // the end of either the elements or the matchers, or until we find a
2997 // mismatch.
2998 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
2999 bool match; // Does the current element match the current matcher?
3000 if (listener_interested) {
3001 StringMatchResultListener s;
3002 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3003 explanations[exam_pos] = s.str();
3004 } else {
3005 match = matchers_[exam_pos].Matches(*it);
3006 }
3007
3008 if (!match) {
3009 mismatch_found = true;
3010 break;
3011 }
3012 }
3013 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3014
3015 // Find how many elements the actual container has. We avoid
3016 // calling size() s.t. this code works for stream-like "containers"
3017 // that don't define size().
3018 size_t actual_count = exam_pos;
3019 for (; it != stl_container.end(); ++it) {
3020 ++actual_count;
3021 }
3022
zhanyong.wan82113312010-01-08 21:55:40 +00003023 if (actual_count != count()) {
3024 // The element count doesn't match. If the container is empty,
3025 // there's no need to explain anything as Google Mock already
3026 // prints the empty container. Otherwise we just need to show
3027 // how many elements there actually are.
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003028 if (listener_interested && (actual_count != 0)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003029 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003030 }
zhanyong.wan82113312010-01-08 21:55:40 +00003031 return false;
3032 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003033
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003034 if (mismatch_found) {
3035 // The element count matches, but the exam_pos-th element doesn't match.
3036 if (listener_interested) {
3037 *listener << "whose element #" << exam_pos << " doesn't match";
3038 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003039 }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003040 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003041 }
zhanyong.wan82113312010-01-08 21:55:40 +00003042
3043 // Every element matches its expectation. We need to explain why
3044 // (the obvious ones can be skipped).
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003045 if (listener_interested) {
3046 bool reason_printed = false;
3047 for (size_t i = 0; i != count(); ++i) {
3048 const internal::string& s = explanations[i];
3049 if (!s.empty()) {
3050 if (reason_printed) {
3051 *listener << ",\nand ";
3052 }
3053 *listener << "whose element #" << i << " matches, " << s;
3054 reason_printed = true;
zhanyong.wan82113312010-01-08 21:55:40 +00003055 }
zhanyong.wan82113312010-01-08 21:55:40 +00003056 }
3057 }
zhanyong.wan82113312010-01-08 21:55:40 +00003058 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003059 }
3060
3061 private:
3062 static Message Elements(size_t count) {
3063 return Message() << count << (count == 1 ? " element" : " elements");
3064 }
3065
3066 size_t count() const { return matchers_.size(); }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003067
3068 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003069
3070 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003071};
3072
zhanyong.wanfb25d532013-07-28 08:24:00 +00003073// Connectivity matrix of (elements X matchers), in element-major order.
3074// Initially, there are no edges.
3075// Use NextGraph() to iterate over all possible edge configurations.
3076// Use Randomize() to generate a random edge configuration.
3077class GTEST_API_ MatchMatrix {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003078 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003079 MatchMatrix(size_t num_elements, size_t num_matchers)
3080 : num_elements_(num_elements),
3081 num_matchers_(num_matchers),
3082 matched_(num_elements_* num_matchers_, 0) {
3083 }
3084
3085 size_t LhsSize() const { return num_elements_; }
3086 size_t RhsSize() const { return num_matchers_; }
3087 bool HasEdge(size_t ilhs, size_t irhs) const {
3088 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3089 }
3090 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3091 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3092 }
3093
3094 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3095 // adds 1 to that number; returns false if incrementing the graph left it
3096 // empty.
3097 bool NextGraph();
3098
3099 void Randomize();
3100
3101 string DebugString() const;
3102
3103 private:
3104 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3105 return ilhs * num_matchers_ + irhs;
3106 }
3107
3108 size_t num_elements_;
3109 size_t num_matchers_;
3110
3111 // Each element is a char interpreted as bool. They are stored as a
3112 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3113 // a (ilhs, irhs) matrix coordinate into an offset.
3114 ::std::vector<char> matched_;
3115};
3116
3117typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3118typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3119
3120// Returns a maximum bipartite matching for the specified graph 'g'.
3121// The matching is represented as a vector of {element, matcher} pairs.
3122GTEST_API_ ElementMatcherPairs
3123FindMaxBipartiteMatching(const MatchMatrix& g);
3124
3125GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
3126 MatchResultListener* listener);
3127
3128// Untyped base class for implementing UnorderedElementsAre. By
3129// putting logic that's not specific to the element type here, we
3130// reduce binary bloat and increase compilation speed.
3131class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3132 protected:
3133 // A vector of matcher describers, one for each element matcher.
3134 // Does not own the describers (and thus can be used only when the
3135 // element matchers are alive).
3136 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3137
3138 // Describes this UnorderedElementsAre matcher.
3139 void DescribeToImpl(::std::ostream* os) const;
3140
3141 // Describes the negation of this UnorderedElementsAre matcher.
3142 void DescribeNegationToImpl(::std::ostream* os) const;
3143
3144 bool VerifyAllElementsAndMatchersAreMatched(
3145 const ::std::vector<string>& element_printouts,
3146 const MatchMatrix& matrix,
3147 MatchResultListener* listener) const;
3148
3149 MatcherDescriberVec& matcher_describers() {
3150 return matcher_describers_;
3151 }
3152
3153 static Message Elements(size_t n) {
3154 return Message() << n << " element" << (n == 1 ? "" : "s");
3155 }
3156
3157 private:
3158 MatcherDescriberVec matcher_describers_;
3159
3160 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3161};
3162
3163// Implements unordered ElementsAre and unordered ElementsAreArray.
3164template <typename Container>
3165class UnorderedElementsAreMatcherImpl
3166 : public MatcherInterface<Container>,
3167 public UnorderedElementsAreMatcherImplBase {
3168 public:
3169 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3170 typedef internal::StlContainerView<RawContainer> View;
3171 typedef typename View::type StlContainer;
3172 typedef typename View::const_reference StlContainerReference;
3173 typedef typename StlContainer::const_iterator StlContainerConstIterator;
3174 typedef typename StlContainer::value_type Element;
3175
3176 // Constructs the matcher from a sequence of element values or
3177 // element matchers.
3178 template <typename InputIter>
3179 UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) {
3180 for (; first != last; ++first) {
3181 matchers_.push_back(MatcherCast<const Element&>(*first));
3182 matcher_describers().push_back(matchers_.back().GetDescriber());
3183 }
3184 }
3185
3186 // Describes what this matcher does.
3187 virtual void DescribeTo(::std::ostream* os) const {
3188 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3189 }
3190
3191 // Describes what the negation of this matcher does.
3192 virtual void DescribeNegationTo(::std::ostream* os) const {
3193 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3194 }
3195
3196 virtual bool MatchAndExplain(Container container,
3197 MatchResultListener* listener) const {
3198 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003199 ::std::vector<string> element_printouts;
3200 MatchMatrix matrix = AnalyzeElements(stl_container.begin(),
3201 stl_container.end(),
3202 &element_printouts,
3203 listener);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003204
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003205 const size_t actual_count = matrix.LhsSize();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003206 if (actual_count == 0 && matchers_.empty()) {
3207 return true;
3208 }
3209 if (actual_count != matchers_.size()) {
3210 // The element count doesn't match. If the container is empty,
3211 // there's no need to explain anything as Google Mock already
3212 // prints the empty container. Otherwise we just need to show
3213 // how many elements there actually are.
3214 if (actual_count != 0 && listener->IsInterested()) {
3215 *listener << "which has " << Elements(actual_count);
3216 }
3217 return false;
3218 }
3219
zhanyong.wanfb25d532013-07-28 08:24:00 +00003220 return VerifyAllElementsAndMatchersAreMatched(element_printouts,
3221 matrix, listener) &&
3222 FindPairing(matrix, listener);
3223 }
3224
3225 private:
3226 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3227
3228 template <typename ElementIter>
3229 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
3230 ::std::vector<string>* element_printouts,
3231 MatchResultListener* listener) const {
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003232 element_printouts->clear();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003233 ::std::vector<char> did_match;
3234 size_t num_elements = 0;
3235 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3236 if (listener->IsInterested()) {
3237 element_printouts->push_back(PrintToString(*elem_first));
3238 }
3239 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3240 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3241 }
3242 }
3243
3244 MatchMatrix matrix(num_elements, matchers_.size());
3245 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3246 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3247 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3248 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3249 }
3250 }
3251 return matrix;
3252 }
3253
3254 MatcherVec matchers_;
3255
3256 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3257};
3258
3259// Functor for use in TransformTuple.
3260// Performs MatcherCast<Target> on an input argument of any type.
3261template <typename Target>
3262struct CastAndAppendTransform {
3263 template <typename Arg>
3264 Matcher<Target> operator()(const Arg& a) const {
3265 return MatcherCast<Target>(a);
3266 }
3267};
3268
3269// Implements UnorderedElementsAre.
3270template <typename MatcherTuple>
3271class UnorderedElementsAreMatcher {
3272 public:
3273 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3274 : matchers_(args) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003275
3276 template <typename Container>
3277 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003278 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003279 typedef typename internal::StlContainerView<RawContainer>::type View;
3280 typedef typename View::value_type Element;
3281 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3282 MatcherVec matchers;
3283 matchers.reserve(::std::tr1::tuple_size<MatcherTuple>::value);
3284 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3285 ::std::back_inserter(matchers));
3286 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3287 matchers.begin(), matchers.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003288 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003289
3290 private:
3291 const MatcherTuple matchers_;
3292 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3293};
3294
3295// Implements ElementsAre.
3296template <typename MatcherTuple>
3297class ElementsAreMatcher {
3298 public:
3299 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3300
3301 template <typename Container>
3302 operator Matcher<Container>() const {
3303 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3304 typedef typename internal::StlContainerView<RawContainer>::type View;
3305 typedef typename View::value_type Element;
3306 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3307 MatcherVec matchers;
3308 matchers.reserve(::std::tr1::tuple_size<MatcherTuple>::value);
3309 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3310 ::std::back_inserter(matchers));
3311 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3312 matchers.begin(), matchers.end()));
3313 }
3314
3315 private:
3316 const MatcherTuple matchers_;
3317 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3318};
3319
3320// Implements UnorderedElementsAreArray().
3321template <typename T>
3322class UnorderedElementsAreArrayMatcher {
3323 public:
3324 UnorderedElementsAreArrayMatcher() {}
3325
3326 template <typename Iter>
3327 UnorderedElementsAreArrayMatcher(Iter first, Iter last)
3328 : matchers_(first, last) {}
3329
3330 template <typename Container>
3331 operator Matcher<Container>() const {
3332 return MakeMatcher(
3333 new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(),
3334 matchers_.end()));
3335 }
3336
3337 private:
3338 ::std::vector<T> matchers_;
3339
3340 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003341};
3342
3343// Implements ElementsAreArray().
3344template <typename T>
3345class ElementsAreArrayMatcher {
3346 public:
jgm38513a82012-11-15 15:50:36 +00003347 template <typename Iter>
3348 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003349
3350 template <typename Container>
3351 operator Matcher<Container>() const {
jgm38513a82012-11-15 15:50:36 +00003352 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3353 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003354 }
3355
3356 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003357 const ::std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003358
3359 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003360};
3361
zhanyong.wanb4140802010-06-08 22:53:57 +00003362// Returns the description for a matcher defined using the MATCHER*()
3363// macro where the user-supplied description string is "", if
3364// 'negation' is false; otherwise returns the description of the
3365// negation of the matcher. 'param_values' contains a list of strings
3366// that are the print-out of the matcher's parameters.
vladlosev587c1b32011-05-20 00:42:22 +00003367GTEST_API_ string FormatMatcherDescription(bool negation,
3368 const char* matcher_name,
3369 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003370
shiqiane35fdd92008-12-10 05:08:54 +00003371} // namespace internal
3372
zhanyong.wanfb25d532013-07-28 08:24:00 +00003373// ElementsAreArray(first, last)
3374// ElementsAreArray(pointer, count)
3375// ElementsAreArray(array)
3376// ElementsAreArray(vector)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003377// ElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00003378//
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003379// The ElementsAreArray() functions are like ElementsAre(...), except
3380// that they are given a homogeneous sequence rather than taking each
3381// element as a function argument. The sequence can be specified as an
3382// array, a pointer and count, a vector, an initializer list, or an
3383// STL iterator range. In each of these cases, the underlying sequence
3384// can be either a sequence of values or a sequence of matchers.
zhanyong.wanfb25d532013-07-28 08:24:00 +00003385//
3386// All forms of ElementsAreArray() make a copy of the input matcher sequence.
3387
3388template <typename Iter>
3389inline internal::ElementsAreArrayMatcher<
3390 typename ::std::iterator_traits<Iter>::value_type>
3391ElementsAreArray(Iter first, Iter last) {
3392 typedef typename ::std::iterator_traits<Iter>::value_type T;
3393 return internal::ElementsAreArrayMatcher<T>(first, last);
3394}
3395
3396template <typename T>
3397inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3398 const T* pointer, size_t count) {
3399 return ElementsAreArray(pointer, pointer + count);
3400}
3401
3402template <typename T, size_t N>
3403inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3404 const T (&array)[N]) {
3405 return ElementsAreArray(array, N);
3406}
3407
3408template <typename T, typename A>
3409inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3410 const ::std::vector<T, A>& vec) {
3411 return ElementsAreArray(vec.begin(), vec.end());
3412}
3413
kosak18489fa2013-12-04 23:49:07 +00003414#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003415template <typename T>
3416inline internal::ElementsAreArrayMatcher<T>
3417ElementsAreArray(::std::initializer_list<T> xs) {
3418 return ElementsAreArray(xs.begin(), xs.end());
3419}
3420#endif
3421
zhanyong.wanfb25d532013-07-28 08:24:00 +00003422// UnorderedElementsAreArray(first, last)
3423// UnorderedElementsAreArray(pointer, count)
3424// UnorderedElementsAreArray(array)
3425// UnorderedElementsAreArray(vector)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003426// UnorderedElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00003427//
3428// The UnorderedElementsAreArray() functions are like
3429// ElementsAreArray(...), but allow matching the elements in any order.
3430template <typename Iter>
3431inline internal::UnorderedElementsAreArrayMatcher<
3432 typename ::std::iterator_traits<Iter>::value_type>
3433UnorderedElementsAreArray(Iter first, Iter last) {
3434 typedef typename ::std::iterator_traits<Iter>::value_type T;
3435 return internal::UnorderedElementsAreArrayMatcher<T>(first, last);
3436}
3437
3438template <typename T>
3439inline internal::UnorderedElementsAreArrayMatcher<T>
3440UnorderedElementsAreArray(const T* pointer, size_t count) {
3441 return UnorderedElementsAreArray(pointer, pointer + count);
3442}
3443
3444template <typename T, size_t N>
3445inline internal::UnorderedElementsAreArrayMatcher<T>
3446UnorderedElementsAreArray(const T (&array)[N]) {
3447 return UnorderedElementsAreArray(array, N);
3448}
3449
3450template <typename T, typename A>
3451inline internal::UnorderedElementsAreArrayMatcher<T>
3452UnorderedElementsAreArray(const ::std::vector<T, A>& vec) {
3453 return UnorderedElementsAreArray(vec.begin(), vec.end());
3454}
3455
kosak18489fa2013-12-04 23:49:07 +00003456#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003457template <typename T>
3458inline internal::UnorderedElementsAreArrayMatcher<T>
3459UnorderedElementsAreArray(::std::initializer_list<T> xs) {
3460 return UnorderedElementsAreArray(xs.begin(), xs.end());
3461}
3462#endif
zhanyong.wanfb25d532013-07-28 08:24:00 +00003463
shiqiane35fdd92008-12-10 05:08:54 +00003464// _ is a matcher that matches anything of any type.
3465//
3466// This definition is fine as:
3467//
3468// 1. The C++ standard permits using the name _ in a namespace that
3469// is not the global namespace or ::std.
3470// 2. The AnythingMatcher class has no data member or constructor,
3471// so it's OK to create global variables of this type.
3472// 3. c-style has approved of using _ in this case.
3473const internal::AnythingMatcher _ = {};
3474// Creates a matcher that matches any value of the given type T.
3475template <typename T>
3476inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
3477
3478// Creates a matcher that matches any value of the given type T.
3479template <typename T>
3480inline Matcher<T> An() { return A<T>(); }
3481
3482// Creates a polymorphic matcher that matches anything equal to x.
3483// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
3484// wouldn't compile.
3485template <typename T>
3486inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
3487
3488// Constructs a Matcher<T> from a 'value' of type T. The constructed
3489// matcher matches any value that's equal to 'value'.
3490template <typename T>
3491Matcher<T>::Matcher(T value) { *this = Eq(value); }
3492
3493// Creates a monomorphic matcher that matches anything with type Lhs
3494// and equal to rhs. A user may need to use this instead of Eq(...)
3495// in order to resolve an overloading ambiguity.
3496//
3497// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
3498// or Matcher<T>(x), but more readable than the latter.
3499//
3500// We could define similar monomorphic matchers for other comparison
3501// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
3502// it yet as those are used much less than Eq() in practice. A user
3503// can always write Matcher<T>(Lt(5)) to be explicit about the type,
3504// for example.
3505template <typename Lhs, typename Rhs>
3506inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
3507
3508// Creates a polymorphic matcher that matches anything >= x.
3509template <typename Rhs>
3510inline internal::GeMatcher<Rhs> Ge(Rhs x) {
3511 return internal::GeMatcher<Rhs>(x);
3512}
3513
3514// Creates a polymorphic matcher that matches anything > x.
3515template <typename Rhs>
3516inline internal::GtMatcher<Rhs> Gt(Rhs x) {
3517 return internal::GtMatcher<Rhs>(x);
3518}
3519
3520// Creates a polymorphic matcher that matches anything <= x.
3521template <typename Rhs>
3522inline internal::LeMatcher<Rhs> Le(Rhs x) {
3523 return internal::LeMatcher<Rhs>(x);
3524}
3525
3526// Creates a polymorphic matcher that matches anything < x.
3527template <typename Rhs>
3528inline internal::LtMatcher<Rhs> Lt(Rhs x) {
3529 return internal::LtMatcher<Rhs>(x);
3530}
3531
3532// Creates a polymorphic matcher that matches anything != x.
3533template <typename Rhs>
3534inline internal::NeMatcher<Rhs> Ne(Rhs x) {
3535 return internal::NeMatcher<Rhs>(x);
3536}
3537
zhanyong.wan2d970ee2009-09-24 21:41:36 +00003538// Creates a polymorphic matcher that matches any NULL pointer.
3539inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
3540 return MakePolymorphicMatcher(internal::IsNullMatcher());
3541}
3542
shiqiane35fdd92008-12-10 05:08:54 +00003543// Creates a polymorphic matcher that matches any non-NULL pointer.
3544// This is convenient as Not(NULL) doesn't compile (the compiler
3545// thinks that that expression is comparing a pointer with an integer).
3546inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
3547 return MakePolymorphicMatcher(internal::NotNullMatcher());
3548}
3549
3550// Creates a polymorphic matcher that matches any argument that
3551// references variable x.
3552template <typename T>
3553inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
3554 return internal::RefMatcher<T&>(x);
3555}
3556
3557// Creates a matcher that matches any double argument approximately
3558// equal to rhs, where two NANs are considered unequal.
3559inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
3560 return internal::FloatingEqMatcher<double>(rhs, false);
3561}
3562
3563// Creates a matcher that matches any double argument approximately
3564// equal to rhs, including NaN values when rhs is NaN.
3565inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
3566 return internal::FloatingEqMatcher<double>(rhs, true);
3567}
3568
zhanyong.wan616180e2013-06-18 18:49:51 +00003569// Creates a matcher that matches any double argument approximately equal to
3570// rhs, up to the specified max absolute error bound, where two NANs are
3571// considered unequal. The max absolute error bound must be non-negative.
3572inline internal::FloatingEqMatcher<double> DoubleNear(
3573 double rhs, double max_abs_error) {
3574 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
3575}
3576
3577// Creates a matcher that matches any double argument approximately equal to
3578// rhs, up to the specified max absolute error bound, including NaN values when
3579// rhs is NaN. The max absolute error bound must be non-negative.
3580inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
3581 double rhs, double max_abs_error) {
3582 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
3583}
3584
shiqiane35fdd92008-12-10 05:08:54 +00003585// Creates a matcher that matches any float argument approximately
3586// equal to rhs, where two NANs are considered unequal.
3587inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
3588 return internal::FloatingEqMatcher<float>(rhs, false);
3589}
3590
zhanyong.wan616180e2013-06-18 18:49:51 +00003591// Creates a matcher that matches any float argument approximately
shiqiane35fdd92008-12-10 05:08:54 +00003592// equal to rhs, including NaN values when rhs is NaN.
3593inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
3594 return internal::FloatingEqMatcher<float>(rhs, true);
3595}
3596
zhanyong.wan616180e2013-06-18 18:49:51 +00003597// Creates a matcher that matches any float argument approximately equal to
3598// rhs, up to the specified max absolute error bound, where two NANs are
3599// considered unequal. The max absolute error bound must be non-negative.
3600inline internal::FloatingEqMatcher<float> FloatNear(
3601 float rhs, float max_abs_error) {
3602 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
3603}
3604
3605// Creates a matcher that matches any float argument approximately equal to
3606// rhs, up to the specified max absolute error bound, including NaN values when
3607// rhs is NaN. The max absolute error bound must be non-negative.
3608inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
3609 float rhs, float max_abs_error) {
3610 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
3611}
3612
shiqiane35fdd92008-12-10 05:08:54 +00003613// Creates a matcher that matches a pointer (raw or smart) that points
3614// to a value that matches inner_matcher.
3615template <typename InnerMatcher>
3616inline internal::PointeeMatcher<InnerMatcher> Pointee(
3617 const InnerMatcher& inner_matcher) {
3618 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
3619}
3620
3621// Creates a matcher that matches an object whose given field matches
3622// 'matcher'. For example,
3623// Field(&Foo::number, Ge(5))
3624// matches a Foo object x iff x.number >= 5.
3625template <typename Class, typename FieldType, typename FieldMatcher>
3626inline PolymorphicMatcher<
3627 internal::FieldMatcher<Class, FieldType> > Field(
3628 FieldType Class::*field, const FieldMatcher& matcher) {
3629 return MakePolymorphicMatcher(
3630 internal::FieldMatcher<Class, FieldType>(
3631 field, MatcherCast<const FieldType&>(matcher)));
3632 // The call to MatcherCast() is required for supporting inner
3633 // matchers of compatible types. For example, it allows
3634 // Field(&Foo::bar, m)
3635 // to compile where bar is an int32 and m is a matcher for int64.
3636}
3637
3638// Creates a matcher that matches an object whose given property
3639// matches 'matcher'. For example,
3640// Property(&Foo::str, StartsWith("hi"))
3641// matches a Foo object x iff x.str() starts with "hi".
3642template <typename Class, typename PropertyType, typename PropertyMatcher>
3643inline PolymorphicMatcher<
3644 internal::PropertyMatcher<Class, PropertyType> > Property(
3645 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
3646 return MakePolymorphicMatcher(
3647 internal::PropertyMatcher<Class, PropertyType>(
3648 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00003649 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00003650 // The call to MatcherCast() is required for supporting inner
3651 // matchers of compatible types. For example, it allows
3652 // Property(&Foo::bar, m)
3653 // to compile where bar() returns an int32 and m is a matcher for int64.
3654}
3655
3656// Creates a matcher that matches an object iff the result of applying
3657// a callable to x matches 'matcher'.
3658// For example,
3659// ResultOf(f, StartsWith("hi"))
3660// matches a Foo object x iff f(x) starts with "hi".
3661// callable parameter can be a function, function pointer, or a functor.
3662// Callable has to satisfy the following conditions:
3663// * It is required to keep no state affecting the results of
3664// the calls on it and make no assumptions about how many calls
3665// will be made. Any state it keeps must be protected from the
3666// concurrent access.
3667// * If it is a function object, it has to define type result_type.
3668// We recommend deriving your functor classes from std::unary_function.
3669template <typename Callable, typename ResultOfMatcher>
3670internal::ResultOfMatcher<Callable> ResultOf(
3671 Callable callable, const ResultOfMatcher& matcher) {
3672 return internal::ResultOfMatcher<Callable>(
3673 callable,
3674 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
3675 matcher));
3676 // The call to MatcherCast() is required for supporting inner
3677 // matchers of compatible types. For example, it allows
3678 // ResultOf(Function, m)
3679 // to compile where Function() returns an int32 and m is a matcher for int64.
3680}
3681
3682// String matchers.
3683
3684// Matches a string equal to str.
3685inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3686 StrEq(const internal::string& str) {
3687 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3688 str, true, true));
3689}
3690
3691// Matches a string not equal to str.
3692inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3693 StrNe(const internal::string& str) {
3694 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3695 str, false, true));
3696}
3697
3698// Matches a string equal to str, ignoring case.
3699inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3700 StrCaseEq(const internal::string& str) {
3701 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3702 str, true, false));
3703}
3704
3705// Matches a string not equal to str, ignoring case.
3706inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3707 StrCaseNe(const internal::string& str) {
3708 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3709 str, false, false));
3710}
3711
3712// Creates a matcher that matches any string, std::string, or C string
3713// that contains the given substring.
3714inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
3715 HasSubstr(const internal::string& substring) {
3716 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
3717 substring));
3718}
3719
3720// Matches a string that starts with 'prefix' (case-sensitive).
3721inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
3722 StartsWith(const internal::string& prefix) {
3723 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
3724 prefix));
3725}
3726
3727// Matches a string that ends with 'suffix' (case-sensitive).
3728inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
3729 EndsWith(const internal::string& suffix) {
3730 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
3731 suffix));
3732}
3733
shiqiane35fdd92008-12-10 05:08:54 +00003734// Matches a string that fully matches regular expression 'regex'.
3735// The matcher takes ownership of 'regex'.
3736inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3737 const internal::RE* regex) {
3738 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
3739}
3740inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3741 const internal::string& regex) {
3742 return MatchesRegex(new internal::RE(regex));
3743}
3744
3745// Matches a string that contains regular expression 'regex'.
3746// The matcher takes ownership of 'regex'.
3747inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3748 const internal::RE* regex) {
3749 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
3750}
3751inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3752 const internal::string& regex) {
3753 return ContainsRegex(new internal::RE(regex));
3754}
3755
shiqiane35fdd92008-12-10 05:08:54 +00003756#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3757// Wide string matchers.
3758
3759// Matches a string equal to str.
3760inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3761 StrEq(const internal::wstring& str) {
3762 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3763 str, true, true));
3764}
3765
3766// Matches a string not equal to str.
3767inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3768 StrNe(const internal::wstring& str) {
3769 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3770 str, false, true));
3771}
3772
3773// Matches a string equal to str, ignoring case.
3774inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3775 StrCaseEq(const internal::wstring& str) {
3776 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3777 str, true, false));
3778}
3779
3780// Matches a string not equal to str, ignoring case.
3781inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3782 StrCaseNe(const internal::wstring& str) {
3783 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3784 str, false, false));
3785}
3786
3787// Creates a matcher that matches any wstring, std::wstring, or C wide string
3788// that contains the given substring.
3789inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
3790 HasSubstr(const internal::wstring& substring) {
3791 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
3792 substring));
3793}
3794
3795// Matches a string that starts with 'prefix' (case-sensitive).
3796inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
3797 StartsWith(const internal::wstring& prefix) {
3798 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
3799 prefix));
3800}
3801
3802// Matches a string that ends with 'suffix' (case-sensitive).
3803inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
3804 EndsWith(const internal::wstring& suffix) {
3805 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
3806 suffix));
3807}
3808
3809#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3810
3811// Creates a polymorphic matcher that matches a 2-tuple where the
3812// first field == the second field.
3813inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
3814
3815// Creates a polymorphic matcher that matches a 2-tuple where the
3816// first field >= the second field.
3817inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
3818
3819// Creates a polymorphic matcher that matches a 2-tuple where the
3820// first field > the second field.
3821inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
3822
3823// Creates a polymorphic matcher that matches a 2-tuple where the
3824// first field <= the second field.
3825inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
3826
3827// Creates a polymorphic matcher that matches a 2-tuple where the
3828// first field < the second field.
3829inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
3830
3831// Creates a polymorphic matcher that matches a 2-tuple where the
3832// first field != the second field.
3833inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
3834
3835// Creates a matcher that matches any value of type T that m doesn't
3836// match.
3837template <typename InnerMatcher>
3838inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
3839 return internal::NotMatcher<InnerMatcher>(m);
3840}
3841
shiqiane35fdd92008-12-10 05:08:54 +00003842// Returns a matcher that matches anything that satisfies the given
3843// predicate. The predicate can be any unary function or functor
3844// whose return type can be implicitly converted to bool.
3845template <typename Predicate>
3846inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
3847Truly(Predicate pred) {
3848 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
3849}
3850
zhanyong.wana31d9ce2013-03-01 01:50:17 +00003851// Returns a matcher that matches the container size. The container must
3852// support both size() and size_type which all STL-like containers provide.
3853// Note that the parameter 'size' can be a value of type size_type as well as
3854// matcher. For instance:
3855// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
3856// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
3857template <typename SizeMatcher>
3858inline internal::SizeIsMatcher<SizeMatcher>
3859SizeIs(const SizeMatcher& size_matcher) {
3860 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
3861}
3862
kosakb6a34882014-03-12 21:06:46 +00003863// Returns a matcher that matches the distance between the container's begin()
3864// iterator and its end() iterator, i.e. the size of the container. This matcher
3865// can be used instead of SizeIs with containers such as std::forward_list which
3866// do not implement size(). The container must provide const_iterator (with
3867// valid iterator_traits), begin() and end().
3868template <typename DistanceMatcher>
3869inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
3870BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
3871 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
3872}
3873
zhanyong.wan6a896b52009-01-16 01:13:50 +00003874// Returns a matcher that matches an equal container.
3875// This matcher behaves like Eq(), but in the event of mismatch lists the
3876// values that are included in one container but not the other. (Duplicate
3877// values and order differences are not explained.)
3878template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00003879inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00003880 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00003881 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00003882 // This following line is for working around a bug in MSVC 8.0,
3883 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00003884 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00003885 return MakePolymorphicMatcher(
3886 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00003887}
3888
zhanyong.wan898725c2011-09-16 16:45:39 +00003889// Returns a matcher that matches a container that, when sorted using
3890// the given comparator, matches container_matcher.
3891template <typename Comparator, typename ContainerMatcher>
3892inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
3893WhenSortedBy(const Comparator& comparator,
3894 const ContainerMatcher& container_matcher) {
3895 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
3896 comparator, container_matcher);
3897}
3898
3899// Returns a matcher that matches a container that, when sorted using
3900// the < operator, matches container_matcher.
3901template <typename ContainerMatcher>
3902inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
3903WhenSorted(const ContainerMatcher& container_matcher) {
3904 return
3905 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
3906 internal::LessComparator(), container_matcher);
3907}
3908
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003909// Matches an STL-style container or a native array that contains the
3910// same number of elements as in rhs, where its i-th element and rhs's
3911// i-th element (as a pair) satisfy the given pair matcher, for all i.
3912// TupleMatcher must be able to be safely cast to Matcher<tuple<const
3913// T1&, const T2&> >, where T1 and T2 are the types of elements in the
3914// LHS container and the RHS container respectively.
3915template <typename TupleMatcher, typename Container>
3916inline internal::PointwiseMatcher<TupleMatcher,
3917 GTEST_REMOVE_CONST_(Container)>
3918Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
3919 // This following line is for working around a bug in MSVC 8.0,
3920 // which causes Container to be a const type sometimes.
3921 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
3922 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
3923 tuple_matcher, rhs);
3924}
3925
zhanyong.wanb8243162009-06-04 05:48:20 +00003926// Matches an STL-style container or a native array that contains at
3927// least one element matching the given value or matcher.
3928//
3929// Examples:
3930// ::std::set<int> page_ids;
3931// page_ids.insert(3);
3932// page_ids.insert(1);
3933// EXPECT_THAT(page_ids, Contains(1));
3934// EXPECT_THAT(page_ids, Contains(Gt(2)));
3935// EXPECT_THAT(page_ids, Not(Contains(4)));
3936//
3937// ::std::map<int, size_t> page_lengths;
3938// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00003939// EXPECT_THAT(page_lengths,
3940// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00003941//
3942// const char* user_ids[] = { "joe", "mike", "tom" };
3943// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
3944template <typename M>
3945inline internal::ContainsMatcher<M> Contains(M matcher) {
3946 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00003947}
3948
zhanyong.wan33605ba2010-04-22 23:37:47 +00003949// Matches an STL-style container or a native array that contains only
3950// elements matching the given value or matcher.
3951//
3952// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
3953// the messages are different.
3954//
3955// Examples:
3956// ::std::set<int> page_ids;
3957// // Each(m) matches an empty container, regardless of what m is.
3958// EXPECT_THAT(page_ids, Each(Eq(1)));
3959// EXPECT_THAT(page_ids, Each(Eq(77)));
3960//
3961// page_ids.insert(3);
3962// EXPECT_THAT(page_ids, Each(Gt(0)));
3963// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
3964// page_ids.insert(1);
3965// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
3966//
3967// ::std::map<int, size_t> page_lengths;
3968// page_lengths[1] = 100;
3969// page_lengths[2] = 200;
3970// page_lengths[3] = 300;
3971// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
3972// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
3973//
3974// const char* user_ids[] = { "joe", "mike", "tom" };
3975// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
3976template <typename M>
3977inline internal::EachMatcher<M> Each(M matcher) {
3978 return internal::EachMatcher<M>(matcher);
3979}
3980
zhanyong.wanb5937da2009-07-16 20:26:41 +00003981// Key(inner_matcher) matches an std::pair whose 'first' field matches
3982// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3983// std::map that contains at least one element whose key is >= 5.
3984template <typename M>
3985inline internal::KeyMatcher<M> Key(M inner_matcher) {
3986 return internal::KeyMatcher<M>(inner_matcher);
3987}
3988
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003989// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
3990// matches first_matcher and whose 'second' field matches second_matcher. For
3991// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
3992// to match a std::map<int, string> that contains exactly one element whose key
3993// is >= 5 and whose value equals "foo".
3994template <typename FirstMatcher, typename SecondMatcher>
3995inline internal::PairMatcher<FirstMatcher, SecondMatcher>
3996Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
3997 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
3998 first_matcher, second_matcher);
3999}
4000
shiqiane35fdd92008-12-10 05:08:54 +00004001// Returns a predicate that is satisfied by anything that matches the
4002// given matcher.
4003template <typename M>
4004inline internal::MatcherAsPredicate<M> Matches(M matcher) {
4005 return internal::MatcherAsPredicate<M>(matcher);
4006}
4007
zhanyong.wanb8243162009-06-04 05:48:20 +00004008// Returns true iff the value matches the matcher.
4009template <typename T, typename M>
4010inline bool Value(const T& value, M matcher) {
4011 return testing::Matches(matcher)(value);
4012}
4013
zhanyong.wan34b034c2010-03-05 21:23:23 +00004014// Matches the value against the given matcher and explains the match
4015// result to listener.
4016template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00004017inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00004018 M matcher, const T& value, MatchResultListener* listener) {
4019 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
4020}
4021
zhanyong.wan616180e2013-06-18 18:49:51 +00004022#if GTEST_LANG_CXX11
4023// Define variadic matcher versions. They are overloaded in
4024// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
4025template <typename... Args>
4026inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
4027 return internal::AllOfMatcher<Args...>(matchers...);
4028}
4029
4030template <typename... Args>
4031inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
4032 return internal::AnyOfMatcher<Args...>(matchers...);
4033}
4034
4035#endif // GTEST_LANG_CXX11
4036
zhanyong.wanbf550852009-06-09 06:09:53 +00004037// AllArgs(m) is a synonym of m. This is useful in
4038//
4039// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
4040//
4041// which is easier to read than
4042//
4043// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
4044template <typename InnerMatcher>
4045inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
4046
shiqiane35fdd92008-12-10 05:08:54 +00004047// These macros allow using matchers to check values in Google Test
4048// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
4049// succeed iff the value matches the matcher. If the assertion fails,
4050// the value and the description of the matcher will be printed.
4051#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
4052 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4053#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
4054 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4055
4056} // namespace testing
4057
4058#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_