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