blob: 0f52ee45d103b6bf9ac84d3e92b837ebdef3778c [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
55namespace testing {
56
57// To implement a matcher Foo for type T, define:
58// 1. a class FooMatcherImpl that implements the
59// MatcherInterface<T> interface, and
60// 2. a factory function that creates a Matcher<T> object from a
61// FooMatcherImpl*.
62//
63// The two-level delegation design makes it possible to allow a user
64// to write "v" instead of "Eq(v)" where a Matcher is expected, which
65// is impossible if we pass matchers by pointers. It also eases
66// ownership management as Matcher objects can now be copied like
67// plain values.
68
zhanyong.wan82113312010-01-08 21:55:40 +000069// MatchResultListener is an abstract class. Its << operator can be
70// used by a matcher to explain why a value matches or doesn't match.
71//
72// TODO(wan@google.com): add method
73// bool InterestedInWhy(bool result) const;
74// to indicate whether the listener is interested in why the match
75// result is 'result'.
76class MatchResultListener {
77 public:
78 // Creates a listener object with the given underlying ostream. The
79 // listener does not own the ostream.
80 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
81 virtual ~MatchResultListener() = 0; // Makes this class abstract.
82
83 // Streams x to the underlying ostream; does nothing if the ostream
84 // is NULL.
85 template <typename T>
86 MatchResultListener& operator<<(const T& x) {
87 if (stream_ != NULL)
88 *stream_ << x;
89 return *this;
90 }
91
92 // Returns the underlying ostream.
93 ::std::ostream* stream() { return stream_; }
94
zhanyong.wana862f1d2010-03-15 21:23:04 +000095 // Returns true iff the listener is interested in an explanation of
96 // the match result. A matcher's MatchAndExplain() method can use
97 // this information to avoid generating the explanation when no one
98 // intends to hear it.
99 bool IsInterested() const { return stream_ != NULL; }
100
zhanyong.wan82113312010-01-08 21:55:40 +0000101 private:
102 ::std::ostream* const stream_;
103
104 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
105};
106
107inline MatchResultListener::~MatchResultListener() {
108}
109
zhanyong.wanfb25d532013-07-28 08:24:00 +0000110// An instance of a subclass of this knows how to describe itself as a
111// matcher.
112class MatcherDescriberInterface {
113 public:
114 virtual ~MatcherDescriberInterface() {}
115
116 // Describes this matcher to an ostream. The function should print
117 // a verb phrase that describes the property a value matching this
118 // matcher should have. The subject of the verb phrase is the value
119 // being matched. For example, the DescribeTo() method of the Gt(7)
120 // matcher prints "is greater than 7".
121 virtual void DescribeTo(::std::ostream* os) const = 0;
122
123 // Describes the negation of this matcher to an ostream. For
124 // example, if the description of this matcher is "is greater than
125 // 7", the negated description could be "is not greater than 7".
126 // You are not required to override this when implementing
127 // MatcherInterface, but it is highly advised so that your matcher
128 // can produce good error messages.
129 virtual void DescribeNegationTo(::std::ostream* os) const {
130 *os << "not (";
131 DescribeTo(os);
132 *os << ")";
133 }
134};
135
shiqiane35fdd92008-12-10 05:08:54 +0000136// The implementation of a matcher.
137template <typename T>
zhanyong.wanfb25d532013-07-28 08:24:00 +0000138class MatcherInterface : public MatcherDescriberInterface {
shiqiane35fdd92008-12-10 05:08:54 +0000139 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000140 // Returns true iff the matcher matches x; also explains the match
zhanyong.wan83f6b082013-03-01 01:47:35 +0000141 // result to 'listener' if necessary (see the next paragraph), in
142 // the form of a non-restrictive relative clause ("which ...",
143 // "whose ...", etc) that describes x. For example, the
144 // MatchAndExplain() method of the Pointee(...) matcher should
145 // generate an explanation like "which points to ...".
146 //
147 // Implementations of MatchAndExplain() should add an explanation of
148 // the match result *if and only if* they can provide additional
149 // information that's not already present (or not obvious) in the
150 // print-out of x and the matcher's description. Whether the match
151 // succeeds is not a factor in deciding whether an explanation is
152 // needed, as sometimes the caller needs to print a failure message
153 // when the match succeeds (e.g. when the matcher is used inside
154 // Not()).
155 //
156 // For example, a "has at least 10 elements" matcher should explain
157 // what the actual element count is, regardless of the match result,
158 // as it is useful information to the reader; on the other hand, an
159 // "is empty" matcher probably only needs to explain what the actual
160 // size is when the match fails, as it's redundant to say that the
161 // size is 0 when the value is already known to be empty.
zhanyong.wan82113312010-01-08 21:55:40 +0000162 //
zhanyong.wandb22c222010-01-28 21:52:29 +0000163 // You should override this method when defining a new matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000164 //
165 // It's the responsibility of the caller (Google Mock) to guarantee
166 // that 'listener' is not NULL. This helps to simplify a matcher's
167 // implementation when it doesn't care about the performance, as it
168 // can talk to 'listener' without checking its validity first.
169 // However, in order to implement dummy listeners efficiently,
170 // listener->stream() may be NULL.
zhanyong.wandb22c222010-01-28 21:52:29 +0000171 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
shiqiane35fdd92008-12-10 05:08:54 +0000172
zhanyong.wanfb25d532013-07-28 08:24:00 +0000173 // Inherits these methods from MatcherDescriberInterface:
174 // virtual void DescribeTo(::std::ostream* os) const = 0;
175 // virtual void DescribeNegationTo(::std::ostream* os) const;
shiqiane35fdd92008-12-10 05:08:54 +0000176};
177
178namespace internal {
179
zhanyong.wan82113312010-01-08 21:55:40 +0000180// A match result listener that ignores the explanation.
181class DummyMatchResultListener : public MatchResultListener {
182 public:
183 DummyMatchResultListener() : MatchResultListener(NULL) {}
184
185 private:
186 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
187};
188
189// A match result listener that forwards the explanation to a given
190// ostream. The difference between this and MatchResultListener is
191// that the former is concrete.
192class StreamMatchResultListener : public MatchResultListener {
193 public:
194 explicit StreamMatchResultListener(::std::ostream* os)
195 : MatchResultListener(os) {}
196
197 private:
198 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
199};
200
201// A match result listener that stores the explanation in a string.
202class StringMatchResultListener : public MatchResultListener {
203 public:
204 StringMatchResultListener() : MatchResultListener(&ss_) {}
205
206 // Returns the explanation heard so far.
207 internal::string str() const { return ss_.str(); }
208
209 private:
210 ::std::stringstream ss_;
211
212 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
213};
214
shiqiane35fdd92008-12-10 05:08:54 +0000215// An internal class for implementing Matcher<T>, which will derive
216// from it. We put functionalities common to all Matcher<T>
217// specializations here to avoid code duplication.
218template <typename T>
219class MatcherBase {
220 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000221 // Returns true iff the matcher matches x; also explains the match
222 // result to 'listener'.
223 bool MatchAndExplain(T x, MatchResultListener* listener) const {
224 return impl_->MatchAndExplain(x, listener);
225 }
226
shiqiane35fdd92008-12-10 05:08:54 +0000227 // Returns true iff this matcher matches x.
zhanyong.wan82113312010-01-08 21:55:40 +0000228 bool Matches(T x) const {
229 DummyMatchResultListener dummy;
230 return MatchAndExplain(x, &dummy);
231 }
shiqiane35fdd92008-12-10 05:08:54 +0000232
233 // Describes this matcher to an ostream.
234 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
235
236 // Describes the negation of this matcher to an ostream.
237 void DescribeNegationTo(::std::ostream* os) const {
238 impl_->DescribeNegationTo(os);
239 }
240
241 // Explains why x matches, or doesn't match, the matcher.
242 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000243 StreamMatchResultListener listener(os);
244 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000245 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000246
zhanyong.wanfb25d532013-07-28 08:24:00 +0000247 // Returns the describer for this matcher object; retains ownership
248 // of the describer, which is only guaranteed to be alive when
249 // this matcher object is alive.
250 const MatcherDescriberInterface* GetDescriber() const {
251 return impl_.get();
252 }
253
shiqiane35fdd92008-12-10 05:08:54 +0000254 protected:
255 MatcherBase() {}
256
257 // Constructs a matcher from its implementation.
258 explicit MatcherBase(const MatcherInterface<T>* impl)
259 : impl_(impl) {}
260
261 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000262
shiqiane35fdd92008-12-10 05:08:54 +0000263 private:
264 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
265 // interfaces. The former dynamically allocates a chunk of memory
266 // to hold the reference count, while the latter tracks all
267 // references using a circular linked list without allocating
268 // memory. It has been observed that linked_ptr performs better in
269 // typical scenarios. However, shared_ptr can out-perform
270 // linked_ptr when there are many more uses of the copy constructor
271 // than the default constructor.
272 //
273 // If performance becomes a problem, we should see if using
274 // shared_ptr helps.
275 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
276};
277
shiqiane35fdd92008-12-10 05:08:54 +0000278} // namespace internal
279
280// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
281// object that can check whether a value of type T matches. The
282// implementation of Matcher<T> is just a linked_ptr to const
283// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
284// from Matcher!
285template <typename T>
286class Matcher : public internal::MatcherBase<T> {
287 public:
vladlosev88032d82010-11-17 23:29:21 +0000288 // Constructs a null matcher. Needed for storing Matcher objects in STL
289 // containers. A default-constructed matcher is not yet initialized. You
290 // cannot use it until a valid value has been assigned to it.
shiqiane35fdd92008-12-10 05:08:54 +0000291 Matcher() {}
292
293 // Constructs a matcher from its implementation.
294 explicit Matcher(const MatcherInterface<T>* impl)
295 : internal::MatcherBase<T>(impl) {}
296
zhanyong.wan18490652009-05-11 18:54:08 +0000297 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000298 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
299 Matcher(T value); // NOLINT
300};
301
302// The following two specializations allow the user to write str
303// instead of Eq(str) and "foo" instead of Eq("foo") when a string
304// matcher is expected.
305template <>
vladlosev587c1b32011-05-20 00:42:22 +0000306class GTEST_API_ Matcher<const internal::string&>
shiqiane35fdd92008-12-10 05:08:54 +0000307 : public internal::MatcherBase<const internal::string&> {
308 public:
309 Matcher() {}
310
311 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
312 : internal::MatcherBase<const internal::string&>(impl) {}
313
314 // Allows the user to write str instead of Eq(str) sometimes, where
315 // str is a string object.
316 Matcher(const internal::string& s); // NOLINT
317
318 // Allows the user to write "foo" instead of Eq("foo") sometimes.
319 Matcher(const char* s); // NOLINT
320};
321
322template <>
vladlosev587c1b32011-05-20 00:42:22 +0000323class GTEST_API_ Matcher<internal::string>
shiqiane35fdd92008-12-10 05:08:54 +0000324 : public internal::MatcherBase<internal::string> {
325 public:
326 Matcher() {}
327
328 explicit Matcher(const MatcherInterface<internal::string>* impl)
329 : internal::MatcherBase<internal::string>(impl) {}
330
331 // Allows the user to write str instead of Eq(str) sometimes, where
332 // str is a string object.
333 Matcher(const internal::string& s); // NOLINT
334
335 // Allows the user to write "foo" instead of Eq("foo") sometimes.
336 Matcher(const char* s); // NOLINT
337};
338
zhanyong.wan1f122a02013-03-25 16:27:03 +0000339#if GTEST_HAS_STRING_PIECE_
340// The following two specializations allow the user to write str
341// instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece
342// matcher is expected.
343template <>
344class GTEST_API_ Matcher<const StringPiece&>
345 : public internal::MatcherBase<const StringPiece&> {
346 public:
347 Matcher() {}
348
349 explicit Matcher(const MatcherInterface<const StringPiece&>* impl)
350 : internal::MatcherBase<const StringPiece&>(impl) {}
351
352 // Allows the user to write str instead of Eq(str) sometimes, where
353 // str is a string object.
354 Matcher(const internal::string& s); // NOLINT
355
356 // Allows the user to write "foo" instead of Eq("foo") sometimes.
357 Matcher(const char* s); // NOLINT
358
359 // Allows the user to pass StringPieces directly.
360 Matcher(StringPiece s); // NOLINT
361};
362
363template <>
364class GTEST_API_ Matcher<StringPiece>
365 : public internal::MatcherBase<StringPiece> {
366 public:
367 Matcher() {}
368
369 explicit Matcher(const MatcherInterface<StringPiece>* impl)
370 : internal::MatcherBase<StringPiece>(impl) {}
371
372 // Allows the user to write str instead of Eq(str) sometimes, where
373 // str is a string object.
374 Matcher(const internal::string& s); // NOLINT
375
376 // Allows the user to write "foo" instead of Eq("foo") sometimes.
377 Matcher(const char* s); // NOLINT
378
379 // Allows the user to pass StringPieces directly.
380 Matcher(StringPiece s); // NOLINT
381};
382#endif // GTEST_HAS_STRING_PIECE_
383
shiqiane35fdd92008-12-10 05:08:54 +0000384// The PolymorphicMatcher class template makes it easy to implement a
385// polymorphic matcher (i.e. a matcher that can match values of more
386// than one type, e.g. Eq(n) and NotNull()).
387//
zhanyong.wandb22c222010-01-28 21:52:29 +0000388// To define a polymorphic matcher, a user should provide an Impl
389// class that has a DescribeTo() method and a DescribeNegationTo()
390// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000391//
zhanyong.wandb22c222010-01-28 21:52:29 +0000392// bool MatchAndExplain(const Value& value,
393// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000394//
395// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000396template <class Impl>
397class PolymorphicMatcher {
398 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000399 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000400
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000401 // Returns a mutable reference to the underlying matcher
402 // implementation object.
403 Impl& mutable_impl() { return impl_; }
404
405 // Returns an immutable reference to the underlying matcher
406 // implementation object.
407 const Impl& impl() const { return impl_; }
408
shiqiane35fdd92008-12-10 05:08:54 +0000409 template <typename T>
410 operator Matcher<T>() const {
411 return Matcher<T>(new MonomorphicImpl<T>(impl_));
412 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000413
shiqiane35fdd92008-12-10 05:08:54 +0000414 private:
415 template <typename T>
416 class MonomorphicImpl : public MatcherInterface<T> {
417 public:
418 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
419
shiqiane35fdd92008-12-10 05:08:54 +0000420 virtual void DescribeTo(::std::ostream* os) const {
421 impl_.DescribeTo(os);
422 }
423
424 virtual void DescribeNegationTo(::std::ostream* os) const {
425 impl_.DescribeNegationTo(os);
426 }
427
zhanyong.wan82113312010-01-08 21:55:40 +0000428 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000429 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000430 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000431
shiqiane35fdd92008-12-10 05:08:54 +0000432 private:
433 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000434
435 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000436 };
437
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000438 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000439
440 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000441};
442
443// Creates a matcher from its implementation. This is easier to use
444// than the Matcher<T> constructor as it doesn't require you to
445// explicitly write the template argument, e.g.
446//
447// MakeMatcher(foo);
448// vs
449// Matcher<const string&>(foo);
450template <typename T>
451inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
452 return Matcher<T>(impl);
zhanyong.wan2eab17b2013-03-08 17:53:24 +0000453}
shiqiane35fdd92008-12-10 05:08:54 +0000454
455// Creates a polymorphic matcher from its implementation. This is
456// easier to use than the PolymorphicMatcher<Impl> constructor as it
457// doesn't require you to explicitly write the template argument, e.g.
458//
459// MakePolymorphicMatcher(foo);
460// vs
461// PolymorphicMatcher<TypeOfFoo>(foo);
462template <class Impl>
463inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
464 return PolymorphicMatcher<Impl>(impl);
465}
466
jgm79a367e2012-04-10 16:02:11 +0000467// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
468// and MUST NOT BE USED IN USER CODE!!!
469namespace internal {
470
471// The MatcherCastImpl class template is a helper for implementing
472// MatcherCast(). We need this helper in order to partially
473// specialize the implementation of MatcherCast() (C++ allows
474// class/struct templates to be partially specialized, but not
475// function templates.).
476
477// This general version is used when MatcherCast()'s argument is a
478// polymorphic matcher (i.e. something that can be converted to a
479// Matcher but is not one yet; for example, Eq(value)) or a value (for
480// example, "hello").
481template <typename T, typename M>
482class MatcherCastImpl {
483 public:
484 static Matcher<T> Cast(M polymorphic_matcher_or_value) {
485 // M can be a polymorhic matcher, in which case we want to use
486 // its conversion operator to create Matcher<T>. Or it can be a value
487 // that should be passed to the Matcher<T>'s constructor.
488 //
489 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
490 // polymorphic matcher because it'll be ambiguous if T has an implicit
491 // constructor from M (this usually happens when T has an implicit
492 // constructor from any type).
493 //
494 // It won't work to unconditionally implict_cast
495 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
496 // a user-defined conversion from M to T if one exists (assuming M is
497 // a value).
498 return CastImpl(
499 polymorphic_matcher_or_value,
500 BooleanConstant<
501 internal::ImplicitlyConvertible<M, Matcher<T> >::value>());
502 }
503
504 private:
505 static Matcher<T> CastImpl(M value, BooleanConstant<false>) {
506 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
507 // matcher. It must be a value then. Use direct initialization to create
508 // a matcher.
509 return Matcher<T>(ImplicitCast_<T>(value));
510 }
511
512 static Matcher<T> CastImpl(M polymorphic_matcher_or_value,
513 BooleanConstant<true>) {
514 // M is implicitly convertible to Matcher<T>, which means that either
515 // M is a polymorhpic matcher or Matcher<T> has an implicit constructor
516 // from M. In both cases using the implicit conversion will produce a
517 // matcher.
518 //
519 // Even if T has an implicit constructor from M, it won't be called because
520 // creating Matcher<T> would require a chain of two user-defined conversions
521 // (first to create T from M and then to create Matcher<T> from T).
522 return polymorphic_matcher_or_value;
523 }
524};
525
526// This more specialized version is used when MatcherCast()'s argument
527// is already a Matcher. This only compiles when type T can be
528// statically converted to type U.
529template <typename T, typename U>
530class MatcherCastImpl<T, Matcher<U> > {
531 public:
532 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
533 return Matcher<T>(new Impl(source_matcher));
534 }
535
536 private:
537 class Impl : public MatcherInterface<T> {
538 public:
539 explicit Impl(const Matcher<U>& source_matcher)
540 : source_matcher_(source_matcher) {}
541
542 // We delegate the matching logic to the source matcher.
543 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
544 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
545 }
546
547 virtual void DescribeTo(::std::ostream* os) const {
548 source_matcher_.DescribeTo(os);
549 }
550
551 virtual void DescribeNegationTo(::std::ostream* os) const {
552 source_matcher_.DescribeNegationTo(os);
553 }
554
555 private:
556 const Matcher<U> source_matcher_;
557
558 GTEST_DISALLOW_ASSIGN_(Impl);
559 };
560};
561
562// This even more specialized version is used for efficiently casting
563// a matcher to its own type.
564template <typename T>
565class MatcherCastImpl<T, Matcher<T> > {
566 public:
567 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
568};
569
570} // namespace internal
571
shiqiane35fdd92008-12-10 05:08:54 +0000572// In order to be safe and clear, casting between different matcher
573// types is done explicitly via MatcherCast<T>(m), which takes a
574// matcher m and returns a Matcher<T>. It compiles only when T can be
575// statically converted to the argument type of m.
576template <typename T, typename M>
jgm79a367e2012-04-10 16:02:11 +0000577inline Matcher<T> MatcherCast(M matcher) {
578 return internal::MatcherCastImpl<T, M>::Cast(matcher);
579}
shiqiane35fdd92008-12-10 05:08:54 +0000580
zhanyong.wan18490652009-05-11 18:54:08 +0000581// Implements SafeMatcherCast().
582//
zhanyong.wan95b12332009-09-25 18:55:50 +0000583// We use an intermediate class to do the actual safe casting as Nokia's
584// Symbian compiler cannot decide between
585// template <T, M> ... (M) and
586// template <T, U> ... (const Matcher<U>&)
587// for function templates but can for member function templates.
588template <typename T>
589class SafeMatcherCastImpl {
590 public:
jgm79a367e2012-04-10 16:02:11 +0000591 // This overload handles polymorphic matchers and values only since
592 // monomorphic matchers are handled by the next one.
zhanyong.wan95b12332009-09-25 18:55:50 +0000593 template <typename M>
jgm79a367e2012-04-10 16:02:11 +0000594 static inline Matcher<T> Cast(M polymorphic_matcher_or_value) {
595 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
zhanyong.wan95b12332009-09-25 18:55:50 +0000596 }
zhanyong.wan18490652009-05-11 18:54:08 +0000597
zhanyong.wan95b12332009-09-25 18:55:50 +0000598 // This overload handles monomorphic matchers.
599 //
600 // In general, if type T can be implicitly converted to type U, we can
601 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
602 // contravariant): just keep a copy of the original Matcher<U>, convert the
603 // argument from type T to U, and then pass it to the underlying Matcher<U>.
604 // The only exception is when U is a reference and T is not, as the
605 // underlying Matcher<U> may be interested in the argument's address, which
606 // is not preserved in the conversion from T to U.
607 template <typename U>
608 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
609 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000610 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000611 T_must_be_implicitly_convertible_to_U);
612 // Enforce that we are not converting a non-reference type T to a reference
613 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000614 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000615 internal::is_reference<T>::value || !internal::is_reference<U>::value,
616 cannot_convert_non_referentce_arg_to_reference);
617 // In case both T and U are arithmetic types, enforce that the
618 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000619 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
620 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000621 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
622 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000623 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000624 kTIsOther || kUIsOther ||
625 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
626 conversion_of_arithmetic_types_must_be_lossless);
627 return MatcherCast<T>(matcher);
628 }
629};
630
631template <typename T, typename M>
632inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
633 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000634}
635
shiqiane35fdd92008-12-10 05:08:54 +0000636// A<T>() returns a matcher that matches any value of type T.
637template <typename T>
638Matcher<T> A();
639
640// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
641// and MUST NOT BE USED IN USER CODE!!!
642namespace internal {
643
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000644// If the explanation is not empty, prints it to the ostream.
645inline void PrintIfNotEmpty(const internal::string& explanation,
zhanyong.wanfb25d532013-07-28 08:24:00 +0000646 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000647 if (explanation != "" && os != NULL) {
648 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000649 }
650}
651
zhanyong.wan736baa82010-09-27 17:44:16 +0000652// Returns true if the given type name is easy to read by a human.
653// This is used to decide whether printing the type of a value might
654// be helpful.
655inline bool IsReadableTypeName(const string& type_name) {
656 // We consider a type name readable if it's short or doesn't contain
657 // a template or function type.
658 return (type_name.length() <= 20 ||
659 type_name.find_first_of("<(") == string::npos);
660}
661
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000662// Matches the value against the given matcher, prints the value and explains
663// the match result to the listener. Returns the match result.
664// 'listener' must not be NULL.
665// Value cannot be passed by const reference, because some matchers take a
666// non-const argument.
667template <typename Value, typename T>
668bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
669 MatchResultListener* listener) {
670 if (!listener->IsInterested()) {
671 // If the listener is not interested, we do not need to construct the
672 // inner explanation.
673 return matcher.Matches(value);
674 }
675
676 StringMatchResultListener inner_listener;
677 const bool match = matcher.MatchAndExplain(value, &inner_listener);
678
679 UniversalPrint(value, listener->stream());
zhanyong.wan736baa82010-09-27 17:44:16 +0000680#if GTEST_HAS_RTTI
681 const string& type_name = GetTypeName<Value>();
682 if (IsReadableTypeName(type_name))
683 *listener->stream() << " (of type " << type_name << ")";
684#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000685 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000686
687 return match;
688}
689
shiqiane35fdd92008-12-10 05:08:54 +0000690// An internal helper class for doing compile-time loop on a tuple's
691// fields.
692template <size_t N>
693class TuplePrefix {
694 public:
695 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
696 // iff the first N fields of matcher_tuple matches the first N
697 // fields of value_tuple, respectively.
698 template <typename MatcherTuple, typename ValueTuple>
699 static bool Matches(const MatcherTuple& matcher_tuple,
700 const ValueTuple& value_tuple) {
701 using ::std::tr1::get;
702 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
703 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
704 }
705
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000706 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000707 // describes failures in matching the first N fields of matchers
708 // against the first N fields of values. If there is no failure,
709 // nothing will be streamed to os.
710 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000711 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
712 const ValueTuple& values,
713 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000714 using ::std::tr1::tuple_element;
715 using ::std::tr1::get;
716
717 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000718 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000719
720 // Then describes the failure (if any) in the (N - 1)-th (0-based)
721 // field.
722 typename tuple_element<N - 1, MatcherTuple>::type matcher =
723 get<N - 1>(matchers);
724 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
725 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000726 StringMatchResultListener listener;
727 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000728 // TODO(wan): include in the message the name of the parameter
729 // as used in MOCK_METHOD*() when possible.
730 *os << " Expected arg #" << N - 1 << ": ";
731 get<N - 1>(matchers).DescribeTo(os);
732 *os << "\n Actual: ";
733 // We remove the reference in type Value to prevent the
734 // universal printer from printing the address of value, which
735 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000736 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000737 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000738 internal::UniversalPrint(value, os);
739 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000740 *os << "\n";
741 }
742 }
743};
744
745// The base case.
746template <>
747class TuplePrefix<0> {
748 public:
749 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000750 static bool Matches(const MatcherTuple& /* matcher_tuple */,
751 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000752 return true;
753 }
754
755 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000756 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
757 const ValueTuple& /* values */,
758 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000759};
760
761// TupleMatches(matcher_tuple, value_tuple) returns true iff all
762// matchers in matcher_tuple match the corresponding fields in
763// value_tuple. It is a compiler error if matcher_tuple and
764// value_tuple have different number of fields or incompatible field
765// types.
766template <typename MatcherTuple, typename ValueTuple>
767bool TupleMatches(const MatcherTuple& matcher_tuple,
768 const ValueTuple& value_tuple) {
769 using ::std::tr1::tuple_size;
770 // Makes sure that matcher_tuple and value_tuple have the same
771 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000772 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000773 tuple_size<ValueTuple>::value,
774 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000775 return TuplePrefix<tuple_size<ValueTuple>::value>::
776 Matches(matcher_tuple, value_tuple);
777}
778
779// Describes failures in matching matchers against values. If there
780// is no failure, nothing will be streamed to os.
781template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000782void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
783 const ValueTuple& values,
784 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000785 using ::std::tr1::tuple_size;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000786 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000787 matchers, values, os);
788}
789
zhanyong.wanfb25d532013-07-28 08:24:00 +0000790// TransformTupleValues and its helper.
791//
792// TransformTupleValuesHelper hides the internal machinery that
793// TransformTupleValues uses to implement a tuple traversal.
794template <typename Tuple, typename Func, typename OutIter>
795class TransformTupleValuesHelper {
796 private:
797 typedef typename ::std::tr1::tuple_size<Tuple> TupleSize;
798
799 public:
800 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
801 // Returns the final value of 'out' in case the caller needs it.
802 static OutIter Run(Func f, const Tuple& t, OutIter out) {
803 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
804 }
805
806 private:
807 template <typename Tup, size_t kRemainingSize>
808 struct IterateOverTuple {
809 OutIter operator() (Func f, const Tup& t, OutIter out) const {
810 *out++ = f(::std::tr1::get<TupleSize::value - kRemainingSize>(t));
811 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
812 }
813 };
814 template <typename Tup>
815 struct IterateOverTuple<Tup, 0> {
816 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
817 return out;
818 }
819 };
820};
821
822// Successively invokes 'f(element)' on each element of the tuple 't',
823// appending each result to the 'out' iterator. Returns the final value
824// of 'out'.
825template <typename Tuple, typename Func, typename OutIter>
826OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
827 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
828}
829
shiqiane35fdd92008-12-10 05:08:54 +0000830// Implements A<T>().
831template <typename T>
832class AnyMatcherImpl : public MatcherInterface<T> {
833 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000834 virtual bool MatchAndExplain(
835 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000836 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
837 virtual void DescribeNegationTo(::std::ostream* os) const {
838 // This is mostly for completeness' safe, as it's not very useful
839 // to write Not(A<bool>()). However we cannot completely rule out
840 // such a possibility, and it doesn't hurt to be prepared.
841 *os << "never matches";
842 }
843};
844
845// Implements _, a matcher that matches any value of any
846// type. This is a polymorphic matcher, so we need a template type
847// conversion operator to make it appearing as a Matcher<T> for any
848// type T.
849class AnythingMatcher {
850 public:
851 template <typename T>
852 operator Matcher<T>() const { return A<T>(); }
853};
854
855// Implements a matcher that compares a given value with a
856// pre-supplied value using one of the ==, <=, <, etc, operators. The
857// two values being compared don't have to have the same type.
858//
859// The matcher defined here is polymorphic (for example, Eq(5) can be
860// used to match an int, a short, a double, etc). Therefore we use
861// a template type conversion operator in the implementation.
862//
863// We define this as a macro in order to eliminate duplicated source
864// code.
865//
866// The following template definition assumes that the Rhs parameter is
867// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000868#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \
869 name, op, relation, negated_relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000870 template <typename Rhs> class name##Matcher { \
871 public: \
872 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
873 template <typename Lhs> \
874 operator Matcher<Lhs>() const { \
875 return MakeMatcher(new Impl<Lhs>(rhs_)); \
876 } \
877 private: \
878 template <typename Lhs> \
879 class Impl : public MatcherInterface<Lhs> { \
880 public: \
881 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
zhanyong.wan82113312010-01-08 21:55:40 +0000882 virtual bool MatchAndExplain(\
883 Lhs lhs, MatchResultListener* /* listener */) const { \
884 return lhs op rhs_; \
885 } \
shiqiane35fdd92008-12-10 05:08:54 +0000886 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000887 *os << relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000888 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000889 } \
890 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000891 *os << negated_relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000892 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000893 } \
894 private: \
895 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000896 GTEST_DISALLOW_ASSIGN_(Impl); \
shiqiane35fdd92008-12-10 05:08:54 +0000897 }; \
898 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000899 GTEST_DISALLOW_ASSIGN_(name##Matcher); \
shiqiane35fdd92008-12-10 05:08:54 +0000900 }
901
902// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
903// respectively.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000904GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
905GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
906GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
907GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
908GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
909GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000910
zhanyong.wane0d051e2009-02-19 00:33:37 +0000911#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000912
vladlosev79b83502009-11-18 00:43:37 +0000913// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000914// pointer that is NULL.
915class IsNullMatcher {
916 public:
vladlosev79b83502009-11-18 00:43:37 +0000917 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000918 bool MatchAndExplain(const Pointer& p,
919 MatchResultListener* /* listener */) const {
920 return GetRawPointer(p) == NULL;
921 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000922
923 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
924 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000925 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000926 }
927};
928
vladlosev79b83502009-11-18 00:43:37 +0000929// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000930// pointer that is not NULL.
931class NotNullMatcher {
932 public:
vladlosev79b83502009-11-18 00:43:37 +0000933 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000934 bool MatchAndExplain(const Pointer& p,
935 MatchResultListener* /* listener */) const {
936 return GetRawPointer(p) != NULL;
937 }
shiqiane35fdd92008-12-10 05:08:54 +0000938
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000939 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +0000940 void DescribeNegationTo(::std::ostream* os) const {
941 *os << "is NULL";
942 }
943};
944
945// Ref(variable) matches any argument that is a reference to
946// 'variable'. This matcher is polymorphic as it can match any
947// super type of the type of 'variable'.
948//
949// The RefMatcher template class implements Ref(variable). It can
950// only be instantiated with a reference type. This prevents a user
951// from mistakenly using Ref(x) to match a non-reference function
952// argument. For example, the following will righteously cause a
953// compiler error:
954//
955// int n;
956// Matcher<int> m1 = Ref(n); // This won't compile.
957// Matcher<int&> m2 = Ref(n); // This will compile.
958template <typename T>
959class RefMatcher;
960
961template <typename T>
962class RefMatcher<T&> {
963 // Google Mock is a generic framework and thus needs to support
964 // mocking any function types, including those that take non-const
965 // reference arguments. Therefore the template parameter T (and
966 // Super below) can be instantiated to either a const type or a
967 // non-const type.
968 public:
969 // RefMatcher() takes a T& instead of const T&, as we want the
970 // compiler to catch using Ref(const_value) as a matcher for a
971 // non-const reference.
972 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
973
974 template <typename Super>
975 operator Matcher<Super&>() const {
976 // By passing object_ (type T&) to Impl(), which expects a Super&,
977 // we make sure that Super is a super type of T. In particular,
978 // this catches using Ref(const_value) as a matcher for a
979 // non-const reference, as you cannot implicitly convert a const
980 // reference to a non-const reference.
981 return MakeMatcher(new Impl<Super>(object_));
982 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000983
shiqiane35fdd92008-12-10 05:08:54 +0000984 private:
985 template <typename Super>
986 class Impl : public MatcherInterface<Super&> {
987 public:
988 explicit Impl(Super& x) : object_(x) {} // NOLINT
989
zhanyong.wandb22c222010-01-28 21:52:29 +0000990 // MatchAndExplain() takes a Super& (as opposed to const Super&)
991 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +0000992 virtual bool MatchAndExplain(
993 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000994 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +0000995 return &x == &object_;
996 }
shiqiane35fdd92008-12-10 05:08:54 +0000997
998 virtual void DescribeTo(::std::ostream* os) const {
999 *os << "references the variable ";
1000 UniversalPrinter<Super&>::Print(object_, os);
1001 }
1002
1003 virtual void DescribeNegationTo(::std::ostream* os) const {
1004 *os << "does not reference the variable ";
1005 UniversalPrinter<Super&>::Print(object_, os);
1006 }
1007
shiqiane35fdd92008-12-10 05:08:54 +00001008 private:
1009 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001010
1011 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001012 };
1013
1014 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001015
1016 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001017};
1018
1019// Polymorphic helper functions for narrow and wide string matchers.
1020inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1021 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1022}
1023
1024inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1025 const wchar_t* rhs) {
1026 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1027}
1028
1029// String comparison for narrow or wide strings that can have embedded NUL
1030// characters.
1031template <typename StringType>
1032bool CaseInsensitiveStringEquals(const StringType& s1,
1033 const StringType& s2) {
1034 // Are the heads equal?
1035 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1036 return false;
1037 }
1038
1039 // Skip the equal heads.
1040 const typename StringType::value_type nul = 0;
1041 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1042
1043 // Are we at the end of either s1 or s2?
1044 if (i1 == StringType::npos || i2 == StringType::npos) {
1045 return i1 == i2;
1046 }
1047
1048 // Are the tails equal?
1049 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1050}
1051
1052// String matchers.
1053
1054// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1055template <typename StringType>
1056class StrEqualityMatcher {
1057 public:
shiqiane35fdd92008-12-10 05:08:54 +00001058 StrEqualityMatcher(const StringType& str, bool expect_eq,
1059 bool case_sensitive)
1060 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1061
jgm38513a82012-11-15 15:50:36 +00001062 // Accepts pointer types, particularly:
1063 // const char*
1064 // char*
1065 // const wchar_t*
1066 // wchar_t*
1067 template <typename CharType>
1068 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001069 if (s == NULL) {
1070 return !expect_eq_;
1071 }
zhanyong.wandb22c222010-01-28 21:52:29 +00001072 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001073 }
1074
jgm38513a82012-11-15 15:50:36 +00001075 // Matches anything that can convert to StringType.
1076 //
1077 // This is a template, not just a plain function with const StringType&,
1078 // because StringPiece has some interfering non-explicit constructors.
1079 template <typename MatcheeStringType>
1080 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001081 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001082 const StringType& s2(s);
1083 const bool eq = case_sensitive_ ? s2 == string_ :
1084 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +00001085 return expect_eq_ == eq;
1086 }
1087
1088 void DescribeTo(::std::ostream* os) const {
1089 DescribeToHelper(expect_eq_, os);
1090 }
1091
1092 void DescribeNegationTo(::std::ostream* os) const {
1093 DescribeToHelper(!expect_eq_, os);
1094 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001095
shiqiane35fdd92008-12-10 05:08:54 +00001096 private:
1097 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001098 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +00001099 *os << "equal to ";
1100 if (!case_sensitive_) {
1101 *os << "(ignoring case) ";
1102 }
vladloseve2e8ba42010-05-13 18:16:03 +00001103 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001104 }
1105
1106 const StringType string_;
1107 const bool expect_eq_;
1108 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001109
1110 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001111};
1112
1113// Implements the polymorphic HasSubstr(substring) matcher, which
1114// can be used as a Matcher<T> as long as T can be converted to a
1115// string.
1116template <typename StringType>
1117class HasSubstrMatcher {
1118 public:
shiqiane35fdd92008-12-10 05:08:54 +00001119 explicit HasSubstrMatcher(const StringType& substring)
1120 : substring_(substring) {}
1121
jgm38513a82012-11-15 15:50:36 +00001122 // Accepts pointer types, particularly:
1123 // const char*
1124 // char*
1125 // const wchar_t*
1126 // wchar_t*
1127 template <typename CharType>
1128 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001129 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001130 }
1131
jgm38513a82012-11-15 15:50:36 +00001132 // Matches anything that can convert to StringType.
1133 //
1134 // This is a template, not just a plain function with const StringType&,
1135 // because StringPiece has some interfering non-explicit constructors.
1136 template <typename MatcheeStringType>
1137 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001138 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001139 const StringType& s2(s);
1140 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001141 }
1142
1143 // Describes what this matcher matches.
1144 void DescribeTo(::std::ostream* os) const {
1145 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001146 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001147 }
1148
1149 void DescribeNegationTo(::std::ostream* os) const {
1150 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001151 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001152 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001153
shiqiane35fdd92008-12-10 05:08:54 +00001154 private:
1155 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001156
1157 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001158};
1159
1160// Implements the polymorphic StartsWith(substring) matcher, which
1161// can be used as a Matcher<T> as long as T can be converted to a
1162// string.
1163template <typename StringType>
1164class StartsWithMatcher {
1165 public:
shiqiane35fdd92008-12-10 05:08:54 +00001166 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1167 }
1168
jgm38513a82012-11-15 15:50:36 +00001169 // Accepts pointer types, particularly:
1170 // const char*
1171 // char*
1172 // const wchar_t*
1173 // wchar_t*
1174 template <typename CharType>
1175 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001176 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001177 }
1178
jgm38513a82012-11-15 15:50:36 +00001179 // Matches anything that can convert to StringType.
1180 //
1181 // This is a template, not just a plain function with const StringType&,
1182 // because StringPiece has some interfering non-explicit constructors.
1183 template <typename MatcheeStringType>
1184 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001185 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001186 const StringType& s2(s);
1187 return s2.length() >= prefix_.length() &&
1188 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001189 }
1190
1191 void DescribeTo(::std::ostream* os) const {
1192 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001193 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001194 }
1195
1196 void DescribeNegationTo(::std::ostream* os) const {
1197 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001198 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001199 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001200
shiqiane35fdd92008-12-10 05:08:54 +00001201 private:
1202 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001203
1204 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001205};
1206
1207// Implements the polymorphic EndsWith(substring) matcher, which
1208// can be used as a Matcher<T> as long as T can be converted to a
1209// string.
1210template <typename StringType>
1211class EndsWithMatcher {
1212 public:
shiqiane35fdd92008-12-10 05:08:54 +00001213 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1214
jgm38513a82012-11-15 15:50:36 +00001215 // Accepts pointer types, particularly:
1216 // const char*
1217 // char*
1218 // const wchar_t*
1219 // wchar_t*
1220 template <typename CharType>
1221 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001222 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001223 }
1224
jgm38513a82012-11-15 15:50:36 +00001225 // Matches anything that can convert to StringType.
1226 //
1227 // This is a template, not just a plain function with const StringType&,
1228 // because StringPiece has some interfering non-explicit constructors.
1229 template <typename MatcheeStringType>
1230 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001231 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001232 const StringType& s2(s);
1233 return s2.length() >= suffix_.length() &&
1234 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001235 }
1236
1237 void DescribeTo(::std::ostream* os) const {
1238 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001239 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001240 }
1241
1242 void DescribeNegationTo(::std::ostream* os) const {
1243 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001244 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001245 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001246
shiqiane35fdd92008-12-10 05:08:54 +00001247 private:
1248 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001249
1250 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001251};
1252
shiqiane35fdd92008-12-10 05:08:54 +00001253// Implements polymorphic matchers MatchesRegex(regex) and
1254// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1255// T can be converted to a string.
1256class MatchesRegexMatcher {
1257 public:
1258 MatchesRegexMatcher(const RE* regex, bool full_match)
1259 : regex_(regex), full_match_(full_match) {}
1260
jgm38513a82012-11-15 15:50:36 +00001261 // Accepts pointer types, particularly:
1262 // const char*
1263 // char*
1264 // const wchar_t*
1265 // wchar_t*
1266 template <typename CharType>
1267 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001268 return s != NULL && MatchAndExplain(internal::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001269 }
1270
jgm38513a82012-11-15 15:50:36 +00001271 // Matches anything that can convert to internal::string.
1272 //
1273 // This is a template, not just a plain function with const internal::string&,
1274 // because StringPiece has some interfering non-explicit constructors.
1275 template <class MatcheeStringType>
1276 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001277 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001278 const internal::string& s2(s);
1279 return full_match_ ? RE::FullMatch(s2, *regex_) :
1280 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001281 }
1282
1283 void DescribeTo(::std::ostream* os) const {
1284 *os << (full_match_ ? "matches" : "contains")
1285 << " regular expression ";
1286 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1287 }
1288
1289 void DescribeNegationTo(::std::ostream* os) const {
1290 *os << "doesn't " << (full_match_ ? "match" : "contain")
1291 << " regular expression ";
1292 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1293 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001294
shiqiane35fdd92008-12-10 05:08:54 +00001295 private:
1296 const internal::linked_ptr<const RE> regex_;
1297 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001298
1299 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001300};
1301
shiqiane35fdd92008-12-10 05:08:54 +00001302// Implements a matcher that compares the two fields of a 2-tuple
1303// using one of the ==, <=, <, etc, operators. The two fields being
1304// compared don't have to have the same type.
1305//
1306// The matcher defined here is polymorphic (for example, Eq() can be
1307// used to match a tuple<int, short>, a tuple<const long&, double>,
1308// etc). Therefore we use a template type conversion operator in the
1309// implementation.
1310//
1311// We define this as a macro in order to eliminate duplicated source
1312// code.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001313#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +00001314 class name##2Matcher { \
1315 public: \
1316 template <typename T1, typename T2> \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001317 operator Matcher< ::std::tr1::tuple<T1, T2> >() const { \
1318 return MakeMatcher(new Impl< ::std::tr1::tuple<T1, T2> >); \
1319 } \
1320 template <typename T1, typename T2> \
shiqiane35fdd92008-12-10 05:08:54 +00001321 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001322 return MakeMatcher(new Impl<const ::std::tr1::tuple<T1, T2>&>); \
shiqiane35fdd92008-12-10 05:08:54 +00001323 } \
1324 private: \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001325 template <typename Tuple> \
1326 class Impl : public MatcherInterface<Tuple> { \
shiqiane35fdd92008-12-10 05:08:54 +00001327 public: \
zhanyong.wan82113312010-01-08 21:55:40 +00001328 virtual bool MatchAndExplain( \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001329 Tuple args, \
zhanyong.wan82113312010-01-08 21:55:40 +00001330 MatchResultListener* /* listener */) const { \
shiqiane35fdd92008-12-10 05:08:54 +00001331 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1332 } \
1333 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001334 *os << "are " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001335 } \
1336 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001337 *os << "aren't " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001338 } \
1339 }; \
1340 }
1341
1342// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001343GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "an equal pair");
1344GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1345 Ge, >=, "a pair where the first >= the second");
1346GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1347 Gt, >, "a pair where the first > the second");
1348GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1349 Le, <=, "a pair where the first <= the second");
1350GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1351 Lt, <, "a pair where the first < the second");
1352GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "an unequal pair");
shiqiane35fdd92008-12-10 05:08:54 +00001353
zhanyong.wane0d051e2009-02-19 00:33:37 +00001354#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001355
zhanyong.wanc6a41232009-05-13 23:38:40 +00001356// Implements the Not(...) matcher for a particular argument type T.
1357// We do not nest it inside the NotMatcher class template, as that
1358// will prevent different instantiations of NotMatcher from sharing
1359// the same NotMatcherImpl<T> class.
1360template <typename T>
1361class NotMatcherImpl : public MatcherInterface<T> {
1362 public:
1363 explicit NotMatcherImpl(const Matcher<T>& matcher)
1364 : matcher_(matcher) {}
1365
zhanyong.wan82113312010-01-08 21:55:40 +00001366 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1367 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001368 }
1369
1370 virtual void DescribeTo(::std::ostream* os) const {
1371 matcher_.DescribeNegationTo(os);
1372 }
1373
1374 virtual void DescribeNegationTo(::std::ostream* os) const {
1375 matcher_.DescribeTo(os);
1376 }
1377
zhanyong.wanc6a41232009-05-13 23:38:40 +00001378 private:
1379 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001380
1381 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001382};
1383
shiqiane35fdd92008-12-10 05:08:54 +00001384// Implements the Not(m) matcher, which matches a value that doesn't
1385// match matcher m.
1386template <typename InnerMatcher>
1387class NotMatcher {
1388 public:
1389 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1390
1391 // This template type conversion operator allows Not(m) to be used
1392 // to match any type m can match.
1393 template <typename T>
1394 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001395 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001396 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001397
shiqiane35fdd92008-12-10 05:08:54 +00001398 private:
shiqiane35fdd92008-12-10 05:08:54 +00001399 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001400
1401 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001402};
1403
zhanyong.wanc6a41232009-05-13 23:38:40 +00001404// Implements the AllOf(m1, m2) matcher for a particular argument type
1405// T. We do not nest it inside the BothOfMatcher class template, as
1406// that will prevent different instantiations of BothOfMatcher from
1407// sharing the same BothOfMatcherImpl<T> class.
1408template <typename T>
1409class BothOfMatcherImpl : public MatcherInterface<T> {
1410 public:
1411 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1412 : matcher1_(matcher1), matcher2_(matcher2) {}
1413
zhanyong.wanc6a41232009-05-13 23:38:40 +00001414 virtual void DescribeTo(::std::ostream* os) const {
1415 *os << "(";
1416 matcher1_.DescribeTo(os);
1417 *os << ") and (";
1418 matcher2_.DescribeTo(os);
1419 *os << ")";
1420 }
1421
1422 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001423 *os << "(";
1424 matcher1_.DescribeNegationTo(os);
1425 *os << ") or (";
1426 matcher2_.DescribeNegationTo(os);
1427 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001428 }
1429
zhanyong.wan82113312010-01-08 21:55:40 +00001430 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1431 // If either matcher1_ or matcher2_ doesn't match x, we only need
1432 // to explain why one of them fails.
1433 StringMatchResultListener listener1;
1434 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1435 *listener << listener1.str();
1436 return false;
1437 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001438
zhanyong.wan82113312010-01-08 21:55:40 +00001439 StringMatchResultListener listener2;
1440 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1441 *listener << listener2.str();
1442 return false;
1443 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001444
zhanyong.wan82113312010-01-08 21:55:40 +00001445 // Otherwise we need to explain why *both* of them match.
1446 const internal::string s1 = listener1.str();
1447 const internal::string s2 = listener2.str();
1448
1449 if (s1 == "") {
1450 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001451 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001452 *listener << s1;
1453 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001454 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001455 }
1456 }
zhanyong.wan82113312010-01-08 21:55:40 +00001457 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001458 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001459
zhanyong.wanc6a41232009-05-13 23:38:40 +00001460 private:
1461 const Matcher<T> matcher1_;
1462 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001463
1464 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001465};
1466
zhanyong.wan616180e2013-06-18 18:49:51 +00001467#if GTEST_LANG_CXX11
1468// MatcherList provides mechanisms for storing a variable number of matchers in
1469// a list structure (ListType) and creating a combining matcher from such a
1470// list.
1471// The template is defined recursively using the following template paramters:
1472// * kSize is the length of the MatcherList.
1473// * Head is the type of the first matcher of the list.
1474// * Tail denotes the types of the remaining matchers of the list.
1475template <int kSize, typename Head, typename... Tail>
1476struct MatcherList {
1477 typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
zhanyong.wan29897032013-06-20 18:59:15 +00001478 typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001479
1480 // BuildList stores variadic type values in a nested pair structure.
1481 // Example:
1482 // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
1483 // the corresponding result of type pair<int, pair<string, float>>.
1484 static ListType BuildList(const Head& matcher, const Tail&... tail) {
1485 return ListType(matcher, MatcherListTail::BuildList(tail...));
1486 }
1487
1488 // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
1489 // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
1490 // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
1491 // constructor taking two Matcher<T>s as input.
1492 template <typename T, template <typename /* T */> class CombiningMatcher>
1493 static Matcher<T> CreateMatcher(const ListType& matchers) {
1494 return Matcher<T>(new CombiningMatcher<T>(
1495 SafeMatcherCast<T>(matchers.first),
1496 MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
1497 matchers.second)));
1498 }
1499};
1500
1501// The following defines the base case for the recursive definition of
1502// MatcherList.
1503template <typename Matcher1, typename Matcher2>
1504struct MatcherList<2, Matcher1, Matcher2> {
zhanyong.wan29897032013-06-20 18:59:15 +00001505 typedef ::std::pair<Matcher1, Matcher2> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001506
1507 static ListType BuildList(const Matcher1& matcher1,
1508 const Matcher2& matcher2) {
zhanyong.wan29897032013-06-20 18:59:15 +00001509 return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
zhanyong.wan616180e2013-06-18 18:49:51 +00001510 }
1511
1512 template <typename T, template <typename /* T */> class CombiningMatcher>
1513 static Matcher<T> CreateMatcher(const ListType& matchers) {
1514 return Matcher<T>(new CombiningMatcher<T>(
1515 SafeMatcherCast<T>(matchers.first),
1516 SafeMatcherCast<T>(matchers.second)));
1517 }
1518};
1519
1520// VariadicMatcher is used for the variadic implementation of
1521// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1522// CombiningMatcher<T> is used to recursively combine the provided matchers
1523// (of type Args...).
1524template <template <typename T> class CombiningMatcher, typename... Args>
1525class VariadicMatcher {
1526 public:
1527 VariadicMatcher(const Args&... matchers) // NOLINT
1528 : matchers_(MatcherListType::BuildList(matchers...)) {}
1529
1530 // This template type conversion operator allows an
1531 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1532 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1533 template <typename T>
1534 operator Matcher<T>() const {
1535 return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
1536 matchers_);
1537 }
1538
1539 private:
1540 typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
1541
1542 const typename MatcherListType::ListType matchers_;
1543
1544 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1545};
1546
1547template <typename... Args>
1548using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
1549
1550#endif // GTEST_LANG_CXX11
1551
shiqiane35fdd92008-12-10 05:08:54 +00001552// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1553// matches a value that matches all of the matchers m_1, ..., and m_n.
1554template <typename Matcher1, typename Matcher2>
1555class BothOfMatcher {
1556 public:
1557 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1558 : matcher1_(matcher1), matcher2_(matcher2) {}
1559
1560 // This template type conversion operator allows a
1561 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1562 // both Matcher1 and Matcher2 can match.
1563 template <typename T>
1564 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001565 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1566 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001567 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001568
shiqiane35fdd92008-12-10 05:08:54 +00001569 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001570 Matcher1 matcher1_;
1571 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001572
1573 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001574};
shiqiane35fdd92008-12-10 05:08:54 +00001575
zhanyong.wanc6a41232009-05-13 23:38:40 +00001576// Implements the AnyOf(m1, m2) matcher for a particular argument type
1577// T. We do not nest it inside the AnyOfMatcher class template, as
1578// that will prevent different instantiations of AnyOfMatcher from
1579// sharing the same EitherOfMatcherImpl<T> class.
1580template <typename T>
1581class EitherOfMatcherImpl : public MatcherInterface<T> {
1582 public:
1583 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1584 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001585
zhanyong.wanc6a41232009-05-13 23:38:40 +00001586 virtual void DescribeTo(::std::ostream* os) const {
1587 *os << "(";
1588 matcher1_.DescribeTo(os);
1589 *os << ") or (";
1590 matcher2_.DescribeTo(os);
1591 *os << ")";
1592 }
shiqiane35fdd92008-12-10 05:08:54 +00001593
zhanyong.wanc6a41232009-05-13 23:38:40 +00001594 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001595 *os << "(";
1596 matcher1_.DescribeNegationTo(os);
1597 *os << ") and (";
1598 matcher2_.DescribeNegationTo(os);
1599 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001600 }
shiqiane35fdd92008-12-10 05:08:54 +00001601
zhanyong.wan82113312010-01-08 21:55:40 +00001602 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1603 // If either matcher1_ or matcher2_ matches x, we just need to
1604 // explain why *one* of them matches.
1605 StringMatchResultListener listener1;
1606 if (matcher1_.MatchAndExplain(x, &listener1)) {
1607 *listener << listener1.str();
1608 return true;
1609 }
1610
1611 StringMatchResultListener listener2;
1612 if (matcher2_.MatchAndExplain(x, &listener2)) {
1613 *listener << listener2.str();
1614 return true;
1615 }
1616
1617 // Otherwise we need to explain why *both* of them fail.
1618 const internal::string s1 = listener1.str();
1619 const internal::string s2 = listener2.str();
1620
1621 if (s1 == "") {
1622 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001623 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001624 *listener << s1;
1625 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001626 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001627 }
1628 }
zhanyong.wan82113312010-01-08 21:55:40 +00001629 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001630 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001631
zhanyong.wanc6a41232009-05-13 23:38:40 +00001632 private:
1633 const Matcher<T> matcher1_;
1634 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001635
1636 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001637};
1638
zhanyong.wan616180e2013-06-18 18:49:51 +00001639#if GTEST_LANG_CXX11
1640// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1641template <typename... Args>
1642using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
1643
1644#endif // GTEST_LANG_CXX11
1645
shiqiane35fdd92008-12-10 05:08:54 +00001646// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1647// matches a value that matches at least one of the matchers m_1, ...,
1648// and m_n.
1649template <typename Matcher1, typename Matcher2>
1650class EitherOfMatcher {
1651 public:
1652 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1653 : matcher1_(matcher1), matcher2_(matcher2) {}
1654
1655 // This template type conversion operator allows a
1656 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1657 // both Matcher1 and Matcher2 can match.
1658 template <typename T>
1659 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001660 return Matcher<T>(new EitherOfMatcherImpl<T>(
1661 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001662 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001663
shiqiane35fdd92008-12-10 05:08:54 +00001664 private:
shiqiane35fdd92008-12-10 05:08:54 +00001665 Matcher1 matcher1_;
1666 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001667
1668 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001669};
1670
1671// Used for implementing Truly(pred), which turns a predicate into a
1672// matcher.
1673template <typename Predicate>
1674class TrulyMatcher {
1675 public:
1676 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1677
1678 // This method template allows Truly(pred) to be used as a matcher
1679 // for type T where T is the argument type of predicate 'pred'. The
1680 // argument is passed by reference as the predicate may be
1681 // interested in the address of the argument.
1682 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001683 bool MatchAndExplain(T& x, // NOLINT
1684 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001685 // Without the if-statement, MSVC sometimes warns about converting
1686 // a value to bool (warning 4800).
1687 //
1688 // We cannot write 'return !!predicate_(x);' as that doesn't work
1689 // when predicate_(x) returns a class convertible to bool but
1690 // having no operator!().
1691 if (predicate_(x))
1692 return true;
1693 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001694 }
1695
1696 void DescribeTo(::std::ostream* os) const {
1697 *os << "satisfies the given predicate";
1698 }
1699
1700 void DescribeNegationTo(::std::ostream* os) const {
1701 *os << "doesn't satisfy the given predicate";
1702 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001703
shiqiane35fdd92008-12-10 05:08:54 +00001704 private:
1705 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001706
1707 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001708};
1709
1710// Used for implementing Matches(matcher), which turns a matcher into
1711// a predicate.
1712template <typename M>
1713class MatcherAsPredicate {
1714 public:
1715 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1716
1717 // This template operator() allows Matches(m) to be used as a
1718 // predicate on type T where m is a matcher on type T.
1719 //
1720 // The argument x is passed by reference instead of by value, as
1721 // some matcher may be interested in its address (e.g. as in
1722 // Matches(Ref(n))(x)).
1723 template <typename T>
1724 bool operator()(const T& x) const {
1725 // We let matcher_ commit to a particular type here instead of
1726 // when the MatcherAsPredicate object was constructed. This
1727 // allows us to write Matches(m) where m is a polymorphic matcher
1728 // (e.g. Eq(5)).
1729 //
1730 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1731 // compile when matcher_ has type Matcher<const T&>; if we write
1732 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1733 // when matcher_ has type Matcher<T>; if we just write
1734 // matcher_.Matches(x), it won't compile when matcher_ is
1735 // polymorphic, e.g. Eq(5).
1736 //
1737 // MatcherCast<const T&>() is necessary for making the code work
1738 // in all of the above situations.
1739 return MatcherCast<const T&>(matcher_).Matches(x);
1740 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001741
shiqiane35fdd92008-12-10 05:08:54 +00001742 private:
1743 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001744
1745 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001746};
1747
1748// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1749// argument M must be a type that can be converted to a matcher.
1750template <typename M>
1751class PredicateFormatterFromMatcher {
1752 public:
1753 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1754
1755 // This template () operator allows a PredicateFormatterFromMatcher
1756 // object to act as a predicate-formatter suitable for using with
1757 // Google Test's EXPECT_PRED_FORMAT1() macro.
1758 template <typename T>
1759 AssertionResult operator()(const char* value_text, const T& x) const {
1760 // We convert matcher_ to a Matcher<const T&> *now* instead of
1761 // when the PredicateFormatterFromMatcher object was constructed,
1762 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1763 // know which type to instantiate it to until we actually see the
1764 // type of x here.
1765 //
zhanyong.wanf4274522013-04-24 02:49:43 +00001766 // We write SafeMatcherCast<const T&>(matcher_) instead of
shiqiane35fdd92008-12-10 05:08:54 +00001767 // Matcher<const T&>(matcher_), as the latter won't compile when
1768 // matcher_ has type Matcher<T> (e.g. An<int>()).
zhanyong.wanf4274522013-04-24 02:49:43 +00001769 // We don't write MatcherCast<const T&> either, as that allows
1770 // potentially unsafe downcasting of the matcher argument.
1771 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001772 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001773 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001774 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001775
1776 ::std::stringstream ss;
1777 ss << "Value of: " << value_text << "\n"
1778 << "Expected: ";
1779 matcher.DescribeTo(&ss);
1780 ss << "\n Actual: " << listener.str();
1781 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001782 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001783
shiqiane35fdd92008-12-10 05:08:54 +00001784 private:
1785 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001786
1787 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001788};
1789
1790// A helper function for converting a matcher to a predicate-formatter
1791// without the user needing to explicitly write the type. This is
1792// used for implementing ASSERT_THAT() and EXPECT_THAT().
1793template <typename M>
1794inline PredicateFormatterFromMatcher<M>
1795MakePredicateFormatterFromMatcher(const M& matcher) {
1796 return PredicateFormatterFromMatcher<M>(matcher);
1797}
1798
zhanyong.wan616180e2013-06-18 18:49:51 +00001799// Implements the polymorphic floating point equality matcher, which matches
1800// two float values using ULP-based approximation or, optionally, a
1801// user-specified epsilon. The template is meant to be instantiated with
1802// FloatType being either float or double.
shiqiane35fdd92008-12-10 05:08:54 +00001803template <typename FloatType>
1804class FloatingEqMatcher {
1805 public:
1806 // Constructor for FloatingEqMatcher.
1807 // The matcher's input will be compared with rhs. The matcher treats two
1808 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
zhanyong.wan616180e2013-06-18 18:49:51 +00001809 // equality comparisons between NANs will always return false. We specify a
1810 // negative max_abs_error_ term to indicate that ULP-based approximation will
1811 // be used for comparison.
shiqiane35fdd92008-12-10 05:08:54 +00001812 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
zhanyong.wan616180e2013-06-18 18:49:51 +00001813 rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
1814 }
1815
1816 // Constructor that supports a user-specified max_abs_error that will be used
1817 // for comparison instead of ULP-based approximation. The max absolute
1818 // should be non-negative.
1819 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan, FloatType max_abs_error) :
1820 rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) {
1821 GTEST_CHECK_(max_abs_error >= 0)
1822 << ", where max_abs_error is" << max_abs_error;
1823 }
shiqiane35fdd92008-12-10 05:08:54 +00001824
1825 // Implements floating point equality matcher as a Matcher<T>.
1826 template <typename T>
1827 class Impl : public MatcherInterface<T> {
1828 public:
zhanyong.wan616180e2013-06-18 18:49:51 +00001829 Impl(FloatType rhs, bool nan_eq_nan, FloatType max_abs_error) :
1830 rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) {}
shiqiane35fdd92008-12-10 05:08:54 +00001831
zhanyong.wan82113312010-01-08 21:55:40 +00001832 virtual bool MatchAndExplain(T value,
1833 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001834 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1835
1836 // Compares NaNs first, if nan_eq_nan_ is true.
zhanyong.wan616180e2013-06-18 18:49:51 +00001837 if (lhs.is_nan() || rhs.is_nan()) {
1838 if (lhs.is_nan() && rhs.is_nan()) {
1839 return nan_eq_nan_;
1840 }
1841 // One is nan; the other is not nan.
1842 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001843 }
zhanyong.wan616180e2013-06-18 18:49:51 +00001844 if (HasMaxAbsError()) {
1845 // We perform an equality check so that inf will match inf, regardless
1846 // of error bounds. If the result of value - rhs_ would result in
1847 // overflow or if either value is inf, the default result is infinity,
1848 // which should only match if max_abs_error_ is also infinity.
1849 return value == rhs_ || fabs(value - rhs_) <= max_abs_error_;
1850 } else {
1851 return lhs.AlmostEquals(rhs);
1852 }
shiqiane35fdd92008-12-10 05:08:54 +00001853 }
1854
1855 virtual void DescribeTo(::std::ostream* os) const {
1856 // os->precision() returns the previously set precision, which we
1857 // store to restore the ostream to its original configuration
1858 // after outputting.
1859 const ::std::streamsize old_precision = os->precision(
1860 ::std::numeric_limits<FloatType>::digits10 + 2);
1861 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1862 if (nan_eq_nan_) {
1863 *os << "is NaN";
1864 } else {
1865 *os << "never matches";
1866 }
1867 } else {
1868 *os << "is approximately " << rhs_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001869 if (HasMaxAbsError()) {
1870 *os << " (absolute error <= " << max_abs_error_ << ")";
1871 }
shiqiane35fdd92008-12-10 05:08:54 +00001872 }
1873 os->precision(old_precision);
1874 }
1875
1876 virtual void DescribeNegationTo(::std::ostream* os) const {
1877 // As before, get original precision.
1878 const ::std::streamsize old_precision = os->precision(
1879 ::std::numeric_limits<FloatType>::digits10 + 2);
1880 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1881 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001882 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00001883 } else {
1884 *os << "is anything";
1885 }
1886 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001887 *os << "isn't approximately " << rhs_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001888 if (HasMaxAbsError()) {
1889 *os << " (absolute error > " << max_abs_error_ << ")";
1890 }
shiqiane35fdd92008-12-10 05:08:54 +00001891 }
1892 // Restore original precision.
1893 os->precision(old_precision);
1894 }
1895
1896 private:
zhanyong.wan616180e2013-06-18 18:49:51 +00001897 bool HasMaxAbsError() const {
1898 return max_abs_error_ >= 0;
1899 }
1900
shiqiane35fdd92008-12-10 05:08:54 +00001901 const FloatType rhs_;
1902 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001903 // max_abs_error will be used for value comparison when >= 0.
1904 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001905
1906 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001907 };
1908
1909 // The following 3 type conversion operators allow FloatEq(rhs) and
1910 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1911 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1912 // (While Google's C++ coding style doesn't allow arguments passed
1913 // by non-const reference, we may see them in code not conforming to
1914 // the style. Therefore Google Mock needs to support them.)
1915 operator Matcher<FloatType>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00001916 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00001917 }
1918
1919 operator Matcher<const FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00001920 return MakeMatcher(
1921 new Impl<const FloatType&>(rhs_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00001922 }
1923
1924 operator Matcher<FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00001925 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00001926 }
jgm79a367e2012-04-10 16:02:11 +00001927
shiqiane35fdd92008-12-10 05:08:54 +00001928 private:
1929 const FloatType rhs_;
1930 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001931 // max_abs_error will be used for value comparison when >= 0.
1932 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001933
1934 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001935};
1936
1937// Implements the Pointee(m) matcher for matching a pointer whose
1938// pointee matches matcher m. The pointer can be either raw or smart.
1939template <typename InnerMatcher>
1940class PointeeMatcher {
1941 public:
1942 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1943
1944 // This type conversion operator template allows Pointee(m) to be
1945 // used as a matcher for any pointer type whose pointee type is
1946 // compatible with the inner matcher, where type Pointer can be
1947 // either a raw pointer or a smart pointer.
1948 //
1949 // The reason we do this instead of relying on
1950 // MakePolymorphicMatcher() is that the latter is not flexible
1951 // enough for implementing the DescribeTo() method of Pointee().
1952 template <typename Pointer>
1953 operator Matcher<Pointer>() const {
1954 return MakeMatcher(new Impl<Pointer>(matcher_));
1955 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001956
shiqiane35fdd92008-12-10 05:08:54 +00001957 private:
1958 // The monomorphic implementation that works for a particular pointer type.
1959 template <typename Pointer>
1960 class Impl : public MatcherInterface<Pointer> {
1961 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00001962 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
1963 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001964
1965 explicit Impl(const InnerMatcher& matcher)
1966 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1967
shiqiane35fdd92008-12-10 05:08:54 +00001968 virtual void DescribeTo(::std::ostream* os) const {
1969 *os << "points to a value that ";
1970 matcher_.DescribeTo(os);
1971 }
1972
1973 virtual void DescribeNegationTo(::std::ostream* os) const {
1974 *os << "does not point to a value that ";
1975 matcher_.DescribeTo(os);
1976 }
1977
zhanyong.wan82113312010-01-08 21:55:40 +00001978 virtual bool MatchAndExplain(Pointer pointer,
1979 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001980 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001981 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001982
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001983 *listener << "which points to ";
1984 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001985 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001986
shiqiane35fdd92008-12-10 05:08:54 +00001987 private:
1988 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001989
1990 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001991 };
1992
1993 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001994
1995 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001996};
1997
1998// Implements the Field() matcher for matching a field (i.e. member
1999// variable) of an object.
2000template <typename Class, typename FieldType>
2001class FieldMatcher {
2002 public:
2003 FieldMatcher(FieldType Class::*field,
2004 const Matcher<const FieldType&>& matcher)
2005 : field_(field), matcher_(matcher) {}
2006
shiqiane35fdd92008-12-10 05:08:54 +00002007 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002008 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002009 matcher_.DescribeTo(os);
2010 }
2011
2012 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002013 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002014 matcher_.DescribeNegationTo(os);
2015 }
2016
zhanyong.wandb22c222010-01-28 21:52:29 +00002017 template <typename T>
2018 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2019 return MatchAndExplainImpl(
2020 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002021 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002022 value, listener);
2023 }
2024
2025 private:
2026 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002027 // Symbian's C++ compiler choose which overload to use. Its type is
2028 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002029 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2030 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002031 *listener << "whose given field is ";
2032 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002033 }
2034
zhanyong.wandb22c222010-01-28 21:52:29 +00002035 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2036 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002037 if (p == NULL)
2038 return false;
2039
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002040 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002041 // Since *p has a field, it must be a class/struct/union type and
2042 // thus cannot be a pointer. Therefore we pass false_type() as
2043 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002044 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002045 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002046
shiqiane35fdd92008-12-10 05:08:54 +00002047 const FieldType Class::*field_;
2048 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002049
2050 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002051};
2052
shiqiane35fdd92008-12-10 05:08:54 +00002053// Implements the Property() matcher for matching a property
2054// (i.e. return value of a getter method) of an object.
2055template <typename Class, typename PropertyType>
2056class PropertyMatcher {
2057 public:
2058 // The property may have a reference type, so 'const PropertyType&'
2059 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00002060 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00002061 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00002062 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00002063
2064 PropertyMatcher(PropertyType (Class::*property)() const,
2065 const Matcher<RefToConstProperty>& matcher)
2066 : property_(property), matcher_(matcher) {}
2067
shiqiane35fdd92008-12-10 05:08:54 +00002068 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002069 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002070 matcher_.DescribeTo(os);
2071 }
2072
2073 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002074 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002075 matcher_.DescribeNegationTo(os);
2076 }
2077
zhanyong.wandb22c222010-01-28 21:52:29 +00002078 template <typename T>
2079 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2080 return MatchAndExplainImpl(
2081 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002082 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002083 value, listener);
2084 }
2085
2086 private:
2087 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002088 // Symbian's C++ compiler choose which overload to use. Its type is
2089 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002090 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2091 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002092 *listener << "whose given property is ";
2093 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2094 // which takes a non-const reference as argument.
2095 RefToConstProperty result = (obj.*property_)();
2096 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002097 }
2098
zhanyong.wandb22c222010-01-28 21:52:29 +00002099 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2100 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002101 if (p == NULL)
2102 return false;
2103
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002104 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002105 // Since *p has a property method, it must be a class/struct/union
2106 // type and thus cannot be a pointer. Therefore we pass
2107 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002108 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002109 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002110
shiqiane35fdd92008-12-10 05:08:54 +00002111 PropertyType (Class::*property_)() const;
2112 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002113
2114 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002115};
2116
shiqiane35fdd92008-12-10 05:08:54 +00002117// Type traits specifying various features of different functors for ResultOf.
2118// The default template specifies features for functor objects.
2119// Functor classes have to typedef argument_type and result_type
2120// to be compatible with ResultOf.
2121template <typename Functor>
2122struct CallableTraits {
2123 typedef typename Functor::result_type ResultType;
2124 typedef Functor StorageType;
2125
zhanyong.wan32de5f52009-12-23 00:13:23 +00002126 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00002127 template <typename T>
2128 static ResultType Invoke(Functor f, T arg) { return f(arg); }
2129};
2130
2131// Specialization for function pointers.
2132template <typename ArgType, typename ResType>
2133struct CallableTraits<ResType(*)(ArgType)> {
2134 typedef ResType ResultType;
2135 typedef ResType(*StorageType)(ArgType);
2136
2137 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002138 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00002139 << "NULL function pointer is passed into ResultOf().";
2140 }
2141 template <typename T>
2142 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2143 return (*f)(arg);
2144 }
2145};
2146
2147// Implements the ResultOf() matcher for matching a return value of a
2148// unary function of an object.
2149template <typename Callable>
2150class ResultOfMatcher {
2151 public:
2152 typedef typename CallableTraits<Callable>::ResultType ResultType;
2153
2154 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
2155 : callable_(callable), matcher_(matcher) {
2156 CallableTraits<Callable>::CheckIsValid(callable_);
2157 }
2158
2159 template <typename T>
2160 operator Matcher<T>() const {
2161 return Matcher<T>(new Impl<T>(callable_, matcher_));
2162 }
2163
2164 private:
2165 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2166
2167 template <typename T>
2168 class Impl : public MatcherInterface<T> {
2169 public:
2170 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
2171 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00002172
2173 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002174 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002175 matcher_.DescribeTo(os);
2176 }
2177
2178 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002179 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002180 matcher_.DescribeNegationTo(os);
2181 }
2182
zhanyong.wan82113312010-01-08 21:55:40 +00002183 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002184 *listener << "which is mapped by the given callable to ";
2185 // Cannot pass the return value (for example, int) to
2186 // MatchPrintAndExplain, which takes a non-const reference as argument.
2187 ResultType result =
2188 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2189 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002190 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002191
shiqiane35fdd92008-12-10 05:08:54 +00002192 private:
2193 // Functors often define operator() as non-const method even though
2194 // they are actualy stateless. But we need to use them even when
2195 // 'this' is a const pointer. It's the user's responsibility not to
2196 // use stateful callables with ResultOf(), which does't guarantee
2197 // how many times the callable will be invoked.
2198 mutable CallableStorageType callable_;
2199 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002200
2201 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002202 }; // class Impl
2203
2204 const CallableStorageType callable_;
2205 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002206
2207 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002208};
2209
zhanyong.wana31d9ce2013-03-01 01:50:17 +00002210// Implements a matcher that checks the size of an STL-style container.
2211template <typename SizeMatcher>
2212class SizeIsMatcher {
2213 public:
2214 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2215 : size_matcher_(size_matcher) {
2216 }
2217
2218 template <typename Container>
2219 operator Matcher<Container>() const {
2220 return MakeMatcher(new Impl<Container>(size_matcher_));
2221 }
2222
2223 template <typename Container>
2224 class Impl : public MatcherInterface<Container> {
2225 public:
2226 typedef internal::StlContainerView<
2227 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2228 typedef typename ContainerView::type::size_type SizeType;
2229 explicit Impl(const SizeMatcher& size_matcher)
2230 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2231
2232 virtual void DescribeTo(::std::ostream* os) const {
2233 *os << "size ";
2234 size_matcher_.DescribeTo(os);
2235 }
2236 virtual void DescribeNegationTo(::std::ostream* os) const {
2237 *os << "size ";
2238 size_matcher_.DescribeNegationTo(os);
2239 }
2240
2241 virtual bool MatchAndExplain(Container container,
2242 MatchResultListener* listener) const {
2243 SizeType size = container.size();
2244 StringMatchResultListener size_listener;
2245 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2246 *listener
2247 << "whose size " << size << (result ? " matches" : " doesn't match");
2248 PrintIfNotEmpty(size_listener.str(), listener->stream());
2249 return result;
2250 }
2251
2252 private:
2253 const Matcher<SizeType> size_matcher_;
2254 GTEST_DISALLOW_ASSIGN_(Impl);
2255 };
2256
2257 private:
2258 const SizeMatcher size_matcher_;
2259 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2260};
2261
zhanyong.wan6a896b52009-01-16 01:13:50 +00002262// Implements an equality matcher for any STL-style container whose elements
2263// support ==. This matcher is like Eq(), but its failure explanations provide
2264// more detailed information that is useful when the container is used as a set.
2265// The failure message reports elements that are in one of the operands but not
2266// the other. The failure messages do not report duplicate or out-of-order
2267// elements in the containers (which don't properly matter to sets, but can
2268// occur if the containers are vectors or lists, for example).
2269//
2270// Uses the container's const_iterator, value_type, operator ==,
2271// begin(), and end().
2272template <typename Container>
2273class ContainerEqMatcher {
2274 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002275 typedef internal::StlContainerView<Container> View;
2276 typedef typename View::type StlContainer;
2277 typedef typename View::const_reference StlContainerReference;
2278
2279 // We make a copy of rhs in case the elements in it are modified
2280 // after this matcher is created.
2281 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
2282 // Makes sure the user doesn't instantiate this class template
2283 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002284 (void)testing::StaticAssertTypeEq<Container,
2285 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002286 }
2287
zhanyong.wan6a896b52009-01-16 01:13:50 +00002288 void DescribeTo(::std::ostream* os) const {
2289 *os << "equals ";
vladloseve2e8ba42010-05-13 18:16:03 +00002290 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002291 }
2292 void DescribeNegationTo(::std::ostream* os) const {
2293 *os << "does not equal ";
vladloseve2e8ba42010-05-13 18:16:03 +00002294 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002295 }
2296
zhanyong.wanb8243162009-06-04 05:48:20 +00002297 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002298 bool MatchAndExplain(const LhsContainer& lhs,
2299 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002300 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002301 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002302 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002303 LhsView;
2304 typedef typename LhsView::type LhsStlContainer;
2305 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00002306 if (lhs_stl_container == rhs_)
2307 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002308
zhanyong.wane122e452010-01-12 09:03:52 +00002309 ::std::ostream* const os = listener->stream();
2310 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002311 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002312 bool printed_header = false;
2313 for (typename LhsStlContainer::const_iterator it =
2314 lhs_stl_container.begin();
2315 it != lhs_stl_container.end(); ++it) {
2316 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
2317 rhs_.end()) {
2318 if (printed_header) {
2319 *os << ", ";
2320 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002321 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002322 printed_header = true;
2323 }
vladloseve2e8ba42010-05-13 18:16:03 +00002324 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002325 }
zhanyong.wane122e452010-01-12 09:03:52 +00002326 }
2327
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002328 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002329 bool printed_header2 = false;
2330 for (typename StlContainer::const_iterator it = rhs_.begin();
2331 it != rhs_.end(); ++it) {
2332 if (internal::ArrayAwareFind(
2333 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2334 lhs_stl_container.end()) {
2335 if (printed_header2) {
2336 *os << ", ";
2337 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002338 *os << (printed_header ? ",\nand" : "which")
2339 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002340 printed_header2 = true;
2341 }
vladloseve2e8ba42010-05-13 18:16:03 +00002342 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002343 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002344 }
2345 }
2346
zhanyong.wane122e452010-01-12 09:03:52 +00002347 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002348 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002349
zhanyong.wan6a896b52009-01-16 01:13:50 +00002350 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00002351 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002352
2353 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002354};
2355
zhanyong.wan898725c2011-09-16 16:45:39 +00002356// A comparator functor that uses the < operator to compare two values.
2357struct LessComparator {
2358 template <typename T, typename U>
2359 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2360};
2361
2362// Implements WhenSortedBy(comparator, container_matcher).
2363template <typename Comparator, typename ContainerMatcher>
2364class WhenSortedByMatcher {
2365 public:
2366 WhenSortedByMatcher(const Comparator& comparator,
2367 const ContainerMatcher& matcher)
2368 : comparator_(comparator), matcher_(matcher) {}
2369
2370 template <typename LhsContainer>
2371 operator Matcher<LhsContainer>() const {
2372 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2373 }
2374
2375 template <typename LhsContainer>
2376 class Impl : public MatcherInterface<LhsContainer> {
2377 public:
2378 typedef internal::StlContainerView<
2379 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2380 typedef typename LhsView::type LhsStlContainer;
2381 typedef typename LhsView::const_reference LhsStlContainerReference;
zhanyong.wana9a59e02013-03-27 16:14:55 +00002382 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2383 // so that we can match associative containers.
2384 typedef typename RemoveConstFromKey<
2385 typename LhsStlContainer::value_type>::type LhsValue;
zhanyong.wan898725c2011-09-16 16:45:39 +00002386
2387 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2388 : comparator_(comparator), matcher_(matcher) {}
2389
2390 virtual void DescribeTo(::std::ostream* os) const {
2391 *os << "(when sorted) ";
2392 matcher_.DescribeTo(os);
2393 }
2394
2395 virtual void DescribeNegationTo(::std::ostream* os) const {
2396 *os << "(when sorted) ";
2397 matcher_.DescribeNegationTo(os);
2398 }
2399
2400 virtual bool MatchAndExplain(LhsContainer lhs,
2401 MatchResultListener* listener) const {
2402 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wanfb25d532013-07-28 08:24:00 +00002403 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2404 lhs_stl_container.end());
2405 ::std::sort(
2406 sorted_container.begin(), sorted_container.end(), comparator_);
zhanyong.wan898725c2011-09-16 16:45:39 +00002407
2408 if (!listener->IsInterested()) {
2409 // If the listener is not interested, we do not need to
2410 // construct the inner explanation.
2411 return matcher_.Matches(sorted_container);
2412 }
2413
2414 *listener << "which is ";
2415 UniversalPrint(sorted_container, listener->stream());
2416 *listener << " when sorted";
2417
2418 StringMatchResultListener inner_listener;
2419 const bool match = matcher_.MatchAndExplain(sorted_container,
2420 &inner_listener);
2421 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2422 return match;
2423 }
2424
2425 private:
2426 const Comparator comparator_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00002427 const Matcher<const ::std::vector<LhsValue>&> matcher_;
zhanyong.wan898725c2011-09-16 16:45:39 +00002428
2429 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2430 };
2431
2432 private:
2433 const Comparator comparator_;
2434 const ContainerMatcher matcher_;
2435
2436 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2437};
2438
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002439// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2440// must be able to be safely cast to Matcher<tuple<const T1&, const
2441// T2&> >, where T1 and T2 are the types of elements in the LHS
2442// container and the RHS container respectively.
2443template <typename TupleMatcher, typename RhsContainer>
2444class PointwiseMatcher {
2445 public:
2446 typedef internal::StlContainerView<RhsContainer> RhsView;
2447 typedef typename RhsView::type RhsStlContainer;
2448 typedef typename RhsStlContainer::value_type RhsValue;
2449
2450 // Like ContainerEq, we make a copy of rhs in case the elements in
2451 // it are modified after this matcher is created.
2452 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2453 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2454 // Makes sure the user doesn't instantiate this class template
2455 // with a const or reference type.
2456 (void)testing::StaticAssertTypeEq<RhsContainer,
2457 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2458 }
2459
2460 template <typename LhsContainer>
2461 operator Matcher<LhsContainer>() const {
2462 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2463 }
2464
2465 template <typename LhsContainer>
2466 class Impl : public MatcherInterface<LhsContainer> {
2467 public:
2468 typedef internal::StlContainerView<
2469 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2470 typedef typename LhsView::type LhsStlContainer;
2471 typedef typename LhsView::const_reference LhsStlContainerReference;
2472 typedef typename LhsStlContainer::value_type LhsValue;
2473 // We pass the LHS value and the RHS value to the inner matcher by
2474 // reference, as they may be expensive to copy. We must use tuple
2475 // instead of pair here, as a pair cannot hold references (C++ 98,
2476 // 20.2.2 [lib.pairs]).
zhanyong.wanfb25d532013-07-28 08:24:00 +00002477 typedef ::std::tr1::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002478
2479 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2480 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2481 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2482 rhs_(rhs) {}
2483
2484 virtual void DescribeTo(::std::ostream* os) const {
2485 *os << "contains " << rhs_.size()
2486 << " values, where each value and its corresponding value in ";
2487 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2488 *os << " ";
2489 mono_tuple_matcher_.DescribeTo(os);
2490 }
2491 virtual void DescribeNegationTo(::std::ostream* os) const {
2492 *os << "doesn't contain exactly " << rhs_.size()
2493 << " values, or contains a value x at some index i"
2494 << " where x and the i-th value of ";
2495 UniversalPrint(rhs_, os);
2496 *os << " ";
2497 mono_tuple_matcher_.DescribeNegationTo(os);
2498 }
2499
2500 virtual bool MatchAndExplain(LhsContainer lhs,
2501 MatchResultListener* listener) const {
2502 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2503 const size_t actual_size = lhs_stl_container.size();
2504 if (actual_size != rhs_.size()) {
2505 *listener << "which contains " << actual_size << " values";
2506 return false;
2507 }
2508
2509 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2510 typename RhsStlContainer::const_iterator right = rhs_.begin();
2511 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2512 const InnerMatcherArg value_pair(*left, *right);
2513
2514 if (listener->IsInterested()) {
2515 StringMatchResultListener inner_listener;
2516 if (!mono_tuple_matcher_.MatchAndExplain(
2517 value_pair, &inner_listener)) {
2518 *listener << "where the value pair (";
2519 UniversalPrint(*left, listener->stream());
2520 *listener << ", ";
2521 UniversalPrint(*right, listener->stream());
2522 *listener << ") at index #" << i << " don't match";
2523 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2524 return false;
2525 }
2526 } else {
2527 if (!mono_tuple_matcher_.Matches(value_pair))
2528 return false;
2529 }
2530 }
2531
2532 return true;
2533 }
2534
2535 private:
2536 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2537 const RhsStlContainer rhs_;
2538
2539 GTEST_DISALLOW_ASSIGN_(Impl);
2540 };
2541
2542 private:
2543 const TupleMatcher tuple_matcher_;
2544 const RhsStlContainer rhs_;
2545
2546 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2547};
2548
zhanyong.wan33605ba2010-04-22 23:37:47 +00002549// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002550template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002551class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002552 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002553 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002554 typedef StlContainerView<RawContainer> View;
2555 typedef typename View::type StlContainer;
2556 typedef typename View::const_reference StlContainerReference;
2557 typedef typename StlContainer::value_type Element;
2558
2559 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002560 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002561 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002562 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002563
zhanyong.wan33605ba2010-04-22 23:37:47 +00002564 // Checks whether:
2565 // * All elements in the container match, if all_elements_should_match.
2566 // * Any element in the container matches, if !all_elements_should_match.
2567 bool MatchAndExplainImpl(bool all_elements_should_match,
2568 Container container,
2569 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002570 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002571 size_t i = 0;
2572 for (typename StlContainer::const_iterator it = stl_container.begin();
2573 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002574 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002575 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2576
2577 if (matches != all_elements_should_match) {
2578 *listener << "whose element #" << i
2579 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002580 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002581 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002582 }
2583 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002584 return all_elements_should_match;
2585 }
2586
2587 protected:
2588 const Matcher<const Element&> inner_matcher_;
2589
2590 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2591};
2592
2593// Implements Contains(element_matcher) for the given argument type Container.
2594// Symmetric to EachMatcherImpl.
2595template <typename Container>
2596class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2597 public:
2598 template <typename InnerMatcher>
2599 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2600 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2601
2602 // Describes what this matcher does.
2603 virtual void DescribeTo(::std::ostream* os) const {
2604 *os << "contains at least one element that ";
2605 this->inner_matcher_.DescribeTo(os);
2606 }
2607
2608 virtual void DescribeNegationTo(::std::ostream* os) const {
2609 *os << "doesn't contain any element that ";
2610 this->inner_matcher_.DescribeTo(os);
2611 }
2612
2613 virtual bool MatchAndExplain(Container container,
2614 MatchResultListener* listener) const {
2615 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002616 }
2617
2618 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002619 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002620};
2621
zhanyong.wan33605ba2010-04-22 23:37:47 +00002622// Implements Each(element_matcher) for the given argument type Container.
2623// Symmetric to ContainsMatcherImpl.
2624template <typename Container>
2625class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2626 public:
2627 template <typename InnerMatcher>
2628 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2629 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2630
2631 // Describes what this matcher does.
2632 virtual void DescribeTo(::std::ostream* os) const {
2633 *os << "only contains elements that ";
2634 this->inner_matcher_.DescribeTo(os);
2635 }
2636
2637 virtual void DescribeNegationTo(::std::ostream* os) const {
2638 *os << "contains some element that ";
2639 this->inner_matcher_.DescribeNegationTo(os);
2640 }
2641
2642 virtual bool MatchAndExplain(Container container,
2643 MatchResultListener* listener) const {
2644 return this->MatchAndExplainImpl(true, container, listener);
2645 }
2646
2647 private:
2648 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2649};
2650
zhanyong.wanb8243162009-06-04 05:48:20 +00002651// Implements polymorphic Contains(element_matcher).
2652template <typename M>
2653class ContainsMatcher {
2654 public:
2655 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2656
2657 template <typename Container>
2658 operator Matcher<Container>() const {
2659 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2660 }
2661
2662 private:
2663 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002664
2665 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002666};
2667
zhanyong.wan33605ba2010-04-22 23:37:47 +00002668// Implements polymorphic Each(element_matcher).
2669template <typename M>
2670class EachMatcher {
2671 public:
2672 explicit EachMatcher(M m) : inner_matcher_(m) {}
2673
2674 template <typename Container>
2675 operator Matcher<Container>() const {
2676 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2677 }
2678
2679 private:
2680 const M inner_matcher_;
2681
2682 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2683};
2684
zhanyong.wanb5937da2009-07-16 20:26:41 +00002685// Implements Key(inner_matcher) for the given argument pair type.
2686// Key(inner_matcher) matches an std::pair whose 'first' field matches
2687// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2688// std::map that contains at least one element whose key is >= 5.
2689template <typename PairType>
2690class KeyMatcherImpl : public MatcherInterface<PairType> {
2691 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002692 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002693 typedef typename RawPairType::first_type KeyType;
2694
2695 template <typename InnerMatcher>
2696 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2697 : inner_matcher_(
2698 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2699 }
2700
2701 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002702 virtual bool MatchAndExplain(PairType key_value,
2703 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002704 StringMatchResultListener inner_listener;
2705 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2706 &inner_listener);
2707 const internal::string explanation = inner_listener.str();
2708 if (explanation != "") {
2709 *listener << "whose first field is a value " << explanation;
2710 }
2711 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002712 }
2713
2714 // Describes what this matcher does.
2715 virtual void DescribeTo(::std::ostream* os) const {
2716 *os << "has a key that ";
2717 inner_matcher_.DescribeTo(os);
2718 }
2719
2720 // Describes what the negation of this matcher does.
2721 virtual void DescribeNegationTo(::std::ostream* os) const {
2722 *os << "doesn't have a key that ";
2723 inner_matcher_.DescribeTo(os);
2724 }
2725
zhanyong.wanb5937da2009-07-16 20:26:41 +00002726 private:
2727 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002728
2729 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002730};
2731
2732// Implements polymorphic Key(matcher_for_key).
2733template <typename M>
2734class KeyMatcher {
2735 public:
2736 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2737
2738 template <typename PairType>
2739 operator Matcher<PairType>() const {
2740 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2741 }
2742
2743 private:
2744 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002745
2746 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002747};
2748
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002749// Implements Pair(first_matcher, second_matcher) for the given argument pair
2750// type with its two matchers. See Pair() function below.
2751template <typename PairType>
2752class PairMatcherImpl : public MatcherInterface<PairType> {
2753 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002754 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002755 typedef typename RawPairType::first_type FirstType;
2756 typedef typename RawPairType::second_type SecondType;
2757
2758 template <typename FirstMatcher, typename SecondMatcher>
2759 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2760 : first_matcher_(
2761 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2762 second_matcher_(
2763 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2764 }
2765
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002766 // Describes what this matcher does.
2767 virtual void DescribeTo(::std::ostream* os) const {
2768 *os << "has a first field that ";
2769 first_matcher_.DescribeTo(os);
2770 *os << ", and has a second field that ";
2771 second_matcher_.DescribeTo(os);
2772 }
2773
2774 // Describes what the negation of this matcher does.
2775 virtual void DescribeNegationTo(::std::ostream* os) const {
2776 *os << "has a first field that ";
2777 first_matcher_.DescribeNegationTo(os);
2778 *os << ", or has a second field that ";
2779 second_matcher_.DescribeNegationTo(os);
2780 }
2781
zhanyong.wan82113312010-01-08 21:55:40 +00002782 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2783 // matches second_matcher.
2784 virtual bool MatchAndExplain(PairType a_pair,
2785 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002786 if (!listener->IsInterested()) {
2787 // If the listener is not interested, we don't need to construct the
2788 // explanation.
2789 return first_matcher_.Matches(a_pair.first) &&
2790 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00002791 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002792 StringMatchResultListener first_inner_listener;
2793 if (!first_matcher_.MatchAndExplain(a_pair.first,
2794 &first_inner_listener)) {
2795 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002796 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002797 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002798 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002799 StringMatchResultListener second_inner_listener;
2800 if (!second_matcher_.MatchAndExplain(a_pair.second,
2801 &second_inner_listener)) {
2802 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002803 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002804 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002805 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002806 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2807 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002808 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002809 }
2810
2811 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002812 void ExplainSuccess(const internal::string& first_explanation,
2813 const internal::string& second_explanation,
2814 MatchResultListener* listener) const {
2815 *listener << "whose both fields match";
2816 if (first_explanation != "") {
2817 *listener << ", where the first field is a value " << first_explanation;
2818 }
2819 if (second_explanation != "") {
2820 *listener << ", ";
2821 if (first_explanation != "") {
2822 *listener << "and ";
2823 } else {
2824 *listener << "where ";
2825 }
2826 *listener << "the second field is a value " << second_explanation;
2827 }
2828 }
2829
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002830 const Matcher<const FirstType&> first_matcher_;
2831 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002832
2833 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002834};
2835
2836// Implements polymorphic Pair(first_matcher, second_matcher).
2837template <typename FirstMatcher, typename SecondMatcher>
2838class PairMatcher {
2839 public:
2840 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2841 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2842
2843 template <typename PairType>
2844 operator Matcher<PairType> () const {
2845 return MakeMatcher(
2846 new PairMatcherImpl<PairType>(
2847 first_matcher_, second_matcher_));
2848 }
2849
2850 private:
2851 const FirstMatcher first_matcher_;
2852 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002853
2854 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002855};
2856
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002857// Implements ElementsAre() and ElementsAreArray().
2858template <typename Container>
2859class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2860 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002861 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002862 typedef internal::StlContainerView<RawContainer> View;
2863 typedef typename View::type StlContainer;
2864 typedef typename View::const_reference StlContainerReference;
2865 typedef typename StlContainer::value_type Element;
2866
2867 // Constructs the matcher from a sequence of element values or
2868 // element matchers.
2869 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00002870 ElementsAreMatcherImpl(InputIter first, InputIter last) {
2871 while (first != last) {
2872 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002873 }
2874 }
2875
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002876 // Describes what this matcher does.
2877 virtual void DescribeTo(::std::ostream* os) const {
2878 if (count() == 0) {
2879 *os << "is empty";
2880 } else if (count() == 1) {
2881 *os << "has 1 element that ";
2882 matchers_[0].DescribeTo(os);
2883 } else {
2884 *os << "has " << Elements(count()) << " where\n";
2885 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002886 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002887 matchers_[i].DescribeTo(os);
2888 if (i + 1 < count()) {
2889 *os << ",\n";
2890 }
2891 }
2892 }
2893 }
2894
2895 // Describes what the negation of this matcher does.
2896 virtual void DescribeNegationTo(::std::ostream* os) const {
2897 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002898 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002899 return;
2900 }
2901
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002902 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002903 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002904 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002905 matchers_[i].DescribeNegationTo(os);
2906 if (i + 1 < count()) {
2907 *os << ", or\n";
2908 }
2909 }
2910 }
2911
zhanyong.wan82113312010-01-08 21:55:40 +00002912 virtual bool MatchAndExplain(Container container,
2913 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002914 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002915 const size_t actual_count = stl_container.size();
2916 if (actual_count != count()) {
2917 // The element count doesn't match. If the container is empty,
2918 // there's no need to explain anything as Google Mock already
2919 // prints the empty container. Otherwise we just need to show
2920 // how many elements there actually are.
zhanyong.wanfb25d532013-07-28 08:24:00 +00002921 if (actual_count != 0 && listener->IsInterested()) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002922 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002923 }
zhanyong.wan82113312010-01-08 21:55:40 +00002924 return false;
2925 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002926
zhanyong.wan82113312010-01-08 21:55:40 +00002927 typename StlContainer::const_iterator it = stl_container.begin();
2928 // explanations[i] is the explanation of the element at index i.
zhanyong.wanfb25d532013-07-28 08:24:00 +00002929 ::std::vector<internal::string> explanations(count());
zhanyong.wan82113312010-01-08 21:55:40 +00002930 for (size_t i = 0; i != count(); ++it, ++i) {
2931 StringMatchResultListener s;
2932 if (matchers_[i].MatchAndExplain(*it, &s)) {
2933 explanations[i] = s.str();
2934 } else {
2935 // The container has the right size but the i-th element
2936 // doesn't match its expectation.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002937 *listener << "whose element #" << i << " doesn't match";
2938 PrintIfNotEmpty(s.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002939 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002940 }
2941 }
zhanyong.wan82113312010-01-08 21:55:40 +00002942
2943 // Every element matches its expectation. We need to explain why
2944 // (the obvious ones can be skipped).
zhanyong.wan82113312010-01-08 21:55:40 +00002945 bool reason_printed = false;
2946 for (size_t i = 0; i != count(); ++i) {
2947 const internal::string& s = explanations[i];
2948 if (!s.empty()) {
2949 if (reason_printed) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002950 *listener << ",\nand ";
zhanyong.wan82113312010-01-08 21:55:40 +00002951 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002952 *listener << "whose element #" << i << " matches, " << s;
zhanyong.wan82113312010-01-08 21:55:40 +00002953 reason_printed = true;
2954 }
2955 }
2956
2957 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002958 }
2959
2960 private:
2961 static Message Elements(size_t count) {
2962 return Message() << count << (count == 1 ? " element" : " elements");
2963 }
2964
2965 size_t count() const { return matchers_.size(); }
zhanyong.wanfb25d532013-07-28 08:24:00 +00002966
2967 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002968
2969 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002970};
2971
zhanyong.wanfb25d532013-07-28 08:24:00 +00002972// Connectivity matrix of (elements X matchers), in element-major order.
2973// Initially, there are no edges.
2974// Use NextGraph() to iterate over all possible edge configurations.
2975// Use Randomize() to generate a random edge configuration.
2976class GTEST_API_ MatchMatrix {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002977 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00002978 MatchMatrix(size_t num_elements, size_t num_matchers)
2979 : num_elements_(num_elements),
2980 num_matchers_(num_matchers),
2981 matched_(num_elements_* num_matchers_, 0) {
2982 }
2983
2984 size_t LhsSize() const { return num_elements_; }
2985 size_t RhsSize() const { return num_matchers_; }
2986 bool HasEdge(size_t ilhs, size_t irhs) const {
2987 return matched_[SpaceIndex(ilhs, irhs)] == 1;
2988 }
2989 void SetEdge(size_t ilhs, size_t irhs, bool b) {
2990 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
2991 }
2992
2993 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
2994 // adds 1 to that number; returns false if incrementing the graph left it
2995 // empty.
2996 bool NextGraph();
2997
2998 void Randomize();
2999
3000 string DebugString() const;
3001
3002 private:
3003 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3004 return ilhs * num_matchers_ + irhs;
3005 }
3006
3007 size_t num_elements_;
3008 size_t num_matchers_;
3009
3010 // Each element is a char interpreted as bool. They are stored as a
3011 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3012 // a (ilhs, irhs) matrix coordinate into an offset.
3013 ::std::vector<char> matched_;
3014};
3015
3016typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3017typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3018
3019// Returns a maximum bipartite matching for the specified graph 'g'.
3020// The matching is represented as a vector of {element, matcher} pairs.
3021GTEST_API_ ElementMatcherPairs
3022FindMaxBipartiteMatching(const MatchMatrix& g);
3023
3024GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
3025 MatchResultListener* listener);
3026
3027// Untyped base class for implementing UnorderedElementsAre. By
3028// putting logic that's not specific to the element type here, we
3029// reduce binary bloat and increase compilation speed.
3030class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3031 protected:
3032 // A vector of matcher describers, one for each element matcher.
3033 // Does not own the describers (and thus can be used only when the
3034 // element matchers are alive).
3035 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3036
3037 // Describes this UnorderedElementsAre matcher.
3038 void DescribeToImpl(::std::ostream* os) const;
3039
3040 // Describes the negation of this UnorderedElementsAre matcher.
3041 void DescribeNegationToImpl(::std::ostream* os) const;
3042
3043 bool VerifyAllElementsAndMatchersAreMatched(
3044 const ::std::vector<string>& element_printouts,
3045 const MatchMatrix& matrix,
3046 MatchResultListener* listener) const;
3047
3048 MatcherDescriberVec& matcher_describers() {
3049 return matcher_describers_;
3050 }
3051
3052 static Message Elements(size_t n) {
3053 return Message() << n << " element" << (n == 1 ? "" : "s");
3054 }
3055
3056 private:
3057 MatcherDescriberVec matcher_describers_;
3058
3059 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3060};
3061
3062// Implements unordered ElementsAre and unordered ElementsAreArray.
3063template <typename Container>
3064class UnorderedElementsAreMatcherImpl
3065 : public MatcherInterface<Container>,
3066 public UnorderedElementsAreMatcherImplBase {
3067 public:
3068 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3069 typedef internal::StlContainerView<RawContainer> View;
3070 typedef typename View::type StlContainer;
3071 typedef typename View::const_reference StlContainerReference;
3072 typedef typename StlContainer::const_iterator StlContainerConstIterator;
3073 typedef typename StlContainer::value_type Element;
3074
3075 // Constructs the matcher from a sequence of element values or
3076 // element matchers.
3077 template <typename InputIter>
3078 UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) {
3079 for (; first != last; ++first) {
3080 matchers_.push_back(MatcherCast<const Element&>(*first));
3081 matcher_describers().push_back(matchers_.back().GetDescriber());
3082 }
3083 }
3084
3085 // Describes what this matcher does.
3086 virtual void DescribeTo(::std::ostream* os) const {
3087 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3088 }
3089
3090 // Describes what the negation of this matcher does.
3091 virtual void DescribeNegationTo(::std::ostream* os) const {
3092 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3093 }
3094
3095 virtual bool MatchAndExplain(Container container,
3096 MatchResultListener* listener) const {
3097 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003098 ::std::vector<string> element_printouts;
3099 MatchMatrix matrix = AnalyzeElements(stl_container.begin(),
3100 stl_container.end(),
3101 &element_printouts,
3102 listener);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003103
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003104 const size_t actual_count = matrix.LhsSize();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003105 if (actual_count == 0 && matchers_.empty()) {
3106 return true;
3107 }
3108 if (actual_count != matchers_.size()) {
3109 // The element count doesn't match. If the container is empty,
3110 // there's no need to explain anything as Google Mock already
3111 // prints the empty container. Otherwise we just need to show
3112 // how many elements there actually are.
3113 if (actual_count != 0 && listener->IsInterested()) {
3114 *listener << "which has " << Elements(actual_count);
3115 }
3116 return false;
3117 }
3118
zhanyong.wanfb25d532013-07-28 08:24:00 +00003119 return VerifyAllElementsAndMatchersAreMatched(element_printouts,
3120 matrix, listener) &&
3121 FindPairing(matrix, listener);
3122 }
3123
3124 private:
3125 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3126
3127 template <typename ElementIter>
3128 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
3129 ::std::vector<string>* element_printouts,
3130 MatchResultListener* listener) const {
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003131 element_printouts->clear();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003132 ::std::vector<char> did_match;
3133 size_t num_elements = 0;
3134 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3135 if (listener->IsInterested()) {
3136 element_printouts->push_back(PrintToString(*elem_first));
3137 }
3138 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3139 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3140 }
3141 }
3142
3143 MatchMatrix matrix(num_elements, matchers_.size());
3144 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3145 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3146 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3147 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3148 }
3149 }
3150 return matrix;
3151 }
3152
3153 MatcherVec matchers_;
3154
3155 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3156};
3157
3158// Functor for use in TransformTuple.
3159// Performs MatcherCast<Target> on an input argument of any type.
3160template <typename Target>
3161struct CastAndAppendTransform {
3162 template <typename Arg>
3163 Matcher<Target> operator()(const Arg& a) const {
3164 return MatcherCast<Target>(a);
3165 }
3166};
3167
3168// Implements UnorderedElementsAre.
3169template <typename MatcherTuple>
3170class UnorderedElementsAreMatcher {
3171 public:
3172 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3173 : matchers_(args) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003174
3175 template <typename Container>
3176 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003177 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003178 typedef typename internal::StlContainerView<RawContainer>::type View;
3179 typedef typename View::value_type Element;
3180 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3181 MatcherVec matchers;
3182 matchers.reserve(::std::tr1::tuple_size<MatcherTuple>::value);
3183 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3184 ::std::back_inserter(matchers));
3185 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3186 matchers.begin(), matchers.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003187 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003188
3189 private:
3190 const MatcherTuple matchers_;
3191 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3192};
3193
3194// Implements ElementsAre.
3195template <typename MatcherTuple>
3196class ElementsAreMatcher {
3197 public:
3198 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3199
3200 template <typename Container>
3201 operator Matcher<Container>() const {
3202 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3203 typedef typename internal::StlContainerView<RawContainer>::type View;
3204 typedef typename View::value_type Element;
3205 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3206 MatcherVec matchers;
3207 matchers.reserve(::std::tr1::tuple_size<MatcherTuple>::value);
3208 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3209 ::std::back_inserter(matchers));
3210 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3211 matchers.begin(), matchers.end()));
3212 }
3213
3214 private:
3215 const MatcherTuple matchers_;
3216 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3217};
3218
3219// Implements UnorderedElementsAreArray().
3220template <typename T>
3221class UnorderedElementsAreArrayMatcher {
3222 public:
3223 UnorderedElementsAreArrayMatcher() {}
3224
3225 template <typename Iter>
3226 UnorderedElementsAreArrayMatcher(Iter first, Iter last)
3227 : matchers_(first, last) {}
3228
3229 template <typename Container>
3230 operator Matcher<Container>() const {
3231 return MakeMatcher(
3232 new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(),
3233 matchers_.end()));
3234 }
3235
3236 private:
3237 ::std::vector<T> matchers_;
3238
3239 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003240};
3241
3242// Implements ElementsAreArray().
3243template <typename T>
3244class ElementsAreArrayMatcher {
3245 public:
jgm38513a82012-11-15 15:50:36 +00003246 template <typename Iter>
3247 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003248
3249 template <typename Container>
3250 operator Matcher<Container>() const {
jgm38513a82012-11-15 15:50:36 +00003251 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3252 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003253 }
3254
3255 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003256 const ::std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003257
3258 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003259};
3260
zhanyong.wanb4140802010-06-08 22:53:57 +00003261// Returns the description for a matcher defined using the MATCHER*()
3262// macro where the user-supplied description string is "", if
3263// 'negation' is false; otherwise returns the description of the
3264// negation of the matcher. 'param_values' contains a list of strings
3265// that are the print-out of the matcher's parameters.
vladlosev587c1b32011-05-20 00:42:22 +00003266GTEST_API_ string FormatMatcherDescription(bool negation,
3267 const char* matcher_name,
3268 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003269
shiqiane35fdd92008-12-10 05:08:54 +00003270} // namespace internal
3271
zhanyong.wanfb25d532013-07-28 08:24:00 +00003272// ElementsAreArray(first, last)
3273// ElementsAreArray(pointer, count)
3274// ElementsAreArray(array)
3275// ElementsAreArray(vector)
3276//
3277// The ElementsAreArray() functions are like ElementsAre(...), except that
3278// they are given a homogeneous sequence rather than taking each element as
3279// a function argument. The sequence can be specified as an array, a
3280// pointer and count, a vector, or an STL iterator range. In each of these
3281// cases, the underlying sequence can be either a sequence of values or a
3282// sequence of matchers.
3283//
3284// * ElementsAreArray(array) deduces the size of the array.
3285//
3286// * ElementsAreArray(pointer, count) form takes a pointer and count.
3287//
3288// * ElementsAreArray(vector) takes a std::vector.
3289//
3290// * ElementsAreArray(first, last) takes any iterator range.
3291//
3292// All forms of ElementsAreArray() make a copy of the input matcher sequence.
3293
3294template <typename Iter>
3295inline internal::ElementsAreArrayMatcher<
3296 typename ::std::iterator_traits<Iter>::value_type>
3297ElementsAreArray(Iter first, Iter last) {
3298 typedef typename ::std::iterator_traits<Iter>::value_type T;
3299 return internal::ElementsAreArrayMatcher<T>(first, last);
3300}
3301
3302template <typename T>
3303inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3304 const T* pointer, size_t count) {
3305 return ElementsAreArray(pointer, pointer + count);
3306}
3307
3308template <typename T, size_t N>
3309inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3310 const T (&array)[N]) {
3311 return ElementsAreArray(array, N);
3312}
3313
3314template <typename T, typename A>
3315inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3316 const ::std::vector<T, A>& vec) {
3317 return ElementsAreArray(vec.begin(), vec.end());
3318}
3319
3320// UnorderedElementsAreArray(first, last)
3321// UnorderedElementsAreArray(pointer, count)
3322// UnorderedElementsAreArray(array)
3323// UnorderedElementsAreArray(vector)
3324//
3325// The UnorderedElementsAreArray() functions are like
3326// ElementsAreArray(...), but allow matching the elements in any order.
3327template <typename Iter>
3328inline internal::UnorderedElementsAreArrayMatcher<
3329 typename ::std::iterator_traits<Iter>::value_type>
3330UnorderedElementsAreArray(Iter first, Iter last) {
3331 typedef typename ::std::iterator_traits<Iter>::value_type T;
3332 return internal::UnorderedElementsAreArrayMatcher<T>(first, last);
3333}
3334
3335template <typename T>
3336inline internal::UnorderedElementsAreArrayMatcher<T>
3337UnorderedElementsAreArray(const T* pointer, size_t count) {
3338 return UnorderedElementsAreArray(pointer, pointer + count);
3339}
3340
3341template <typename T, size_t N>
3342inline internal::UnorderedElementsAreArrayMatcher<T>
3343UnorderedElementsAreArray(const T (&array)[N]) {
3344 return UnorderedElementsAreArray(array, N);
3345}
3346
3347template <typename T, typename A>
3348inline internal::UnorderedElementsAreArrayMatcher<T>
3349UnorderedElementsAreArray(const ::std::vector<T, A>& vec) {
3350 return UnorderedElementsAreArray(vec.begin(), vec.end());
3351}
3352
3353
shiqiane35fdd92008-12-10 05:08:54 +00003354// _ is a matcher that matches anything of any type.
3355//
3356// This definition is fine as:
3357//
3358// 1. The C++ standard permits using the name _ in a namespace that
3359// is not the global namespace or ::std.
3360// 2. The AnythingMatcher class has no data member or constructor,
3361// so it's OK to create global variables of this type.
3362// 3. c-style has approved of using _ in this case.
3363const internal::AnythingMatcher _ = {};
3364// Creates a matcher that matches any value of the given type T.
3365template <typename T>
3366inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
3367
3368// Creates a matcher that matches any value of the given type T.
3369template <typename T>
3370inline Matcher<T> An() { return A<T>(); }
3371
3372// Creates a polymorphic matcher that matches anything equal to x.
3373// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
3374// wouldn't compile.
3375template <typename T>
3376inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
3377
3378// Constructs a Matcher<T> from a 'value' of type T. The constructed
3379// matcher matches any value that's equal to 'value'.
3380template <typename T>
3381Matcher<T>::Matcher(T value) { *this = Eq(value); }
3382
3383// Creates a monomorphic matcher that matches anything with type Lhs
3384// and equal to rhs. A user may need to use this instead of Eq(...)
3385// in order to resolve an overloading ambiguity.
3386//
3387// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
3388// or Matcher<T>(x), but more readable than the latter.
3389//
3390// We could define similar monomorphic matchers for other comparison
3391// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
3392// it yet as those are used much less than Eq() in practice. A user
3393// can always write Matcher<T>(Lt(5)) to be explicit about the type,
3394// for example.
3395template <typename Lhs, typename Rhs>
3396inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
3397
3398// Creates a polymorphic matcher that matches anything >= x.
3399template <typename Rhs>
3400inline internal::GeMatcher<Rhs> Ge(Rhs x) {
3401 return internal::GeMatcher<Rhs>(x);
3402}
3403
3404// Creates a polymorphic matcher that matches anything > x.
3405template <typename Rhs>
3406inline internal::GtMatcher<Rhs> Gt(Rhs x) {
3407 return internal::GtMatcher<Rhs>(x);
3408}
3409
3410// Creates a polymorphic matcher that matches anything <= x.
3411template <typename Rhs>
3412inline internal::LeMatcher<Rhs> Le(Rhs x) {
3413 return internal::LeMatcher<Rhs>(x);
3414}
3415
3416// Creates a polymorphic matcher that matches anything < x.
3417template <typename Rhs>
3418inline internal::LtMatcher<Rhs> Lt(Rhs x) {
3419 return internal::LtMatcher<Rhs>(x);
3420}
3421
3422// Creates a polymorphic matcher that matches anything != x.
3423template <typename Rhs>
3424inline internal::NeMatcher<Rhs> Ne(Rhs x) {
3425 return internal::NeMatcher<Rhs>(x);
3426}
3427
zhanyong.wan2d970ee2009-09-24 21:41:36 +00003428// Creates a polymorphic matcher that matches any NULL pointer.
3429inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
3430 return MakePolymorphicMatcher(internal::IsNullMatcher());
3431}
3432
shiqiane35fdd92008-12-10 05:08:54 +00003433// Creates a polymorphic matcher that matches any non-NULL pointer.
3434// This is convenient as Not(NULL) doesn't compile (the compiler
3435// thinks that that expression is comparing a pointer with an integer).
3436inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
3437 return MakePolymorphicMatcher(internal::NotNullMatcher());
3438}
3439
3440// Creates a polymorphic matcher that matches any argument that
3441// references variable x.
3442template <typename T>
3443inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
3444 return internal::RefMatcher<T&>(x);
3445}
3446
3447// Creates a matcher that matches any double argument approximately
3448// equal to rhs, where two NANs are considered unequal.
3449inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
3450 return internal::FloatingEqMatcher<double>(rhs, false);
3451}
3452
3453// Creates a matcher that matches any double argument approximately
3454// equal to rhs, including NaN values when rhs is NaN.
3455inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
3456 return internal::FloatingEqMatcher<double>(rhs, true);
3457}
3458
zhanyong.wan616180e2013-06-18 18:49:51 +00003459// Creates a matcher that matches any double argument approximately equal to
3460// rhs, up to the specified max absolute error bound, where two NANs are
3461// considered unequal. The max absolute error bound must be non-negative.
3462inline internal::FloatingEqMatcher<double> DoubleNear(
3463 double rhs, double max_abs_error) {
3464 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
3465}
3466
3467// Creates a matcher that matches any double argument approximately equal to
3468// rhs, up to the specified max absolute error bound, including NaN values when
3469// rhs is NaN. The max absolute error bound must be non-negative.
3470inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
3471 double rhs, double max_abs_error) {
3472 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
3473}
3474
shiqiane35fdd92008-12-10 05:08:54 +00003475// Creates a matcher that matches any float argument approximately
3476// equal to rhs, where two NANs are considered unequal.
3477inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
3478 return internal::FloatingEqMatcher<float>(rhs, false);
3479}
3480
zhanyong.wan616180e2013-06-18 18:49:51 +00003481// Creates a matcher that matches any float argument approximately
shiqiane35fdd92008-12-10 05:08:54 +00003482// equal to rhs, including NaN values when rhs is NaN.
3483inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
3484 return internal::FloatingEqMatcher<float>(rhs, true);
3485}
3486
zhanyong.wan616180e2013-06-18 18:49:51 +00003487// Creates a matcher that matches any float argument approximately equal to
3488// rhs, up to the specified max absolute error bound, where two NANs are
3489// considered unequal. The max absolute error bound must be non-negative.
3490inline internal::FloatingEqMatcher<float> FloatNear(
3491 float rhs, float max_abs_error) {
3492 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
3493}
3494
3495// Creates a matcher that matches any float argument approximately equal to
3496// rhs, up to the specified max absolute error bound, including NaN values when
3497// rhs is NaN. The max absolute error bound must be non-negative.
3498inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
3499 float rhs, float max_abs_error) {
3500 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
3501}
3502
shiqiane35fdd92008-12-10 05:08:54 +00003503// Creates a matcher that matches a pointer (raw or smart) that points
3504// to a value that matches inner_matcher.
3505template <typename InnerMatcher>
3506inline internal::PointeeMatcher<InnerMatcher> Pointee(
3507 const InnerMatcher& inner_matcher) {
3508 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
3509}
3510
3511// Creates a matcher that matches an object whose given field matches
3512// 'matcher'. For example,
3513// Field(&Foo::number, Ge(5))
3514// matches a Foo object x iff x.number >= 5.
3515template <typename Class, typename FieldType, typename FieldMatcher>
3516inline PolymorphicMatcher<
3517 internal::FieldMatcher<Class, FieldType> > Field(
3518 FieldType Class::*field, const FieldMatcher& matcher) {
3519 return MakePolymorphicMatcher(
3520 internal::FieldMatcher<Class, FieldType>(
3521 field, MatcherCast<const FieldType&>(matcher)));
3522 // The call to MatcherCast() is required for supporting inner
3523 // matchers of compatible types. For example, it allows
3524 // Field(&Foo::bar, m)
3525 // to compile where bar is an int32 and m is a matcher for int64.
3526}
3527
3528// Creates a matcher that matches an object whose given property
3529// matches 'matcher'. For example,
3530// Property(&Foo::str, StartsWith("hi"))
3531// matches a Foo object x iff x.str() starts with "hi".
3532template <typename Class, typename PropertyType, typename PropertyMatcher>
3533inline PolymorphicMatcher<
3534 internal::PropertyMatcher<Class, PropertyType> > Property(
3535 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
3536 return MakePolymorphicMatcher(
3537 internal::PropertyMatcher<Class, PropertyType>(
3538 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00003539 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00003540 // The call to MatcherCast() is required for supporting inner
3541 // matchers of compatible types. For example, it allows
3542 // Property(&Foo::bar, m)
3543 // to compile where bar() returns an int32 and m is a matcher for int64.
3544}
3545
3546// Creates a matcher that matches an object iff the result of applying
3547// a callable to x matches 'matcher'.
3548// For example,
3549// ResultOf(f, StartsWith("hi"))
3550// matches a Foo object x iff f(x) starts with "hi".
3551// callable parameter can be a function, function pointer, or a functor.
3552// Callable has to satisfy the following conditions:
3553// * It is required to keep no state affecting the results of
3554// the calls on it and make no assumptions about how many calls
3555// will be made. Any state it keeps must be protected from the
3556// concurrent access.
3557// * If it is a function object, it has to define type result_type.
3558// We recommend deriving your functor classes from std::unary_function.
3559template <typename Callable, typename ResultOfMatcher>
3560internal::ResultOfMatcher<Callable> ResultOf(
3561 Callable callable, const ResultOfMatcher& matcher) {
3562 return internal::ResultOfMatcher<Callable>(
3563 callable,
3564 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
3565 matcher));
3566 // The call to MatcherCast() is required for supporting inner
3567 // matchers of compatible types. For example, it allows
3568 // ResultOf(Function, m)
3569 // to compile where Function() returns an int32 and m is a matcher for int64.
3570}
3571
3572// String matchers.
3573
3574// Matches a string equal to str.
3575inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3576 StrEq(const internal::string& str) {
3577 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3578 str, true, true));
3579}
3580
3581// Matches a string not equal to str.
3582inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3583 StrNe(const internal::string& str) {
3584 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3585 str, false, true));
3586}
3587
3588// Matches a string equal to str, ignoring case.
3589inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3590 StrCaseEq(const internal::string& str) {
3591 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3592 str, true, false));
3593}
3594
3595// Matches a string not equal to str, ignoring case.
3596inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3597 StrCaseNe(const internal::string& str) {
3598 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3599 str, false, false));
3600}
3601
3602// Creates a matcher that matches any string, std::string, or C string
3603// that contains the given substring.
3604inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
3605 HasSubstr(const internal::string& substring) {
3606 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
3607 substring));
3608}
3609
3610// Matches a string that starts with 'prefix' (case-sensitive).
3611inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
3612 StartsWith(const internal::string& prefix) {
3613 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
3614 prefix));
3615}
3616
3617// Matches a string that ends with 'suffix' (case-sensitive).
3618inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
3619 EndsWith(const internal::string& suffix) {
3620 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
3621 suffix));
3622}
3623
shiqiane35fdd92008-12-10 05:08:54 +00003624// Matches a string that fully matches regular expression 'regex'.
3625// The matcher takes ownership of 'regex'.
3626inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3627 const internal::RE* regex) {
3628 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
3629}
3630inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3631 const internal::string& regex) {
3632 return MatchesRegex(new internal::RE(regex));
3633}
3634
3635// Matches a string that contains regular expression 'regex'.
3636// The matcher takes ownership of 'regex'.
3637inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3638 const internal::RE* regex) {
3639 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
3640}
3641inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3642 const internal::string& regex) {
3643 return ContainsRegex(new internal::RE(regex));
3644}
3645
shiqiane35fdd92008-12-10 05:08:54 +00003646#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3647// Wide string matchers.
3648
3649// Matches a string equal to str.
3650inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3651 StrEq(const internal::wstring& str) {
3652 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3653 str, true, true));
3654}
3655
3656// Matches a string not equal to str.
3657inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3658 StrNe(const internal::wstring& str) {
3659 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3660 str, false, true));
3661}
3662
3663// Matches a string equal to str, ignoring case.
3664inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3665 StrCaseEq(const internal::wstring& str) {
3666 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3667 str, true, false));
3668}
3669
3670// Matches a string not equal to str, ignoring case.
3671inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3672 StrCaseNe(const internal::wstring& str) {
3673 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3674 str, false, false));
3675}
3676
3677// Creates a matcher that matches any wstring, std::wstring, or C wide string
3678// that contains the given substring.
3679inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
3680 HasSubstr(const internal::wstring& substring) {
3681 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
3682 substring));
3683}
3684
3685// Matches a string that starts with 'prefix' (case-sensitive).
3686inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
3687 StartsWith(const internal::wstring& prefix) {
3688 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
3689 prefix));
3690}
3691
3692// Matches a string that ends with 'suffix' (case-sensitive).
3693inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
3694 EndsWith(const internal::wstring& suffix) {
3695 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
3696 suffix));
3697}
3698
3699#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3700
3701// Creates a polymorphic matcher that matches a 2-tuple where the
3702// first field == the second field.
3703inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
3704
3705// Creates a polymorphic matcher that matches a 2-tuple where the
3706// first field >= the second field.
3707inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
3708
3709// Creates a polymorphic matcher that matches a 2-tuple where the
3710// first field > the second field.
3711inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
3712
3713// Creates a polymorphic matcher that matches a 2-tuple where the
3714// first field <= the second field.
3715inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
3716
3717// Creates a polymorphic matcher that matches a 2-tuple where the
3718// first field < the second field.
3719inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
3720
3721// Creates a polymorphic matcher that matches a 2-tuple where the
3722// first field != the second field.
3723inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
3724
3725// Creates a matcher that matches any value of type T that m doesn't
3726// match.
3727template <typename InnerMatcher>
3728inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
3729 return internal::NotMatcher<InnerMatcher>(m);
3730}
3731
shiqiane35fdd92008-12-10 05:08:54 +00003732// Returns a matcher that matches anything that satisfies the given
3733// predicate. The predicate can be any unary function or functor
3734// whose return type can be implicitly converted to bool.
3735template <typename Predicate>
3736inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
3737Truly(Predicate pred) {
3738 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
3739}
3740
zhanyong.wana31d9ce2013-03-01 01:50:17 +00003741// Returns a matcher that matches the container size. The container must
3742// support both size() and size_type which all STL-like containers provide.
3743// Note that the parameter 'size' can be a value of type size_type as well as
3744// matcher. For instance:
3745// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
3746// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
3747template <typename SizeMatcher>
3748inline internal::SizeIsMatcher<SizeMatcher>
3749SizeIs(const SizeMatcher& size_matcher) {
3750 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
3751}
3752
zhanyong.wan6a896b52009-01-16 01:13:50 +00003753// Returns a matcher that matches an equal container.
3754// This matcher behaves like Eq(), but in the event of mismatch lists the
3755// values that are included in one container but not the other. (Duplicate
3756// values and order differences are not explained.)
3757template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00003758inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00003759 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00003760 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00003761 // This following line is for working around a bug in MSVC 8.0,
3762 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00003763 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00003764 return MakePolymorphicMatcher(
3765 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00003766}
3767
zhanyong.wan898725c2011-09-16 16:45:39 +00003768// Returns a matcher that matches a container that, when sorted using
3769// the given comparator, matches container_matcher.
3770template <typename Comparator, typename ContainerMatcher>
3771inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
3772WhenSortedBy(const Comparator& comparator,
3773 const ContainerMatcher& container_matcher) {
3774 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
3775 comparator, container_matcher);
3776}
3777
3778// Returns a matcher that matches a container that, when sorted using
3779// the < operator, matches container_matcher.
3780template <typename ContainerMatcher>
3781inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
3782WhenSorted(const ContainerMatcher& container_matcher) {
3783 return
3784 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
3785 internal::LessComparator(), container_matcher);
3786}
3787
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003788// Matches an STL-style container or a native array that contains the
3789// same number of elements as in rhs, where its i-th element and rhs's
3790// i-th element (as a pair) satisfy the given pair matcher, for all i.
3791// TupleMatcher must be able to be safely cast to Matcher<tuple<const
3792// T1&, const T2&> >, where T1 and T2 are the types of elements in the
3793// LHS container and the RHS container respectively.
3794template <typename TupleMatcher, typename Container>
3795inline internal::PointwiseMatcher<TupleMatcher,
3796 GTEST_REMOVE_CONST_(Container)>
3797Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
3798 // This following line is for working around a bug in MSVC 8.0,
3799 // which causes Container to be a const type sometimes.
3800 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
3801 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
3802 tuple_matcher, rhs);
3803}
3804
zhanyong.wanb8243162009-06-04 05:48:20 +00003805// Matches an STL-style container or a native array that contains at
3806// least one element matching the given value or matcher.
3807//
3808// Examples:
3809// ::std::set<int> page_ids;
3810// page_ids.insert(3);
3811// page_ids.insert(1);
3812// EXPECT_THAT(page_ids, Contains(1));
3813// EXPECT_THAT(page_ids, Contains(Gt(2)));
3814// EXPECT_THAT(page_ids, Not(Contains(4)));
3815//
3816// ::std::map<int, size_t> page_lengths;
3817// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00003818// EXPECT_THAT(page_lengths,
3819// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00003820//
3821// const char* user_ids[] = { "joe", "mike", "tom" };
3822// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
3823template <typename M>
3824inline internal::ContainsMatcher<M> Contains(M matcher) {
3825 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00003826}
3827
zhanyong.wan33605ba2010-04-22 23:37:47 +00003828// Matches an STL-style container or a native array that contains only
3829// elements matching the given value or matcher.
3830//
3831// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
3832// the messages are different.
3833//
3834// Examples:
3835// ::std::set<int> page_ids;
3836// // Each(m) matches an empty container, regardless of what m is.
3837// EXPECT_THAT(page_ids, Each(Eq(1)));
3838// EXPECT_THAT(page_ids, Each(Eq(77)));
3839//
3840// page_ids.insert(3);
3841// EXPECT_THAT(page_ids, Each(Gt(0)));
3842// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
3843// page_ids.insert(1);
3844// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
3845//
3846// ::std::map<int, size_t> page_lengths;
3847// page_lengths[1] = 100;
3848// page_lengths[2] = 200;
3849// page_lengths[3] = 300;
3850// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
3851// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
3852//
3853// const char* user_ids[] = { "joe", "mike", "tom" };
3854// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
3855template <typename M>
3856inline internal::EachMatcher<M> Each(M matcher) {
3857 return internal::EachMatcher<M>(matcher);
3858}
3859
zhanyong.wanb5937da2009-07-16 20:26:41 +00003860// Key(inner_matcher) matches an std::pair whose 'first' field matches
3861// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3862// std::map that contains at least one element whose key is >= 5.
3863template <typename M>
3864inline internal::KeyMatcher<M> Key(M inner_matcher) {
3865 return internal::KeyMatcher<M>(inner_matcher);
3866}
3867
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003868// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
3869// matches first_matcher and whose 'second' field matches second_matcher. For
3870// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
3871// to match a std::map<int, string> that contains exactly one element whose key
3872// is >= 5 and whose value equals "foo".
3873template <typename FirstMatcher, typename SecondMatcher>
3874inline internal::PairMatcher<FirstMatcher, SecondMatcher>
3875Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
3876 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
3877 first_matcher, second_matcher);
3878}
3879
shiqiane35fdd92008-12-10 05:08:54 +00003880// Returns a predicate that is satisfied by anything that matches the
3881// given matcher.
3882template <typename M>
3883inline internal::MatcherAsPredicate<M> Matches(M matcher) {
3884 return internal::MatcherAsPredicate<M>(matcher);
3885}
3886
zhanyong.wanb8243162009-06-04 05:48:20 +00003887// Returns true iff the value matches the matcher.
3888template <typename T, typename M>
3889inline bool Value(const T& value, M matcher) {
3890 return testing::Matches(matcher)(value);
3891}
3892
zhanyong.wan34b034c2010-03-05 21:23:23 +00003893// Matches the value against the given matcher and explains the match
3894// result to listener.
3895template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00003896inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00003897 M matcher, const T& value, MatchResultListener* listener) {
3898 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
3899}
3900
zhanyong.wan616180e2013-06-18 18:49:51 +00003901#if GTEST_LANG_CXX11
3902// Define variadic matcher versions. They are overloaded in
3903// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
3904template <typename... Args>
3905inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
3906 return internal::AllOfMatcher<Args...>(matchers...);
3907}
3908
3909template <typename... Args>
3910inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
3911 return internal::AnyOfMatcher<Args...>(matchers...);
3912}
3913
3914#endif // GTEST_LANG_CXX11
3915
zhanyong.wanbf550852009-06-09 06:09:53 +00003916// AllArgs(m) is a synonym of m. This is useful in
3917//
3918// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
3919//
3920// which is easier to read than
3921//
3922// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
3923template <typename InnerMatcher>
3924inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
3925
shiqiane35fdd92008-12-10 05:08:54 +00003926// These macros allow using matchers to check values in Google Test
3927// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
3928// succeed iff the value matches the matcher. If the assertion fails,
3929// the value and the description of the matcher will be printed.
3930#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
3931 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3932#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
3933 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3934
3935} // namespace testing
3936
3937#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_