blob: ca09756f6c011e68d2e58646294e67c195c966de [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements some commonly used argument matchers. More
35// matchers can be defined by the user implementing the
36// MatcherInterface<T> interface if necessary.
37
38#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
39#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
40
zhanyong.wan616180e2013-06-18 18:49:51 +000041#include <math.h>
zhanyong.wan6a896b52009-01-16 01:13:50 +000042#include <algorithm>
zhanyong.wanfb25d532013-07-28 08:24:00 +000043#include <iterator>
zhanyong.wan16cf4732009-05-14 20:55:30 +000044#include <limits>
shiqiane35fdd92008-12-10 05:08:54 +000045#include <ostream> // NOLINT
46#include <sstream>
47#include <string>
zhanyong.wanab5b77c2010-05-17 19:32:48 +000048#include <utility>
shiqiane35fdd92008-12-10 05:08:54 +000049#include <vector>
50
zhanyong.wan53e08c42010-09-14 05:38:21 +000051#include "gmock/internal/gmock-internal-utils.h"
52#include "gmock/internal/gmock-port.h"
53#include "gtest/gtest.h"
shiqiane35fdd92008-12-10 05:08:54 +000054
kosak18489fa2013-12-04 23:49:07 +000055#if GTEST_HAS_STD_INITIALIZER_LIST_
56# include <initializer_list> // NOLINT -- must be after gtest.h
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +000057#endif
58
shiqiane35fdd92008-12-10 05:08:54 +000059namespace testing {
60
61// To implement a matcher Foo for type T, define:
62// 1. a class FooMatcherImpl that implements the
63// MatcherInterface<T> interface, and
64// 2. a factory function that creates a Matcher<T> object from a
65// FooMatcherImpl*.
66//
67// The two-level delegation design makes it possible to allow a user
68// to write "v" instead of "Eq(v)" where a Matcher is expected, which
69// is impossible if we pass matchers by pointers. It also eases
70// ownership management as Matcher objects can now be copied like
71// plain values.
72
zhanyong.wan82113312010-01-08 21:55:40 +000073// MatchResultListener is an abstract class. Its << operator can be
74// used by a matcher to explain why a value matches or doesn't match.
75//
76// TODO(wan@google.com): add method
77// bool InterestedInWhy(bool result) const;
78// to indicate whether the listener is interested in why the match
79// result is 'result'.
80class MatchResultListener {
81 public:
82 // Creates a listener object with the given underlying ostream. The
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +000083 // listener does not own the ostream, and does not dereference it
84 // in the constructor or destructor.
zhanyong.wan82113312010-01-08 21:55:40 +000085 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
86 virtual ~MatchResultListener() = 0; // Makes this class abstract.
87
88 // Streams x to the underlying ostream; does nothing if the ostream
89 // is NULL.
90 template <typename T>
91 MatchResultListener& operator<<(const T& x) {
92 if (stream_ != NULL)
93 *stream_ << x;
94 return *this;
95 }
96
97 // Returns the underlying ostream.
98 ::std::ostream* stream() { return stream_; }
99
zhanyong.wana862f1d2010-03-15 21:23:04 +0000100 // Returns true iff the listener is interested in an explanation of
101 // the match result. A matcher's MatchAndExplain() method can use
102 // this information to avoid generating the explanation when no one
103 // intends to hear it.
104 bool IsInterested() const { return stream_ != NULL; }
105
zhanyong.wan82113312010-01-08 21:55:40 +0000106 private:
107 ::std::ostream* const stream_;
108
109 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
110};
111
112inline MatchResultListener::~MatchResultListener() {
113}
114
zhanyong.wanfb25d532013-07-28 08:24:00 +0000115// An instance of a subclass of this knows how to describe itself as a
116// matcher.
117class MatcherDescriberInterface {
118 public:
119 virtual ~MatcherDescriberInterface() {}
120
121 // Describes this matcher to an ostream. The function should print
122 // a verb phrase that describes the property a value matching this
123 // matcher should have. The subject of the verb phrase is the value
124 // being matched. For example, the DescribeTo() method of the Gt(7)
125 // matcher prints "is greater than 7".
126 virtual void DescribeTo(::std::ostream* os) const = 0;
127
128 // Describes the negation of this matcher to an ostream. For
129 // example, if the description of this matcher is "is greater than
130 // 7", the negated description could be "is not greater than 7".
131 // You are not required to override this when implementing
132 // MatcherInterface, but it is highly advised so that your matcher
133 // can produce good error messages.
134 virtual void DescribeNegationTo(::std::ostream* os) const {
135 *os << "not (";
136 DescribeTo(os);
137 *os << ")";
138 }
139};
140
shiqiane35fdd92008-12-10 05:08:54 +0000141// The implementation of a matcher.
142template <typename T>
zhanyong.wanfb25d532013-07-28 08:24:00 +0000143class MatcherInterface : public MatcherDescriberInterface {
shiqiane35fdd92008-12-10 05:08:54 +0000144 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000145 // Returns true iff the matcher matches x; also explains the match
zhanyong.wan83f6b082013-03-01 01:47:35 +0000146 // result to 'listener' if necessary (see the next paragraph), in
147 // the form of a non-restrictive relative clause ("which ...",
148 // "whose ...", etc) that describes x. For example, the
149 // MatchAndExplain() method of the Pointee(...) matcher should
150 // generate an explanation like "which points to ...".
151 //
152 // Implementations of MatchAndExplain() should add an explanation of
153 // the match result *if and only if* they can provide additional
154 // information that's not already present (or not obvious) in the
155 // print-out of x and the matcher's description. Whether the match
156 // succeeds is not a factor in deciding whether an explanation is
157 // needed, as sometimes the caller needs to print a failure message
158 // when the match succeeds (e.g. when the matcher is used inside
159 // Not()).
160 //
161 // For example, a "has at least 10 elements" matcher should explain
162 // what the actual element count is, regardless of the match result,
163 // as it is useful information to the reader; on the other hand, an
164 // "is empty" matcher probably only needs to explain what the actual
165 // size is when the match fails, as it's redundant to say that the
166 // size is 0 when the value is already known to be empty.
zhanyong.wan82113312010-01-08 21:55:40 +0000167 //
zhanyong.wandb22c222010-01-28 21:52:29 +0000168 // You should override this method when defining a new matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000169 //
170 // It's the responsibility of the caller (Google Mock) to guarantee
171 // that 'listener' is not NULL. This helps to simplify a matcher's
172 // implementation when it doesn't care about the performance, as it
173 // can talk to 'listener' without checking its validity first.
174 // However, in order to implement dummy listeners efficiently,
175 // listener->stream() may be NULL.
zhanyong.wandb22c222010-01-28 21:52:29 +0000176 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
shiqiane35fdd92008-12-10 05:08:54 +0000177
zhanyong.wanfb25d532013-07-28 08:24:00 +0000178 // Inherits these methods from MatcherDescriberInterface:
179 // virtual void DescribeTo(::std::ostream* os) const = 0;
180 // virtual void DescribeNegationTo(::std::ostream* os) const;
shiqiane35fdd92008-12-10 05:08:54 +0000181};
182
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000183// A match result listener that stores the explanation in a string.
184class StringMatchResultListener : public MatchResultListener {
185 public:
186 StringMatchResultListener() : MatchResultListener(&ss_) {}
187
188 // Returns the explanation accumulated so far.
189 internal::string str() const { return ss_.str(); }
190
191 // Clears the explanation accumulated so far.
192 void Clear() { ss_.str(""); }
193
194 private:
195 ::std::stringstream ss_;
196
197 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
198};
199
shiqiane35fdd92008-12-10 05:08:54 +0000200namespace internal {
201
kosak506340a2014-11-17 01:47:54 +0000202struct AnyEq {
203 template <typename A, typename B>
204 bool operator()(const A& a, const B& b) const { return a == b; }
205};
206struct AnyNe {
207 template <typename A, typename B>
208 bool operator()(const A& a, const B& b) const { return a != b; }
209};
210struct AnyLt {
211 template <typename A, typename B>
212 bool operator()(const A& a, const B& b) const { return a < b; }
213};
214struct AnyGt {
215 template <typename A, typename B>
216 bool operator()(const A& a, const B& b) const { return a > b; }
217};
218struct AnyLe {
219 template <typename A, typename B>
220 bool operator()(const A& a, const B& b) const { return a <= b; }
221};
222struct AnyGe {
223 template <typename A, typename B>
224 bool operator()(const A& a, const B& b) const { return a >= b; }
225};
226
zhanyong.wan82113312010-01-08 21:55:40 +0000227// A match result listener that ignores the explanation.
228class DummyMatchResultListener : public MatchResultListener {
229 public:
230 DummyMatchResultListener() : MatchResultListener(NULL) {}
231
232 private:
233 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
234};
235
236// A match result listener that forwards the explanation to a given
237// ostream. The difference between this and MatchResultListener is
238// that the former is concrete.
239class StreamMatchResultListener : public MatchResultListener {
240 public:
241 explicit StreamMatchResultListener(::std::ostream* os)
242 : MatchResultListener(os) {}
243
244 private:
245 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
246};
247
shiqiane35fdd92008-12-10 05:08:54 +0000248// An internal class for implementing Matcher<T>, which will derive
249// from it. We put functionalities common to all Matcher<T>
250// specializations here to avoid code duplication.
251template <typename T>
252class MatcherBase {
253 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000254 // Returns true iff the matcher matches x; also explains the match
255 // result to 'listener'.
256 bool MatchAndExplain(T x, MatchResultListener* listener) const {
257 return impl_->MatchAndExplain(x, listener);
258 }
259
shiqiane35fdd92008-12-10 05:08:54 +0000260 // Returns true iff this matcher matches x.
zhanyong.wan82113312010-01-08 21:55:40 +0000261 bool Matches(T x) const {
262 DummyMatchResultListener dummy;
263 return MatchAndExplain(x, &dummy);
264 }
shiqiane35fdd92008-12-10 05:08:54 +0000265
266 // Describes this matcher to an ostream.
267 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
268
269 // Describes the negation of this matcher to an ostream.
270 void DescribeNegationTo(::std::ostream* os) const {
271 impl_->DescribeNegationTo(os);
272 }
273
274 // Explains why x matches, or doesn't match, the matcher.
275 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000276 StreamMatchResultListener listener(os);
277 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000278 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000279
zhanyong.wanfb25d532013-07-28 08:24:00 +0000280 // Returns the describer for this matcher object; retains ownership
281 // of the describer, which is only guaranteed to be alive when
282 // this matcher object is alive.
283 const MatcherDescriberInterface* GetDescriber() const {
284 return impl_.get();
285 }
286
shiqiane35fdd92008-12-10 05:08:54 +0000287 protected:
288 MatcherBase() {}
289
290 // Constructs a matcher from its implementation.
291 explicit MatcherBase(const MatcherInterface<T>* impl)
292 : impl_(impl) {}
293
294 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000295
shiqiane35fdd92008-12-10 05:08:54 +0000296 private:
297 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
298 // interfaces. The former dynamically allocates a chunk of memory
299 // to hold the reference count, while the latter tracks all
300 // references using a circular linked list without allocating
301 // memory. It has been observed that linked_ptr performs better in
302 // typical scenarios. However, shared_ptr can out-perform
303 // linked_ptr when there are many more uses of the copy constructor
304 // than the default constructor.
305 //
306 // If performance becomes a problem, we should see if using
307 // shared_ptr helps.
308 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
309};
310
shiqiane35fdd92008-12-10 05:08:54 +0000311} // namespace internal
312
313// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
314// object that can check whether a value of type T matches. The
315// implementation of Matcher<T> is just a linked_ptr to const
316// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
317// from Matcher!
318template <typename T>
319class Matcher : public internal::MatcherBase<T> {
320 public:
vladlosev88032d82010-11-17 23:29:21 +0000321 // Constructs a null matcher. Needed for storing Matcher objects in STL
322 // containers. A default-constructed matcher is not yet initialized. You
323 // cannot use it until a valid value has been assigned to it.
shiqiane35fdd92008-12-10 05:08:54 +0000324 Matcher() {}
325
326 // Constructs a matcher from its implementation.
327 explicit Matcher(const MatcherInterface<T>* impl)
328 : internal::MatcherBase<T>(impl) {}
329
zhanyong.wan18490652009-05-11 18:54:08 +0000330 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000331 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
332 Matcher(T value); // NOLINT
333};
334
335// The following two specializations allow the user to write str
336// instead of Eq(str) and "foo" instead of Eq("foo") when a string
337// matcher is expected.
338template <>
vladlosev587c1b32011-05-20 00:42:22 +0000339class GTEST_API_ Matcher<const internal::string&>
shiqiane35fdd92008-12-10 05:08:54 +0000340 : public internal::MatcherBase<const internal::string&> {
341 public:
342 Matcher() {}
343
344 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
345 : internal::MatcherBase<const internal::string&>(impl) {}
346
347 // Allows the user to write str instead of Eq(str) sometimes, where
348 // str is a string object.
349 Matcher(const internal::string& s); // NOLINT
350
351 // Allows the user to write "foo" instead of Eq("foo") sometimes.
352 Matcher(const char* s); // NOLINT
353};
354
355template <>
vladlosev587c1b32011-05-20 00:42:22 +0000356class GTEST_API_ Matcher<internal::string>
shiqiane35fdd92008-12-10 05:08:54 +0000357 : public internal::MatcherBase<internal::string> {
358 public:
359 Matcher() {}
360
361 explicit Matcher(const MatcherInterface<internal::string>* impl)
362 : internal::MatcherBase<internal::string>(impl) {}
363
364 // Allows the user to write str instead of Eq(str) sometimes, where
365 // str is a string object.
366 Matcher(const internal::string& s); // NOLINT
367
368 // Allows the user to write "foo" instead of Eq("foo") sometimes.
369 Matcher(const char* s); // NOLINT
370};
371
zhanyong.wan1f122a02013-03-25 16:27:03 +0000372#if GTEST_HAS_STRING_PIECE_
373// The following two specializations allow the user to write str
374// instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece
375// matcher is expected.
376template <>
377class GTEST_API_ Matcher<const StringPiece&>
378 : public internal::MatcherBase<const StringPiece&> {
379 public:
380 Matcher() {}
381
382 explicit Matcher(const MatcherInterface<const StringPiece&>* impl)
383 : internal::MatcherBase<const StringPiece&>(impl) {}
384
385 // Allows the user to write str instead of Eq(str) sometimes, where
386 // str is a string object.
387 Matcher(const internal::string& s); // NOLINT
388
389 // Allows the user to write "foo" instead of Eq("foo") sometimes.
390 Matcher(const char* s); // NOLINT
391
392 // Allows the user to pass StringPieces directly.
393 Matcher(StringPiece s); // NOLINT
394};
395
396template <>
397class GTEST_API_ Matcher<StringPiece>
398 : public internal::MatcherBase<StringPiece> {
399 public:
400 Matcher() {}
401
402 explicit Matcher(const MatcherInterface<StringPiece>* impl)
403 : internal::MatcherBase<StringPiece>(impl) {}
404
405 // Allows the user to write str instead of Eq(str) sometimes, where
406 // str is a string object.
407 Matcher(const internal::string& s); // NOLINT
408
409 // Allows the user to write "foo" instead of Eq("foo") sometimes.
410 Matcher(const char* s); // NOLINT
411
412 // Allows the user to pass StringPieces directly.
413 Matcher(StringPiece s); // NOLINT
414};
415#endif // GTEST_HAS_STRING_PIECE_
416
shiqiane35fdd92008-12-10 05:08:54 +0000417// The PolymorphicMatcher class template makes it easy to implement a
418// polymorphic matcher (i.e. a matcher that can match values of more
419// than one type, e.g. Eq(n) and NotNull()).
420//
zhanyong.wandb22c222010-01-28 21:52:29 +0000421// To define a polymorphic matcher, a user should provide an Impl
422// class that has a DescribeTo() method and a DescribeNegationTo()
423// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000424//
zhanyong.wandb22c222010-01-28 21:52:29 +0000425// bool MatchAndExplain(const Value& value,
426// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000427//
428// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000429template <class Impl>
430class PolymorphicMatcher {
431 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000432 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000433
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000434 // Returns a mutable reference to the underlying matcher
435 // implementation object.
436 Impl& mutable_impl() { return impl_; }
437
438 // Returns an immutable reference to the underlying matcher
439 // implementation object.
440 const Impl& impl() const { return impl_; }
441
shiqiane35fdd92008-12-10 05:08:54 +0000442 template <typename T>
443 operator Matcher<T>() const {
444 return Matcher<T>(new MonomorphicImpl<T>(impl_));
445 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000446
shiqiane35fdd92008-12-10 05:08:54 +0000447 private:
448 template <typename T>
449 class MonomorphicImpl : public MatcherInterface<T> {
450 public:
451 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
452
shiqiane35fdd92008-12-10 05:08:54 +0000453 virtual void DescribeTo(::std::ostream* os) const {
454 impl_.DescribeTo(os);
455 }
456
457 virtual void DescribeNegationTo(::std::ostream* os) const {
458 impl_.DescribeNegationTo(os);
459 }
460
zhanyong.wan82113312010-01-08 21:55:40 +0000461 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000462 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000463 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000464
shiqiane35fdd92008-12-10 05:08:54 +0000465 private:
466 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000467
468 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000469 };
470
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000471 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000472
473 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000474};
475
476// Creates a matcher from its implementation. This is easier to use
477// than the Matcher<T> constructor as it doesn't require you to
478// explicitly write the template argument, e.g.
479//
480// MakeMatcher(foo);
481// vs
482// Matcher<const string&>(foo);
483template <typename T>
484inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
485 return Matcher<T>(impl);
zhanyong.wan2eab17b2013-03-08 17:53:24 +0000486}
shiqiane35fdd92008-12-10 05:08:54 +0000487
488// Creates a polymorphic matcher from its implementation. This is
489// easier to use than the PolymorphicMatcher<Impl> constructor as it
490// doesn't require you to explicitly write the template argument, e.g.
491//
492// MakePolymorphicMatcher(foo);
493// vs
494// PolymorphicMatcher<TypeOfFoo>(foo);
495template <class Impl>
496inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
497 return PolymorphicMatcher<Impl>(impl);
498}
499
jgm79a367e2012-04-10 16:02:11 +0000500// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
501// and MUST NOT BE USED IN USER CODE!!!
502namespace internal {
503
504// The MatcherCastImpl class template is a helper for implementing
505// MatcherCast(). We need this helper in order to partially
506// specialize the implementation of MatcherCast() (C++ allows
507// class/struct templates to be partially specialized, but not
508// function templates.).
509
510// This general version is used when MatcherCast()'s argument is a
511// polymorphic matcher (i.e. something that can be converted to a
512// Matcher but is not one yet; for example, Eq(value)) or a value (for
513// example, "hello").
514template <typename T, typename M>
515class MatcherCastImpl {
516 public:
kosak5f2a6ca2013-12-03 01:43:07 +0000517 static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
jgm79a367e2012-04-10 16:02:11 +0000518 // M can be a polymorhic matcher, in which case we want to use
519 // its conversion operator to create Matcher<T>. Or it can be a value
520 // that should be passed to the Matcher<T>'s constructor.
521 //
522 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
523 // polymorphic matcher because it'll be ambiguous if T has an implicit
524 // constructor from M (this usually happens when T has an implicit
525 // constructor from any type).
526 //
527 // It won't work to unconditionally implict_cast
528 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
529 // a user-defined conversion from M to T if one exists (assuming M is
530 // a value).
531 return CastImpl(
532 polymorphic_matcher_or_value,
533 BooleanConstant<
534 internal::ImplicitlyConvertible<M, Matcher<T> >::value>());
535 }
536
537 private:
kosak5f2a6ca2013-12-03 01:43:07 +0000538 static Matcher<T> CastImpl(const M& value, BooleanConstant<false>) {
jgm79a367e2012-04-10 16:02:11 +0000539 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
540 // matcher. It must be a value then. Use direct initialization to create
541 // a matcher.
542 return Matcher<T>(ImplicitCast_<T>(value));
543 }
544
kosak5f2a6ca2013-12-03 01:43:07 +0000545 static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
jgm79a367e2012-04-10 16:02:11 +0000546 BooleanConstant<true>) {
547 // M is implicitly convertible to Matcher<T>, which means that either
548 // M is a polymorhpic matcher or Matcher<T> has an implicit constructor
549 // from M. In both cases using the implicit conversion will produce a
550 // matcher.
551 //
552 // Even if T has an implicit constructor from M, it won't be called because
553 // creating Matcher<T> would require a chain of two user-defined conversions
554 // (first to create T from M and then to create Matcher<T> from T).
555 return polymorphic_matcher_or_value;
556 }
557};
558
559// This more specialized version is used when MatcherCast()'s argument
560// is already a Matcher. This only compiles when type T can be
561// statically converted to type U.
562template <typename T, typename U>
563class MatcherCastImpl<T, Matcher<U> > {
564 public:
565 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
566 return Matcher<T>(new Impl(source_matcher));
567 }
568
569 private:
570 class Impl : public MatcherInterface<T> {
571 public:
572 explicit Impl(const Matcher<U>& source_matcher)
573 : source_matcher_(source_matcher) {}
574
575 // We delegate the matching logic to the source matcher.
576 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
577 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
578 }
579
580 virtual void DescribeTo(::std::ostream* os) const {
581 source_matcher_.DescribeTo(os);
582 }
583
584 virtual void DescribeNegationTo(::std::ostream* os) const {
585 source_matcher_.DescribeNegationTo(os);
586 }
587
588 private:
589 const Matcher<U> source_matcher_;
590
591 GTEST_DISALLOW_ASSIGN_(Impl);
592 };
593};
594
595// This even more specialized version is used for efficiently casting
596// a matcher to its own type.
597template <typename T>
598class MatcherCastImpl<T, Matcher<T> > {
599 public:
600 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
601};
602
603} // namespace internal
604
shiqiane35fdd92008-12-10 05:08:54 +0000605// In order to be safe and clear, casting between different matcher
606// types is done explicitly via MatcherCast<T>(m), which takes a
607// matcher m and returns a Matcher<T>. It compiles only when T can be
608// statically converted to the argument type of m.
609template <typename T, typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000610inline Matcher<T> MatcherCast(const M& matcher) {
jgm79a367e2012-04-10 16:02:11 +0000611 return internal::MatcherCastImpl<T, M>::Cast(matcher);
612}
shiqiane35fdd92008-12-10 05:08:54 +0000613
zhanyong.wan18490652009-05-11 18:54:08 +0000614// Implements SafeMatcherCast().
615//
zhanyong.wan95b12332009-09-25 18:55:50 +0000616// We use an intermediate class to do the actual safe casting as Nokia's
617// Symbian compiler cannot decide between
618// template <T, M> ... (M) and
619// template <T, U> ... (const Matcher<U>&)
620// for function templates but can for member function templates.
621template <typename T>
622class SafeMatcherCastImpl {
623 public:
jgm79a367e2012-04-10 16:02:11 +0000624 // This overload handles polymorphic matchers and values only since
625 // monomorphic matchers are handled by the next one.
zhanyong.wan95b12332009-09-25 18:55:50 +0000626 template <typename M>
kosak5f2a6ca2013-12-03 01:43:07 +0000627 static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
jgm79a367e2012-04-10 16:02:11 +0000628 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
zhanyong.wan95b12332009-09-25 18:55:50 +0000629 }
zhanyong.wan18490652009-05-11 18:54:08 +0000630
zhanyong.wan95b12332009-09-25 18:55:50 +0000631 // This overload handles monomorphic matchers.
632 //
633 // In general, if type T can be implicitly converted to type U, we can
634 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
635 // contravariant): just keep a copy of the original Matcher<U>, convert the
636 // argument from type T to U, and then pass it to the underlying Matcher<U>.
637 // The only exception is when U is a reference and T is not, as the
638 // underlying Matcher<U> may be interested in the argument's address, which
639 // is not preserved in the conversion from T to U.
640 template <typename U>
641 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
642 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000643 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000644 T_must_be_implicitly_convertible_to_U);
645 // Enforce that we are not converting a non-reference type T to a reference
646 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000647 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000648 internal::is_reference<T>::value || !internal::is_reference<U>::value,
649 cannot_convert_non_referentce_arg_to_reference);
650 // In case both T and U are arithmetic types, enforce that the
651 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000652 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
653 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000654 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
655 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000656 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000657 kTIsOther || kUIsOther ||
658 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
659 conversion_of_arithmetic_types_must_be_lossless);
660 return MatcherCast<T>(matcher);
661 }
662};
663
664template <typename T, typename M>
665inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
666 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000667}
668
shiqiane35fdd92008-12-10 05:08:54 +0000669// A<T>() returns a matcher that matches any value of type T.
670template <typename T>
671Matcher<T> A();
672
673// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
674// and MUST NOT BE USED IN USER CODE!!!
675namespace internal {
676
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000677// If the explanation is not empty, prints it to the ostream.
678inline void PrintIfNotEmpty(const internal::string& explanation,
zhanyong.wanfb25d532013-07-28 08:24:00 +0000679 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000680 if (explanation != "" && os != NULL) {
681 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000682 }
683}
684
zhanyong.wan736baa82010-09-27 17:44:16 +0000685// Returns true if the given type name is easy to read by a human.
686// This is used to decide whether printing the type of a value might
687// be helpful.
688inline bool IsReadableTypeName(const string& type_name) {
689 // We consider a type name readable if it's short or doesn't contain
690 // a template or function type.
691 return (type_name.length() <= 20 ||
692 type_name.find_first_of("<(") == string::npos);
693}
694
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000695// Matches the value against the given matcher, prints the value and explains
696// the match result to the listener. Returns the match result.
697// 'listener' must not be NULL.
698// Value cannot be passed by const reference, because some matchers take a
699// non-const argument.
700template <typename Value, typename T>
701bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
702 MatchResultListener* listener) {
703 if (!listener->IsInterested()) {
704 // If the listener is not interested, we do not need to construct the
705 // inner explanation.
706 return matcher.Matches(value);
707 }
708
709 StringMatchResultListener inner_listener;
710 const bool match = matcher.MatchAndExplain(value, &inner_listener);
711
712 UniversalPrint(value, listener->stream());
zhanyong.wan736baa82010-09-27 17:44:16 +0000713#if GTEST_HAS_RTTI
714 const string& type_name = GetTypeName<Value>();
715 if (IsReadableTypeName(type_name))
716 *listener->stream() << " (of type " << type_name << ")";
717#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000718 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000719
720 return match;
721}
722
shiqiane35fdd92008-12-10 05:08:54 +0000723// An internal helper class for doing compile-time loop on a tuple's
724// fields.
725template <size_t N>
726class TuplePrefix {
727 public:
728 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
729 // iff the first N fields of matcher_tuple matches the first N
730 // fields of value_tuple, respectively.
731 template <typename MatcherTuple, typename ValueTuple>
732 static bool Matches(const MatcherTuple& matcher_tuple,
733 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000734 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
735 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
736 }
737
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000738 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000739 // describes failures in matching the first N fields of matchers
740 // against the first N fields of values. If there is no failure,
741 // nothing will be streamed to os.
742 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000743 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
744 const ValueTuple& values,
745 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000746 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000747 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000748
749 // Then describes the failure (if any) in the (N - 1)-th (0-based)
750 // field.
751 typename tuple_element<N - 1, MatcherTuple>::type matcher =
752 get<N - 1>(matchers);
753 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
754 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000755 StringMatchResultListener listener;
756 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000757 // TODO(wan): include in the message the name of the parameter
758 // as used in MOCK_METHOD*() when possible.
759 *os << " Expected arg #" << N - 1 << ": ";
760 get<N - 1>(matchers).DescribeTo(os);
761 *os << "\n Actual: ";
762 // We remove the reference in type Value to prevent the
763 // universal printer from printing the address of value, which
764 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000765 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000766 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000767 internal::UniversalPrint(value, os);
768 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000769 *os << "\n";
770 }
771 }
772};
773
774// The base case.
775template <>
776class TuplePrefix<0> {
777 public:
778 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000779 static bool Matches(const MatcherTuple& /* matcher_tuple */,
780 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000781 return true;
782 }
783
784 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000785 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
786 const ValueTuple& /* values */,
787 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000788};
789
790// TupleMatches(matcher_tuple, value_tuple) returns true iff all
791// matchers in matcher_tuple match the corresponding fields in
792// value_tuple. It is a compiler error if matcher_tuple and
793// value_tuple have different number of fields or incompatible field
794// types.
795template <typename MatcherTuple, typename ValueTuple>
796bool TupleMatches(const MatcherTuple& matcher_tuple,
797 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000798 // Makes sure that matcher_tuple and value_tuple have the same
799 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000800 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000801 tuple_size<ValueTuple>::value,
802 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000803 return TuplePrefix<tuple_size<ValueTuple>::value>::
804 Matches(matcher_tuple, value_tuple);
805}
806
807// Describes failures in matching matchers against values. If there
808// is no failure, nothing will be streamed to os.
809template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000810void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
811 const ValueTuple& values,
812 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000813 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000814 matchers, values, os);
815}
816
zhanyong.wanfb25d532013-07-28 08:24:00 +0000817// TransformTupleValues and its helper.
818//
819// TransformTupleValuesHelper hides the internal machinery that
820// TransformTupleValues uses to implement a tuple traversal.
821template <typename Tuple, typename Func, typename OutIter>
822class TransformTupleValuesHelper {
823 private:
kosakbd018832014-04-02 20:30:00 +0000824 typedef ::testing::tuple_size<Tuple> TupleSize;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000825
826 public:
827 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
828 // Returns the final value of 'out' in case the caller needs it.
829 static OutIter Run(Func f, const Tuple& t, OutIter out) {
830 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
831 }
832
833 private:
834 template <typename Tup, size_t kRemainingSize>
835 struct IterateOverTuple {
836 OutIter operator() (Func f, const Tup& t, OutIter out) const {
kosakbd018832014-04-02 20:30:00 +0000837 *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
zhanyong.wanfb25d532013-07-28 08:24:00 +0000838 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
839 }
840 };
841 template <typename Tup>
842 struct IterateOverTuple<Tup, 0> {
843 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
844 return out;
845 }
846 };
847};
848
849// Successively invokes 'f(element)' on each element of the tuple 't',
850// appending each result to the 'out' iterator. Returns the final value
851// of 'out'.
852template <typename Tuple, typename Func, typename OutIter>
853OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
854 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
855}
856
shiqiane35fdd92008-12-10 05:08:54 +0000857// Implements A<T>().
858template <typename T>
859class AnyMatcherImpl : public MatcherInterface<T> {
860 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000861 virtual bool MatchAndExplain(
862 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000863 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
864 virtual void DescribeNegationTo(::std::ostream* os) const {
865 // This is mostly for completeness' safe, as it's not very useful
866 // to write Not(A<bool>()). However we cannot completely rule out
867 // such a possibility, and it doesn't hurt to be prepared.
868 *os << "never matches";
869 }
870};
871
872// Implements _, a matcher that matches any value of any
873// type. This is a polymorphic matcher, so we need a template type
874// conversion operator to make it appearing as a Matcher<T> for any
875// type T.
876class AnythingMatcher {
877 public:
878 template <typename T>
879 operator Matcher<T>() const { return A<T>(); }
880};
881
882// Implements a matcher that compares a given value with a
883// pre-supplied value using one of the ==, <=, <, etc, operators. The
884// two values being compared don't have to have the same type.
885//
886// The matcher defined here is polymorphic (for example, Eq(5) can be
887// used to match an int, a short, a double, etc). Therefore we use
888// a template type conversion operator in the implementation.
889//
shiqiane35fdd92008-12-10 05:08:54 +0000890// The following template definition assumes that the Rhs parameter is
891// a "bare" type (i.e. neither 'const T' nor 'T&').
kosak506340a2014-11-17 01:47:54 +0000892template <typename D, typename Rhs, typename Op>
893class ComparisonBase {
894 public:
895 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
896 template <typename Lhs>
897 operator Matcher<Lhs>() const {
898 return MakeMatcher(new Impl<Lhs>(rhs_));
shiqiane35fdd92008-12-10 05:08:54 +0000899 }
900
kosak506340a2014-11-17 01:47:54 +0000901 private:
902 template <typename Lhs>
903 class Impl : public MatcherInterface<Lhs> {
904 public:
905 explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
906 virtual bool MatchAndExplain(
907 Lhs lhs, MatchResultListener* /* listener */) const {
908 return Op()(lhs, rhs_);
909 }
910 virtual void DescribeTo(::std::ostream* os) const {
911 *os << D::Desc() << " ";
912 UniversalPrint(rhs_, os);
913 }
914 virtual void DescribeNegationTo(::std::ostream* os) const {
915 *os << D::NegatedDesc() << " ";
916 UniversalPrint(rhs_, os);
917 }
918 private:
919 Rhs rhs_;
920 GTEST_DISALLOW_ASSIGN_(Impl);
921 };
922 Rhs rhs_;
923 GTEST_DISALLOW_ASSIGN_(ComparisonBase);
924};
shiqiane35fdd92008-12-10 05:08:54 +0000925
kosak506340a2014-11-17 01:47:54 +0000926template <typename Rhs>
927class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
928 public:
929 explicit EqMatcher(const Rhs& rhs)
930 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
931 static const char* Desc() { return "is equal to"; }
932 static const char* NegatedDesc() { return "isn't equal to"; }
933};
934template <typename Rhs>
935class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
936 public:
937 explicit NeMatcher(const Rhs& rhs)
938 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
939 static const char* Desc() { return "isn't equal to"; }
940 static const char* NegatedDesc() { return "is equal to"; }
941};
942template <typename Rhs>
943class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
944 public:
945 explicit LtMatcher(const Rhs& rhs)
946 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
947 static const char* Desc() { return "is <"; }
948 static const char* NegatedDesc() { return "isn't <"; }
949};
950template <typename Rhs>
951class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
952 public:
953 explicit GtMatcher(const Rhs& rhs)
954 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
955 static const char* Desc() { return "is >"; }
956 static const char* NegatedDesc() { return "isn't >"; }
957};
958template <typename Rhs>
959class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
960 public:
961 explicit LeMatcher(const Rhs& rhs)
962 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
963 static const char* Desc() { return "is <="; }
964 static const char* NegatedDesc() { return "isn't <="; }
965};
966template <typename Rhs>
967class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
968 public:
969 explicit GeMatcher(const Rhs& rhs)
970 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
971 static const char* Desc() { return "is >="; }
972 static const char* NegatedDesc() { return "isn't >="; }
973};
shiqiane35fdd92008-12-10 05:08:54 +0000974
vladlosev79b83502009-11-18 00:43:37 +0000975// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000976// pointer that is NULL.
977class IsNullMatcher {
978 public:
vladlosev79b83502009-11-18 00:43:37 +0000979 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000980 bool MatchAndExplain(const Pointer& p,
981 MatchResultListener* /* listener */) const {
982 return GetRawPointer(p) == NULL;
983 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000984
985 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
986 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000987 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000988 }
989};
990
vladlosev79b83502009-11-18 00:43:37 +0000991// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000992// pointer that is not NULL.
993class NotNullMatcher {
994 public:
vladlosev79b83502009-11-18 00:43:37 +0000995 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000996 bool MatchAndExplain(const Pointer& p,
997 MatchResultListener* /* listener */) const {
998 return GetRawPointer(p) != NULL;
999 }
shiqiane35fdd92008-12-10 05:08:54 +00001000
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001001 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +00001002 void DescribeNegationTo(::std::ostream* os) const {
1003 *os << "is NULL";
1004 }
1005};
1006
1007// Ref(variable) matches any argument that is a reference to
1008// 'variable'. This matcher is polymorphic as it can match any
1009// super type of the type of 'variable'.
1010//
1011// The RefMatcher template class implements Ref(variable). It can
1012// only be instantiated with a reference type. This prevents a user
1013// from mistakenly using Ref(x) to match a non-reference function
1014// argument. For example, the following will righteously cause a
1015// compiler error:
1016//
1017// int n;
1018// Matcher<int> m1 = Ref(n); // This won't compile.
1019// Matcher<int&> m2 = Ref(n); // This will compile.
1020template <typename T>
1021class RefMatcher;
1022
1023template <typename T>
1024class RefMatcher<T&> {
1025 // Google Mock is a generic framework and thus needs to support
1026 // mocking any function types, including those that take non-const
1027 // reference arguments. Therefore the template parameter T (and
1028 // Super below) can be instantiated to either a const type or a
1029 // non-const type.
1030 public:
1031 // RefMatcher() takes a T& instead of const T&, as we want the
1032 // compiler to catch using Ref(const_value) as a matcher for a
1033 // non-const reference.
1034 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
1035
1036 template <typename Super>
1037 operator Matcher<Super&>() const {
1038 // By passing object_ (type T&) to Impl(), which expects a Super&,
1039 // we make sure that Super is a super type of T. In particular,
1040 // this catches using Ref(const_value) as a matcher for a
1041 // non-const reference, as you cannot implicitly convert a const
1042 // reference to a non-const reference.
1043 return MakeMatcher(new Impl<Super>(object_));
1044 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001045
shiqiane35fdd92008-12-10 05:08:54 +00001046 private:
1047 template <typename Super>
1048 class Impl : public MatcherInterface<Super&> {
1049 public:
1050 explicit Impl(Super& x) : object_(x) {} // NOLINT
1051
zhanyong.wandb22c222010-01-28 21:52:29 +00001052 // MatchAndExplain() takes a Super& (as opposed to const Super&)
1053 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +00001054 virtual bool MatchAndExplain(
1055 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001056 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +00001057 return &x == &object_;
1058 }
shiqiane35fdd92008-12-10 05:08:54 +00001059
1060 virtual void DescribeTo(::std::ostream* os) const {
1061 *os << "references the variable ";
1062 UniversalPrinter<Super&>::Print(object_, os);
1063 }
1064
1065 virtual void DescribeNegationTo(::std::ostream* os) const {
1066 *os << "does not reference the variable ";
1067 UniversalPrinter<Super&>::Print(object_, os);
1068 }
1069
shiqiane35fdd92008-12-10 05:08:54 +00001070 private:
1071 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001072
1073 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001074 };
1075
1076 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001077
1078 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001079};
1080
1081// Polymorphic helper functions for narrow and wide string matchers.
1082inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1083 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1084}
1085
1086inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1087 const wchar_t* rhs) {
1088 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1089}
1090
1091// String comparison for narrow or wide strings that can have embedded NUL
1092// characters.
1093template <typename StringType>
1094bool CaseInsensitiveStringEquals(const StringType& s1,
1095 const StringType& s2) {
1096 // Are the heads equal?
1097 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1098 return false;
1099 }
1100
1101 // Skip the equal heads.
1102 const typename StringType::value_type nul = 0;
1103 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1104
1105 // Are we at the end of either s1 or s2?
1106 if (i1 == StringType::npos || i2 == StringType::npos) {
1107 return i1 == i2;
1108 }
1109
1110 // Are the tails equal?
1111 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1112}
1113
1114// String matchers.
1115
1116// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1117template <typename StringType>
1118class StrEqualityMatcher {
1119 public:
shiqiane35fdd92008-12-10 05:08:54 +00001120 StrEqualityMatcher(const StringType& str, bool expect_eq,
1121 bool case_sensitive)
1122 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1123
jgm38513a82012-11-15 15:50:36 +00001124 // Accepts pointer types, particularly:
1125 // const char*
1126 // char*
1127 // const wchar_t*
1128 // wchar_t*
1129 template <typename CharType>
1130 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001131 if (s == NULL) {
1132 return !expect_eq_;
1133 }
zhanyong.wandb22c222010-01-28 21:52:29 +00001134 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001135 }
1136
jgm38513a82012-11-15 15:50:36 +00001137 // Matches anything that can convert to StringType.
1138 //
1139 // This is a template, not just a plain function with const StringType&,
1140 // because StringPiece has some interfering non-explicit constructors.
1141 template <typename MatcheeStringType>
1142 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001143 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001144 const StringType& s2(s);
1145 const bool eq = case_sensitive_ ? s2 == string_ :
1146 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +00001147 return expect_eq_ == eq;
1148 }
1149
1150 void DescribeTo(::std::ostream* os) const {
1151 DescribeToHelper(expect_eq_, os);
1152 }
1153
1154 void DescribeNegationTo(::std::ostream* os) const {
1155 DescribeToHelper(!expect_eq_, os);
1156 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001157
shiqiane35fdd92008-12-10 05:08:54 +00001158 private:
1159 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001160 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +00001161 *os << "equal to ";
1162 if (!case_sensitive_) {
1163 *os << "(ignoring case) ";
1164 }
vladloseve2e8ba42010-05-13 18:16:03 +00001165 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001166 }
1167
1168 const StringType string_;
1169 const bool expect_eq_;
1170 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001171
1172 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001173};
1174
1175// Implements the polymorphic HasSubstr(substring) matcher, which
1176// can be used as a Matcher<T> as long as T can be converted to a
1177// string.
1178template <typename StringType>
1179class HasSubstrMatcher {
1180 public:
shiqiane35fdd92008-12-10 05:08:54 +00001181 explicit HasSubstrMatcher(const StringType& substring)
1182 : substring_(substring) {}
1183
jgm38513a82012-11-15 15:50:36 +00001184 // Accepts pointer types, particularly:
1185 // const char*
1186 // char*
1187 // const wchar_t*
1188 // wchar_t*
1189 template <typename CharType>
1190 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001191 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001192 }
1193
jgm38513a82012-11-15 15:50:36 +00001194 // Matches anything that can convert to StringType.
1195 //
1196 // This is a template, not just a plain function with const StringType&,
1197 // because StringPiece has some interfering non-explicit constructors.
1198 template <typename MatcheeStringType>
1199 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001200 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001201 const StringType& s2(s);
1202 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001203 }
1204
1205 // Describes what this matcher matches.
1206 void DescribeTo(::std::ostream* os) const {
1207 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001208 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001209 }
1210
1211 void DescribeNegationTo(::std::ostream* os) const {
1212 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001213 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001214 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001215
shiqiane35fdd92008-12-10 05:08:54 +00001216 private:
1217 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001218
1219 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001220};
1221
1222// Implements the polymorphic StartsWith(substring) matcher, which
1223// can be used as a Matcher<T> as long as T can be converted to a
1224// string.
1225template <typename StringType>
1226class StartsWithMatcher {
1227 public:
shiqiane35fdd92008-12-10 05:08:54 +00001228 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1229 }
1230
jgm38513a82012-11-15 15:50:36 +00001231 // Accepts pointer types, particularly:
1232 // const char*
1233 // char*
1234 // const wchar_t*
1235 // wchar_t*
1236 template <typename CharType>
1237 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001238 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001239 }
1240
jgm38513a82012-11-15 15:50:36 +00001241 // Matches anything that can convert to StringType.
1242 //
1243 // This is a template, not just a plain function with const StringType&,
1244 // because StringPiece has some interfering non-explicit constructors.
1245 template <typename MatcheeStringType>
1246 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001247 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001248 const StringType& s2(s);
1249 return s2.length() >= prefix_.length() &&
1250 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001251 }
1252
1253 void DescribeTo(::std::ostream* os) const {
1254 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001255 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001256 }
1257
1258 void DescribeNegationTo(::std::ostream* os) const {
1259 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001260 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001261 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001262
shiqiane35fdd92008-12-10 05:08:54 +00001263 private:
1264 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001265
1266 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001267};
1268
1269// Implements the polymorphic EndsWith(substring) matcher, which
1270// can be used as a Matcher<T> as long as T can be converted to a
1271// string.
1272template <typename StringType>
1273class EndsWithMatcher {
1274 public:
shiqiane35fdd92008-12-10 05:08:54 +00001275 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1276
jgm38513a82012-11-15 15:50:36 +00001277 // Accepts pointer types, particularly:
1278 // const char*
1279 // char*
1280 // const wchar_t*
1281 // wchar_t*
1282 template <typename CharType>
1283 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001284 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001285 }
1286
jgm38513a82012-11-15 15:50:36 +00001287 // Matches anything that can convert to StringType.
1288 //
1289 // This is a template, not just a plain function with const StringType&,
1290 // because StringPiece has some interfering non-explicit constructors.
1291 template <typename MatcheeStringType>
1292 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001293 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001294 const StringType& s2(s);
1295 return s2.length() >= suffix_.length() &&
1296 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001297 }
1298
1299 void DescribeTo(::std::ostream* os) const {
1300 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001301 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001302 }
1303
1304 void DescribeNegationTo(::std::ostream* os) const {
1305 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001306 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001307 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001308
shiqiane35fdd92008-12-10 05:08:54 +00001309 private:
1310 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001311
1312 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001313};
1314
shiqiane35fdd92008-12-10 05:08:54 +00001315// Implements polymorphic matchers MatchesRegex(regex) and
1316// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1317// T can be converted to a string.
1318class MatchesRegexMatcher {
1319 public:
1320 MatchesRegexMatcher(const RE* regex, bool full_match)
1321 : regex_(regex), full_match_(full_match) {}
1322
jgm38513a82012-11-15 15:50:36 +00001323 // Accepts pointer types, particularly:
1324 // const char*
1325 // char*
1326 // const wchar_t*
1327 // wchar_t*
1328 template <typename CharType>
1329 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001330 return s != NULL && MatchAndExplain(internal::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001331 }
1332
jgm38513a82012-11-15 15:50:36 +00001333 // Matches anything that can convert to internal::string.
1334 //
1335 // This is a template, not just a plain function with const internal::string&,
1336 // because StringPiece has some interfering non-explicit constructors.
1337 template <class MatcheeStringType>
1338 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001339 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001340 const internal::string& s2(s);
1341 return full_match_ ? RE::FullMatch(s2, *regex_) :
1342 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001343 }
1344
1345 void DescribeTo(::std::ostream* os) const {
1346 *os << (full_match_ ? "matches" : "contains")
1347 << " regular expression ";
1348 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1349 }
1350
1351 void DescribeNegationTo(::std::ostream* os) const {
1352 *os << "doesn't " << (full_match_ ? "match" : "contain")
1353 << " regular expression ";
1354 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1355 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001356
shiqiane35fdd92008-12-10 05:08:54 +00001357 private:
1358 const internal::linked_ptr<const RE> regex_;
1359 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001360
1361 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001362};
1363
shiqiane35fdd92008-12-10 05:08:54 +00001364// Implements a matcher that compares the two fields of a 2-tuple
1365// using one of the ==, <=, <, etc, operators. The two fields being
1366// compared don't have to have the same type.
1367//
1368// The matcher defined here is polymorphic (for example, Eq() can be
1369// used to match a tuple<int, short>, a tuple<const long&, double>,
1370// etc). Therefore we use a template type conversion operator in the
1371// implementation.
kosak506340a2014-11-17 01:47:54 +00001372template <typename D, typename Op>
1373class PairMatchBase {
1374 public:
1375 template <typename T1, typename T2>
1376 operator Matcher< ::testing::tuple<T1, T2> >() const {
1377 return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >);
1378 }
1379 template <typename T1, typename T2>
1380 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
1381 return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>);
shiqiane35fdd92008-12-10 05:08:54 +00001382 }
1383
kosak506340a2014-11-17 01:47:54 +00001384 private:
1385 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
1386 return os << D::Desc();
1387 }
shiqiane35fdd92008-12-10 05:08:54 +00001388
kosak506340a2014-11-17 01:47:54 +00001389 template <typename Tuple>
1390 class Impl : public MatcherInterface<Tuple> {
1391 public:
1392 virtual bool MatchAndExplain(
1393 Tuple args,
1394 MatchResultListener* /* listener */) const {
1395 return Op()(::testing::get<0>(args), ::testing::get<1>(args));
1396 }
1397 virtual void DescribeTo(::std::ostream* os) const {
1398 *os << "are " << GetDesc;
1399 }
1400 virtual void DescribeNegationTo(::std::ostream* os) const {
1401 *os << "aren't " << GetDesc;
1402 }
1403 };
1404};
1405
1406class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
1407 public:
1408 static const char* Desc() { return "an equal pair"; }
1409};
1410class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
1411 public:
1412 static const char* Desc() { return "an unequal pair"; }
1413};
1414class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
1415 public:
1416 static const char* Desc() { return "a pair where the first < the second"; }
1417};
1418class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
1419 public:
1420 static const char* Desc() { return "a pair where the first > the second"; }
1421};
1422class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
1423 public:
1424 static const char* Desc() { return "a pair where the first <= the second"; }
1425};
1426class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
1427 public:
1428 static const char* Desc() { return "a pair where the first >= the second"; }
1429};
shiqiane35fdd92008-12-10 05:08:54 +00001430
zhanyong.wanc6a41232009-05-13 23:38:40 +00001431// Implements the Not(...) matcher for a particular argument type T.
1432// We do not nest it inside the NotMatcher class template, as that
1433// will prevent different instantiations of NotMatcher from sharing
1434// the same NotMatcherImpl<T> class.
1435template <typename T>
1436class NotMatcherImpl : public MatcherInterface<T> {
1437 public:
1438 explicit NotMatcherImpl(const Matcher<T>& matcher)
1439 : matcher_(matcher) {}
1440
zhanyong.wan82113312010-01-08 21:55:40 +00001441 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1442 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001443 }
1444
1445 virtual void DescribeTo(::std::ostream* os) const {
1446 matcher_.DescribeNegationTo(os);
1447 }
1448
1449 virtual void DescribeNegationTo(::std::ostream* os) const {
1450 matcher_.DescribeTo(os);
1451 }
1452
zhanyong.wanc6a41232009-05-13 23:38:40 +00001453 private:
1454 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001455
1456 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001457};
1458
shiqiane35fdd92008-12-10 05:08:54 +00001459// Implements the Not(m) matcher, which matches a value that doesn't
1460// match matcher m.
1461template <typename InnerMatcher>
1462class NotMatcher {
1463 public:
1464 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1465
1466 // This template type conversion operator allows Not(m) to be used
1467 // to match any type m can match.
1468 template <typename T>
1469 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001470 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001471 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001472
shiqiane35fdd92008-12-10 05:08:54 +00001473 private:
shiqiane35fdd92008-12-10 05:08:54 +00001474 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001475
1476 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001477};
1478
zhanyong.wanc6a41232009-05-13 23:38:40 +00001479// Implements the AllOf(m1, m2) matcher for a particular argument type
1480// T. We do not nest it inside the BothOfMatcher class template, as
1481// that will prevent different instantiations of BothOfMatcher from
1482// sharing the same BothOfMatcherImpl<T> class.
1483template <typename T>
1484class BothOfMatcherImpl : public MatcherInterface<T> {
1485 public:
1486 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1487 : matcher1_(matcher1), matcher2_(matcher2) {}
1488
zhanyong.wanc6a41232009-05-13 23:38:40 +00001489 virtual void DescribeTo(::std::ostream* os) const {
1490 *os << "(";
1491 matcher1_.DescribeTo(os);
1492 *os << ") and (";
1493 matcher2_.DescribeTo(os);
1494 *os << ")";
1495 }
1496
1497 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001498 *os << "(";
1499 matcher1_.DescribeNegationTo(os);
1500 *os << ") or (";
1501 matcher2_.DescribeNegationTo(os);
1502 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001503 }
1504
zhanyong.wan82113312010-01-08 21:55:40 +00001505 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1506 // If either matcher1_ or matcher2_ doesn't match x, we only need
1507 // to explain why one of them fails.
1508 StringMatchResultListener listener1;
1509 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1510 *listener << listener1.str();
1511 return false;
1512 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001513
zhanyong.wan82113312010-01-08 21:55:40 +00001514 StringMatchResultListener listener2;
1515 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1516 *listener << listener2.str();
1517 return false;
1518 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001519
zhanyong.wan82113312010-01-08 21:55:40 +00001520 // Otherwise we need to explain why *both* of them match.
1521 const internal::string s1 = listener1.str();
1522 const internal::string s2 = listener2.str();
1523
1524 if (s1 == "") {
1525 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001526 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001527 *listener << s1;
1528 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001529 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001530 }
1531 }
zhanyong.wan82113312010-01-08 21:55:40 +00001532 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001533 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001534
zhanyong.wanc6a41232009-05-13 23:38:40 +00001535 private:
1536 const Matcher<T> matcher1_;
1537 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001538
1539 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001540};
1541
zhanyong.wan616180e2013-06-18 18:49:51 +00001542#if GTEST_LANG_CXX11
1543// MatcherList provides mechanisms for storing a variable number of matchers in
1544// a list structure (ListType) and creating a combining matcher from such a
1545// list.
1546// The template is defined recursively using the following template paramters:
1547// * kSize is the length of the MatcherList.
1548// * Head is the type of the first matcher of the list.
1549// * Tail denotes the types of the remaining matchers of the list.
1550template <int kSize, typename Head, typename... Tail>
1551struct MatcherList {
1552 typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
zhanyong.wan29897032013-06-20 18:59:15 +00001553 typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001554
1555 // BuildList stores variadic type values in a nested pair structure.
1556 // Example:
1557 // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
1558 // the corresponding result of type pair<int, pair<string, float>>.
1559 static ListType BuildList(const Head& matcher, const Tail&... tail) {
1560 return ListType(matcher, MatcherListTail::BuildList(tail...));
1561 }
1562
1563 // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
1564 // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
1565 // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
1566 // constructor taking two Matcher<T>s as input.
1567 template <typename T, template <typename /* T */> class CombiningMatcher>
1568 static Matcher<T> CreateMatcher(const ListType& matchers) {
1569 return Matcher<T>(new CombiningMatcher<T>(
1570 SafeMatcherCast<T>(matchers.first),
1571 MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
1572 matchers.second)));
1573 }
1574};
1575
1576// The following defines the base case for the recursive definition of
1577// MatcherList.
1578template <typename Matcher1, typename Matcher2>
1579struct MatcherList<2, Matcher1, Matcher2> {
zhanyong.wan29897032013-06-20 18:59:15 +00001580 typedef ::std::pair<Matcher1, Matcher2> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001581
1582 static ListType BuildList(const Matcher1& matcher1,
1583 const Matcher2& matcher2) {
zhanyong.wan29897032013-06-20 18:59:15 +00001584 return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
zhanyong.wan616180e2013-06-18 18:49:51 +00001585 }
1586
1587 template <typename T, template <typename /* T */> class CombiningMatcher>
1588 static Matcher<T> CreateMatcher(const ListType& matchers) {
1589 return Matcher<T>(new CombiningMatcher<T>(
1590 SafeMatcherCast<T>(matchers.first),
1591 SafeMatcherCast<T>(matchers.second)));
1592 }
1593};
1594
1595// VariadicMatcher is used for the variadic implementation of
1596// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1597// CombiningMatcher<T> is used to recursively combine the provided matchers
1598// (of type Args...).
1599template <template <typename T> class CombiningMatcher, typename... Args>
1600class VariadicMatcher {
1601 public:
1602 VariadicMatcher(const Args&... matchers) // NOLINT
1603 : matchers_(MatcherListType::BuildList(matchers...)) {}
1604
1605 // This template type conversion operator allows an
1606 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1607 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1608 template <typename T>
1609 operator Matcher<T>() const {
1610 return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
1611 matchers_);
1612 }
1613
1614 private:
1615 typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
1616
1617 const typename MatcherListType::ListType matchers_;
1618
1619 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1620};
1621
1622template <typename... Args>
1623using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
1624
1625#endif // GTEST_LANG_CXX11
1626
shiqiane35fdd92008-12-10 05:08:54 +00001627// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1628// matches a value that matches all of the matchers m_1, ..., and m_n.
1629template <typename Matcher1, typename Matcher2>
1630class BothOfMatcher {
1631 public:
1632 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1633 : matcher1_(matcher1), matcher2_(matcher2) {}
1634
1635 // This template type conversion operator allows a
1636 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1637 // both Matcher1 and Matcher2 can match.
1638 template <typename T>
1639 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001640 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1641 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001642 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001643
shiqiane35fdd92008-12-10 05:08:54 +00001644 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001645 Matcher1 matcher1_;
1646 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001647
1648 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001649};
shiqiane35fdd92008-12-10 05:08:54 +00001650
zhanyong.wanc6a41232009-05-13 23:38:40 +00001651// Implements the AnyOf(m1, m2) matcher for a particular argument type
1652// T. We do not nest it inside the AnyOfMatcher class template, as
1653// that will prevent different instantiations of AnyOfMatcher from
1654// sharing the same EitherOfMatcherImpl<T> class.
1655template <typename T>
1656class EitherOfMatcherImpl : public MatcherInterface<T> {
1657 public:
1658 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1659 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001660
zhanyong.wanc6a41232009-05-13 23:38:40 +00001661 virtual void DescribeTo(::std::ostream* os) const {
1662 *os << "(";
1663 matcher1_.DescribeTo(os);
1664 *os << ") or (";
1665 matcher2_.DescribeTo(os);
1666 *os << ")";
1667 }
shiqiane35fdd92008-12-10 05:08:54 +00001668
zhanyong.wanc6a41232009-05-13 23:38:40 +00001669 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001670 *os << "(";
1671 matcher1_.DescribeNegationTo(os);
1672 *os << ") and (";
1673 matcher2_.DescribeNegationTo(os);
1674 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001675 }
shiqiane35fdd92008-12-10 05:08:54 +00001676
zhanyong.wan82113312010-01-08 21:55:40 +00001677 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1678 // If either matcher1_ or matcher2_ matches x, we just need to
1679 // explain why *one* of them matches.
1680 StringMatchResultListener listener1;
1681 if (matcher1_.MatchAndExplain(x, &listener1)) {
1682 *listener << listener1.str();
1683 return true;
1684 }
1685
1686 StringMatchResultListener listener2;
1687 if (matcher2_.MatchAndExplain(x, &listener2)) {
1688 *listener << listener2.str();
1689 return true;
1690 }
1691
1692 // Otherwise we need to explain why *both* of them fail.
1693 const internal::string s1 = listener1.str();
1694 const internal::string s2 = listener2.str();
1695
1696 if (s1 == "") {
1697 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001698 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001699 *listener << s1;
1700 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001701 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001702 }
1703 }
zhanyong.wan82113312010-01-08 21:55:40 +00001704 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001705 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001706
zhanyong.wanc6a41232009-05-13 23:38:40 +00001707 private:
1708 const Matcher<T> matcher1_;
1709 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001710
1711 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001712};
1713
zhanyong.wan616180e2013-06-18 18:49:51 +00001714#if GTEST_LANG_CXX11
1715// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1716template <typename... Args>
1717using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
1718
1719#endif // GTEST_LANG_CXX11
1720
shiqiane35fdd92008-12-10 05:08:54 +00001721// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1722// matches a value that matches at least one of the matchers m_1, ...,
1723// and m_n.
1724template <typename Matcher1, typename Matcher2>
1725class EitherOfMatcher {
1726 public:
1727 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1728 : matcher1_(matcher1), matcher2_(matcher2) {}
1729
1730 // This template type conversion operator allows a
1731 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1732 // both Matcher1 and Matcher2 can match.
1733 template <typename T>
1734 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001735 return Matcher<T>(new EitherOfMatcherImpl<T>(
1736 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001737 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001738
shiqiane35fdd92008-12-10 05:08:54 +00001739 private:
shiqiane35fdd92008-12-10 05:08:54 +00001740 Matcher1 matcher1_;
1741 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001742
1743 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001744};
1745
1746// Used for implementing Truly(pred), which turns a predicate into a
1747// matcher.
1748template <typename Predicate>
1749class TrulyMatcher {
1750 public:
1751 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1752
1753 // This method template allows Truly(pred) to be used as a matcher
1754 // for type T where T is the argument type of predicate 'pred'. The
1755 // argument is passed by reference as the predicate may be
1756 // interested in the address of the argument.
1757 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001758 bool MatchAndExplain(T& x, // NOLINT
1759 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001760 // Without the if-statement, MSVC sometimes warns about converting
1761 // a value to bool (warning 4800).
1762 //
1763 // We cannot write 'return !!predicate_(x);' as that doesn't work
1764 // when predicate_(x) returns a class convertible to bool but
1765 // having no operator!().
1766 if (predicate_(x))
1767 return true;
1768 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001769 }
1770
1771 void DescribeTo(::std::ostream* os) const {
1772 *os << "satisfies the given predicate";
1773 }
1774
1775 void DescribeNegationTo(::std::ostream* os) const {
1776 *os << "doesn't satisfy the given predicate";
1777 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001778
shiqiane35fdd92008-12-10 05:08:54 +00001779 private:
1780 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001781
1782 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001783};
1784
1785// Used for implementing Matches(matcher), which turns a matcher into
1786// a predicate.
1787template <typename M>
1788class MatcherAsPredicate {
1789 public:
1790 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1791
1792 // This template operator() allows Matches(m) to be used as a
1793 // predicate on type T where m is a matcher on type T.
1794 //
1795 // The argument x is passed by reference instead of by value, as
1796 // some matcher may be interested in its address (e.g. as in
1797 // Matches(Ref(n))(x)).
1798 template <typename T>
1799 bool operator()(const T& x) const {
1800 // We let matcher_ commit to a particular type here instead of
1801 // when the MatcherAsPredicate object was constructed. This
1802 // allows us to write Matches(m) where m is a polymorphic matcher
1803 // (e.g. Eq(5)).
1804 //
1805 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1806 // compile when matcher_ has type Matcher<const T&>; if we write
1807 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1808 // when matcher_ has type Matcher<T>; if we just write
1809 // matcher_.Matches(x), it won't compile when matcher_ is
1810 // polymorphic, e.g. Eq(5).
1811 //
1812 // MatcherCast<const T&>() is necessary for making the code work
1813 // in all of the above situations.
1814 return MatcherCast<const T&>(matcher_).Matches(x);
1815 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001816
shiqiane35fdd92008-12-10 05:08:54 +00001817 private:
1818 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001819
1820 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001821};
1822
1823// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1824// argument M must be a type that can be converted to a matcher.
1825template <typename M>
1826class PredicateFormatterFromMatcher {
1827 public:
1828 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1829
1830 // This template () operator allows a PredicateFormatterFromMatcher
1831 // object to act as a predicate-formatter suitable for using with
1832 // Google Test's EXPECT_PRED_FORMAT1() macro.
1833 template <typename T>
1834 AssertionResult operator()(const char* value_text, const T& x) const {
1835 // We convert matcher_ to a Matcher<const T&> *now* instead of
1836 // when the PredicateFormatterFromMatcher object was constructed,
1837 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1838 // know which type to instantiate it to until we actually see the
1839 // type of x here.
1840 //
zhanyong.wanf4274522013-04-24 02:49:43 +00001841 // We write SafeMatcherCast<const T&>(matcher_) instead of
shiqiane35fdd92008-12-10 05:08:54 +00001842 // Matcher<const T&>(matcher_), as the latter won't compile when
1843 // matcher_ has type Matcher<T> (e.g. An<int>()).
zhanyong.wanf4274522013-04-24 02:49:43 +00001844 // We don't write MatcherCast<const T&> either, as that allows
1845 // potentially unsafe downcasting of the matcher argument.
1846 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001847 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001848 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001849 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001850
1851 ::std::stringstream ss;
1852 ss << "Value of: " << value_text << "\n"
1853 << "Expected: ";
1854 matcher.DescribeTo(&ss);
1855 ss << "\n Actual: " << listener.str();
1856 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001857 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001858
shiqiane35fdd92008-12-10 05:08:54 +00001859 private:
1860 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001861
1862 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001863};
1864
1865// A helper function for converting a matcher to a predicate-formatter
1866// without the user needing to explicitly write the type. This is
1867// used for implementing ASSERT_THAT() and EXPECT_THAT().
1868template <typename M>
1869inline PredicateFormatterFromMatcher<M>
1870MakePredicateFormatterFromMatcher(const M& matcher) {
1871 return PredicateFormatterFromMatcher<M>(matcher);
1872}
1873
zhanyong.wan616180e2013-06-18 18:49:51 +00001874// Implements the polymorphic floating point equality matcher, which matches
1875// two float values using ULP-based approximation or, optionally, a
1876// user-specified epsilon. The template is meant to be instantiated with
1877// FloatType being either float or double.
shiqiane35fdd92008-12-10 05:08:54 +00001878template <typename FloatType>
1879class FloatingEqMatcher {
1880 public:
1881 // Constructor for FloatingEqMatcher.
kosak6b817802015-01-08 02:38:14 +00001882 // The matcher's input will be compared with expected. The matcher treats two
shiqiane35fdd92008-12-10 05:08:54 +00001883 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
zhanyong.wan616180e2013-06-18 18:49:51 +00001884 // equality comparisons between NANs will always return false. We specify a
1885 // negative max_abs_error_ term to indicate that ULP-based approximation will
1886 // be used for comparison.
kosak6b817802015-01-08 02:38:14 +00001887 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
1888 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001889 }
1890
1891 // Constructor that supports a user-specified max_abs_error that will be used
1892 // for comparison instead of ULP-based approximation. The max absolute
1893 // should be non-negative.
kosak6b817802015-01-08 02:38:14 +00001894 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
1895 FloatType max_abs_error)
1896 : expected_(expected),
1897 nan_eq_nan_(nan_eq_nan),
1898 max_abs_error_(max_abs_error) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001899 GTEST_CHECK_(max_abs_error >= 0)
1900 << ", where max_abs_error is" << max_abs_error;
1901 }
shiqiane35fdd92008-12-10 05:08:54 +00001902
1903 // Implements floating point equality matcher as a Matcher<T>.
1904 template <typename T>
1905 class Impl : public MatcherInterface<T> {
1906 public:
kosak6b817802015-01-08 02:38:14 +00001907 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
1908 : expected_(expected),
1909 nan_eq_nan_(nan_eq_nan),
1910 max_abs_error_(max_abs_error) {}
shiqiane35fdd92008-12-10 05:08:54 +00001911
zhanyong.wan82113312010-01-08 21:55:40 +00001912 virtual bool MatchAndExplain(T value,
kosak6b817802015-01-08 02:38:14 +00001913 MatchResultListener* listener) const {
1914 const FloatingPoint<FloatType> actual(value), expected(expected_);
shiqiane35fdd92008-12-10 05:08:54 +00001915
1916 // Compares NaNs first, if nan_eq_nan_ is true.
kosak6b817802015-01-08 02:38:14 +00001917 if (actual.is_nan() || expected.is_nan()) {
1918 if (actual.is_nan() && expected.is_nan()) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001919 return nan_eq_nan_;
1920 }
1921 // One is nan; the other is not nan.
1922 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001923 }
zhanyong.wan616180e2013-06-18 18:49:51 +00001924 if (HasMaxAbsError()) {
1925 // We perform an equality check so that inf will match inf, regardless
kosak6b817802015-01-08 02:38:14 +00001926 // of error bounds. If the result of value - expected_ would result in
zhanyong.wan616180e2013-06-18 18:49:51 +00001927 // overflow or if either value is inf, the default result is infinity,
1928 // which should only match if max_abs_error_ is also infinity.
kosak6b817802015-01-08 02:38:14 +00001929 if (value == expected_) {
1930 return true;
1931 }
1932
1933 const FloatType diff = value - expected_;
1934 if (fabs(diff) <= max_abs_error_) {
1935 return true;
1936 }
1937
1938 if (listener->IsInterested()) {
1939 *listener << "which is " << diff << " from " << expected_;
1940 }
1941 return false;
zhanyong.wan616180e2013-06-18 18:49:51 +00001942 } else {
kosak6b817802015-01-08 02:38:14 +00001943 return actual.AlmostEquals(expected);
zhanyong.wan616180e2013-06-18 18:49:51 +00001944 }
shiqiane35fdd92008-12-10 05:08:54 +00001945 }
1946
1947 virtual void DescribeTo(::std::ostream* os) const {
1948 // os->precision() returns the previously set precision, which we
1949 // store to restore the ostream to its original configuration
1950 // after outputting.
1951 const ::std::streamsize old_precision = os->precision(
1952 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00001953 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00001954 if (nan_eq_nan_) {
1955 *os << "is NaN";
1956 } else {
1957 *os << "never matches";
1958 }
1959 } else {
kosak6b817802015-01-08 02:38:14 +00001960 *os << "is approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001961 if (HasMaxAbsError()) {
1962 *os << " (absolute error <= " << max_abs_error_ << ")";
1963 }
shiqiane35fdd92008-12-10 05:08:54 +00001964 }
1965 os->precision(old_precision);
1966 }
1967
1968 virtual void DescribeNegationTo(::std::ostream* os) const {
1969 // As before, get original precision.
1970 const ::std::streamsize old_precision = os->precision(
1971 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00001972 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00001973 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001974 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00001975 } else {
1976 *os << "is anything";
1977 }
1978 } else {
kosak6b817802015-01-08 02:38:14 +00001979 *os << "isn't approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001980 if (HasMaxAbsError()) {
1981 *os << " (absolute error > " << max_abs_error_ << ")";
1982 }
shiqiane35fdd92008-12-10 05:08:54 +00001983 }
1984 // Restore original precision.
1985 os->precision(old_precision);
1986 }
1987
1988 private:
zhanyong.wan616180e2013-06-18 18:49:51 +00001989 bool HasMaxAbsError() const {
1990 return max_abs_error_ >= 0;
1991 }
1992
kosak6b817802015-01-08 02:38:14 +00001993 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00001994 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001995 // max_abs_error will be used for value comparison when >= 0.
1996 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001997
1998 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001999 };
2000
kosak6b817802015-01-08 02:38:14 +00002001 // The following 3 type conversion operators allow FloatEq(expected) and
2002 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
shiqiane35fdd92008-12-10 05:08:54 +00002003 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
2004 // (While Google's C++ coding style doesn't allow arguments passed
2005 // by non-const reference, we may see them in code not conforming to
2006 // the style. Therefore Google Mock needs to support them.)
2007 operator Matcher<FloatType>() const {
kosak6b817802015-01-08 02:38:14 +00002008 return MakeMatcher(
2009 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002010 }
2011
2012 operator Matcher<const FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00002013 return MakeMatcher(
kosak6b817802015-01-08 02:38:14 +00002014 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002015 }
2016
2017 operator Matcher<FloatType&>() const {
kosak6b817802015-01-08 02:38:14 +00002018 return MakeMatcher(
2019 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002020 }
jgm79a367e2012-04-10 16:02:11 +00002021
shiqiane35fdd92008-12-10 05:08:54 +00002022 private:
kosak6b817802015-01-08 02:38:14 +00002023 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002024 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002025 // max_abs_error will be used for value comparison when >= 0.
2026 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002027
2028 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002029};
2030
2031// Implements the Pointee(m) matcher for matching a pointer whose
2032// pointee matches matcher m. The pointer can be either raw or smart.
2033template <typename InnerMatcher>
2034class PointeeMatcher {
2035 public:
2036 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
2037
2038 // This type conversion operator template allows Pointee(m) to be
2039 // used as a matcher for any pointer type whose pointee type is
2040 // compatible with the inner matcher, where type Pointer can be
2041 // either a raw pointer or a smart pointer.
2042 //
2043 // The reason we do this instead of relying on
2044 // MakePolymorphicMatcher() is that the latter is not flexible
2045 // enough for implementing the DescribeTo() method of Pointee().
2046 template <typename Pointer>
2047 operator Matcher<Pointer>() const {
2048 return MakeMatcher(new Impl<Pointer>(matcher_));
2049 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002050
shiqiane35fdd92008-12-10 05:08:54 +00002051 private:
2052 // The monomorphic implementation that works for a particular pointer type.
2053 template <typename Pointer>
2054 class Impl : public MatcherInterface<Pointer> {
2055 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00002056 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
2057 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00002058
2059 explicit Impl(const InnerMatcher& matcher)
2060 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
2061
shiqiane35fdd92008-12-10 05:08:54 +00002062 virtual void DescribeTo(::std::ostream* os) const {
2063 *os << "points to a value that ";
2064 matcher_.DescribeTo(os);
2065 }
2066
2067 virtual void DescribeNegationTo(::std::ostream* os) const {
2068 *os << "does not point to a value that ";
2069 matcher_.DescribeTo(os);
2070 }
2071
zhanyong.wan82113312010-01-08 21:55:40 +00002072 virtual bool MatchAndExplain(Pointer pointer,
2073 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00002074 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00002075 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002076
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002077 *listener << "which points to ";
2078 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002079 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002080
shiqiane35fdd92008-12-10 05:08:54 +00002081 private:
2082 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002083
2084 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002085 };
2086
2087 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002088
2089 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002090};
2091
billydonahue1f5fdea2014-05-19 17:54:51 +00002092// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2093// reference that matches inner_matcher when dynamic_cast<T> is applied.
2094// The result of dynamic_cast<To> is forwarded to the inner matcher.
2095// If To is a pointer and the cast fails, the inner matcher will receive NULL.
2096// If To is a reference and the cast fails, this matcher returns false
2097// immediately.
2098template <typename To>
2099class WhenDynamicCastToMatcherBase {
2100 public:
2101 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2102 : matcher_(matcher) {}
2103
2104 void DescribeTo(::std::ostream* os) const {
2105 GetCastTypeDescription(os);
2106 matcher_.DescribeTo(os);
2107 }
2108
2109 void DescribeNegationTo(::std::ostream* os) const {
2110 GetCastTypeDescription(os);
2111 matcher_.DescribeNegationTo(os);
2112 }
2113
2114 protected:
2115 const Matcher<To> matcher_;
2116
2117 static string GetToName() {
2118#if GTEST_HAS_RTTI
2119 return GetTypeName<To>();
2120#else // GTEST_HAS_RTTI
2121 return "the target type";
2122#endif // GTEST_HAS_RTTI
2123 }
2124
2125 private:
2126 static void GetCastTypeDescription(::std::ostream* os) {
2127 *os << "when dynamic_cast to " << GetToName() << ", ";
2128 }
2129
2130 GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2131};
2132
2133// Primary template.
2134// To is a pointer. Cast and forward the result.
2135template <typename To>
2136class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2137 public:
2138 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2139 : WhenDynamicCastToMatcherBase<To>(matcher) {}
2140
2141 template <typename From>
2142 bool MatchAndExplain(From from, MatchResultListener* listener) const {
2143 // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail?
2144 To to = dynamic_cast<To>(from);
2145 return MatchPrintAndExplain(to, this->matcher_, listener);
2146 }
2147};
2148
2149// Specialize for references.
2150// In this case we return false if the dynamic_cast fails.
2151template <typename To>
2152class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2153 public:
2154 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2155 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2156
2157 template <typename From>
2158 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2159 // We don't want an std::bad_cast here, so do the cast with pointers.
2160 To* to = dynamic_cast<To*>(&from);
2161 if (to == NULL) {
2162 *listener << "which cannot be dynamic_cast to " << this->GetToName();
2163 return false;
2164 }
2165 return MatchPrintAndExplain(*to, this->matcher_, listener);
2166 }
2167};
2168
shiqiane35fdd92008-12-10 05:08:54 +00002169// Implements the Field() matcher for matching a field (i.e. member
2170// variable) of an object.
2171template <typename Class, typename FieldType>
2172class FieldMatcher {
2173 public:
2174 FieldMatcher(FieldType Class::*field,
2175 const Matcher<const FieldType&>& matcher)
2176 : field_(field), matcher_(matcher) {}
2177
shiqiane35fdd92008-12-10 05:08:54 +00002178 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002179 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002180 matcher_.DescribeTo(os);
2181 }
2182
2183 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002184 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002185 matcher_.DescribeNegationTo(os);
2186 }
2187
zhanyong.wandb22c222010-01-28 21:52:29 +00002188 template <typename T>
2189 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2190 return MatchAndExplainImpl(
2191 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002192 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002193 value, listener);
2194 }
2195
2196 private:
2197 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002198 // Symbian's C++ compiler choose which overload to use. Its type is
2199 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002200 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2201 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002202 *listener << "whose given field is ";
2203 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002204 }
2205
zhanyong.wandb22c222010-01-28 21:52:29 +00002206 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2207 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002208 if (p == NULL)
2209 return false;
2210
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002211 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002212 // Since *p has a field, it must be a class/struct/union type and
2213 // thus cannot be a pointer. Therefore we pass false_type() as
2214 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002215 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002216 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002217
shiqiane35fdd92008-12-10 05:08:54 +00002218 const FieldType Class::*field_;
2219 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002220
2221 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002222};
2223
shiqiane35fdd92008-12-10 05:08:54 +00002224// Implements the Property() matcher for matching a property
2225// (i.e. return value of a getter method) of an object.
2226template <typename Class, typename PropertyType>
2227class PropertyMatcher {
2228 public:
2229 // The property may have a reference type, so 'const PropertyType&'
2230 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00002231 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00002232 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00002233 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00002234
2235 PropertyMatcher(PropertyType (Class::*property)() const,
2236 const Matcher<RefToConstProperty>& matcher)
2237 : property_(property), matcher_(matcher) {}
2238
shiqiane35fdd92008-12-10 05:08:54 +00002239 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002240 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002241 matcher_.DescribeTo(os);
2242 }
2243
2244 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002245 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002246 matcher_.DescribeNegationTo(os);
2247 }
2248
zhanyong.wandb22c222010-01-28 21:52:29 +00002249 template <typename T>
2250 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2251 return MatchAndExplainImpl(
2252 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002253 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002254 value, listener);
2255 }
2256
2257 private:
2258 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002259 // Symbian's C++ compiler choose which overload to use. Its type is
2260 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002261 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2262 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002263 *listener << "whose given property is ";
2264 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2265 // which takes a non-const reference as argument.
2266 RefToConstProperty result = (obj.*property_)();
2267 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002268 }
2269
zhanyong.wandb22c222010-01-28 21:52:29 +00002270 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2271 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002272 if (p == NULL)
2273 return false;
2274
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002275 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002276 // Since *p has a property method, it must be a class/struct/union
2277 // type and thus cannot be a pointer. Therefore we pass
2278 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002279 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002280 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002281
shiqiane35fdd92008-12-10 05:08:54 +00002282 PropertyType (Class::*property_)() const;
2283 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002284
2285 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002286};
2287
shiqiane35fdd92008-12-10 05:08:54 +00002288// Type traits specifying various features of different functors for ResultOf.
2289// The default template specifies features for functor objects.
2290// Functor classes have to typedef argument_type and result_type
2291// to be compatible with ResultOf.
2292template <typename Functor>
2293struct CallableTraits {
2294 typedef typename Functor::result_type ResultType;
2295 typedef Functor StorageType;
2296
zhanyong.wan32de5f52009-12-23 00:13:23 +00002297 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00002298 template <typename T>
2299 static ResultType Invoke(Functor f, T arg) { return f(arg); }
2300};
2301
2302// Specialization for function pointers.
2303template <typename ArgType, typename ResType>
2304struct CallableTraits<ResType(*)(ArgType)> {
2305 typedef ResType ResultType;
2306 typedef ResType(*StorageType)(ArgType);
2307
2308 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002309 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00002310 << "NULL function pointer is passed into ResultOf().";
2311 }
2312 template <typename T>
2313 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2314 return (*f)(arg);
2315 }
2316};
2317
2318// Implements the ResultOf() matcher for matching a return value of a
2319// unary function of an object.
2320template <typename Callable>
2321class ResultOfMatcher {
2322 public:
2323 typedef typename CallableTraits<Callable>::ResultType ResultType;
2324
2325 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
2326 : callable_(callable), matcher_(matcher) {
2327 CallableTraits<Callable>::CheckIsValid(callable_);
2328 }
2329
2330 template <typename T>
2331 operator Matcher<T>() const {
2332 return Matcher<T>(new Impl<T>(callable_, matcher_));
2333 }
2334
2335 private:
2336 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2337
2338 template <typename T>
2339 class Impl : public MatcherInterface<T> {
2340 public:
2341 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
2342 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00002343
2344 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002345 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002346 matcher_.DescribeTo(os);
2347 }
2348
2349 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002350 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002351 matcher_.DescribeNegationTo(os);
2352 }
2353
zhanyong.wan82113312010-01-08 21:55:40 +00002354 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002355 *listener << "which is mapped by the given callable to ";
2356 // Cannot pass the return value (for example, int) to
2357 // MatchPrintAndExplain, which takes a non-const reference as argument.
2358 ResultType result =
2359 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2360 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002361 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002362
shiqiane35fdd92008-12-10 05:08:54 +00002363 private:
2364 // Functors often define operator() as non-const method even though
2365 // they are actualy stateless. But we need to use them even when
2366 // 'this' is a const pointer. It's the user's responsibility not to
2367 // use stateful callables with ResultOf(), which does't guarantee
2368 // how many times the callable will be invoked.
2369 mutable CallableStorageType callable_;
2370 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002371
2372 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002373 }; // class Impl
2374
2375 const CallableStorageType callable_;
2376 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002377
2378 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002379};
2380
zhanyong.wana31d9ce2013-03-01 01:50:17 +00002381// Implements a matcher that checks the size of an STL-style container.
2382template <typename SizeMatcher>
2383class SizeIsMatcher {
2384 public:
2385 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2386 : size_matcher_(size_matcher) {
2387 }
2388
2389 template <typename Container>
2390 operator Matcher<Container>() const {
2391 return MakeMatcher(new Impl<Container>(size_matcher_));
2392 }
2393
2394 template <typename Container>
2395 class Impl : public MatcherInterface<Container> {
2396 public:
2397 typedef internal::StlContainerView<
2398 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2399 typedef typename ContainerView::type::size_type SizeType;
2400 explicit Impl(const SizeMatcher& size_matcher)
2401 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2402
2403 virtual void DescribeTo(::std::ostream* os) const {
2404 *os << "size ";
2405 size_matcher_.DescribeTo(os);
2406 }
2407 virtual void DescribeNegationTo(::std::ostream* os) const {
2408 *os << "size ";
2409 size_matcher_.DescribeNegationTo(os);
2410 }
2411
2412 virtual bool MatchAndExplain(Container container,
2413 MatchResultListener* listener) const {
2414 SizeType size = container.size();
2415 StringMatchResultListener size_listener;
2416 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2417 *listener
2418 << "whose size " << size << (result ? " matches" : " doesn't match");
2419 PrintIfNotEmpty(size_listener.str(), listener->stream());
2420 return result;
2421 }
2422
2423 private:
2424 const Matcher<SizeType> size_matcher_;
2425 GTEST_DISALLOW_ASSIGN_(Impl);
2426 };
2427
2428 private:
2429 const SizeMatcher size_matcher_;
2430 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2431};
2432
kosakb6a34882014-03-12 21:06:46 +00002433// Implements a matcher that checks the begin()..end() distance of an STL-style
2434// container.
2435template <typename DistanceMatcher>
2436class BeginEndDistanceIsMatcher {
2437 public:
2438 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2439 : distance_matcher_(distance_matcher) {}
2440
2441 template <typename Container>
2442 operator Matcher<Container>() const {
2443 return MakeMatcher(new Impl<Container>(distance_matcher_));
2444 }
2445
2446 template <typename Container>
2447 class Impl : public MatcherInterface<Container> {
2448 public:
2449 typedef internal::StlContainerView<
2450 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2451 typedef typename std::iterator_traits<
2452 typename ContainerView::type::const_iterator>::difference_type
2453 DistanceType;
2454 explicit Impl(const DistanceMatcher& distance_matcher)
2455 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2456
2457 virtual void DescribeTo(::std::ostream* os) const {
2458 *os << "distance between begin() and end() ";
2459 distance_matcher_.DescribeTo(os);
2460 }
2461 virtual void DescribeNegationTo(::std::ostream* os) const {
2462 *os << "distance between begin() and end() ";
2463 distance_matcher_.DescribeNegationTo(os);
2464 }
2465
2466 virtual bool MatchAndExplain(Container container,
2467 MatchResultListener* listener) const {
kosak5b9cbbb2014-11-17 00:28:55 +00002468#if GTEST_HAS_STD_BEGIN_AND_END_
kosakb6a34882014-03-12 21:06:46 +00002469 using std::begin;
2470 using std::end;
2471 DistanceType distance = std::distance(begin(container), end(container));
2472#else
2473 DistanceType distance = std::distance(container.begin(), container.end());
2474#endif
2475 StringMatchResultListener distance_listener;
2476 const bool result =
2477 distance_matcher_.MatchAndExplain(distance, &distance_listener);
2478 *listener << "whose distance between begin() and end() " << distance
2479 << (result ? " matches" : " doesn't match");
2480 PrintIfNotEmpty(distance_listener.str(), listener->stream());
2481 return result;
2482 }
2483
2484 private:
2485 const Matcher<DistanceType> distance_matcher_;
2486 GTEST_DISALLOW_ASSIGN_(Impl);
2487 };
2488
2489 private:
2490 const DistanceMatcher distance_matcher_;
2491 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2492};
2493
zhanyong.wan6a896b52009-01-16 01:13:50 +00002494// Implements an equality matcher for any STL-style container whose elements
2495// support ==. This matcher is like Eq(), but its failure explanations provide
2496// more detailed information that is useful when the container is used as a set.
2497// The failure message reports elements that are in one of the operands but not
2498// the other. The failure messages do not report duplicate or out-of-order
2499// elements in the containers (which don't properly matter to sets, but can
2500// occur if the containers are vectors or lists, for example).
2501//
2502// Uses the container's const_iterator, value_type, operator ==,
2503// begin(), and end().
2504template <typename Container>
2505class ContainerEqMatcher {
2506 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002507 typedef internal::StlContainerView<Container> View;
2508 typedef typename View::type StlContainer;
2509 typedef typename View::const_reference StlContainerReference;
2510
kosak6b817802015-01-08 02:38:14 +00002511 // We make a copy of expected in case the elements in it are modified
zhanyong.wanb8243162009-06-04 05:48:20 +00002512 // after this matcher is created.
kosak6b817802015-01-08 02:38:14 +00002513 explicit ContainerEqMatcher(const Container& expected)
2514 : expected_(View::Copy(expected)) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002515 // Makes sure the user doesn't instantiate this class template
2516 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002517 (void)testing::StaticAssertTypeEq<Container,
2518 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002519 }
2520
zhanyong.wan6a896b52009-01-16 01:13:50 +00002521 void DescribeTo(::std::ostream* os) const {
2522 *os << "equals ";
kosak6b817802015-01-08 02:38:14 +00002523 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002524 }
2525 void DescribeNegationTo(::std::ostream* os) const {
2526 *os << "does not equal ";
kosak6b817802015-01-08 02:38:14 +00002527 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002528 }
2529
zhanyong.wanb8243162009-06-04 05:48:20 +00002530 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002531 bool MatchAndExplain(const LhsContainer& lhs,
2532 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002533 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002534 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002535 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002536 LhsView;
2537 typedef typename LhsView::type LhsStlContainer;
2538 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
kosak6b817802015-01-08 02:38:14 +00002539 if (lhs_stl_container == expected_)
zhanyong.wane122e452010-01-12 09:03:52 +00002540 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002541
zhanyong.wane122e452010-01-12 09:03:52 +00002542 ::std::ostream* const os = listener->stream();
2543 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002544 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002545 bool printed_header = false;
2546 for (typename LhsStlContainer::const_iterator it =
2547 lhs_stl_container.begin();
2548 it != lhs_stl_container.end(); ++it) {
kosak6b817802015-01-08 02:38:14 +00002549 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
2550 expected_.end()) {
zhanyong.wane122e452010-01-12 09:03:52 +00002551 if (printed_header) {
2552 *os << ", ";
2553 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002554 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002555 printed_header = true;
2556 }
vladloseve2e8ba42010-05-13 18:16:03 +00002557 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002558 }
zhanyong.wane122e452010-01-12 09:03:52 +00002559 }
2560
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002561 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002562 bool printed_header2 = false;
kosak6b817802015-01-08 02:38:14 +00002563 for (typename StlContainer::const_iterator it = expected_.begin();
2564 it != expected_.end(); ++it) {
zhanyong.wane122e452010-01-12 09:03:52 +00002565 if (internal::ArrayAwareFind(
2566 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2567 lhs_stl_container.end()) {
2568 if (printed_header2) {
2569 *os << ", ";
2570 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002571 *os << (printed_header ? ",\nand" : "which")
2572 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002573 printed_header2 = true;
2574 }
vladloseve2e8ba42010-05-13 18:16:03 +00002575 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002576 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002577 }
2578 }
2579
zhanyong.wane122e452010-01-12 09:03:52 +00002580 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002581 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002582
zhanyong.wan6a896b52009-01-16 01:13:50 +00002583 private:
kosak6b817802015-01-08 02:38:14 +00002584 const StlContainer expected_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002585
2586 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002587};
2588
zhanyong.wan898725c2011-09-16 16:45:39 +00002589// A comparator functor that uses the < operator to compare two values.
2590struct LessComparator {
2591 template <typename T, typename U>
2592 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2593};
2594
2595// Implements WhenSortedBy(comparator, container_matcher).
2596template <typename Comparator, typename ContainerMatcher>
2597class WhenSortedByMatcher {
2598 public:
2599 WhenSortedByMatcher(const Comparator& comparator,
2600 const ContainerMatcher& matcher)
2601 : comparator_(comparator), matcher_(matcher) {}
2602
2603 template <typename LhsContainer>
2604 operator Matcher<LhsContainer>() const {
2605 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2606 }
2607
2608 template <typename LhsContainer>
2609 class Impl : public MatcherInterface<LhsContainer> {
2610 public:
2611 typedef internal::StlContainerView<
2612 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2613 typedef typename LhsView::type LhsStlContainer;
2614 typedef typename LhsView::const_reference LhsStlContainerReference;
zhanyong.wana9a59e02013-03-27 16:14:55 +00002615 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2616 // so that we can match associative containers.
2617 typedef typename RemoveConstFromKey<
2618 typename LhsStlContainer::value_type>::type LhsValue;
zhanyong.wan898725c2011-09-16 16:45:39 +00002619
2620 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2621 : comparator_(comparator), matcher_(matcher) {}
2622
2623 virtual void DescribeTo(::std::ostream* os) const {
2624 *os << "(when sorted) ";
2625 matcher_.DescribeTo(os);
2626 }
2627
2628 virtual void DescribeNegationTo(::std::ostream* os) const {
2629 *os << "(when sorted) ";
2630 matcher_.DescribeNegationTo(os);
2631 }
2632
2633 virtual bool MatchAndExplain(LhsContainer lhs,
2634 MatchResultListener* listener) const {
2635 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wanfb25d532013-07-28 08:24:00 +00002636 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2637 lhs_stl_container.end());
2638 ::std::sort(
2639 sorted_container.begin(), sorted_container.end(), comparator_);
zhanyong.wan898725c2011-09-16 16:45:39 +00002640
2641 if (!listener->IsInterested()) {
2642 // If the listener is not interested, we do not need to
2643 // construct the inner explanation.
2644 return matcher_.Matches(sorted_container);
2645 }
2646
2647 *listener << "which is ";
2648 UniversalPrint(sorted_container, listener->stream());
2649 *listener << " when sorted";
2650
2651 StringMatchResultListener inner_listener;
2652 const bool match = matcher_.MatchAndExplain(sorted_container,
2653 &inner_listener);
2654 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2655 return match;
2656 }
2657
2658 private:
2659 const Comparator comparator_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00002660 const Matcher<const ::std::vector<LhsValue>&> matcher_;
zhanyong.wan898725c2011-09-16 16:45:39 +00002661
2662 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2663 };
2664
2665 private:
2666 const Comparator comparator_;
2667 const ContainerMatcher matcher_;
2668
2669 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2670};
2671
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002672// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2673// must be able to be safely cast to Matcher<tuple<const T1&, const
2674// T2&> >, where T1 and T2 are the types of elements in the LHS
2675// container and the RHS container respectively.
2676template <typename TupleMatcher, typename RhsContainer>
2677class PointwiseMatcher {
2678 public:
2679 typedef internal::StlContainerView<RhsContainer> RhsView;
2680 typedef typename RhsView::type RhsStlContainer;
2681 typedef typename RhsStlContainer::value_type RhsValue;
2682
2683 // Like ContainerEq, we make a copy of rhs in case the elements in
2684 // it are modified after this matcher is created.
2685 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2686 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2687 // Makes sure the user doesn't instantiate this class template
2688 // with a const or reference type.
2689 (void)testing::StaticAssertTypeEq<RhsContainer,
2690 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2691 }
2692
2693 template <typename LhsContainer>
2694 operator Matcher<LhsContainer>() const {
2695 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2696 }
2697
2698 template <typename LhsContainer>
2699 class Impl : public MatcherInterface<LhsContainer> {
2700 public:
2701 typedef internal::StlContainerView<
2702 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2703 typedef typename LhsView::type LhsStlContainer;
2704 typedef typename LhsView::const_reference LhsStlContainerReference;
2705 typedef typename LhsStlContainer::value_type LhsValue;
2706 // We pass the LHS value and the RHS value to the inner matcher by
2707 // reference, as they may be expensive to copy. We must use tuple
2708 // instead of pair here, as a pair cannot hold references (C++ 98,
2709 // 20.2.2 [lib.pairs]).
kosakbd018832014-04-02 20:30:00 +00002710 typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002711
2712 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2713 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2714 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2715 rhs_(rhs) {}
2716
2717 virtual void DescribeTo(::std::ostream* os) const {
2718 *os << "contains " << rhs_.size()
2719 << " values, where each value and its corresponding value in ";
2720 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2721 *os << " ";
2722 mono_tuple_matcher_.DescribeTo(os);
2723 }
2724 virtual void DescribeNegationTo(::std::ostream* os) const {
2725 *os << "doesn't contain exactly " << rhs_.size()
2726 << " values, or contains a value x at some index i"
2727 << " where x and the i-th value of ";
2728 UniversalPrint(rhs_, os);
2729 *os << " ";
2730 mono_tuple_matcher_.DescribeNegationTo(os);
2731 }
2732
2733 virtual bool MatchAndExplain(LhsContainer lhs,
2734 MatchResultListener* listener) const {
2735 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2736 const size_t actual_size = lhs_stl_container.size();
2737 if (actual_size != rhs_.size()) {
2738 *listener << "which contains " << actual_size << " values";
2739 return false;
2740 }
2741
2742 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2743 typename RhsStlContainer::const_iterator right = rhs_.begin();
2744 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2745 const InnerMatcherArg value_pair(*left, *right);
2746
2747 if (listener->IsInterested()) {
2748 StringMatchResultListener inner_listener;
2749 if (!mono_tuple_matcher_.MatchAndExplain(
2750 value_pair, &inner_listener)) {
2751 *listener << "where the value pair (";
2752 UniversalPrint(*left, listener->stream());
2753 *listener << ", ";
2754 UniversalPrint(*right, listener->stream());
2755 *listener << ") at index #" << i << " don't match";
2756 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2757 return false;
2758 }
2759 } else {
2760 if (!mono_tuple_matcher_.Matches(value_pair))
2761 return false;
2762 }
2763 }
2764
2765 return true;
2766 }
2767
2768 private:
2769 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2770 const RhsStlContainer rhs_;
2771
2772 GTEST_DISALLOW_ASSIGN_(Impl);
2773 };
2774
2775 private:
2776 const TupleMatcher tuple_matcher_;
2777 const RhsStlContainer rhs_;
2778
2779 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2780};
2781
zhanyong.wan33605ba2010-04-22 23:37:47 +00002782// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002783template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002784class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002785 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002786 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002787 typedef StlContainerView<RawContainer> View;
2788 typedef typename View::type StlContainer;
2789 typedef typename View::const_reference StlContainerReference;
2790 typedef typename StlContainer::value_type Element;
2791
2792 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002793 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002794 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002795 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002796
zhanyong.wan33605ba2010-04-22 23:37:47 +00002797 // Checks whether:
2798 // * All elements in the container match, if all_elements_should_match.
2799 // * Any element in the container matches, if !all_elements_should_match.
2800 bool MatchAndExplainImpl(bool all_elements_should_match,
2801 Container container,
2802 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002803 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002804 size_t i = 0;
2805 for (typename StlContainer::const_iterator it = stl_container.begin();
2806 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002807 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002808 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2809
2810 if (matches != all_elements_should_match) {
2811 *listener << "whose element #" << i
2812 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002813 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002814 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002815 }
2816 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002817 return all_elements_should_match;
2818 }
2819
2820 protected:
2821 const Matcher<const Element&> inner_matcher_;
2822
2823 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2824};
2825
2826// Implements Contains(element_matcher) for the given argument type Container.
2827// Symmetric to EachMatcherImpl.
2828template <typename Container>
2829class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2830 public:
2831 template <typename InnerMatcher>
2832 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2833 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2834
2835 // Describes what this matcher does.
2836 virtual void DescribeTo(::std::ostream* os) const {
2837 *os << "contains at least one element that ";
2838 this->inner_matcher_.DescribeTo(os);
2839 }
2840
2841 virtual void DescribeNegationTo(::std::ostream* os) const {
2842 *os << "doesn't contain any element that ";
2843 this->inner_matcher_.DescribeTo(os);
2844 }
2845
2846 virtual bool MatchAndExplain(Container container,
2847 MatchResultListener* listener) const {
2848 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002849 }
2850
2851 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002852 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002853};
2854
zhanyong.wan33605ba2010-04-22 23:37:47 +00002855// Implements Each(element_matcher) for the given argument type Container.
2856// Symmetric to ContainsMatcherImpl.
2857template <typename Container>
2858class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2859 public:
2860 template <typename InnerMatcher>
2861 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2862 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2863
2864 // Describes what this matcher does.
2865 virtual void DescribeTo(::std::ostream* os) const {
2866 *os << "only contains elements that ";
2867 this->inner_matcher_.DescribeTo(os);
2868 }
2869
2870 virtual void DescribeNegationTo(::std::ostream* os) const {
2871 *os << "contains some element that ";
2872 this->inner_matcher_.DescribeNegationTo(os);
2873 }
2874
2875 virtual bool MatchAndExplain(Container container,
2876 MatchResultListener* listener) const {
2877 return this->MatchAndExplainImpl(true, container, listener);
2878 }
2879
2880 private:
2881 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2882};
2883
zhanyong.wanb8243162009-06-04 05:48:20 +00002884// Implements polymorphic Contains(element_matcher).
2885template <typename M>
2886class ContainsMatcher {
2887 public:
2888 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2889
2890 template <typename Container>
2891 operator Matcher<Container>() const {
2892 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2893 }
2894
2895 private:
2896 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002897
2898 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002899};
2900
zhanyong.wan33605ba2010-04-22 23:37:47 +00002901// Implements polymorphic Each(element_matcher).
2902template <typename M>
2903class EachMatcher {
2904 public:
2905 explicit EachMatcher(M m) : inner_matcher_(m) {}
2906
2907 template <typename Container>
2908 operator Matcher<Container>() const {
2909 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2910 }
2911
2912 private:
2913 const M inner_matcher_;
2914
2915 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2916};
2917
zhanyong.wanb5937da2009-07-16 20:26:41 +00002918// Implements Key(inner_matcher) for the given argument pair type.
2919// Key(inner_matcher) matches an std::pair whose 'first' field matches
2920// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2921// std::map that contains at least one element whose key is >= 5.
2922template <typename PairType>
2923class KeyMatcherImpl : public MatcherInterface<PairType> {
2924 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002925 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002926 typedef typename RawPairType::first_type KeyType;
2927
2928 template <typename InnerMatcher>
2929 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2930 : inner_matcher_(
2931 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2932 }
2933
2934 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002935 virtual bool MatchAndExplain(PairType key_value,
2936 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002937 StringMatchResultListener inner_listener;
2938 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2939 &inner_listener);
2940 const internal::string explanation = inner_listener.str();
2941 if (explanation != "") {
2942 *listener << "whose first field is a value " << explanation;
2943 }
2944 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002945 }
2946
2947 // Describes what this matcher does.
2948 virtual void DescribeTo(::std::ostream* os) const {
2949 *os << "has a key that ";
2950 inner_matcher_.DescribeTo(os);
2951 }
2952
2953 // Describes what the negation of this matcher does.
2954 virtual void DescribeNegationTo(::std::ostream* os) const {
2955 *os << "doesn't have a key that ";
2956 inner_matcher_.DescribeTo(os);
2957 }
2958
zhanyong.wanb5937da2009-07-16 20:26:41 +00002959 private:
2960 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002961
2962 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002963};
2964
2965// Implements polymorphic Key(matcher_for_key).
2966template <typename M>
2967class KeyMatcher {
2968 public:
2969 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2970
2971 template <typename PairType>
2972 operator Matcher<PairType>() const {
2973 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2974 }
2975
2976 private:
2977 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002978
2979 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002980};
2981
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002982// Implements Pair(first_matcher, second_matcher) for the given argument pair
2983// type with its two matchers. See Pair() function below.
2984template <typename PairType>
2985class PairMatcherImpl : public MatcherInterface<PairType> {
2986 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002987 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002988 typedef typename RawPairType::first_type FirstType;
2989 typedef typename RawPairType::second_type SecondType;
2990
2991 template <typename FirstMatcher, typename SecondMatcher>
2992 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2993 : first_matcher_(
2994 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2995 second_matcher_(
2996 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2997 }
2998
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002999 // Describes what this matcher does.
3000 virtual void DescribeTo(::std::ostream* os) const {
3001 *os << "has a first field that ";
3002 first_matcher_.DescribeTo(os);
3003 *os << ", and has a second field that ";
3004 second_matcher_.DescribeTo(os);
3005 }
3006
3007 // Describes what the negation of this matcher does.
3008 virtual void DescribeNegationTo(::std::ostream* os) const {
3009 *os << "has a first field that ";
3010 first_matcher_.DescribeNegationTo(os);
3011 *os << ", or has a second field that ";
3012 second_matcher_.DescribeNegationTo(os);
3013 }
3014
zhanyong.wan82113312010-01-08 21:55:40 +00003015 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3016 // matches second_matcher.
3017 virtual bool MatchAndExplain(PairType a_pair,
3018 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003019 if (!listener->IsInterested()) {
3020 // If the listener is not interested, we don't need to construct the
3021 // explanation.
3022 return first_matcher_.Matches(a_pair.first) &&
3023 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00003024 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003025 StringMatchResultListener first_inner_listener;
3026 if (!first_matcher_.MatchAndExplain(a_pair.first,
3027 &first_inner_listener)) {
3028 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003029 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003030 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003031 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003032 StringMatchResultListener second_inner_listener;
3033 if (!second_matcher_.MatchAndExplain(a_pair.second,
3034 &second_inner_listener)) {
3035 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003036 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003037 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003038 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003039 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3040 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00003041 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003042 }
3043
3044 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003045 void ExplainSuccess(const internal::string& first_explanation,
3046 const internal::string& second_explanation,
3047 MatchResultListener* listener) const {
3048 *listener << "whose both fields match";
3049 if (first_explanation != "") {
3050 *listener << ", where the first field is a value " << first_explanation;
3051 }
3052 if (second_explanation != "") {
3053 *listener << ", ";
3054 if (first_explanation != "") {
3055 *listener << "and ";
3056 } else {
3057 *listener << "where ";
3058 }
3059 *listener << "the second field is a value " << second_explanation;
3060 }
3061 }
3062
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003063 const Matcher<const FirstType&> first_matcher_;
3064 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003065
3066 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003067};
3068
3069// Implements polymorphic Pair(first_matcher, second_matcher).
3070template <typename FirstMatcher, typename SecondMatcher>
3071class PairMatcher {
3072 public:
3073 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3074 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3075
3076 template <typename PairType>
3077 operator Matcher<PairType> () const {
3078 return MakeMatcher(
3079 new PairMatcherImpl<PairType>(
3080 first_matcher_, second_matcher_));
3081 }
3082
3083 private:
3084 const FirstMatcher first_matcher_;
3085 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003086
3087 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003088};
3089
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003090// Implements ElementsAre() and ElementsAreArray().
3091template <typename Container>
3092class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3093 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003094 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003095 typedef internal::StlContainerView<RawContainer> View;
3096 typedef typename View::type StlContainer;
3097 typedef typename View::const_reference StlContainerReference;
3098 typedef typename StlContainer::value_type Element;
3099
3100 // Constructs the matcher from a sequence of element values or
3101 // element matchers.
3102 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00003103 ElementsAreMatcherImpl(InputIter first, InputIter last) {
3104 while (first != last) {
3105 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003106 }
3107 }
3108
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003109 // Describes what this matcher does.
3110 virtual void DescribeTo(::std::ostream* os) const {
3111 if (count() == 0) {
3112 *os << "is empty";
3113 } else if (count() == 1) {
3114 *os << "has 1 element that ";
3115 matchers_[0].DescribeTo(os);
3116 } else {
3117 *os << "has " << Elements(count()) << " where\n";
3118 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003119 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003120 matchers_[i].DescribeTo(os);
3121 if (i + 1 < count()) {
3122 *os << ",\n";
3123 }
3124 }
3125 }
3126 }
3127
3128 // Describes what the negation of this matcher does.
3129 virtual void DescribeNegationTo(::std::ostream* os) const {
3130 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003131 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003132 return;
3133 }
3134
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003135 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003136 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003137 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003138 matchers_[i].DescribeNegationTo(os);
3139 if (i + 1 < count()) {
3140 *os << ", or\n";
3141 }
3142 }
3143 }
3144
zhanyong.wan82113312010-01-08 21:55:40 +00003145 virtual bool MatchAndExplain(Container container,
3146 MatchResultListener* listener) const {
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003147 // To work with stream-like "containers", we must only walk
3148 // through the elements in one pass.
3149
3150 const bool listener_interested = listener->IsInterested();
3151
3152 // explanations[i] is the explanation of the element at index i.
3153 ::std::vector<internal::string> explanations(count());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003154 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003155 typename StlContainer::const_iterator it = stl_container.begin();
3156 size_t exam_pos = 0;
3157 bool mismatch_found = false; // Have we found a mismatched element yet?
3158
3159 // Go through the elements and matchers in pairs, until we reach
3160 // the end of either the elements or the matchers, or until we find a
3161 // mismatch.
3162 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3163 bool match; // Does the current element match the current matcher?
3164 if (listener_interested) {
3165 StringMatchResultListener s;
3166 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3167 explanations[exam_pos] = s.str();
3168 } else {
3169 match = matchers_[exam_pos].Matches(*it);
3170 }
3171
3172 if (!match) {
3173 mismatch_found = true;
3174 break;
3175 }
3176 }
3177 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3178
3179 // Find how many elements the actual container has. We avoid
3180 // calling size() s.t. this code works for stream-like "containers"
3181 // that don't define size().
3182 size_t actual_count = exam_pos;
3183 for (; it != stl_container.end(); ++it) {
3184 ++actual_count;
3185 }
3186
zhanyong.wan82113312010-01-08 21:55:40 +00003187 if (actual_count != count()) {
3188 // The element count doesn't match. If the container is empty,
3189 // there's no need to explain anything as Google Mock already
3190 // prints the empty container. Otherwise we just need to show
3191 // how many elements there actually are.
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003192 if (listener_interested && (actual_count != 0)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003193 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003194 }
zhanyong.wan82113312010-01-08 21:55:40 +00003195 return false;
3196 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003197
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003198 if (mismatch_found) {
3199 // The element count matches, but the exam_pos-th element doesn't match.
3200 if (listener_interested) {
3201 *listener << "whose element #" << exam_pos << " doesn't match";
3202 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003203 }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003204 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003205 }
zhanyong.wan82113312010-01-08 21:55:40 +00003206
3207 // Every element matches its expectation. We need to explain why
3208 // (the obvious ones can be skipped).
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003209 if (listener_interested) {
3210 bool reason_printed = false;
3211 for (size_t i = 0; i != count(); ++i) {
3212 const internal::string& s = explanations[i];
3213 if (!s.empty()) {
3214 if (reason_printed) {
3215 *listener << ",\nand ";
3216 }
3217 *listener << "whose element #" << i << " matches, " << s;
3218 reason_printed = true;
zhanyong.wan82113312010-01-08 21:55:40 +00003219 }
zhanyong.wan82113312010-01-08 21:55:40 +00003220 }
3221 }
zhanyong.wan82113312010-01-08 21:55:40 +00003222 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003223 }
3224
3225 private:
3226 static Message Elements(size_t count) {
3227 return Message() << count << (count == 1 ? " element" : " elements");
3228 }
3229
3230 size_t count() const { return matchers_.size(); }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003231
3232 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003233
3234 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003235};
3236
zhanyong.wanfb25d532013-07-28 08:24:00 +00003237// Connectivity matrix of (elements X matchers), in element-major order.
3238// Initially, there are no edges.
3239// Use NextGraph() to iterate over all possible edge configurations.
3240// Use Randomize() to generate a random edge configuration.
3241class GTEST_API_ MatchMatrix {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003242 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003243 MatchMatrix(size_t num_elements, size_t num_matchers)
3244 : num_elements_(num_elements),
3245 num_matchers_(num_matchers),
3246 matched_(num_elements_* num_matchers_, 0) {
3247 }
3248
3249 size_t LhsSize() const { return num_elements_; }
3250 size_t RhsSize() const { return num_matchers_; }
3251 bool HasEdge(size_t ilhs, size_t irhs) const {
3252 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3253 }
3254 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3255 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3256 }
3257
3258 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3259 // adds 1 to that number; returns false if incrementing the graph left it
3260 // empty.
3261 bool NextGraph();
3262
3263 void Randomize();
3264
3265 string DebugString() const;
3266
3267 private:
3268 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3269 return ilhs * num_matchers_ + irhs;
3270 }
3271
3272 size_t num_elements_;
3273 size_t num_matchers_;
3274
3275 // Each element is a char interpreted as bool. They are stored as a
3276 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3277 // a (ilhs, irhs) matrix coordinate into an offset.
3278 ::std::vector<char> matched_;
3279};
3280
3281typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3282typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3283
3284// Returns a maximum bipartite matching for the specified graph 'g'.
3285// The matching is represented as a vector of {element, matcher} pairs.
3286GTEST_API_ ElementMatcherPairs
3287FindMaxBipartiteMatching(const MatchMatrix& g);
3288
3289GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
3290 MatchResultListener* listener);
3291
3292// Untyped base class for implementing UnorderedElementsAre. By
3293// putting logic that's not specific to the element type here, we
3294// reduce binary bloat and increase compilation speed.
3295class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3296 protected:
3297 // A vector of matcher describers, one for each element matcher.
3298 // Does not own the describers (and thus can be used only when the
3299 // element matchers are alive).
3300 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3301
3302 // Describes this UnorderedElementsAre matcher.
3303 void DescribeToImpl(::std::ostream* os) const;
3304
3305 // Describes the negation of this UnorderedElementsAre matcher.
3306 void DescribeNegationToImpl(::std::ostream* os) const;
3307
3308 bool VerifyAllElementsAndMatchersAreMatched(
3309 const ::std::vector<string>& element_printouts,
3310 const MatchMatrix& matrix,
3311 MatchResultListener* listener) const;
3312
3313 MatcherDescriberVec& matcher_describers() {
3314 return matcher_describers_;
3315 }
3316
3317 static Message Elements(size_t n) {
3318 return Message() << n << " element" << (n == 1 ? "" : "s");
3319 }
3320
3321 private:
3322 MatcherDescriberVec matcher_describers_;
3323
3324 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3325};
3326
3327// Implements unordered ElementsAre and unordered ElementsAreArray.
3328template <typename Container>
3329class UnorderedElementsAreMatcherImpl
3330 : public MatcherInterface<Container>,
3331 public UnorderedElementsAreMatcherImplBase {
3332 public:
3333 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3334 typedef internal::StlContainerView<RawContainer> View;
3335 typedef typename View::type StlContainer;
3336 typedef typename View::const_reference StlContainerReference;
3337 typedef typename StlContainer::const_iterator StlContainerConstIterator;
3338 typedef typename StlContainer::value_type Element;
3339
3340 // Constructs the matcher from a sequence of element values or
3341 // element matchers.
3342 template <typename InputIter>
3343 UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) {
3344 for (; first != last; ++first) {
3345 matchers_.push_back(MatcherCast<const Element&>(*first));
3346 matcher_describers().push_back(matchers_.back().GetDescriber());
3347 }
3348 }
3349
3350 // Describes what this matcher does.
3351 virtual void DescribeTo(::std::ostream* os) const {
3352 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3353 }
3354
3355 // Describes what the negation of this matcher does.
3356 virtual void DescribeNegationTo(::std::ostream* os) const {
3357 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3358 }
3359
3360 virtual bool MatchAndExplain(Container container,
3361 MatchResultListener* listener) const {
3362 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003363 ::std::vector<string> element_printouts;
3364 MatchMatrix matrix = AnalyzeElements(stl_container.begin(),
3365 stl_container.end(),
3366 &element_printouts,
3367 listener);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003368
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003369 const size_t actual_count = matrix.LhsSize();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003370 if (actual_count == 0 && matchers_.empty()) {
3371 return true;
3372 }
3373 if (actual_count != matchers_.size()) {
3374 // The element count doesn't match. If the container is empty,
3375 // there's no need to explain anything as Google Mock already
3376 // prints the empty container. Otherwise we just need to show
3377 // how many elements there actually are.
3378 if (actual_count != 0 && listener->IsInterested()) {
3379 *listener << "which has " << Elements(actual_count);
3380 }
3381 return false;
3382 }
3383
zhanyong.wanfb25d532013-07-28 08:24:00 +00003384 return VerifyAllElementsAndMatchersAreMatched(element_printouts,
3385 matrix, listener) &&
3386 FindPairing(matrix, listener);
3387 }
3388
3389 private:
3390 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3391
3392 template <typename ElementIter>
3393 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
3394 ::std::vector<string>* element_printouts,
3395 MatchResultListener* listener) const {
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003396 element_printouts->clear();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003397 ::std::vector<char> did_match;
3398 size_t num_elements = 0;
3399 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3400 if (listener->IsInterested()) {
3401 element_printouts->push_back(PrintToString(*elem_first));
3402 }
3403 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3404 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3405 }
3406 }
3407
3408 MatchMatrix matrix(num_elements, matchers_.size());
3409 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3410 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3411 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3412 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3413 }
3414 }
3415 return matrix;
3416 }
3417
3418 MatcherVec matchers_;
3419
3420 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3421};
3422
3423// Functor for use in TransformTuple.
3424// Performs MatcherCast<Target> on an input argument of any type.
3425template <typename Target>
3426struct CastAndAppendTransform {
3427 template <typename Arg>
3428 Matcher<Target> operator()(const Arg& a) const {
3429 return MatcherCast<Target>(a);
3430 }
3431};
3432
3433// Implements UnorderedElementsAre.
3434template <typename MatcherTuple>
3435class UnorderedElementsAreMatcher {
3436 public:
3437 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3438 : matchers_(args) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003439
3440 template <typename Container>
3441 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003442 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003443 typedef typename internal::StlContainerView<RawContainer>::type View;
3444 typedef typename View::value_type Element;
3445 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3446 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003447 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003448 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3449 ::std::back_inserter(matchers));
3450 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3451 matchers.begin(), matchers.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003452 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003453
3454 private:
3455 const MatcherTuple matchers_;
3456 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3457};
3458
3459// Implements ElementsAre.
3460template <typename MatcherTuple>
3461class ElementsAreMatcher {
3462 public:
3463 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3464
3465 template <typename Container>
3466 operator Matcher<Container>() const {
3467 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3468 typedef typename internal::StlContainerView<RawContainer>::type View;
3469 typedef typename View::value_type Element;
3470 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3471 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003472 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003473 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3474 ::std::back_inserter(matchers));
3475 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3476 matchers.begin(), matchers.end()));
3477 }
3478
3479 private:
3480 const MatcherTuple matchers_;
3481 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3482};
3483
3484// Implements UnorderedElementsAreArray().
3485template <typename T>
3486class UnorderedElementsAreArrayMatcher {
3487 public:
3488 UnorderedElementsAreArrayMatcher() {}
3489
3490 template <typename Iter>
3491 UnorderedElementsAreArrayMatcher(Iter first, Iter last)
3492 : matchers_(first, last) {}
3493
3494 template <typename Container>
3495 operator Matcher<Container>() const {
3496 return MakeMatcher(
3497 new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(),
3498 matchers_.end()));
3499 }
3500
3501 private:
3502 ::std::vector<T> matchers_;
3503
3504 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003505};
3506
3507// Implements ElementsAreArray().
3508template <typename T>
3509class ElementsAreArrayMatcher {
3510 public:
jgm38513a82012-11-15 15:50:36 +00003511 template <typename Iter>
3512 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003513
3514 template <typename Container>
3515 operator Matcher<Container>() const {
jgm38513a82012-11-15 15:50:36 +00003516 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3517 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003518 }
3519
3520 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003521 const ::std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003522
3523 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003524};
3525
kosak2336e9c2014-07-28 22:57:30 +00003526// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3527// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3528// second) is a polymorphic matcher that matches a value x iff tm
3529// matches tuple (x, second). Useful for implementing
3530// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3531//
3532// BoundSecondMatcher is copyable and assignable, as we need to put
3533// instances of this class in a vector when implementing
3534// UnorderedPointwise().
3535template <typename Tuple2Matcher, typename Second>
3536class BoundSecondMatcher {
3537 public:
3538 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3539 : tuple2_matcher_(tm), second_value_(second) {}
3540
3541 template <typename T>
3542 operator Matcher<T>() const {
3543 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3544 }
3545
3546 // We have to define this for UnorderedPointwise() to compile in
3547 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3548 // which requires the elements to be assignable in C++98. The
3549 // compiler cannot generate the operator= for us, as Tuple2Matcher
3550 // and Second may not be assignable.
3551 //
3552 // However, this should never be called, so the implementation just
3553 // need to assert.
3554 void operator=(const BoundSecondMatcher& /*rhs*/) {
3555 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3556 }
3557
3558 private:
3559 template <typename T>
3560 class Impl : public MatcherInterface<T> {
3561 public:
3562 typedef ::testing::tuple<T, Second> ArgTuple;
3563
3564 Impl(const Tuple2Matcher& tm, const Second& second)
3565 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3566 second_value_(second) {}
3567
3568 virtual void DescribeTo(::std::ostream* os) const {
3569 *os << "and ";
3570 UniversalPrint(second_value_, os);
3571 *os << " ";
3572 mono_tuple2_matcher_.DescribeTo(os);
3573 }
3574
3575 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3576 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3577 listener);
3578 }
3579
3580 private:
3581 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3582 const Second second_value_;
3583
3584 GTEST_DISALLOW_ASSIGN_(Impl);
3585 };
3586
3587 const Tuple2Matcher tuple2_matcher_;
3588 const Second second_value_;
3589};
3590
3591// Given a 2-tuple matcher tm and a value second,
3592// MatcherBindSecond(tm, second) returns a matcher that matches a
3593// value x iff tm matches tuple (x, second). Useful for implementing
3594// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3595template <typename Tuple2Matcher, typename Second>
3596BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
3597 const Tuple2Matcher& tm, const Second& second) {
3598 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
3599}
3600
zhanyong.wanb4140802010-06-08 22:53:57 +00003601// Returns the description for a matcher defined using the MATCHER*()
3602// macro where the user-supplied description string is "", if
3603// 'negation' is false; otherwise returns the description of the
3604// negation of the matcher. 'param_values' contains a list of strings
3605// that are the print-out of the matcher's parameters.
vladlosev587c1b32011-05-20 00:42:22 +00003606GTEST_API_ string FormatMatcherDescription(bool negation,
3607 const char* matcher_name,
3608 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003609
shiqiane35fdd92008-12-10 05:08:54 +00003610} // namespace internal
3611
zhanyong.wanfb25d532013-07-28 08:24:00 +00003612// ElementsAreArray(first, last)
3613// ElementsAreArray(pointer, count)
3614// ElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00003615// ElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003616// ElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00003617//
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003618// The ElementsAreArray() functions are like ElementsAre(...), except
3619// that they are given a homogeneous sequence rather than taking each
3620// element as a function argument. The sequence can be specified as an
3621// array, a pointer and count, a vector, an initializer list, or an
3622// STL iterator range. In each of these cases, the underlying sequence
3623// can be either a sequence of values or a sequence of matchers.
zhanyong.wanfb25d532013-07-28 08:24:00 +00003624//
3625// All forms of ElementsAreArray() make a copy of the input matcher sequence.
3626
3627template <typename Iter>
3628inline internal::ElementsAreArrayMatcher<
3629 typename ::std::iterator_traits<Iter>::value_type>
3630ElementsAreArray(Iter first, Iter last) {
3631 typedef typename ::std::iterator_traits<Iter>::value_type T;
3632 return internal::ElementsAreArrayMatcher<T>(first, last);
3633}
3634
3635template <typename T>
3636inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3637 const T* pointer, size_t count) {
3638 return ElementsAreArray(pointer, pointer + count);
3639}
3640
3641template <typename T, size_t N>
3642inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3643 const T (&array)[N]) {
3644 return ElementsAreArray(array, N);
3645}
3646
kosak06678922014-07-28 20:01:28 +00003647template <typename Container>
3648inline internal::ElementsAreArrayMatcher<typename Container::value_type>
3649ElementsAreArray(const Container& container) {
3650 return ElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00003651}
3652
kosak18489fa2013-12-04 23:49:07 +00003653#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003654template <typename T>
3655inline internal::ElementsAreArrayMatcher<T>
3656ElementsAreArray(::std::initializer_list<T> xs) {
3657 return ElementsAreArray(xs.begin(), xs.end());
3658}
3659#endif
3660
zhanyong.wanfb25d532013-07-28 08:24:00 +00003661// UnorderedElementsAreArray(first, last)
3662// UnorderedElementsAreArray(pointer, count)
3663// UnorderedElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00003664// UnorderedElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003665// UnorderedElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00003666//
3667// The UnorderedElementsAreArray() functions are like
3668// ElementsAreArray(...), but allow matching the elements in any order.
3669template <typename Iter>
3670inline internal::UnorderedElementsAreArrayMatcher<
3671 typename ::std::iterator_traits<Iter>::value_type>
3672UnorderedElementsAreArray(Iter first, Iter last) {
3673 typedef typename ::std::iterator_traits<Iter>::value_type T;
3674 return internal::UnorderedElementsAreArrayMatcher<T>(first, last);
3675}
3676
3677template <typename T>
3678inline internal::UnorderedElementsAreArrayMatcher<T>
3679UnorderedElementsAreArray(const T* pointer, size_t count) {
3680 return UnorderedElementsAreArray(pointer, pointer + count);
3681}
3682
3683template <typename T, size_t N>
3684inline internal::UnorderedElementsAreArrayMatcher<T>
3685UnorderedElementsAreArray(const T (&array)[N]) {
3686 return UnorderedElementsAreArray(array, N);
3687}
3688
kosak06678922014-07-28 20:01:28 +00003689template <typename Container>
3690inline internal::UnorderedElementsAreArrayMatcher<
3691 typename Container::value_type>
3692UnorderedElementsAreArray(const Container& container) {
3693 return UnorderedElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00003694}
3695
kosak18489fa2013-12-04 23:49:07 +00003696#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003697template <typename T>
3698inline internal::UnorderedElementsAreArrayMatcher<T>
3699UnorderedElementsAreArray(::std::initializer_list<T> xs) {
3700 return UnorderedElementsAreArray(xs.begin(), xs.end());
3701}
3702#endif
zhanyong.wanfb25d532013-07-28 08:24:00 +00003703
shiqiane35fdd92008-12-10 05:08:54 +00003704// _ is a matcher that matches anything of any type.
3705//
3706// This definition is fine as:
3707//
3708// 1. The C++ standard permits using the name _ in a namespace that
3709// is not the global namespace or ::std.
3710// 2. The AnythingMatcher class has no data member or constructor,
3711// so it's OK to create global variables of this type.
3712// 3. c-style has approved of using _ in this case.
3713const internal::AnythingMatcher _ = {};
3714// Creates a matcher that matches any value of the given type T.
3715template <typename T>
3716inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
3717
3718// Creates a matcher that matches any value of the given type T.
3719template <typename T>
3720inline Matcher<T> An() { return A<T>(); }
3721
3722// Creates a polymorphic matcher that matches anything equal to x.
3723// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
3724// wouldn't compile.
3725template <typename T>
3726inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
3727
3728// Constructs a Matcher<T> from a 'value' of type T. The constructed
3729// matcher matches any value that's equal to 'value'.
3730template <typename T>
3731Matcher<T>::Matcher(T value) { *this = Eq(value); }
3732
3733// Creates a monomorphic matcher that matches anything with type Lhs
3734// and equal to rhs. A user may need to use this instead of Eq(...)
3735// in order to resolve an overloading ambiguity.
3736//
3737// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
3738// or Matcher<T>(x), but more readable than the latter.
3739//
3740// We could define similar monomorphic matchers for other comparison
3741// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
3742// it yet as those are used much less than Eq() in practice. A user
3743// can always write Matcher<T>(Lt(5)) to be explicit about the type,
3744// for example.
3745template <typename Lhs, typename Rhs>
3746inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
3747
3748// Creates a polymorphic matcher that matches anything >= x.
3749template <typename Rhs>
3750inline internal::GeMatcher<Rhs> Ge(Rhs x) {
3751 return internal::GeMatcher<Rhs>(x);
3752}
3753
3754// Creates a polymorphic matcher that matches anything > x.
3755template <typename Rhs>
3756inline internal::GtMatcher<Rhs> Gt(Rhs x) {
3757 return internal::GtMatcher<Rhs>(x);
3758}
3759
3760// Creates a polymorphic matcher that matches anything <= x.
3761template <typename Rhs>
3762inline internal::LeMatcher<Rhs> Le(Rhs x) {
3763 return internal::LeMatcher<Rhs>(x);
3764}
3765
3766// Creates a polymorphic matcher that matches anything < x.
3767template <typename Rhs>
3768inline internal::LtMatcher<Rhs> Lt(Rhs x) {
3769 return internal::LtMatcher<Rhs>(x);
3770}
3771
3772// Creates a polymorphic matcher that matches anything != x.
3773template <typename Rhs>
3774inline internal::NeMatcher<Rhs> Ne(Rhs x) {
3775 return internal::NeMatcher<Rhs>(x);
3776}
3777
zhanyong.wan2d970ee2009-09-24 21:41:36 +00003778// Creates a polymorphic matcher that matches any NULL pointer.
3779inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
3780 return MakePolymorphicMatcher(internal::IsNullMatcher());
3781}
3782
shiqiane35fdd92008-12-10 05:08:54 +00003783// Creates a polymorphic matcher that matches any non-NULL pointer.
3784// This is convenient as Not(NULL) doesn't compile (the compiler
3785// thinks that that expression is comparing a pointer with an integer).
3786inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
3787 return MakePolymorphicMatcher(internal::NotNullMatcher());
3788}
3789
3790// Creates a polymorphic matcher that matches any argument that
3791// references variable x.
3792template <typename T>
3793inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
3794 return internal::RefMatcher<T&>(x);
3795}
3796
3797// Creates a matcher that matches any double argument approximately
3798// equal to rhs, where two NANs are considered unequal.
3799inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
3800 return internal::FloatingEqMatcher<double>(rhs, false);
3801}
3802
3803// Creates a matcher that matches any double argument approximately
3804// equal to rhs, including NaN values when rhs is NaN.
3805inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
3806 return internal::FloatingEqMatcher<double>(rhs, true);
3807}
3808
zhanyong.wan616180e2013-06-18 18:49:51 +00003809// Creates a matcher that matches any double argument approximately equal to
3810// rhs, up to the specified max absolute error bound, where two NANs are
3811// considered unequal. The max absolute error bound must be non-negative.
3812inline internal::FloatingEqMatcher<double> DoubleNear(
3813 double rhs, double max_abs_error) {
3814 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
3815}
3816
3817// Creates a matcher that matches any double argument approximately equal to
3818// rhs, up to the specified max absolute error bound, including NaN values when
3819// rhs is NaN. The max absolute error bound must be non-negative.
3820inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
3821 double rhs, double max_abs_error) {
3822 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
3823}
3824
shiqiane35fdd92008-12-10 05:08:54 +00003825// Creates a matcher that matches any float argument approximately
3826// equal to rhs, where two NANs are considered unequal.
3827inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
3828 return internal::FloatingEqMatcher<float>(rhs, false);
3829}
3830
zhanyong.wan616180e2013-06-18 18:49:51 +00003831// Creates a matcher that matches any float argument approximately
shiqiane35fdd92008-12-10 05:08:54 +00003832// equal to rhs, including NaN values when rhs is NaN.
3833inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
3834 return internal::FloatingEqMatcher<float>(rhs, true);
3835}
3836
zhanyong.wan616180e2013-06-18 18:49:51 +00003837// Creates a matcher that matches any float argument approximately equal to
3838// rhs, up to the specified max absolute error bound, where two NANs are
3839// considered unequal. The max absolute error bound must be non-negative.
3840inline internal::FloatingEqMatcher<float> FloatNear(
3841 float rhs, float max_abs_error) {
3842 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
3843}
3844
3845// Creates a matcher that matches any float argument approximately equal to
3846// rhs, up to the specified max absolute error bound, including NaN values when
3847// rhs is NaN. The max absolute error bound must be non-negative.
3848inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
3849 float rhs, float max_abs_error) {
3850 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
3851}
3852
shiqiane35fdd92008-12-10 05:08:54 +00003853// Creates a matcher that matches a pointer (raw or smart) that points
3854// to a value that matches inner_matcher.
3855template <typename InnerMatcher>
3856inline internal::PointeeMatcher<InnerMatcher> Pointee(
3857 const InnerMatcher& inner_matcher) {
3858 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
3859}
3860
billydonahue1f5fdea2014-05-19 17:54:51 +00003861// Creates a matcher that matches a pointer or reference that matches
3862// inner_matcher when dynamic_cast<To> is applied.
3863// The result of dynamic_cast<To> is forwarded to the inner matcher.
3864// If To is a pointer and the cast fails, the inner matcher will receive NULL.
3865// If To is a reference and the cast fails, this matcher returns false
3866// immediately.
3867template <typename To>
3868inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
3869WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
3870 return MakePolymorphicMatcher(
3871 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
3872}
3873
shiqiane35fdd92008-12-10 05:08:54 +00003874// Creates a matcher that matches an object whose given field matches
3875// 'matcher'. For example,
3876// Field(&Foo::number, Ge(5))
3877// matches a Foo object x iff x.number >= 5.
3878template <typename Class, typename FieldType, typename FieldMatcher>
3879inline PolymorphicMatcher<
3880 internal::FieldMatcher<Class, FieldType> > Field(
3881 FieldType Class::*field, const FieldMatcher& matcher) {
3882 return MakePolymorphicMatcher(
3883 internal::FieldMatcher<Class, FieldType>(
3884 field, MatcherCast<const FieldType&>(matcher)));
3885 // The call to MatcherCast() is required for supporting inner
3886 // matchers of compatible types. For example, it allows
3887 // Field(&Foo::bar, m)
3888 // to compile where bar is an int32 and m is a matcher for int64.
3889}
3890
3891// Creates a matcher that matches an object whose given property
3892// matches 'matcher'. For example,
3893// Property(&Foo::str, StartsWith("hi"))
3894// matches a Foo object x iff x.str() starts with "hi".
3895template <typename Class, typename PropertyType, typename PropertyMatcher>
3896inline PolymorphicMatcher<
3897 internal::PropertyMatcher<Class, PropertyType> > Property(
3898 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
3899 return MakePolymorphicMatcher(
3900 internal::PropertyMatcher<Class, PropertyType>(
3901 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00003902 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00003903 // The call to MatcherCast() is required for supporting inner
3904 // matchers of compatible types. For example, it allows
3905 // Property(&Foo::bar, m)
3906 // to compile where bar() returns an int32 and m is a matcher for int64.
3907}
3908
3909// Creates a matcher that matches an object iff the result of applying
3910// a callable to x matches 'matcher'.
3911// For example,
3912// ResultOf(f, StartsWith("hi"))
3913// matches a Foo object x iff f(x) starts with "hi".
3914// callable parameter can be a function, function pointer, or a functor.
3915// Callable has to satisfy the following conditions:
3916// * It is required to keep no state affecting the results of
3917// the calls on it and make no assumptions about how many calls
3918// will be made. Any state it keeps must be protected from the
3919// concurrent access.
3920// * If it is a function object, it has to define type result_type.
3921// We recommend deriving your functor classes from std::unary_function.
3922template <typename Callable, typename ResultOfMatcher>
3923internal::ResultOfMatcher<Callable> ResultOf(
3924 Callable callable, const ResultOfMatcher& matcher) {
3925 return internal::ResultOfMatcher<Callable>(
3926 callable,
3927 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
3928 matcher));
3929 // The call to MatcherCast() is required for supporting inner
3930 // matchers of compatible types. For example, it allows
3931 // ResultOf(Function, m)
3932 // to compile where Function() returns an int32 and m is a matcher for int64.
3933}
3934
3935// String matchers.
3936
3937// Matches a string equal to str.
3938inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3939 StrEq(const internal::string& str) {
3940 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3941 str, true, true));
3942}
3943
3944// Matches a string not equal to str.
3945inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3946 StrNe(const internal::string& str) {
3947 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3948 str, false, true));
3949}
3950
3951// Matches a string equal to str, ignoring case.
3952inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3953 StrCaseEq(const internal::string& str) {
3954 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3955 str, true, false));
3956}
3957
3958// Matches a string not equal to str, ignoring case.
3959inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3960 StrCaseNe(const internal::string& str) {
3961 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3962 str, false, false));
3963}
3964
3965// Creates a matcher that matches any string, std::string, or C string
3966// that contains the given substring.
3967inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
3968 HasSubstr(const internal::string& substring) {
3969 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
3970 substring));
3971}
3972
3973// Matches a string that starts with 'prefix' (case-sensitive).
3974inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
3975 StartsWith(const internal::string& prefix) {
3976 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
3977 prefix));
3978}
3979
3980// Matches a string that ends with 'suffix' (case-sensitive).
3981inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
3982 EndsWith(const internal::string& suffix) {
3983 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
3984 suffix));
3985}
3986
shiqiane35fdd92008-12-10 05:08:54 +00003987// Matches a string that fully matches regular expression 'regex'.
3988// The matcher takes ownership of 'regex'.
3989inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3990 const internal::RE* regex) {
3991 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
3992}
3993inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3994 const internal::string& regex) {
3995 return MatchesRegex(new internal::RE(regex));
3996}
3997
3998// Matches a string that contains regular expression 'regex'.
3999// The matcher takes ownership of 'regex'.
4000inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4001 const internal::RE* regex) {
4002 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4003}
4004inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4005 const internal::string& regex) {
4006 return ContainsRegex(new internal::RE(regex));
4007}
4008
shiqiane35fdd92008-12-10 05:08:54 +00004009#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4010// Wide string matchers.
4011
4012// Matches a string equal to str.
4013inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4014 StrEq(const internal::wstring& str) {
4015 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4016 str, true, true));
4017}
4018
4019// Matches a string not equal to str.
4020inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4021 StrNe(const internal::wstring& str) {
4022 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4023 str, false, true));
4024}
4025
4026// Matches a string equal to str, ignoring case.
4027inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4028 StrCaseEq(const internal::wstring& str) {
4029 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4030 str, true, false));
4031}
4032
4033// Matches a string not equal to str, ignoring case.
4034inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4035 StrCaseNe(const internal::wstring& str) {
4036 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4037 str, false, false));
4038}
4039
4040// Creates a matcher that matches any wstring, std::wstring, or C wide string
4041// that contains the given substring.
4042inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
4043 HasSubstr(const internal::wstring& substring) {
4044 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
4045 substring));
4046}
4047
4048// Matches a string that starts with 'prefix' (case-sensitive).
4049inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
4050 StartsWith(const internal::wstring& prefix) {
4051 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
4052 prefix));
4053}
4054
4055// Matches a string that ends with 'suffix' (case-sensitive).
4056inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
4057 EndsWith(const internal::wstring& suffix) {
4058 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
4059 suffix));
4060}
4061
4062#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4063
4064// Creates a polymorphic matcher that matches a 2-tuple where the
4065// first field == the second field.
4066inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4067
4068// Creates a polymorphic matcher that matches a 2-tuple where the
4069// first field >= the second field.
4070inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4071
4072// Creates a polymorphic matcher that matches a 2-tuple where the
4073// first field > the second field.
4074inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4075
4076// Creates a polymorphic matcher that matches a 2-tuple where the
4077// first field <= the second field.
4078inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4079
4080// Creates a polymorphic matcher that matches a 2-tuple where the
4081// first field < the second field.
4082inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4083
4084// Creates a polymorphic matcher that matches a 2-tuple where the
4085// first field != the second field.
4086inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4087
4088// Creates a matcher that matches any value of type T that m doesn't
4089// match.
4090template <typename InnerMatcher>
4091inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4092 return internal::NotMatcher<InnerMatcher>(m);
4093}
4094
shiqiane35fdd92008-12-10 05:08:54 +00004095// Returns a matcher that matches anything that satisfies the given
4096// predicate. The predicate can be any unary function or functor
4097// whose return type can be implicitly converted to bool.
4098template <typename Predicate>
4099inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4100Truly(Predicate pred) {
4101 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4102}
4103
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004104// Returns a matcher that matches the container size. The container must
4105// support both size() and size_type which all STL-like containers provide.
4106// Note that the parameter 'size' can be a value of type size_type as well as
4107// matcher. For instance:
4108// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
4109// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
4110template <typename SizeMatcher>
4111inline internal::SizeIsMatcher<SizeMatcher>
4112SizeIs(const SizeMatcher& size_matcher) {
4113 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4114}
4115
kosakb6a34882014-03-12 21:06:46 +00004116// Returns a matcher that matches the distance between the container's begin()
4117// iterator and its end() iterator, i.e. the size of the container. This matcher
4118// can be used instead of SizeIs with containers such as std::forward_list which
4119// do not implement size(). The container must provide const_iterator (with
4120// valid iterator_traits), begin() and end().
4121template <typename DistanceMatcher>
4122inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4123BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4124 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4125}
4126
zhanyong.wan6a896b52009-01-16 01:13:50 +00004127// Returns a matcher that matches an equal container.
4128// This matcher behaves like Eq(), but in the event of mismatch lists the
4129// values that are included in one container but not the other. (Duplicate
4130// values and order differences are not explained.)
4131template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00004132inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00004133 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004134 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00004135 // This following line is for working around a bug in MSVC 8.0,
4136 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00004137 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00004138 return MakePolymorphicMatcher(
4139 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00004140}
4141
zhanyong.wan898725c2011-09-16 16:45:39 +00004142// Returns a matcher that matches a container that, when sorted using
4143// the given comparator, matches container_matcher.
4144template <typename Comparator, typename ContainerMatcher>
4145inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4146WhenSortedBy(const Comparator& comparator,
4147 const ContainerMatcher& container_matcher) {
4148 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4149 comparator, container_matcher);
4150}
4151
4152// Returns a matcher that matches a container that, when sorted using
4153// the < operator, matches container_matcher.
4154template <typename ContainerMatcher>
4155inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4156WhenSorted(const ContainerMatcher& container_matcher) {
4157 return
4158 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4159 internal::LessComparator(), container_matcher);
4160}
4161
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004162// Matches an STL-style container or a native array that contains the
4163// same number of elements as in rhs, where its i-th element and rhs's
4164// i-th element (as a pair) satisfy the given pair matcher, for all i.
4165// TupleMatcher must be able to be safely cast to Matcher<tuple<const
4166// T1&, const T2&> >, where T1 and T2 are the types of elements in the
4167// LHS container and the RHS container respectively.
4168template <typename TupleMatcher, typename Container>
4169inline internal::PointwiseMatcher<TupleMatcher,
4170 GTEST_REMOVE_CONST_(Container)>
4171Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4172 // This following line is for working around a bug in MSVC 8.0,
kosak2336e9c2014-07-28 22:57:30 +00004173 // which causes Container to be a const type sometimes (e.g. when
4174 // rhs is a const int[])..
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004175 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4176 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4177 tuple_matcher, rhs);
4178}
4179
kosak2336e9c2014-07-28 22:57:30 +00004180#if GTEST_HAS_STD_INITIALIZER_LIST_
4181
4182// Supports the Pointwise(m, {a, b, c}) syntax.
4183template <typename TupleMatcher, typename T>
4184inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4185 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4186 return Pointwise(tuple_matcher, std::vector<T>(rhs));
4187}
4188
4189#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4190
4191// UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4192// container or a native array that contains the same number of
4193// elements as in rhs, where in some permutation of the container, its
4194// i-th element and rhs's i-th element (as a pair) satisfy the given
4195// pair matcher, for all i. Tuple2Matcher must be able to be safely
4196// cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4197// the types of elements in the LHS container and the RHS container
4198// respectively.
4199//
4200// This is like Pointwise(pair_matcher, rhs), except that the element
4201// order doesn't matter.
4202template <typename Tuple2Matcher, typename RhsContainer>
4203inline internal::UnorderedElementsAreArrayMatcher<
4204 typename internal::BoundSecondMatcher<
4205 Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4206 RhsContainer)>::type::value_type> >
4207UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4208 const RhsContainer& rhs_container) {
4209 // This following line is for working around a bug in MSVC 8.0,
4210 // which causes RhsContainer to be a const type sometimes (e.g. when
4211 // rhs_container is a const int[]).
4212 typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4213
4214 // RhsView allows the same code to handle RhsContainer being a
4215 // STL-style container and it being a native C-style array.
4216 typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4217 typedef typename RhsView::type RhsStlContainer;
4218 typedef typename RhsStlContainer::value_type Second;
4219 const RhsStlContainer& rhs_stl_container =
4220 RhsView::ConstReference(rhs_container);
4221
4222 // Create a matcher for each element in rhs_container.
4223 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4224 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4225 it != rhs_stl_container.end(); ++it) {
4226 matchers.push_back(
4227 internal::MatcherBindSecond(tuple2_matcher, *it));
4228 }
4229
4230 // Delegate the work to UnorderedElementsAreArray().
4231 return UnorderedElementsAreArray(matchers);
4232}
4233
4234#if GTEST_HAS_STD_INITIALIZER_LIST_
4235
4236// Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4237template <typename Tuple2Matcher, typename T>
4238inline internal::UnorderedElementsAreArrayMatcher<
4239 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4240UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4241 std::initializer_list<T> rhs) {
4242 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4243}
4244
4245#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4246
zhanyong.wanb8243162009-06-04 05:48:20 +00004247// Matches an STL-style container or a native array that contains at
4248// least one element matching the given value or matcher.
4249//
4250// Examples:
4251// ::std::set<int> page_ids;
4252// page_ids.insert(3);
4253// page_ids.insert(1);
4254// EXPECT_THAT(page_ids, Contains(1));
4255// EXPECT_THAT(page_ids, Contains(Gt(2)));
4256// EXPECT_THAT(page_ids, Not(Contains(4)));
4257//
4258// ::std::map<int, size_t> page_lengths;
4259// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00004260// EXPECT_THAT(page_lengths,
4261// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004262//
4263// const char* user_ids[] = { "joe", "mike", "tom" };
4264// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4265template <typename M>
4266inline internal::ContainsMatcher<M> Contains(M matcher) {
4267 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004268}
4269
zhanyong.wan33605ba2010-04-22 23:37:47 +00004270// Matches an STL-style container or a native array that contains only
4271// elements matching the given value or matcher.
4272//
4273// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
4274// the messages are different.
4275//
4276// Examples:
4277// ::std::set<int> page_ids;
4278// // Each(m) matches an empty container, regardless of what m is.
4279// EXPECT_THAT(page_ids, Each(Eq(1)));
4280// EXPECT_THAT(page_ids, Each(Eq(77)));
4281//
4282// page_ids.insert(3);
4283// EXPECT_THAT(page_ids, Each(Gt(0)));
4284// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
4285// page_ids.insert(1);
4286// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
4287//
4288// ::std::map<int, size_t> page_lengths;
4289// page_lengths[1] = 100;
4290// page_lengths[2] = 200;
4291// page_lengths[3] = 300;
4292// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
4293// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
4294//
4295// const char* user_ids[] = { "joe", "mike", "tom" };
4296// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
4297template <typename M>
4298inline internal::EachMatcher<M> Each(M matcher) {
4299 return internal::EachMatcher<M>(matcher);
4300}
4301
zhanyong.wanb5937da2009-07-16 20:26:41 +00004302// Key(inner_matcher) matches an std::pair whose 'first' field matches
4303// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
4304// std::map that contains at least one element whose key is >= 5.
4305template <typename M>
4306inline internal::KeyMatcher<M> Key(M inner_matcher) {
4307 return internal::KeyMatcher<M>(inner_matcher);
4308}
4309
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00004310// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
4311// matches first_matcher and whose 'second' field matches second_matcher. For
4312// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
4313// to match a std::map<int, string> that contains exactly one element whose key
4314// is >= 5 and whose value equals "foo".
4315template <typename FirstMatcher, typename SecondMatcher>
4316inline internal::PairMatcher<FirstMatcher, SecondMatcher>
4317Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
4318 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
4319 first_matcher, second_matcher);
4320}
4321
shiqiane35fdd92008-12-10 05:08:54 +00004322// Returns a predicate that is satisfied by anything that matches the
4323// given matcher.
4324template <typename M>
4325inline internal::MatcherAsPredicate<M> Matches(M matcher) {
4326 return internal::MatcherAsPredicate<M>(matcher);
4327}
4328
zhanyong.wanb8243162009-06-04 05:48:20 +00004329// Returns true iff the value matches the matcher.
4330template <typename T, typename M>
4331inline bool Value(const T& value, M matcher) {
4332 return testing::Matches(matcher)(value);
4333}
4334
zhanyong.wan34b034c2010-03-05 21:23:23 +00004335// Matches the value against the given matcher and explains the match
4336// result to listener.
4337template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00004338inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00004339 M matcher, const T& value, MatchResultListener* listener) {
4340 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
4341}
4342
zhanyong.wan616180e2013-06-18 18:49:51 +00004343#if GTEST_LANG_CXX11
4344// Define variadic matcher versions. They are overloaded in
4345// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
4346template <typename... Args>
4347inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
4348 return internal::AllOfMatcher<Args...>(matchers...);
4349}
4350
4351template <typename... Args>
4352inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
4353 return internal::AnyOfMatcher<Args...>(matchers...);
4354}
4355
4356#endif // GTEST_LANG_CXX11
4357
zhanyong.wanbf550852009-06-09 06:09:53 +00004358// AllArgs(m) is a synonym of m. This is useful in
4359//
4360// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
4361//
4362// which is easier to read than
4363//
4364// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
4365template <typename InnerMatcher>
4366inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
4367
shiqiane35fdd92008-12-10 05:08:54 +00004368// These macros allow using matchers to check values in Google Test
4369// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
4370// succeed iff the value matches the matcher. If the assertion fails,
4371// the value and the description of the matcher will be printed.
4372#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
4373 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4374#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
4375 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4376
4377} // namespace testing
4378
4379#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
billydonahue1f5fdea2014-05-19 17:54:51 +00004380