blob: 822337b12b3d8f687e6b5c55bc334de4f7119893 [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 {
kosak6305ff52015-04-28 22:36:31 +0000982#if GTEST_LANG_CXX11
983 return p == nullptr;
984#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +0000985 return GetRawPointer(p) == NULL;
kosak6305ff52015-04-28 22:36:31 +0000986#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +0000987 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000988
989 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
990 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000991 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000992 }
993};
994
vladlosev79b83502009-11-18 00:43:37 +0000995// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000996// pointer that is not NULL.
997class NotNullMatcher {
998 public:
vladlosev79b83502009-11-18 00:43:37 +0000999 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +00001000 bool MatchAndExplain(const Pointer& p,
1001 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001002#if GTEST_LANG_CXX11
1003 return p != nullptr;
1004#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001005 return GetRawPointer(p) != NULL;
kosak6305ff52015-04-28 22:36:31 +00001006#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001007 }
shiqiane35fdd92008-12-10 05:08:54 +00001008
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001009 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +00001010 void DescribeNegationTo(::std::ostream* os) const {
1011 *os << "is NULL";
1012 }
1013};
1014
1015// Ref(variable) matches any argument that is a reference to
1016// 'variable'. This matcher is polymorphic as it can match any
1017// super type of the type of 'variable'.
1018//
1019// The RefMatcher template class implements Ref(variable). It can
1020// only be instantiated with a reference type. This prevents a user
1021// from mistakenly using Ref(x) to match a non-reference function
1022// argument. For example, the following will righteously cause a
1023// compiler error:
1024//
1025// int n;
1026// Matcher<int> m1 = Ref(n); // This won't compile.
1027// Matcher<int&> m2 = Ref(n); // This will compile.
1028template <typename T>
1029class RefMatcher;
1030
1031template <typename T>
1032class RefMatcher<T&> {
1033 // Google Mock is a generic framework and thus needs to support
1034 // mocking any function types, including those that take non-const
1035 // reference arguments. Therefore the template parameter T (and
1036 // Super below) can be instantiated to either a const type or a
1037 // non-const type.
1038 public:
1039 // RefMatcher() takes a T& instead of const T&, as we want the
1040 // compiler to catch using Ref(const_value) as a matcher for a
1041 // non-const reference.
1042 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
1043
1044 template <typename Super>
1045 operator Matcher<Super&>() const {
1046 // By passing object_ (type T&) to Impl(), which expects a Super&,
1047 // we make sure that Super is a super type of T. In particular,
1048 // this catches using Ref(const_value) as a matcher for a
1049 // non-const reference, as you cannot implicitly convert a const
1050 // reference to a non-const reference.
1051 return MakeMatcher(new Impl<Super>(object_));
1052 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001053
shiqiane35fdd92008-12-10 05:08:54 +00001054 private:
1055 template <typename Super>
1056 class Impl : public MatcherInterface<Super&> {
1057 public:
1058 explicit Impl(Super& x) : object_(x) {} // NOLINT
1059
zhanyong.wandb22c222010-01-28 21:52:29 +00001060 // MatchAndExplain() takes a Super& (as opposed to const Super&)
1061 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +00001062 virtual bool MatchAndExplain(
1063 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001064 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +00001065 return &x == &object_;
1066 }
shiqiane35fdd92008-12-10 05:08:54 +00001067
1068 virtual void DescribeTo(::std::ostream* os) const {
1069 *os << "references the variable ";
1070 UniversalPrinter<Super&>::Print(object_, os);
1071 }
1072
1073 virtual void DescribeNegationTo(::std::ostream* os) const {
1074 *os << "does not reference the variable ";
1075 UniversalPrinter<Super&>::Print(object_, os);
1076 }
1077
shiqiane35fdd92008-12-10 05:08:54 +00001078 private:
1079 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001080
1081 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001082 };
1083
1084 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001085
1086 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001087};
1088
1089// Polymorphic helper functions for narrow and wide string matchers.
1090inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1091 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1092}
1093
1094inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1095 const wchar_t* rhs) {
1096 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1097}
1098
1099// String comparison for narrow or wide strings that can have embedded NUL
1100// characters.
1101template <typename StringType>
1102bool CaseInsensitiveStringEquals(const StringType& s1,
1103 const StringType& s2) {
1104 // Are the heads equal?
1105 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1106 return false;
1107 }
1108
1109 // Skip the equal heads.
1110 const typename StringType::value_type nul = 0;
1111 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1112
1113 // Are we at the end of either s1 or s2?
1114 if (i1 == StringType::npos || i2 == StringType::npos) {
1115 return i1 == i2;
1116 }
1117
1118 // Are the tails equal?
1119 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1120}
1121
1122// String matchers.
1123
1124// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1125template <typename StringType>
1126class StrEqualityMatcher {
1127 public:
shiqiane35fdd92008-12-10 05:08:54 +00001128 StrEqualityMatcher(const StringType& str, bool expect_eq,
1129 bool case_sensitive)
1130 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1131
jgm38513a82012-11-15 15:50:36 +00001132 // Accepts pointer types, particularly:
1133 // const char*
1134 // char*
1135 // const wchar_t*
1136 // wchar_t*
1137 template <typename CharType>
1138 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001139 if (s == NULL) {
1140 return !expect_eq_;
1141 }
zhanyong.wandb22c222010-01-28 21:52:29 +00001142 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001143 }
1144
jgm38513a82012-11-15 15:50:36 +00001145 // Matches anything that can convert to StringType.
1146 //
1147 // This is a template, not just a plain function with const StringType&,
1148 // because StringPiece has some interfering non-explicit constructors.
1149 template <typename MatcheeStringType>
1150 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001151 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001152 const StringType& s2(s);
1153 const bool eq = case_sensitive_ ? s2 == string_ :
1154 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +00001155 return expect_eq_ == eq;
1156 }
1157
1158 void DescribeTo(::std::ostream* os) const {
1159 DescribeToHelper(expect_eq_, os);
1160 }
1161
1162 void DescribeNegationTo(::std::ostream* os) const {
1163 DescribeToHelper(!expect_eq_, os);
1164 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001165
shiqiane35fdd92008-12-10 05:08:54 +00001166 private:
1167 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001168 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +00001169 *os << "equal to ";
1170 if (!case_sensitive_) {
1171 *os << "(ignoring case) ";
1172 }
vladloseve2e8ba42010-05-13 18:16:03 +00001173 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001174 }
1175
1176 const StringType string_;
1177 const bool expect_eq_;
1178 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001179
1180 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001181};
1182
1183// Implements the polymorphic HasSubstr(substring) matcher, which
1184// can be used as a Matcher<T> as long as T can be converted to a
1185// string.
1186template <typename StringType>
1187class HasSubstrMatcher {
1188 public:
shiqiane35fdd92008-12-10 05:08:54 +00001189 explicit HasSubstrMatcher(const StringType& substring)
1190 : substring_(substring) {}
1191
jgm38513a82012-11-15 15:50:36 +00001192 // Accepts pointer types, particularly:
1193 // const char*
1194 // char*
1195 // const wchar_t*
1196 // wchar_t*
1197 template <typename CharType>
1198 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001199 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001200 }
1201
jgm38513a82012-11-15 15:50:36 +00001202 // Matches anything that can convert to StringType.
1203 //
1204 // This is a template, not just a plain function with const StringType&,
1205 // because StringPiece has some interfering non-explicit constructors.
1206 template <typename MatcheeStringType>
1207 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001208 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001209 const StringType& s2(s);
1210 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001211 }
1212
1213 // Describes what this matcher matches.
1214 void DescribeTo(::std::ostream* os) const {
1215 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001216 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001217 }
1218
1219 void DescribeNegationTo(::std::ostream* os) const {
1220 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001221 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001222 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001223
shiqiane35fdd92008-12-10 05:08:54 +00001224 private:
1225 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001226
1227 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001228};
1229
1230// Implements the polymorphic StartsWith(substring) matcher, which
1231// can be used as a Matcher<T> as long as T can be converted to a
1232// string.
1233template <typename StringType>
1234class StartsWithMatcher {
1235 public:
shiqiane35fdd92008-12-10 05:08:54 +00001236 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1237 }
1238
jgm38513a82012-11-15 15:50:36 +00001239 // Accepts pointer types, particularly:
1240 // const char*
1241 // char*
1242 // const wchar_t*
1243 // wchar_t*
1244 template <typename CharType>
1245 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001246 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001247 }
1248
jgm38513a82012-11-15 15:50:36 +00001249 // Matches anything that can convert to StringType.
1250 //
1251 // This is a template, not just a plain function with const StringType&,
1252 // because StringPiece has some interfering non-explicit constructors.
1253 template <typename MatcheeStringType>
1254 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001255 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001256 const StringType& s2(s);
1257 return s2.length() >= prefix_.length() &&
1258 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001259 }
1260
1261 void DescribeTo(::std::ostream* os) const {
1262 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001263 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001264 }
1265
1266 void DescribeNegationTo(::std::ostream* os) const {
1267 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001268 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001269 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001270
shiqiane35fdd92008-12-10 05:08:54 +00001271 private:
1272 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001273
1274 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001275};
1276
1277// Implements the polymorphic EndsWith(substring) matcher, which
1278// can be used as a Matcher<T> as long as T can be converted to a
1279// string.
1280template <typename StringType>
1281class EndsWithMatcher {
1282 public:
shiqiane35fdd92008-12-10 05:08:54 +00001283 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1284
jgm38513a82012-11-15 15:50:36 +00001285 // Accepts pointer types, particularly:
1286 // const char*
1287 // char*
1288 // const wchar_t*
1289 // wchar_t*
1290 template <typename CharType>
1291 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001292 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001293 }
1294
jgm38513a82012-11-15 15:50:36 +00001295 // Matches anything that can convert to StringType.
1296 //
1297 // This is a template, not just a plain function with const StringType&,
1298 // because StringPiece has some interfering non-explicit constructors.
1299 template <typename MatcheeStringType>
1300 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001301 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001302 const StringType& s2(s);
1303 return s2.length() >= suffix_.length() &&
1304 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001305 }
1306
1307 void DescribeTo(::std::ostream* os) const {
1308 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001309 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001310 }
1311
1312 void DescribeNegationTo(::std::ostream* os) const {
1313 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001314 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001315 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001316
shiqiane35fdd92008-12-10 05:08:54 +00001317 private:
1318 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001319
1320 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001321};
1322
shiqiane35fdd92008-12-10 05:08:54 +00001323// Implements polymorphic matchers MatchesRegex(regex) and
1324// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1325// T can be converted to a string.
1326class MatchesRegexMatcher {
1327 public:
1328 MatchesRegexMatcher(const RE* regex, bool full_match)
1329 : regex_(regex), full_match_(full_match) {}
1330
jgm38513a82012-11-15 15:50:36 +00001331 // Accepts pointer types, particularly:
1332 // const char*
1333 // char*
1334 // const wchar_t*
1335 // wchar_t*
1336 template <typename CharType>
1337 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001338 return s != NULL && MatchAndExplain(internal::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001339 }
1340
jgm38513a82012-11-15 15:50:36 +00001341 // Matches anything that can convert to internal::string.
1342 //
1343 // This is a template, not just a plain function with const internal::string&,
1344 // because StringPiece has some interfering non-explicit constructors.
1345 template <class MatcheeStringType>
1346 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001347 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001348 const internal::string& s2(s);
1349 return full_match_ ? RE::FullMatch(s2, *regex_) :
1350 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001351 }
1352
1353 void DescribeTo(::std::ostream* os) const {
1354 *os << (full_match_ ? "matches" : "contains")
1355 << " regular expression ";
1356 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1357 }
1358
1359 void DescribeNegationTo(::std::ostream* os) const {
1360 *os << "doesn't " << (full_match_ ? "match" : "contain")
1361 << " regular expression ";
1362 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1363 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001364
shiqiane35fdd92008-12-10 05:08:54 +00001365 private:
1366 const internal::linked_ptr<const RE> regex_;
1367 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001368
1369 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001370};
1371
shiqiane35fdd92008-12-10 05:08:54 +00001372// Implements a matcher that compares the two fields of a 2-tuple
1373// using one of the ==, <=, <, etc, operators. The two fields being
1374// compared don't have to have the same type.
1375//
1376// The matcher defined here is polymorphic (for example, Eq() can be
1377// used to match a tuple<int, short>, a tuple<const long&, double>,
1378// etc). Therefore we use a template type conversion operator in the
1379// implementation.
kosak506340a2014-11-17 01:47:54 +00001380template <typename D, typename Op>
1381class PairMatchBase {
1382 public:
1383 template <typename T1, typename T2>
1384 operator Matcher< ::testing::tuple<T1, T2> >() const {
1385 return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >);
1386 }
1387 template <typename T1, typename T2>
1388 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
1389 return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>);
shiqiane35fdd92008-12-10 05:08:54 +00001390 }
1391
kosak506340a2014-11-17 01:47:54 +00001392 private:
1393 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
1394 return os << D::Desc();
1395 }
shiqiane35fdd92008-12-10 05:08:54 +00001396
kosak506340a2014-11-17 01:47:54 +00001397 template <typename Tuple>
1398 class Impl : public MatcherInterface<Tuple> {
1399 public:
1400 virtual bool MatchAndExplain(
1401 Tuple args,
1402 MatchResultListener* /* listener */) const {
1403 return Op()(::testing::get<0>(args), ::testing::get<1>(args));
1404 }
1405 virtual void DescribeTo(::std::ostream* os) const {
1406 *os << "are " << GetDesc;
1407 }
1408 virtual void DescribeNegationTo(::std::ostream* os) const {
1409 *os << "aren't " << GetDesc;
1410 }
1411 };
1412};
1413
1414class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
1415 public:
1416 static const char* Desc() { return "an equal pair"; }
1417};
1418class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
1419 public:
1420 static const char* Desc() { return "an unequal pair"; }
1421};
1422class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
1423 public:
1424 static const char* Desc() { return "a pair where the first < the second"; }
1425};
1426class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
1427 public:
1428 static const char* Desc() { return "a pair where the first > the second"; }
1429};
1430class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
1431 public:
1432 static const char* Desc() { return "a pair where the first <= the second"; }
1433};
1434class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
1435 public:
1436 static const char* Desc() { return "a pair where the first >= the second"; }
1437};
shiqiane35fdd92008-12-10 05:08:54 +00001438
zhanyong.wanc6a41232009-05-13 23:38:40 +00001439// Implements the Not(...) matcher for a particular argument type T.
1440// We do not nest it inside the NotMatcher class template, as that
1441// will prevent different instantiations of NotMatcher from sharing
1442// the same NotMatcherImpl<T> class.
1443template <typename T>
1444class NotMatcherImpl : public MatcherInterface<T> {
1445 public:
1446 explicit NotMatcherImpl(const Matcher<T>& matcher)
1447 : matcher_(matcher) {}
1448
zhanyong.wan82113312010-01-08 21:55:40 +00001449 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1450 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001451 }
1452
1453 virtual void DescribeTo(::std::ostream* os) const {
1454 matcher_.DescribeNegationTo(os);
1455 }
1456
1457 virtual void DescribeNegationTo(::std::ostream* os) const {
1458 matcher_.DescribeTo(os);
1459 }
1460
zhanyong.wanc6a41232009-05-13 23:38:40 +00001461 private:
1462 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001463
1464 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001465};
1466
shiqiane35fdd92008-12-10 05:08:54 +00001467// Implements the Not(m) matcher, which matches a value that doesn't
1468// match matcher m.
1469template <typename InnerMatcher>
1470class NotMatcher {
1471 public:
1472 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1473
1474 // This template type conversion operator allows Not(m) to be used
1475 // to match any type m can match.
1476 template <typename T>
1477 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001478 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001479 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001480
shiqiane35fdd92008-12-10 05:08:54 +00001481 private:
shiqiane35fdd92008-12-10 05:08:54 +00001482 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001483
1484 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001485};
1486
zhanyong.wanc6a41232009-05-13 23:38:40 +00001487// Implements the AllOf(m1, m2) matcher for a particular argument type
1488// T. We do not nest it inside the BothOfMatcher class template, as
1489// that will prevent different instantiations of BothOfMatcher from
1490// sharing the same BothOfMatcherImpl<T> class.
1491template <typename T>
1492class BothOfMatcherImpl : public MatcherInterface<T> {
1493 public:
1494 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1495 : matcher1_(matcher1), matcher2_(matcher2) {}
1496
zhanyong.wanc6a41232009-05-13 23:38:40 +00001497 virtual void DescribeTo(::std::ostream* os) const {
1498 *os << "(";
1499 matcher1_.DescribeTo(os);
1500 *os << ") and (";
1501 matcher2_.DescribeTo(os);
1502 *os << ")";
1503 }
1504
1505 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001506 *os << "(";
1507 matcher1_.DescribeNegationTo(os);
1508 *os << ") or (";
1509 matcher2_.DescribeNegationTo(os);
1510 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001511 }
1512
zhanyong.wan82113312010-01-08 21:55:40 +00001513 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1514 // If either matcher1_ or matcher2_ doesn't match x, we only need
1515 // to explain why one of them fails.
1516 StringMatchResultListener listener1;
1517 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1518 *listener << listener1.str();
1519 return false;
1520 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001521
zhanyong.wan82113312010-01-08 21:55:40 +00001522 StringMatchResultListener listener2;
1523 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1524 *listener << listener2.str();
1525 return false;
1526 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001527
zhanyong.wan82113312010-01-08 21:55:40 +00001528 // Otherwise we need to explain why *both* of them match.
1529 const internal::string s1 = listener1.str();
1530 const internal::string s2 = listener2.str();
1531
1532 if (s1 == "") {
1533 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001534 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001535 *listener << s1;
1536 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001537 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001538 }
1539 }
zhanyong.wan82113312010-01-08 21:55:40 +00001540 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001541 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001542
zhanyong.wanc6a41232009-05-13 23:38:40 +00001543 private:
1544 const Matcher<T> matcher1_;
1545 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001546
1547 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001548};
1549
zhanyong.wan616180e2013-06-18 18:49:51 +00001550#if GTEST_LANG_CXX11
1551// MatcherList provides mechanisms for storing a variable number of matchers in
1552// a list structure (ListType) and creating a combining matcher from such a
1553// list.
1554// The template is defined recursively using the following template paramters:
1555// * kSize is the length of the MatcherList.
1556// * Head is the type of the first matcher of the list.
1557// * Tail denotes the types of the remaining matchers of the list.
1558template <int kSize, typename Head, typename... Tail>
1559struct MatcherList {
1560 typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
zhanyong.wan29897032013-06-20 18:59:15 +00001561 typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001562
1563 // BuildList stores variadic type values in a nested pair structure.
1564 // Example:
1565 // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
1566 // the corresponding result of type pair<int, pair<string, float>>.
1567 static ListType BuildList(const Head& matcher, const Tail&... tail) {
1568 return ListType(matcher, MatcherListTail::BuildList(tail...));
1569 }
1570
1571 // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
1572 // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
1573 // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
1574 // constructor taking two Matcher<T>s as input.
1575 template <typename T, template <typename /* T */> class CombiningMatcher>
1576 static Matcher<T> CreateMatcher(const ListType& matchers) {
1577 return Matcher<T>(new CombiningMatcher<T>(
1578 SafeMatcherCast<T>(matchers.first),
1579 MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
1580 matchers.second)));
1581 }
1582};
1583
1584// The following defines the base case for the recursive definition of
1585// MatcherList.
1586template <typename Matcher1, typename Matcher2>
1587struct MatcherList<2, Matcher1, Matcher2> {
zhanyong.wan29897032013-06-20 18:59:15 +00001588 typedef ::std::pair<Matcher1, Matcher2> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001589
1590 static ListType BuildList(const Matcher1& matcher1,
1591 const Matcher2& matcher2) {
zhanyong.wan29897032013-06-20 18:59:15 +00001592 return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
zhanyong.wan616180e2013-06-18 18:49:51 +00001593 }
1594
1595 template <typename T, template <typename /* T */> class CombiningMatcher>
1596 static Matcher<T> CreateMatcher(const ListType& matchers) {
1597 return Matcher<T>(new CombiningMatcher<T>(
1598 SafeMatcherCast<T>(matchers.first),
1599 SafeMatcherCast<T>(matchers.second)));
1600 }
1601};
1602
1603// VariadicMatcher is used for the variadic implementation of
1604// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1605// CombiningMatcher<T> is used to recursively combine the provided matchers
1606// (of type Args...).
1607template <template <typename T> class CombiningMatcher, typename... Args>
1608class VariadicMatcher {
1609 public:
1610 VariadicMatcher(const Args&... matchers) // NOLINT
1611 : matchers_(MatcherListType::BuildList(matchers...)) {}
1612
1613 // This template type conversion operator allows an
1614 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1615 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1616 template <typename T>
1617 operator Matcher<T>() const {
1618 return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
1619 matchers_);
1620 }
1621
1622 private:
1623 typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
1624
1625 const typename MatcherListType::ListType matchers_;
1626
1627 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1628};
1629
1630template <typename... Args>
1631using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
1632
1633#endif // GTEST_LANG_CXX11
1634
shiqiane35fdd92008-12-10 05:08:54 +00001635// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1636// matches a value that matches all of the matchers m_1, ..., and m_n.
1637template <typename Matcher1, typename Matcher2>
1638class BothOfMatcher {
1639 public:
1640 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1641 : matcher1_(matcher1), matcher2_(matcher2) {}
1642
1643 // This template type conversion operator allows a
1644 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1645 // both Matcher1 and Matcher2 can match.
1646 template <typename T>
1647 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001648 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1649 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001650 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001651
shiqiane35fdd92008-12-10 05:08:54 +00001652 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001653 Matcher1 matcher1_;
1654 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001655
1656 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001657};
shiqiane35fdd92008-12-10 05:08:54 +00001658
zhanyong.wanc6a41232009-05-13 23:38:40 +00001659// Implements the AnyOf(m1, m2) matcher for a particular argument type
1660// T. We do not nest it inside the AnyOfMatcher class template, as
1661// that will prevent different instantiations of AnyOfMatcher from
1662// sharing the same EitherOfMatcherImpl<T> class.
1663template <typename T>
1664class EitherOfMatcherImpl : public MatcherInterface<T> {
1665 public:
1666 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1667 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001668
zhanyong.wanc6a41232009-05-13 23:38:40 +00001669 virtual void DescribeTo(::std::ostream* os) const {
1670 *os << "(";
1671 matcher1_.DescribeTo(os);
1672 *os << ") or (";
1673 matcher2_.DescribeTo(os);
1674 *os << ")";
1675 }
shiqiane35fdd92008-12-10 05:08:54 +00001676
zhanyong.wanc6a41232009-05-13 23:38:40 +00001677 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001678 *os << "(";
1679 matcher1_.DescribeNegationTo(os);
1680 *os << ") and (";
1681 matcher2_.DescribeNegationTo(os);
1682 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001683 }
shiqiane35fdd92008-12-10 05:08:54 +00001684
zhanyong.wan82113312010-01-08 21:55:40 +00001685 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1686 // If either matcher1_ or matcher2_ matches x, we just need to
1687 // explain why *one* of them matches.
1688 StringMatchResultListener listener1;
1689 if (matcher1_.MatchAndExplain(x, &listener1)) {
1690 *listener << listener1.str();
1691 return true;
1692 }
1693
1694 StringMatchResultListener listener2;
1695 if (matcher2_.MatchAndExplain(x, &listener2)) {
1696 *listener << listener2.str();
1697 return true;
1698 }
1699
1700 // Otherwise we need to explain why *both* of them fail.
1701 const internal::string s1 = listener1.str();
1702 const internal::string s2 = listener2.str();
1703
1704 if (s1 == "") {
1705 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001706 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001707 *listener << s1;
1708 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001709 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001710 }
1711 }
zhanyong.wan82113312010-01-08 21:55:40 +00001712 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001713 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001714
zhanyong.wanc6a41232009-05-13 23:38:40 +00001715 private:
1716 const Matcher<T> matcher1_;
1717 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001718
1719 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001720};
1721
zhanyong.wan616180e2013-06-18 18:49:51 +00001722#if GTEST_LANG_CXX11
1723// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1724template <typename... Args>
1725using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
1726
1727#endif // GTEST_LANG_CXX11
1728
shiqiane35fdd92008-12-10 05:08:54 +00001729// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1730// matches a value that matches at least one of the matchers m_1, ...,
1731// and m_n.
1732template <typename Matcher1, typename Matcher2>
1733class EitherOfMatcher {
1734 public:
1735 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1736 : matcher1_(matcher1), matcher2_(matcher2) {}
1737
1738 // This template type conversion operator allows a
1739 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1740 // both Matcher1 and Matcher2 can match.
1741 template <typename T>
1742 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001743 return Matcher<T>(new EitherOfMatcherImpl<T>(
1744 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001745 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001746
shiqiane35fdd92008-12-10 05:08:54 +00001747 private:
shiqiane35fdd92008-12-10 05:08:54 +00001748 Matcher1 matcher1_;
1749 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001750
1751 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001752};
1753
1754// Used for implementing Truly(pred), which turns a predicate into a
1755// matcher.
1756template <typename Predicate>
1757class TrulyMatcher {
1758 public:
1759 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1760
1761 // This method template allows Truly(pred) to be used as a matcher
1762 // for type T where T is the argument type of predicate 'pred'. The
1763 // argument is passed by reference as the predicate may be
1764 // interested in the address of the argument.
1765 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001766 bool MatchAndExplain(T& x, // NOLINT
1767 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001768 // Without the if-statement, MSVC sometimes warns about converting
1769 // a value to bool (warning 4800).
1770 //
1771 // We cannot write 'return !!predicate_(x);' as that doesn't work
1772 // when predicate_(x) returns a class convertible to bool but
1773 // having no operator!().
1774 if (predicate_(x))
1775 return true;
1776 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001777 }
1778
1779 void DescribeTo(::std::ostream* os) const {
1780 *os << "satisfies the given predicate";
1781 }
1782
1783 void DescribeNegationTo(::std::ostream* os) const {
1784 *os << "doesn't satisfy the given predicate";
1785 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001786
shiqiane35fdd92008-12-10 05:08:54 +00001787 private:
1788 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001789
1790 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001791};
1792
1793// Used for implementing Matches(matcher), which turns a matcher into
1794// a predicate.
1795template <typename M>
1796class MatcherAsPredicate {
1797 public:
1798 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1799
1800 // This template operator() allows Matches(m) to be used as a
1801 // predicate on type T where m is a matcher on type T.
1802 //
1803 // The argument x is passed by reference instead of by value, as
1804 // some matcher may be interested in its address (e.g. as in
1805 // Matches(Ref(n))(x)).
1806 template <typename T>
1807 bool operator()(const T& x) const {
1808 // We let matcher_ commit to a particular type here instead of
1809 // when the MatcherAsPredicate object was constructed. This
1810 // allows us to write Matches(m) where m is a polymorphic matcher
1811 // (e.g. Eq(5)).
1812 //
1813 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1814 // compile when matcher_ has type Matcher<const T&>; if we write
1815 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1816 // when matcher_ has type Matcher<T>; if we just write
1817 // matcher_.Matches(x), it won't compile when matcher_ is
1818 // polymorphic, e.g. Eq(5).
1819 //
1820 // MatcherCast<const T&>() is necessary for making the code work
1821 // in all of the above situations.
1822 return MatcherCast<const T&>(matcher_).Matches(x);
1823 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001824
shiqiane35fdd92008-12-10 05:08:54 +00001825 private:
1826 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001827
1828 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001829};
1830
1831// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1832// argument M must be a type that can be converted to a matcher.
1833template <typename M>
1834class PredicateFormatterFromMatcher {
1835 public:
1836 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1837
1838 // This template () operator allows a PredicateFormatterFromMatcher
1839 // object to act as a predicate-formatter suitable for using with
1840 // Google Test's EXPECT_PRED_FORMAT1() macro.
1841 template <typename T>
1842 AssertionResult operator()(const char* value_text, const T& x) const {
1843 // We convert matcher_ to a Matcher<const T&> *now* instead of
1844 // when the PredicateFormatterFromMatcher object was constructed,
1845 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1846 // know which type to instantiate it to until we actually see the
1847 // type of x here.
1848 //
zhanyong.wanf4274522013-04-24 02:49:43 +00001849 // We write SafeMatcherCast<const T&>(matcher_) instead of
shiqiane35fdd92008-12-10 05:08:54 +00001850 // Matcher<const T&>(matcher_), as the latter won't compile when
1851 // matcher_ has type Matcher<T> (e.g. An<int>()).
zhanyong.wanf4274522013-04-24 02:49:43 +00001852 // We don't write MatcherCast<const T&> either, as that allows
1853 // potentially unsafe downcasting of the matcher argument.
1854 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001855 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001856 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001857 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001858
1859 ::std::stringstream ss;
1860 ss << "Value of: " << value_text << "\n"
1861 << "Expected: ";
1862 matcher.DescribeTo(&ss);
1863 ss << "\n Actual: " << listener.str();
1864 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001865 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001866
shiqiane35fdd92008-12-10 05:08:54 +00001867 private:
1868 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001869
1870 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001871};
1872
1873// A helper function for converting a matcher to a predicate-formatter
1874// without the user needing to explicitly write the type. This is
1875// used for implementing ASSERT_THAT() and EXPECT_THAT().
1876template <typename M>
1877inline PredicateFormatterFromMatcher<M>
1878MakePredicateFormatterFromMatcher(const M& matcher) {
1879 return PredicateFormatterFromMatcher<M>(matcher);
1880}
1881
zhanyong.wan616180e2013-06-18 18:49:51 +00001882// Implements the polymorphic floating point equality matcher, which matches
1883// two float values using ULP-based approximation or, optionally, a
1884// user-specified epsilon. The template is meant to be instantiated with
1885// FloatType being either float or double.
shiqiane35fdd92008-12-10 05:08:54 +00001886template <typename FloatType>
1887class FloatingEqMatcher {
1888 public:
1889 // Constructor for FloatingEqMatcher.
kosak6b817802015-01-08 02:38:14 +00001890 // The matcher's input will be compared with expected. The matcher treats two
shiqiane35fdd92008-12-10 05:08:54 +00001891 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
zhanyong.wan616180e2013-06-18 18:49:51 +00001892 // equality comparisons between NANs will always return false. We specify a
1893 // negative max_abs_error_ term to indicate that ULP-based approximation will
1894 // be used for comparison.
kosak6b817802015-01-08 02:38:14 +00001895 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
1896 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001897 }
1898
1899 // Constructor that supports a user-specified max_abs_error that will be used
1900 // for comparison instead of ULP-based approximation. The max absolute
1901 // should be non-negative.
kosak6b817802015-01-08 02:38:14 +00001902 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
1903 FloatType max_abs_error)
1904 : expected_(expected),
1905 nan_eq_nan_(nan_eq_nan),
1906 max_abs_error_(max_abs_error) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001907 GTEST_CHECK_(max_abs_error >= 0)
1908 << ", where max_abs_error is" << max_abs_error;
1909 }
shiqiane35fdd92008-12-10 05:08:54 +00001910
1911 // Implements floating point equality matcher as a Matcher<T>.
1912 template <typename T>
1913 class Impl : public MatcherInterface<T> {
1914 public:
kosak6b817802015-01-08 02:38:14 +00001915 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
1916 : expected_(expected),
1917 nan_eq_nan_(nan_eq_nan),
1918 max_abs_error_(max_abs_error) {}
shiqiane35fdd92008-12-10 05:08:54 +00001919
zhanyong.wan82113312010-01-08 21:55:40 +00001920 virtual bool MatchAndExplain(T value,
kosak6b817802015-01-08 02:38:14 +00001921 MatchResultListener* listener) const {
1922 const FloatingPoint<FloatType> actual(value), expected(expected_);
shiqiane35fdd92008-12-10 05:08:54 +00001923
1924 // Compares NaNs first, if nan_eq_nan_ is true.
kosak6b817802015-01-08 02:38:14 +00001925 if (actual.is_nan() || expected.is_nan()) {
1926 if (actual.is_nan() && expected.is_nan()) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001927 return nan_eq_nan_;
1928 }
1929 // One is nan; the other is not nan.
1930 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001931 }
zhanyong.wan616180e2013-06-18 18:49:51 +00001932 if (HasMaxAbsError()) {
1933 // We perform an equality check so that inf will match inf, regardless
kosak6b817802015-01-08 02:38:14 +00001934 // of error bounds. If the result of value - expected_ would result in
zhanyong.wan616180e2013-06-18 18:49:51 +00001935 // overflow or if either value is inf, the default result is infinity,
1936 // which should only match if max_abs_error_ is also infinity.
kosak6b817802015-01-08 02:38:14 +00001937 if (value == expected_) {
1938 return true;
1939 }
1940
1941 const FloatType diff = value - expected_;
1942 if (fabs(diff) <= max_abs_error_) {
1943 return true;
1944 }
1945
1946 if (listener->IsInterested()) {
1947 *listener << "which is " << diff << " from " << expected_;
1948 }
1949 return false;
zhanyong.wan616180e2013-06-18 18:49:51 +00001950 } else {
kosak6b817802015-01-08 02:38:14 +00001951 return actual.AlmostEquals(expected);
zhanyong.wan616180e2013-06-18 18:49:51 +00001952 }
shiqiane35fdd92008-12-10 05:08:54 +00001953 }
1954
1955 virtual void DescribeTo(::std::ostream* os) const {
1956 // os->precision() returns the previously set precision, which we
1957 // store to restore the ostream to its original configuration
1958 // after outputting.
1959 const ::std::streamsize old_precision = os->precision(
1960 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00001961 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00001962 if (nan_eq_nan_) {
1963 *os << "is NaN";
1964 } else {
1965 *os << "never matches";
1966 }
1967 } else {
kosak6b817802015-01-08 02:38:14 +00001968 *os << "is approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001969 if (HasMaxAbsError()) {
1970 *os << " (absolute error <= " << max_abs_error_ << ")";
1971 }
shiqiane35fdd92008-12-10 05:08:54 +00001972 }
1973 os->precision(old_precision);
1974 }
1975
1976 virtual void DescribeNegationTo(::std::ostream* os) const {
1977 // As before, get original precision.
1978 const ::std::streamsize old_precision = os->precision(
1979 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00001980 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00001981 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001982 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00001983 } else {
1984 *os << "is anything";
1985 }
1986 } else {
kosak6b817802015-01-08 02:38:14 +00001987 *os << "isn't approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001988 if (HasMaxAbsError()) {
1989 *os << " (absolute error > " << max_abs_error_ << ")";
1990 }
shiqiane35fdd92008-12-10 05:08:54 +00001991 }
1992 // Restore original precision.
1993 os->precision(old_precision);
1994 }
1995
1996 private:
zhanyong.wan616180e2013-06-18 18:49:51 +00001997 bool HasMaxAbsError() const {
1998 return max_abs_error_ >= 0;
1999 }
2000
kosak6b817802015-01-08 02:38:14 +00002001 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002002 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002003 // max_abs_error will be used for value comparison when >= 0.
2004 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002005
2006 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002007 };
2008
kosak6b817802015-01-08 02:38:14 +00002009 // The following 3 type conversion operators allow FloatEq(expected) and
2010 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
shiqiane35fdd92008-12-10 05:08:54 +00002011 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
2012 // (While Google's C++ coding style doesn't allow arguments passed
2013 // by non-const reference, we may see them in code not conforming to
2014 // the style. Therefore Google Mock needs to support them.)
2015 operator Matcher<FloatType>() const {
kosak6b817802015-01-08 02:38:14 +00002016 return MakeMatcher(
2017 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002018 }
2019
2020 operator Matcher<const FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00002021 return MakeMatcher(
kosak6b817802015-01-08 02:38:14 +00002022 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002023 }
2024
2025 operator Matcher<FloatType&>() const {
kosak6b817802015-01-08 02:38:14 +00002026 return MakeMatcher(
2027 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002028 }
jgm79a367e2012-04-10 16:02:11 +00002029
shiqiane35fdd92008-12-10 05:08:54 +00002030 private:
kosak6b817802015-01-08 02:38:14 +00002031 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002032 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002033 // max_abs_error will be used for value comparison when >= 0.
2034 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002035
2036 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002037};
2038
2039// Implements the Pointee(m) matcher for matching a pointer whose
2040// pointee matches matcher m. The pointer can be either raw or smart.
2041template <typename InnerMatcher>
2042class PointeeMatcher {
2043 public:
2044 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
2045
2046 // This type conversion operator template allows Pointee(m) to be
2047 // used as a matcher for any pointer type whose pointee type is
2048 // compatible with the inner matcher, where type Pointer can be
2049 // either a raw pointer or a smart pointer.
2050 //
2051 // The reason we do this instead of relying on
2052 // MakePolymorphicMatcher() is that the latter is not flexible
2053 // enough for implementing the DescribeTo() method of Pointee().
2054 template <typename Pointer>
2055 operator Matcher<Pointer>() const {
2056 return MakeMatcher(new Impl<Pointer>(matcher_));
2057 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002058
shiqiane35fdd92008-12-10 05:08:54 +00002059 private:
2060 // The monomorphic implementation that works for a particular pointer type.
2061 template <typename Pointer>
2062 class Impl : public MatcherInterface<Pointer> {
2063 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00002064 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
2065 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00002066
2067 explicit Impl(const InnerMatcher& matcher)
2068 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
2069
shiqiane35fdd92008-12-10 05:08:54 +00002070 virtual void DescribeTo(::std::ostream* os) const {
2071 *os << "points to a value that ";
2072 matcher_.DescribeTo(os);
2073 }
2074
2075 virtual void DescribeNegationTo(::std::ostream* os) const {
2076 *os << "does not point to a value that ";
2077 matcher_.DescribeTo(os);
2078 }
2079
zhanyong.wan82113312010-01-08 21:55:40 +00002080 virtual bool MatchAndExplain(Pointer pointer,
2081 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00002082 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00002083 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002084
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002085 *listener << "which points to ";
2086 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002087 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002088
shiqiane35fdd92008-12-10 05:08:54 +00002089 private:
2090 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002091
2092 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002093 };
2094
2095 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002096
2097 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002098};
2099
billydonahue1f5fdea2014-05-19 17:54:51 +00002100// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2101// reference that matches inner_matcher when dynamic_cast<T> is applied.
2102// The result of dynamic_cast<To> is forwarded to the inner matcher.
2103// If To is a pointer and the cast fails, the inner matcher will receive NULL.
2104// If To is a reference and the cast fails, this matcher returns false
2105// immediately.
2106template <typename To>
2107class WhenDynamicCastToMatcherBase {
2108 public:
2109 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2110 : matcher_(matcher) {}
2111
2112 void DescribeTo(::std::ostream* os) const {
2113 GetCastTypeDescription(os);
2114 matcher_.DescribeTo(os);
2115 }
2116
2117 void DescribeNegationTo(::std::ostream* os) const {
2118 GetCastTypeDescription(os);
2119 matcher_.DescribeNegationTo(os);
2120 }
2121
2122 protected:
2123 const Matcher<To> matcher_;
2124
2125 static string GetToName() {
2126#if GTEST_HAS_RTTI
2127 return GetTypeName<To>();
2128#else // GTEST_HAS_RTTI
2129 return "the target type";
2130#endif // GTEST_HAS_RTTI
2131 }
2132
2133 private:
2134 static void GetCastTypeDescription(::std::ostream* os) {
2135 *os << "when dynamic_cast to " << GetToName() << ", ";
2136 }
2137
2138 GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2139};
2140
2141// Primary template.
2142// To is a pointer. Cast and forward the result.
2143template <typename To>
2144class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2145 public:
2146 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2147 : WhenDynamicCastToMatcherBase<To>(matcher) {}
2148
2149 template <typename From>
2150 bool MatchAndExplain(From from, MatchResultListener* listener) const {
2151 // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail?
2152 To to = dynamic_cast<To>(from);
2153 return MatchPrintAndExplain(to, this->matcher_, listener);
2154 }
2155};
2156
2157// Specialize for references.
2158// In this case we return false if the dynamic_cast fails.
2159template <typename To>
2160class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2161 public:
2162 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2163 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2164
2165 template <typename From>
2166 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2167 // We don't want an std::bad_cast here, so do the cast with pointers.
2168 To* to = dynamic_cast<To*>(&from);
2169 if (to == NULL) {
2170 *listener << "which cannot be dynamic_cast to " << this->GetToName();
2171 return false;
2172 }
2173 return MatchPrintAndExplain(*to, this->matcher_, listener);
2174 }
2175};
2176
shiqiane35fdd92008-12-10 05:08:54 +00002177// Implements the Field() matcher for matching a field (i.e. member
2178// variable) of an object.
2179template <typename Class, typename FieldType>
2180class FieldMatcher {
2181 public:
2182 FieldMatcher(FieldType Class::*field,
2183 const Matcher<const FieldType&>& matcher)
2184 : field_(field), matcher_(matcher) {}
2185
shiqiane35fdd92008-12-10 05:08:54 +00002186 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002187 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002188 matcher_.DescribeTo(os);
2189 }
2190
2191 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002192 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002193 matcher_.DescribeNegationTo(os);
2194 }
2195
zhanyong.wandb22c222010-01-28 21:52:29 +00002196 template <typename T>
2197 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2198 return MatchAndExplainImpl(
2199 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002200 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002201 value, listener);
2202 }
2203
2204 private:
2205 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002206 // Symbian's C++ compiler choose which overload to use. Its type is
2207 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002208 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2209 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002210 *listener << "whose given field is ";
2211 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002212 }
2213
zhanyong.wandb22c222010-01-28 21:52:29 +00002214 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2215 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002216 if (p == NULL)
2217 return false;
2218
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002219 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002220 // Since *p has a field, it must be a class/struct/union type and
2221 // thus cannot be a pointer. Therefore we pass false_type() as
2222 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002223 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002224 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002225
shiqiane35fdd92008-12-10 05:08:54 +00002226 const FieldType Class::*field_;
2227 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002228
2229 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002230};
2231
shiqiane35fdd92008-12-10 05:08:54 +00002232// Implements the Property() matcher for matching a property
2233// (i.e. return value of a getter method) of an object.
2234template <typename Class, typename PropertyType>
2235class PropertyMatcher {
2236 public:
2237 // The property may have a reference type, so 'const PropertyType&'
2238 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00002239 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00002240 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00002241 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00002242
2243 PropertyMatcher(PropertyType (Class::*property)() const,
2244 const Matcher<RefToConstProperty>& matcher)
2245 : property_(property), matcher_(matcher) {}
2246
shiqiane35fdd92008-12-10 05:08:54 +00002247 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002248 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002249 matcher_.DescribeTo(os);
2250 }
2251
2252 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002253 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002254 matcher_.DescribeNegationTo(os);
2255 }
2256
zhanyong.wandb22c222010-01-28 21:52:29 +00002257 template <typename T>
2258 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2259 return MatchAndExplainImpl(
2260 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002261 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002262 value, listener);
2263 }
2264
2265 private:
2266 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002267 // Symbian's C++ compiler choose which overload to use. Its type is
2268 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002269 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2270 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002271 *listener << "whose given property is ";
2272 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2273 // which takes a non-const reference as argument.
kosak02d64792015-02-14 02:22:21 +00002274#if defined(_PREFAST_ ) && _MSC_VER == 1800
2275 // Workaround bug in VC++ 2013's /analyze parser.
2276 // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move
2277 posix::Abort(); // To make sure it is never run.
2278 return false;
2279#else
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002280 RefToConstProperty result = (obj.*property_)();
2281 return MatchPrintAndExplain(result, matcher_, listener);
kosak02d64792015-02-14 02:22:21 +00002282#endif
shiqiane35fdd92008-12-10 05:08:54 +00002283 }
2284
zhanyong.wandb22c222010-01-28 21:52:29 +00002285 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2286 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002287 if (p == NULL)
2288 return false;
2289
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002290 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002291 // Since *p has a property method, it must be a class/struct/union
2292 // type and thus cannot be a pointer. Therefore we pass
2293 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002294 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002295 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002296
shiqiane35fdd92008-12-10 05:08:54 +00002297 PropertyType (Class::*property_)() const;
2298 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002299
2300 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002301};
2302
shiqiane35fdd92008-12-10 05:08:54 +00002303// Type traits specifying various features of different functors for ResultOf.
2304// The default template specifies features for functor objects.
2305// Functor classes have to typedef argument_type and result_type
2306// to be compatible with ResultOf.
2307template <typename Functor>
2308struct CallableTraits {
2309 typedef typename Functor::result_type ResultType;
2310 typedef Functor StorageType;
2311
zhanyong.wan32de5f52009-12-23 00:13:23 +00002312 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00002313 template <typename T>
2314 static ResultType Invoke(Functor f, T arg) { return f(arg); }
2315};
2316
2317// Specialization for function pointers.
2318template <typename ArgType, typename ResType>
2319struct CallableTraits<ResType(*)(ArgType)> {
2320 typedef ResType ResultType;
2321 typedef ResType(*StorageType)(ArgType);
2322
2323 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002324 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00002325 << "NULL function pointer is passed into ResultOf().";
2326 }
2327 template <typename T>
2328 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2329 return (*f)(arg);
2330 }
2331};
2332
2333// Implements the ResultOf() matcher for matching a return value of a
2334// unary function of an object.
2335template <typename Callable>
2336class ResultOfMatcher {
2337 public:
2338 typedef typename CallableTraits<Callable>::ResultType ResultType;
2339
2340 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
2341 : callable_(callable), matcher_(matcher) {
2342 CallableTraits<Callable>::CheckIsValid(callable_);
2343 }
2344
2345 template <typename T>
2346 operator Matcher<T>() const {
2347 return Matcher<T>(new Impl<T>(callable_, matcher_));
2348 }
2349
2350 private:
2351 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2352
2353 template <typename T>
2354 class Impl : public MatcherInterface<T> {
2355 public:
2356 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
2357 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00002358
2359 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002360 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002361 matcher_.DescribeTo(os);
2362 }
2363
2364 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002365 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002366 matcher_.DescribeNegationTo(os);
2367 }
2368
zhanyong.wan82113312010-01-08 21:55:40 +00002369 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002370 *listener << "which is mapped by the given callable to ";
2371 // Cannot pass the return value (for example, int) to
2372 // MatchPrintAndExplain, which takes a non-const reference as argument.
2373 ResultType result =
2374 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2375 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002376 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002377
shiqiane35fdd92008-12-10 05:08:54 +00002378 private:
2379 // Functors often define operator() as non-const method even though
2380 // they are actualy stateless. But we need to use them even when
2381 // 'this' is a const pointer. It's the user's responsibility not to
2382 // use stateful callables with ResultOf(), which does't guarantee
2383 // how many times the callable will be invoked.
2384 mutable CallableStorageType callable_;
2385 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002386
2387 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002388 }; // class Impl
2389
2390 const CallableStorageType callable_;
2391 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002392
2393 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002394};
2395
zhanyong.wana31d9ce2013-03-01 01:50:17 +00002396// Implements a matcher that checks the size of an STL-style container.
2397template <typename SizeMatcher>
2398class SizeIsMatcher {
2399 public:
2400 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2401 : size_matcher_(size_matcher) {
2402 }
2403
2404 template <typename Container>
2405 operator Matcher<Container>() const {
2406 return MakeMatcher(new Impl<Container>(size_matcher_));
2407 }
2408
2409 template <typename Container>
2410 class Impl : public MatcherInterface<Container> {
2411 public:
2412 typedef internal::StlContainerView<
2413 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2414 typedef typename ContainerView::type::size_type SizeType;
2415 explicit Impl(const SizeMatcher& size_matcher)
2416 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2417
2418 virtual void DescribeTo(::std::ostream* os) const {
2419 *os << "size ";
2420 size_matcher_.DescribeTo(os);
2421 }
2422 virtual void DescribeNegationTo(::std::ostream* os) const {
2423 *os << "size ";
2424 size_matcher_.DescribeNegationTo(os);
2425 }
2426
2427 virtual bool MatchAndExplain(Container container,
2428 MatchResultListener* listener) const {
2429 SizeType size = container.size();
2430 StringMatchResultListener size_listener;
2431 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2432 *listener
2433 << "whose size " << size << (result ? " matches" : " doesn't match");
2434 PrintIfNotEmpty(size_listener.str(), listener->stream());
2435 return result;
2436 }
2437
2438 private:
2439 const Matcher<SizeType> size_matcher_;
2440 GTEST_DISALLOW_ASSIGN_(Impl);
2441 };
2442
2443 private:
2444 const SizeMatcher size_matcher_;
2445 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2446};
2447
kosakb6a34882014-03-12 21:06:46 +00002448// Implements a matcher that checks the begin()..end() distance of an STL-style
2449// container.
2450template <typename DistanceMatcher>
2451class BeginEndDistanceIsMatcher {
2452 public:
2453 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2454 : distance_matcher_(distance_matcher) {}
2455
2456 template <typename Container>
2457 operator Matcher<Container>() const {
2458 return MakeMatcher(new Impl<Container>(distance_matcher_));
2459 }
2460
2461 template <typename Container>
2462 class Impl : public MatcherInterface<Container> {
2463 public:
2464 typedef internal::StlContainerView<
2465 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2466 typedef typename std::iterator_traits<
2467 typename ContainerView::type::const_iterator>::difference_type
2468 DistanceType;
2469 explicit Impl(const DistanceMatcher& distance_matcher)
2470 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2471
2472 virtual void DescribeTo(::std::ostream* os) const {
2473 *os << "distance between begin() and end() ";
2474 distance_matcher_.DescribeTo(os);
2475 }
2476 virtual void DescribeNegationTo(::std::ostream* os) const {
2477 *os << "distance between begin() and end() ";
2478 distance_matcher_.DescribeNegationTo(os);
2479 }
2480
2481 virtual bool MatchAndExplain(Container container,
2482 MatchResultListener* listener) const {
kosak5b9cbbb2014-11-17 00:28:55 +00002483#if GTEST_HAS_STD_BEGIN_AND_END_
kosakb6a34882014-03-12 21:06:46 +00002484 using std::begin;
2485 using std::end;
2486 DistanceType distance = std::distance(begin(container), end(container));
2487#else
2488 DistanceType distance = std::distance(container.begin(), container.end());
2489#endif
2490 StringMatchResultListener distance_listener;
2491 const bool result =
2492 distance_matcher_.MatchAndExplain(distance, &distance_listener);
2493 *listener << "whose distance between begin() and end() " << distance
2494 << (result ? " matches" : " doesn't match");
2495 PrintIfNotEmpty(distance_listener.str(), listener->stream());
2496 return result;
2497 }
2498
2499 private:
2500 const Matcher<DistanceType> distance_matcher_;
2501 GTEST_DISALLOW_ASSIGN_(Impl);
2502 };
2503
2504 private:
2505 const DistanceMatcher distance_matcher_;
2506 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2507};
2508
zhanyong.wan6a896b52009-01-16 01:13:50 +00002509// Implements an equality matcher for any STL-style container whose elements
2510// support ==. This matcher is like Eq(), but its failure explanations provide
2511// more detailed information that is useful when the container is used as a set.
2512// The failure message reports elements that are in one of the operands but not
2513// the other. The failure messages do not report duplicate or out-of-order
2514// elements in the containers (which don't properly matter to sets, but can
2515// occur if the containers are vectors or lists, for example).
2516//
2517// Uses the container's const_iterator, value_type, operator ==,
2518// begin(), and end().
2519template <typename Container>
2520class ContainerEqMatcher {
2521 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002522 typedef internal::StlContainerView<Container> View;
2523 typedef typename View::type StlContainer;
2524 typedef typename View::const_reference StlContainerReference;
2525
kosak6b817802015-01-08 02:38:14 +00002526 // We make a copy of expected in case the elements in it are modified
zhanyong.wanb8243162009-06-04 05:48:20 +00002527 // after this matcher is created.
kosak6b817802015-01-08 02:38:14 +00002528 explicit ContainerEqMatcher(const Container& expected)
2529 : expected_(View::Copy(expected)) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002530 // Makes sure the user doesn't instantiate this class template
2531 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002532 (void)testing::StaticAssertTypeEq<Container,
2533 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002534 }
2535
zhanyong.wan6a896b52009-01-16 01:13:50 +00002536 void DescribeTo(::std::ostream* os) const {
2537 *os << "equals ";
kosak6b817802015-01-08 02:38:14 +00002538 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002539 }
2540 void DescribeNegationTo(::std::ostream* os) const {
2541 *os << "does not equal ";
kosak6b817802015-01-08 02:38:14 +00002542 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002543 }
2544
zhanyong.wanb8243162009-06-04 05:48:20 +00002545 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002546 bool MatchAndExplain(const LhsContainer& lhs,
2547 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002548 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002549 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002550 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002551 LhsView;
2552 typedef typename LhsView::type LhsStlContainer;
2553 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
kosak6b817802015-01-08 02:38:14 +00002554 if (lhs_stl_container == expected_)
zhanyong.wane122e452010-01-12 09:03:52 +00002555 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002556
zhanyong.wane122e452010-01-12 09:03:52 +00002557 ::std::ostream* const os = listener->stream();
2558 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002559 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002560 bool printed_header = false;
2561 for (typename LhsStlContainer::const_iterator it =
2562 lhs_stl_container.begin();
2563 it != lhs_stl_container.end(); ++it) {
kosak6b817802015-01-08 02:38:14 +00002564 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
2565 expected_.end()) {
zhanyong.wane122e452010-01-12 09:03:52 +00002566 if (printed_header) {
2567 *os << ", ";
2568 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002569 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002570 printed_header = true;
2571 }
vladloseve2e8ba42010-05-13 18:16:03 +00002572 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002573 }
zhanyong.wane122e452010-01-12 09:03:52 +00002574 }
2575
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002576 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002577 bool printed_header2 = false;
kosak6b817802015-01-08 02:38:14 +00002578 for (typename StlContainer::const_iterator it = expected_.begin();
2579 it != expected_.end(); ++it) {
zhanyong.wane122e452010-01-12 09:03:52 +00002580 if (internal::ArrayAwareFind(
2581 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2582 lhs_stl_container.end()) {
2583 if (printed_header2) {
2584 *os << ", ";
2585 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002586 *os << (printed_header ? ",\nand" : "which")
2587 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002588 printed_header2 = true;
2589 }
vladloseve2e8ba42010-05-13 18:16:03 +00002590 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002591 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002592 }
2593 }
2594
zhanyong.wane122e452010-01-12 09:03:52 +00002595 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002596 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002597
zhanyong.wan6a896b52009-01-16 01:13:50 +00002598 private:
kosak6b817802015-01-08 02:38:14 +00002599 const StlContainer expected_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002600
2601 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002602};
2603
zhanyong.wan898725c2011-09-16 16:45:39 +00002604// A comparator functor that uses the < operator to compare two values.
2605struct LessComparator {
2606 template <typename T, typename U>
2607 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2608};
2609
2610// Implements WhenSortedBy(comparator, container_matcher).
2611template <typename Comparator, typename ContainerMatcher>
2612class WhenSortedByMatcher {
2613 public:
2614 WhenSortedByMatcher(const Comparator& comparator,
2615 const ContainerMatcher& matcher)
2616 : comparator_(comparator), matcher_(matcher) {}
2617
2618 template <typename LhsContainer>
2619 operator Matcher<LhsContainer>() const {
2620 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2621 }
2622
2623 template <typename LhsContainer>
2624 class Impl : public MatcherInterface<LhsContainer> {
2625 public:
2626 typedef internal::StlContainerView<
2627 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2628 typedef typename LhsView::type LhsStlContainer;
2629 typedef typename LhsView::const_reference LhsStlContainerReference;
zhanyong.wana9a59e02013-03-27 16:14:55 +00002630 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2631 // so that we can match associative containers.
2632 typedef typename RemoveConstFromKey<
2633 typename LhsStlContainer::value_type>::type LhsValue;
zhanyong.wan898725c2011-09-16 16:45:39 +00002634
2635 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2636 : comparator_(comparator), matcher_(matcher) {}
2637
2638 virtual void DescribeTo(::std::ostream* os) const {
2639 *os << "(when sorted) ";
2640 matcher_.DescribeTo(os);
2641 }
2642
2643 virtual void DescribeNegationTo(::std::ostream* os) const {
2644 *os << "(when sorted) ";
2645 matcher_.DescribeNegationTo(os);
2646 }
2647
2648 virtual bool MatchAndExplain(LhsContainer lhs,
2649 MatchResultListener* listener) const {
2650 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wanfb25d532013-07-28 08:24:00 +00002651 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2652 lhs_stl_container.end());
2653 ::std::sort(
2654 sorted_container.begin(), sorted_container.end(), comparator_);
zhanyong.wan898725c2011-09-16 16:45:39 +00002655
2656 if (!listener->IsInterested()) {
2657 // If the listener is not interested, we do not need to
2658 // construct the inner explanation.
2659 return matcher_.Matches(sorted_container);
2660 }
2661
2662 *listener << "which is ";
2663 UniversalPrint(sorted_container, listener->stream());
2664 *listener << " when sorted";
2665
2666 StringMatchResultListener inner_listener;
2667 const bool match = matcher_.MatchAndExplain(sorted_container,
2668 &inner_listener);
2669 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2670 return match;
2671 }
2672
2673 private:
2674 const Comparator comparator_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00002675 const Matcher<const ::std::vector<LhsValue>&> matcher_;
zhanyong.wan898725c2011-09-16 16:45:39 +00002676
2677 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2678 };
2679
2680 private:
2681 const Comparator comparator_;
2682 const ContainerMatcher matcher_;
2683
2684 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2685};
2686
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002687// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2688// must be able to be safely cast to Matcher<tuple<const T1&, const
2689// T2&> >, where T1 and T2 are the types of elements in the LHS
2690// container and the RHS container respectively.
2691template <typename TupleMatcher, typename RhsContainer>
2692class PointwiseMatcher {
2693 public:
2694 typedef internal::StlContainerView<RhsContainer> RhsView;
2695 typedef typename RhsView::type RhsStlContainer;
2696 typedef typename RhsStlContainer::value_type RhsValue;
2697
2698 // Like ContainerEq, we make a copy of rhs in case the elements in
2699 // it are modified after this matcher is created.
2700 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2701 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2702 // Makes sure the user doesn't instantiate this class template
2703 // with a const or reference type.
2704 (void)testing::StaticAssertTypeEq<RhsContainer,
2705 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2706 }
2707
2708 template <typename LhsContainer>
2709 operator Matcher<LhsContainer>() const {
2710 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2711 }
2712
2713 template <typename LhsContainer>
2714 class Impl : public MatcherInterface<LhsContainer> {
2715 public:
2716 typedef internal::StlContainerView<
2717 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2718 typedef typename LhsView::type LhsStlContainer;
2719 typedef typename LhsView::const_reference LhsStlContainerReference;
2720 typedef typename LhsStlContainer::value_type LhsValue;
2721 // We pass the LHS value and the RHS value to the inner matcher by
2722 // reference, as they may be expensive to copy. We must use tuple
2723 // instead of pair here, as a pair cannot hold references (C++ 98,
2724 // 20.2.2 [lib.pairs]).
kosakbd018832014-04-02 20:30:00 +00002725 typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002726
2727 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2728 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2729 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2730 rhs_(rhs) {}
2731
2732 virtual void DescribeTo(::std::ostream* os) const {
2733 *os << "contains " << rhs_.size()
2734 << " values, where each value and its corresponding value in ";
2735 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2736 *os << " ";
2737 mono_tuple_matcher_.DescribeTo(os);
2738 }
2739 virtual void DescribeNegationTo(::std::ostream* os) const {
2740 *os << "doesn't contain exactly " << rhs_.size()
2741 << " values, or contains a value x at some index i"
2742 << " where x and the i-th value of ";
2743 UniversalPrint(rhs_, os);
2744 *os << " ";
2745 mono_tuple_matcher_.DescribeNegationTo(os);
2746 }
2747
2748 virtual bool MatchAndExplain(LhsContainer lhs,
2749 MatchResultListener* listener) const {
2750 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2751 const size_t actual_size = lhs_stl_container.size();
2752 if (actual_size != rhs_.size()) {
2753 *listener << "which contains " << actual_size << " values";
2754 return false;
2755 }
2756
2757 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2758 typename RhsStlContainer::const_iterator right = rhs_.begin();
2759 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2760 const InnerMatcherArg value_pair(*left, *right);
2761
2762 if (listener->IsInterested()) {
2763 StringMatchResultListener inner_listener;
2764 if (!mono_tuple_matcher_.MatchAndExplain(
2765 value_pair, &inner_listener)) {
2766 *listener << "where the value pair (";
2767 UniversalPrint(*left, listener->stream());
2768 *listener << ", ";
2769 UniversalPrint(*right, listener->stream());
2770 *listener << ") at index #" << i << " don't match";
2771 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2772 return false;
2773 }
2774 } else {
2775 if (!mono_tuple_matcher_.Matches(value_pair))
2776 return false;
2777 }
2778 }
2779
2780 return true;
2781 }
2782
2783 private:
2784 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2785 const RhsStlContainer rhs_;
2786
2787 GTEST_DISALLOW_ASSIGN_(Impl);
2788 };
2789
2790 private:
2791 const TupleMatcher tuple_matcher_;
2792 const RhsStlContainer rhs_;
2793
2794 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2795};
2796
zhanyong.wan33605ba2010-04-22 23:37:47 +00002797// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002798template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002799class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002800 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002801 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002802 typedef StlContainerView<RawContainer> View;
2803 typedef typename View::type StlContainer;
2804 typedef typename View::const_reference StlContainerReference;
2805 typedef typename StlContainer::value_type Element;
2806
2807 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002808 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002809 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002810 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002811
zhanyong.wan33605ba2010-04-22 23:37:47 +00002812 // Checks whether:
2813 // * All elements in the container match, if all_elements_should_match.
2814 // * Any element in the container matches, if !all_elements_should_match.
2815 bool MatchAndExplainImpl(bool all_elements_should_match,
2816 Container container,
2817 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002818 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002819 size_t i = 0;
2820 for (typename StlContainer::const_iterator it = stl_container.begin();
2821 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002822 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002823 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2824
2825 if (matches != all_elements_should_match) {
2826 *listener << "whose element #" << i
2827 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002828 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002829 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002830 }
2831 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002832 return all_elements_should_match;
2833 }
2834
2835 protected:
2836 const Matcher<const Element&> inner_matcher_;
2837
2838 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2839};
2840
2841// Implements Contains(element_matcher) for the given argument type Container.
2842// Symmetric to EachMatcherImpl.
2843template <typename Container>
2844class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2845 public:
2846 template <typename InnerMatcher>
2847 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2848 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2849
2850 // Describes what this matcher does.
2851 virtual void DescribeTo(::std::ostream* os) const {
2852 *os << "contains at least one element that ";
2853 this->inner_matcher_.DescribeTo(os);
2854 }
2855
2856 virtual void DescribeNegationTo(::std::ostream* os) const {
2857 *os << "doesn't contain any element that ";
2858 this->inner_matcher_.DescribeTo(os);
2859 }
2860
2861 virtual bool MatchAndExplain(Container container,
2862 MatchResultListener* listener) const {
2863 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002864 }
2865
2866 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002867 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002868};
2869
zhanyong.wan33605ba2010-04-22 23:37:47 +00002870// Implements Each(element_matcher) for the given argument type Container.
2871// Symmetric to ContainsMatcherImpl.
2872template <typename Container>
2873class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2874 public:
2875 template <typename InnerMatcher>
2876 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2877 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2878
2879 // Describes what this matcher does.
2880 virtual void DescribeTo(::std::ostream* os) const {
2881 *os << "only contains elements that ";
2882 this->inner_matcher_.DescribeTo(os);
2883 }
2884
2885 virtual void DescribeNegationTo(::std::ostream* os) const {
2886 *os << "contains some element that ";
2887 this->inner_matcher_.DescribeNegationTo(os);
2888 }
2889
2890 virtual bool MatchAndExplain(Container container,
2891 MatchResultListener* listener) const {
2892 return this->MatchAndExplainImpl(true, container, listener);
2893 }
2894
2895 private:
2896 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2897};
2898
zhanyong.wanb8243162009-06-04 05:48:20 +00002899// Implements polymorphic Contains(element_matcher).
2900template <typename M>
2901class ContainsMatcher {
2902 public:
2903 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2904
2905 template <typename Container>
2906 operator Matcher<Container>() const {
2907 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2908 }
2909
2910 private:
2911 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002912
2913 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002914};
2915
zhanyong.wan33605ba2010-04-22 23:37:47 +00002916// Implements polymorphic Each(element_matcher).
2917template <typename M>
2918class EachMatcher {
2919 public:
2920 explicit EachMatcher(M m) : inner_matcher_(m) {}
2921
2922 template <typename Container>
2923 operator Matcher<Container>() const {
2924 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2925 }
2926
2927 private:
2928 const M inner_matcher_;
2929
2930 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2931};
2932
zhanyong.wanb5937da2009-07-16 20:26:41 +00002933// Implements Key(inner_matcher) for the given argument pair type.
2934// Key(inner_matcher) matches an std::pair whose 'first' field matches
2935// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2936// std::map that contains at least one element whose key is >= 5.
2937template <typename PairType>
2938class KeyMatcherImpl : public MatcherInterface<PairType> {
2939 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002940 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002941 typedef typename RawPairType::first_type KeyType;
2942
2943 template <typename InnerMatcher>
2944 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2945 : inner_matcher_(
2946 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2947 }
2948
2949 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002950 virtual bool MatchAndExplain(PairType key_value,
2951 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002952 StringMatchResultListener inner_listener;
2953 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2954 &inner_listener);
2955 const internal::string explanation = inner_listener.str();
2956 if (explanation != "") {
2957 *listener << "whose first field is a value " << explanation;
2958 }
2959 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002960 }
2961
2962 // Describes what this matcher does.
2963 virtual void DescribeTo(::std::ostream* os) const {
2964 *os << "has a key that ";
2965 inner_matcher_.DescribeTo(os);
2966 }
2967
2968 // Describes what the negation of this matcher does.
2969 virtual void DescribeNegationTo(::std::ostream* os) const {
2970 *os << "doesn't have a key that ";
2971 inner_matcher_.DescribeTo(os);
2972 }
2973
zhanyong.wanb5937da2009-07-16 20:26:41 +00002974 private:
2975 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002976
2977 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002978};
2979
2980// Implements polymorphic Key(matcher_for_key).
2981template <typename M>
2982class KeyMatcher {
2983 public:
2984 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2985
2986 template <typename PairType>
2987 operator Matcher<PairType>() const {
2988 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2989 }
2990
2991 private:
2992 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002993
2994 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002995};
2996
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002997// Implements Pair(first_matcher, second_matcher) for the given argument pair
2998// type with its two matchers. See Pair() function below.
2999template <typename PairType>
3000class PairMatcherImpl : public MatcherInterface<PairType> {
3001 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003002 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003003 typedef typename RawPairType::first_type FirstType;
3004 typedef typename RawPairType::second_type SecondType;
3005
3006 template <typename FirstMatcher, typename SecondMatcher>
3007 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
3008 : first_matcher_(
3009 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
3010 second_matcher_(
3011 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
3012 }
3013
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003014 // Describes what this matcher does.
3015 virtual void DescribeTo(::std::ostream* os) const {
3016 *os << "has a first field that ";
3017 first_matcher_.DescribeTo(os);
3018 *os << ", and has a second field that ";
3019 second_matcher_.DescribeTo(os);
3020 }
3021
3022 // Describes what the negation of this matcher does.
3023 virtual void DescribeNegationTo(::std::ostream* os) const {
3024 *os << "has a first field that ";
3025 first_matcher_.DescribeNegationTo(os);
3026 *os << ", or has a second field that ";
3027 second_matcher_.DescribeNegationTo(os);
3028 }
3029
zhanyong.wan82113312010-01-08 21:55:40 +00003030 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3031 // matches second_matcher.
3032 virtual bool MatchAndExplain(PairType a_pair,
3033 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003034 if (!listener->IsInterested()) {
3035 // If the listener is not interested, we don't need to construct the
3036 // explanation.
3037 return first_matcher_.Matches(a_pair.first) &&
3038 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00003039 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003040 StringMatchResultListener first_inner_listener;
3041 if (!first_matcher_.MatchAndExplain(a_pair.first,
3042 &first_inner_listener)) {
3043 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003044 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003045 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003046 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003047 StringMatchResultListener second_inner_listener;
3048 if (!second_matcher_.MatchAndExplain(a_pair.second,
3049 &second_inner_listener)) {
3050 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003051 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003052 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003053 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003054 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3055 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00003056 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003057 }
3058
3059 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003060 void ExplainSuccess(const internal::string& first_explanation,
3061 const internal::string& second_explanation,
3062 MatchResultListener* listener) const {
3063 *listener << "whose both fields match";
3064 if (first_explanation != "") {
3065 *listener << ", where the first field is a value " << first_explanation;
3066 }
3067 if (second_explanation != "") {
3068 *listener << ", ";
3069 if (first_explanation != "") {
3070 *listener << "and ";
3071 } else {
3072 *listener << "where ";
3073 }
3074 *listener << "the second field is a value " << second_explanation;
3075 }
3076 }
3077
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003078 const Matcher<const FirstType&> first_matcher_;
3079 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003080
3081 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003082};
3083
3084// Implements polymorphic Pair(first_matcher, second_matcher).
3085template <typename FirstMatcher, typename SecondMatcher>
3086class PairMatcher {
3087 public:
3088 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3089 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3090
3091 template <typename PairType>
3092 operator Matcher<PairType> () const {
3093 return MakeMatcher(
3094 new PairMatcherImpl<PairType>(
3095 first_matcher_, second_matcher_));
3096 }
3097
3098 private:
3099 const FirstMatcher first_matcher_;
3100 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003101
3102 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003103};
3104
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003105// Implements ElementsAre() and ElementsAreArray().
3106template <typename Container>
3107class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3108 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003109 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003110 typedef internal::StlContainerView<RawContainer> View;
3111 typedef typename View::type StlContainer;
3112 typedef typename View::const_reference StlContainerReference;
3113 typedef typename StlContainer::value_type Element;
3114
3115 // Constructs the matcher from a sequence of element values or
3116 // element matchers.
3117 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00003118 ElementsAreMatcherImpl(InputIter first, InputIter last) {
3119 while (first != last) {
3120 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003121 }
3122 }
3123
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003124 // Describes what this matcher does.
3125 virtual void DescribeTo(::std::ostream* os) const {
3126 if (count() == 0) {
3127 *os << "is empty";
3128 } else if (count() == 1) {
3129 *os << "has 1 element that ";
3130 matchers_[0].DescribeTo(os);
3131 } else {
3132 *os << "has " << Elements(count()) << " where\n";
3133 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003134 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003135 matchers_[i].DescribeTo(os);
3136 if (i + 1 < count()) {
3137 *os << ",\n";
3138 }
3139 }
3140 }
3141 }
3142
3143 // Describes what the negation of this matcher does.
3144 virtual void DescribeNegationTo(::std::ostream* os) const {
3145 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003146 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003147 return;
3148 }
3149
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003150 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003151 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003152 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003153 matchers_[i].DescribeNegationTo(os);
3154 if (i + 1 < count()) {
3155 *os << ", or\n";
3156 }
3157 }
3158 }
3159
zhanyong.wan82113312010-01-08 21:55:40 +00003160 virtual bool MatchAndExplain(Container container,
3161 MatchResultListener* listener) const {
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003162 // To work with stream-like "containers", we must only walk
3163 // through the elements in one pass.
3164
3165 const bool listener_interested = listener->IsInterested();
3166
3167 // explanations[i] is the explanation of the element at index i.
3168 ::std::vector<internal::string> explanations(count());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003169 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003170 typename StlContainer::const_iterator it = stl_container.begin();
3171 size_t exam_pos = 0;
3172 bool mismatch_found = false; // Have we found a mismatched element yet?
3173
3174 // Go through the elements and matchers in pairs, until we reach
3175 // the end of either the elements or the matchers, or until we find a
3176 // mismatch.
3177 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3178 bool match; // Does the current element match the current matcher?
3179 if (listener_interested) {
3180 StringMatchResultListener s;
3181 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3182 explanations[exam_pos] = s.str();
3183 } else {
3184 match = matchers_[exam_pos].Matches(*it);
3185 }
3186
3187 if (!match) {
3188 mismatch_found = true;
3189 break;
3190 }
3191 }
3192 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3193
3194 // Find how many elements the actual container has. We avoid
3195 // calling size() s.t. this code works for stream-like "containers"
3196 // that don't define size().
3197 size_t actual_count = exam_pos;
3198 for (; it != stl_container.end(); ++it) {
3199 ++actual_count;
3200 }
3201
zhanyong.wan82113312010-01-08 21:55:40 +00003202 if (actual_count != count()) {
3203 // The element count doesn't match. If the container is empty,
3204 // there's no need to explain anything as Google Mock already
3205 // prints the empty container. Otherwise we just need to show
3206 // how many elements there actually are.
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003207 if (listener_interested && (actual_count != 0)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003208 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003209 }
zhanyong.wan82113312010-01-08 21:55:40 +00003210 return false;
3211 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003212
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003213 if (mismatch_found) {
3214 // The element count matches, but the exam_pos-th element doesn't match.
3215 if (listener_interested) {
3216 *listener << "whose element #" << exam_pos << " doesn't match";
3217 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003218 }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003219 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003220 }
zhanyong.wan82113312010-01-08 21:55:40 +00003221
3222 // Every element matches its expectation. We need to explain why
3223 // (the obvious ones can be skipped).
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003224 if (listener_interested) {
3225 bool reason_printed = false;
3226 for (size_t i = 0; i != count(); ++i) {
3227 const internal::string& s = explanations[i];
3228 if (!s.empty()) {
3229 if (reason_printed) {
3230 *listener << ",\nand ";
3231 }
3232 *listener << "whose element #" << i << " matches, " << s;
3233 reason_printed = true;
zhanyong.wan82113312010-01-08 21:55:40 +00003234 }
zhanyong.wan82113312010-01-08 21:55:40 +00003235 }
3236 }
zhanyong.wan82113312010-01-08 21:55:40 +00003237 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003238 }
3239
3240 private:
3241 static Message Elements(size_t count) {
3242 return Message() << count << (count == 1 ? " element" : " elements");
3243 }
3244
3245 size_t count() const { return matchers_.size(); }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003246
3247 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003248
3249 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003250};
3251
zhanyong.wanfb25d532013-07-28 08:24:00 +00003252// Connectivity matrix of (elements X matchers), in element-major order.
3253// Initially, there are no edges.
3254// Use NextGraph() to iterate over all possible edge configurations.
3255// Use Randomize() to generate a random edge configuration.
3256class GTEST_API_ MatchMatrix {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003257 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003258 MatchMatrix(size_t num_elements, size_t num_matchers)
3259 : num_elements_(num_elements),
3260 num_matchers_(num_matchers),
3261 matched_(num_elements_* num_matchers_, 0) {
3262 }
3263
3264 size_t LhsSize() const { return num_elements_; }
3265 size_t RhsSize() const { return num_matchers_; }
3266 bool HasEdge(size_t ilhs, size_t irhs) const {
3267 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3268 }
3269 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3270 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3271 }
3272
3273 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3274 // adds 1 to that number; returns false if incrementing the graph left it
3275 // empty.
3276 bool NextGraph();
3277
3278 void Randomize();
3279
3280 string DebugString() const;
3281
3282 private:
3283 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3284 return ilhs * num_matchers_ + irhs;
3285 }
3286
3287 size_t num_elements_;
3288 size_t num_matchers_;
3289
3290 // Each element is a char interpreted as bool. They are stored as a
3291 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3292 // a (ilhs, irhs) matrix coordinate into an offset.
3293 ::std::vector<char> matched_;
3294};
3295
3296typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3297typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3298
3299// Returns a maximum bipartite matching for the specified graph 'g'.
3300// The matching is represented as a vector of {element, matcher} pairs.
3301GTEST_API_ ElementMatcherPairs
3302FindMaxBipartiteMatching(const MatchMatrix& g);
3303
3304GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
3305 MatchResultListener* listener);
3306
3307// Untyped base class for implementing UnorderedElementsAre. By
3308// putting logic that's not specific to the element type here, we
3309// reduce binary bloat and increase compilation speed.
3310class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3311 protected:
3312 // A vector of matcher describers, one for each element matcher.
3313 // Does not own the describers (and thus can be used only when the
3314 // element matchers are alive).
3315 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3316
3317 // Describes this UnorderedElementsAre matcher.
3318 void DescribeToImpl(::std::ostream* os) const;
3319
3320 // Describes the negation of this UnorderedElementsAre matcher.
3321 void DescribeNegationToImpl(::std::ostream* os) const;
3322
3323 bool VerifyAllElementsAndMatchersAreMatched(
3324 const ::std::vector<string>& element_printouts,
3325 const MatchMatrix& matrix,
3326 MatchResultListener* listener) const;
3327
3328 MatcherDescriberVec& matcher_describers() {
3329 return matcher_describers_;
3330 }
3331
3332 static Message Elements(size_t n) {
3333 return Message() << n << " element" << (n == 1 ? "" : "s");
3334 }
3335
3336 private:
3337 MatcherDescriberVec matcher_describers_;
3338
3339 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3340};
3341
3342// Implements unordered ElementsAre and unordered ElementsAreArray.
3343template <typename Container>
3344class UnorderedElementsAreMatcherImpl
3345 : public MatcherInterface<Container>,
3346 public UnorderedElementsAreMatcherImplBase {
3347 public:
3348 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3349 typedef internal::StlContainerView<RawContainer> View;
3350 typedef typename View::type StlContainer;
3351 typedef typename View::const_reference StlContainerReference;
3352 typedef typename StlContainer::const_iterator StlContainerConstIterator;
3353 typedef typename StlContainer::value_type Element;
3354
3355 // Constructs the matcher from a sequence of element values or
3356 // element matchers.
3357 template <typename InputIter>
3358 UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) {
3359 for (; first != last; ++first) {
3360 matchers_.push_back(MatcherCast<const Element&>(*first));
3361 matcher_describers().push_back(matchers_.back().GetDescriber());
3362 }
3363 }
3364
3365 // Describes what this matcher does.
3366 virtual void DescribeTo(::std::ostream* os) const {
3367 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3368 }
3369
3370 // Describes what the negation of this matcher does.
3371 virtual void DescribeNegationTo(::std::ostream* os) const {
3372 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3373 }
3374
3375 virtual bool MatchAndExplain(Container container,
3376 MatchResultListener* listener) const {
3377 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003378 ::std::vector<string> element_printouts;
3379 MatchMatrix matrix = AnalyzeElements(stl_container.begin(),
3380 stl_container.end(),
3381 &element_printouts,
3382 listener);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003383
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003384 const size_t actual_count = matrix.LhsSize();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003385 if (actual_count == 0 && matchers_.empty()) {
3386 return true;
3387 }
3388 if (actual_count != matchers_.size()) {
3389 // The element count doesn't match. If the container is empty,
3390 // there's no need to explain anything as Google Mock already
3391 // prints the empty container. Otherwise we just need to show
3392 // how many elements there actually are.
3393 if (actual_count != 0 && listener->IsInterested()) {
3394 *listener << "which has " << Elements(actual_count);
3395 }
3396 return false;
3397 }
3398
zhanyong.wanfb25d532013-07-28 08:24:00 +00003399 return VerifyAllElementsAndMatchersAreMatched(element_printouts,
3400 matrix, listener) &&
3401 FindPairing(matrix, listener);
3402 }
3403
3404 private:
3405 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3406
3407 template <typename ElementIter>
3408 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
3409 ::std::vector<string>* element_printouts,
3410 MatchResultListener* listener) const {
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003411 element_printouts->clear();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003412 ::std::vector<char> did_match;
3413 size_t num_elements = 0;
3414 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3415 if (listener->IsInterested()) {
3416 element_printouts->push_back(PrintToString(*elem_first));
3417 }
3418 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3419 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3420 }
3421 }
3422
3423 MatchMatrix matrix(num_elements, matchers_.size());
3424 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3425 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3426 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3427 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3428 }
3429 }
3430 return matrix;
3431 }
3432
3433 MatcherVec matchers_;
3434
3435 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3436};
3437
3438// Functor for use in TransformTuple.
3439// Performs MatcherCast<Target> on an input argument of any type.
3440template <typename Target>
3441struct CastAndAppendTransform {
3442 template <typename Arg>
3443 Matcher<Target> operator()(const Arg& a) const {
3444 return MatcherCast<Target>(a);
3445 }
3446};
3447
3448// Implements UnorderedElementsAre.
3449template <typename MatcherTuple>
3450class UnorderedElementsAreMatcher {
3451 public:
3452 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3453 : matchers_(args) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003454
3455 template <typename Container>
3456 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003457 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003458 typedef typename internal::StlContainerView<RawContainer>::type View;
3459 typedef typename View::value_type Element;
3460 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3461 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003462 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003463 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3464 ::std::back_inserter(matchers));
3465 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3466 matchers.begin(), matchers.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003467 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003468
3469 private:
3470 const MatcherTuple matchers_;
3471 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3472};
3473
3474// Implements ElementsAre.
3475template <typename MatcherTuple>
3476class ElementsAreMatcher {
3477 public:
3478 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3479
3480 template <typename Container>
3481 operator Matcher<Container>() const {
3482 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3483 typedef typename internal::StlContainerView<RawContainer>::type View;
3484 typedef typename View::value_type Element;
3485 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3486 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003487 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003488 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3489 ::std::back_inserter(matchers));
3490 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3491 matchers.begin(), matchers.end()));
3492 }
3493
3494 private:
3495 const MatcherTuple matchers_;
3496 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3497};
3498
3499// Implements UnorderedElementsAreArray().
3500template <typename T>
3501class UnorderedElementsAreArrayMatcher {
3502 public:
3503 UnorderedElementsAreArrayMatcher() {}
3504
3505 template <typename Iter>
3506 UnorderedElementsAreArrayMatcher(Iter first, Iter last)
3507 : matchers_(first, last) {}
3508
3509 template <typename Container>
3510 operator Matcher<Container>() const {
3511 return MakeMatcher(
3512 new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(),
3513 matchers_.end()));
3514 }
3515
3516 private:
3517 ::std::vector<T> matchers_;
3518
3519 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003520};
3521
3522// Implements ElementsAreArray().
3523template <typename T>
3524class ElementsAreArrayMatcher {
3525 public:
jgm38513a82012-11-15 15:50:36 +00003526 template <typename Iter>
3527 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003528
3529 template <typename Container>
3530 operator Matcher<Container>() const {
jgm38513a82012-11-15 15:50:36 +00003531 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3532 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003533 }
3534
3535 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003536 const ::std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003537
3538 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003539};
3540
kosak2336e9c2014-07-28 22:57:30 +00003541// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3542// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3543// second) is a polymorphic matcher that matches a value x iff tm
3544// matches tuple (x, second). Useful for implementing
3545// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3546//
3547// BoundSecondMatcher is copyable and assignable, as we need to put
3548// instances of this class in a vector when implementing
3549// UnorderedPointwise().
3550template <typename Tuple2Matcher, typename Second>
3551class BoundSecondMatcher {
3552 public:
3553 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3554 : tuple2_matcher_(tm), second_value_(second) {}
3555
3556 template <typename T>
3557 operator Matcher<T>() const {
3558 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3559 }
3560
3561 // We have to define this for UnorderedPointwise() to compile in
3562 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3563 // which requires the elements to be assignable in C++98. The
3564 // compiler cannot generate the operator= for us, as Tuple2Matcher
3565 // and Second may not be assignable.
3566 //
3567 // However, this should never be called, so the implementation just
3568 // need to assert.
3569 void operator=(const BoundSecondMatcher& /*rhs*/) {
3570 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3571 }
3572
3573 private:
3574 template <typename T>
3575 class Impl : public MatcherInterface<T> {
3576 public:
3577 typedef ::testing::tuple<T, Second> ArgTuple;
3578
3579 Impl(const Tuple2Matcher& tm, const Second& second)
3580 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3581 second_value_(second) {}
3582
3583 virtual void DescribeTo(::std::ostream* os) const {
3584 *os << "and ";
3585 UniversalPrint(second_value_, os);
3586 *os << " ";
3587 mono_tuple2_matcher_.DescribeTo(os);
3588 }
3589
3590 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3591 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3592 listener);
3593 }
3594
3595 private:
3596 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3597 const Second second_value_;
3598
3599 GTEST_DISALLOW_ASSIGN_(Impl);
3600 };
3601
3602 const Tuple2Matcher tuple2_matcher_;
3603 const Second second_value_;
3604};
3605
3606// Given a 2-tuple matcher tm and a value second,
3607// MatcherBindSecond(tm, second) returns a matcher that matches a
3608// value x iff tm matches tuple (x, second). Useful for implementing
3609// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3610template <typename Tuple2Matcher, typename Second>
3611BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
3612 const Tuple2Matcher& tm, const Second& second) {
3613 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
3614}
3615
zhanyong.wanb4140802010-06-08 22:53:57 +00003616// Returns the description for a matcher defined using the MATCHER*()
3617// macro where the user-supplied description string is "", if
3618// 'negation' is false; otherwise returns the description of the
3619// negation of the matcher. 'param_values' contains a list of strings
3620// that are the print-out of the matcher's parameters.
vladlosev587c1b32011-05-20 00:42:22 +00003621GTEST_API_ string FormatMatcherDescription(bool negation,
3622 const char* matcher_name,
3623 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003624
shiqiane35fdd92008-12-10 05:08:54 +00003625} // namespace internal
3626
zhanyong.wanfb25d532013-07-28 08:24:00 +00003627// ElementsAreArray(first, last)
3628// ElementsAreArray(pointer, count)
3629// ElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00003630// ElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003631// ElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00003632//
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003633// The ElementsAreArray() functions are like ElementsAre(...), except
3634// that they are given a homogeneous sequence rather than taking each
3635// element as a function argument. The sequence can be specified as an
3636// array, a pointer and count, a vector, an initializer list, or an
3637// STL iterator range. In each of these cases, the underlying sequence
3638// can be either a sequence of values or a sequence of matchers.
zhanyong.wanfb25d532013-07-28 08:24:00 +00003639//
3640// All forms of ElementsAreArray() make a copy of the input matcher sequence.
3641
3642template <typename Iter>
3643inline internal::ElementsAreArrayMatcher<
3644 typename ::std::iterator_traits<Iter>::value_type>
3645ElementsAreArray(Iter first, Iter last) {
3646 typedef typename ::std::iterator_traits<Iter>::value_type T;
3647 return internal::ElementsAreArrayMatcher<T>(first, last);
3648}
3649
3650template <typename T>
3651inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3652 const T* pointer, size_t count) {
3653 return ElementsAreArray(pointer, pointer + count);
3654}
3655
3656template <typename T, size_t N>
3657inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3658 const T (&array)[N]) {
3659 return ElementsAreArray(array, N);
3660}
3661
kosak06678922014-07-28 20:01:28 +00003662template <typename Container>
3663inline internal::ElementsAreArrayMatcher<typename Container::value_type>
3664ElementsAreArray(const Container& container) {
3665 return ElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00003666}
3667
kosak18489fa2013-12-04 23:49:07 +00003668#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003669template <typename T>
3670inline internal::ElementsAreArrayMatcher<T>
3671ElementsAreArray(::std::initializer_list<T> xs) {
3672 return ElementsAreArray(xs.begin(), xs.end());
3673}
3674#endif
3675
zhanyong.wanfb25d532013-07-28 08:24:00 +00003676// UnorderedElementsAreArray(first, last)
3677// UnorderedElementsAreArray(pointer, count)
3678// UnorderedElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00003679// UnorderedElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003680// UnorderedElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00003681//
3682// The UnorderedElementsAreArray() functions are like
3683// ElementsAreArray(...), but allow matching the elements in any order.
3684template <typename Iter>
3685inline internal::UnorderedElementsAreArrayMatcher<
3686 typename ::std::iterator_traits<Iter>::value_type>
3687UnorderedElementsAreArray(Iter first, Iter last) {
3688 typedef typename ::std::iterator_traits<Iter>::value_type T;
3689 return internal::UnorderedElementsAreArrayMatcher<T>(first, last);
3690}
3691
3692template <typename T>
3693inline internal::UnorderedElementsAreArrayMatcher<T>
3694UnorderedElementsAreArray(const T* pointer, size_t count) {
3695 return UnorderedElementsAreArray(pointer, pointer + count);
3696}
3697
3698template <typename T, size_t N>
3699inline internal::UnorderedElementsAreArrayMatcher<T>
3700UnorderedElementsAreArray(const T (&array)[N]) {
3701 return UnorderedElementsAreArray(array, N);
3702}
3703
kosak06678922014-07-28 20:01:28 +00003704template <typename Container>
3705inline internal::UnorderedElementsAreArrayMatcher<
3706 typename Container::value_type>
3707UnorderedElementsAreArray(const Container& container) {
3708 return UnorderedElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00003709}
3710
kosak18489fa2013-12-04 23:49:07 +00003711#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003712template <typename T>
3713inline internal::UnorderedElementsAreArrayMatcher<T>
3714UnorderedElementsAreArray(::std::initializer_list<T> xs) {
3715 return UnorderedElementsAreArray(xs.begin(), xs.end());
3716}
3717#endif
zhanyong.wanfb25d532013-07-28 08:24:00 +00003718
shiqiane35fdd92008-12-10 05:08:54 +00003719// _ is a matcher that matches anything of any type.
3720//
3721// This definition is fine as:
3722//
3723// 1. The C++ standard permits using the name _ in a namespace that
3724// is not the global namespace or ::std.
3725// 2. The AnythingMatcher class has no data member or constructor,
3726// so it's OK to create global variables of this type.
3727// 3. c-style has approved of using _ in this case.
3728const internal::AnythingMatcher _ = {};
3729// Creates a matcher that matches any value of the given type T.
3730template <typename T>
3731inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
3732
3733// Creates a matcher that matches any value of the given type T.
3734template <typename T>
3735inline Matcher<T> An() { return A<T>(); }
3736
3737// Creates a polymorphic matcher that matches anything equal to x.
3738// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
3739// wouldn't compile.
3740template <typename T>
3741inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
3742
3743// Constructs a Matcher<T> from a 'value' of type T. The constructed
3744// matcher matches any value that's equal to 'value'.
3745template <typename T>
3746Matcher<T>::Matcher(T value) { *this = Eq(value); }
3747
3748// Creates a monomorphic matcher that matches anything with type Lhs
3749// and equal to rhs. A user may need to use this instead of Eq(...)
3750// in order to resolve an overloading ambiguity.
3751//
3752// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
3753// or Matcher<T>(x), but more readable than the latter.
3754//
3755// We could define similar monomorphic matchers for other comparison
3756// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
3757// it yet as those are used much less than Eq() in practice. A user
3758// can always write Matcher<T>(Lt(5)) to be explicit about the type,
3759// for example.
3760template <typename Lhs, typename Rhs>
3761inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
3762
3763// Creates a polymorphic matcher that matches anything >= x.
3764template <typename Rhs>
3765inline internal::GeMatcher<Rhs> Ge(Rhs x) {
3766 return internal::GeMatcher<Rhs>(x);
3767}
3768
3769// Creates a polymorphic matcher that matches anything > x.
3770template <typename Rhs>
3771inline internal::GtMatcher<Rhs> Gt(Rhs x) {
3772 return internal::GtMatcher<Rhs>(x);
3773}
3774
3775// Creates a polymorphic matcher that matches anything <= x.
3776template <typename Rhs>
3777inline internal::LeMatcher<Rhs> Le(Rhs x) {
3778 return internal::LeMatcher<Rhs>(x);
3779}
3780
3781// Creates a polymorphic matcher that matches anything < x.
3782template <typename Rhs>
3783inline internal::LtMatcher<Rhs> Lt(Rhs x) {
3784 return internal::LtMatcher<Rhs>(x);
3785}
3786
3787// Creates a polymorphic matcher that matches anything != x.
3788template <typename Rhs>
3789inline internal::NeMatcher<Rhs> Ne(Rhs x) {
3790 return internal::NeMatcher<Rhs>(x);
3791}
3792
zhanyong.wan2d970ee2009-09-24 21:41:36 +00003793// Creates a polymorphic matcher that matches any NULL pointer.
3794inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
3795 return MakePolymorphicMatcher(internal::IsNullMatcher());
3796}
3797
shiqiane35fdd92008-12-10 05:08:54 +00003798// Creates a polymorphic matcher that matches any non-NULL pointer.
3799// This is convenient as Not(NULL) doesn't compile (the compiler
3800// thinks that that expression is comparing a pointer with an integer).
3801inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
3802 return MakePolymorphicMatcher(internal::NotNullMatcher());
3803}
3804
3805// Creates a polymorphic matcher that matches any argument that
3806// references variable x.
3807template <typename T>
3808inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
3809 return internal::RefMatcher<T&>(x);
3810}
3811
3812// Creates a matcher that matches any double argument approximately
3813// equal to rhs, where two NANs are considered unequal.
3814inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
3815 return internal::FloatingEqMatcher<double>(rhs, false);
3816}
3817
3818// Creates a matcher that matches any double argument approximately
3819// equal to rhs, including NaN values when rhs is NaN.
3820inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
3821 return internal::FloatingEqMatcher<double>(rhs, true);
3822}
3823
zhanyong.wan616180e2013-06-18 18:49:51 +00003824// Creates a matcher that matches any double argument approximately equal to
3825// rhs, up to the specified max absolute error bound, where two NANs are
3826// considered unequal. The max absolute error bound must be non-negative.
3827inline internal::FloatingEqMatcher<double> DoubleNear(
3828 double rhs, double max_abs_error) {
3829 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
3830}
3831
3832// Creates a matcher that matches any double argument approximately equal to
3833// rhs, up to the specified max absolute error bound, including NaN values when
3834// rhs is NaN. The max absolute error bound must be non-negative.
3835inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
3836 double rhs, double max_abs_error) {
3837 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
3838}
3839
shiqiane35fdd92008-12-10 05:08:54 +00003840// Creates a matcher that matches any float argument approximately
3841// equal to rhs, where two NANs are considered unequal.
3842inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
3843 return internal::FloatingEqMatcher<float>(rhs, false);
3844}
3845
zhanyong.wan616180e2013-06-18 18:49:51 +00003846// Creates a matcher that matches any float argument approximately
shiqiane35fdd92008-12-10 05:08:54 +00003847// equal to rhs, including NaN values when rhs is NaN.
3848inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
3849 return internal::FloatingEqMatcher<float>(rhs, true);
3850}
3851
zhanyong.wan616180e2013-06-18 18:49:51 +00003852// Creates a matcher that matches any float argument approximately equal to
3853// rhs, up to the specified max absolute error bound, where two NANs are
3854// considered unequal. The max absolute error bound must be non-negative.
3855inline internal::FloatingEqMatcher<float> FloatNear(
3856 float rhs, float max_abs_error) {
3857 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
3858}
3859
3860// Creates a matcher that matches any float argument approximately equal to
3861// rhs, up to the specified max absolute error bound, including NaN values when
3862// rhs is NaN. The max absolute error bound must be non-negative.
3863inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
3864 float rhs, float max_abs_error) {
3865 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
3866}
3867
shiqiane35fdd92008-12-10 05:08:54 +00003868// Creates a matcher that matches a pointer (raw or smart) that points
3869// to a value that matches inner_matcher.
3870template <typename InnerMatcher>
3871inline internal::PointeeMatcher<InnerMatcher> Pointee(
3872 const InnerMatcher& inner_matcher) {
3873 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
3874}
3875
billydonahue1f5fdea2014-05-19 17:54:51 +00003876// Creates a matcher that matches a pointer or reference that matches
3877// inner_matcher when dynamic_cast<To> is applied.
3878// The result of dynamic_cast<To> is forwarded to the inner matcher.
3879// If To is a pointer and the cast fails, the inner matcher will receive NULL.
3880// If To is a reference and the cast fails, this matcher returns false
3881// immediately.
3882template <typename To>
3883inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
3884WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
3885 return MakePolymorphicMatcher(
3886 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
3887}
3888
shiqiane35fdd92008-12-10 05:08:54 +00003889// Creates a matcher that matches an object whose given field matches
3890// 'matcher'. For example,
3891// Field(&Foo::number, Ge(5))
3892// matches a Foo object x iff x.number >= 5.
3893template <typename Class, typename FieldType, typename FieldMatcher>
3894inline PolymorphicMatcher<
3895 internal::FieldMatcher<Class, FieldType> > Field(
3896 FieldType Class::*field, const FieldMatcher& matcher) {
3897 return MakePolymorphicMatcher(
3898 internal::FieldMatcher<Class, FieldType>(
3899 field, MatcherCast<const FieldType&>(matcher)));
3900 // The call to MatcherCast() is required for supporting inner
3901 // matchers of compatible types. For example, it allows
3902 // Field(&Foo::bar, m)
3903 // to compile where bar is an int32 and m is a matcher for int64.
3904}
3905
3906// Creates a matcher that matches an object whose given property
3907// matches 'matcher'. For example,
3908// Property(&Foo::str, StartsWith("hi"))
3909// matches a Foo object x iff x.str() starts with "hi".
3910template <typename Class, typename PropertyType, typename PropertyMatcher>
3911inline PolymorphicMatcher<
3912 internal::PropertyMatcher<Class, PropertyType> > Property(
3913 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
3914 return MakePolymorphicMatcher(
3915 internal::PropertyMatcher<Class, PropertyType>(
3916 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00003917 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00003918 // The call to MatcherCast() is required for supporting inner
3919 // matchers of compatible types. For example, it allows
3920 // Property(&Foo::bar, m)
3921 // to compile where bar() returns an int32 and m is a matcher for int64.
3922}
3923
3924// Creates a matcher that matches an object iff the result of applying
3925// a callable to x matches 'matcher'.
3926// For example,
3927// ResultOf(f, StartsWith("hi"))
3928// matches a Foo object x iff f(x) starts with "hi".
3929// callable parameter can be a function, function pointer, or a functor.
3930// Callable has to satisfy the following conditions:
3931// * It is required to keep no state affecting the results of
3932// the calls on it and make no assumptions about how many calls
3933// will be made. Any state it keeps must be protected from the
3934// concurrent access.
3935// * If it is a function object, it has to define type result_type.
3936// We recommend deriving your functor classes from std::unary_function.
3937template <typename Callable, typename ResultOfMatcher>
3938internal::ResultOfMatcher<Callable> ResultOf(
3939 Callable callable, const ResultOfMatcher& matcher) {
3940 return internal::ResultOfMatcher<Callable>(
3941 callable,
3942 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
3943 matcher));
3944 // The call to MatcherCast() is required for supporting inner
3945 // matchers of compatible types. For example, it allows
3946 // ResultOf(Function, m)
3947 // to compile where Function() returns an int32 and m is a matcher for int64.
3948}
3949
3950// String matchers.
3951
3952// Matches a string equal to str.
3953inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3954 StrEq(const internal::string& str) {
3955 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3956 str, true, true));
3957}
3958
3959// Matches a string not equal to str.
3960inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3961 StrNe(const internal::string& str) {
3962 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3963 str, false, true));
3964}
3965
3966// Matches a string equal to str, ignoring case.
3967inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3968 StrCaseEq(const internal::string& str) {
3969 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3970 str, true, false));
3971}
3972
3973// Matches a string not equal to str, ignoring case.
3974inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3975 StrCaseNe(const internal::string& str) {
3976 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3977 str, false, false));
3978}
3979
3980// Creates a matcher that matches any string, std::string, or C string
3981// that contains the given substring.
3982inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
3983 HasSubstr(const internal::string& substring) {
3984 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
3985 substring));
3986}
3987
3988// Matches a string that starts with 'prefix' (case-sensitive).
3989inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
3990 StartsWith(const internal::string& prefix) {
3991 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
3992 prefix));
3993}
3994
3995// Matches a string that ends with 'suffix' (case-sensitive).
3996inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
3997 EndsWith(const internal::string& suffix) {
3998 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
3999 suffix));
4000}
4001
shiqiane35fdd92008-12-10 05:08:54 +00004002// Matches a string that fully matches regular expression 'regex'.
4003// The matcher takes ownership of 'regex'.
4004inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4005 const internal::RE* regex) {
4006 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
4007}
4008inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4009 const internal::string& regex) {
4010 return MatchesRegex(new internal::RE(regex));
4011}
4012
4013// Matches a string that contains regular expression 'regex'.
4014// The matcher takes ownership of 'regex'.
4015inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4016 const internal::RE* regex) {
4017 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4018}
4019inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4020 const internal::string& regex) {
4021 return ContainsRegex(new internal::RE(regex));
4022}
4023
shiqiane35fdd92008-12-10 05:08:54 +00004024#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4025// Wide string matchers.
4026
4027// Matches a string equal to str.
4028inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4029 StrEq(const internal::wstring& str) {
4030 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4031 str, true, true));
4032}
4033
4034// Matches a string not equal to str.
4035inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4036 StrNe(const internal::wstring& str) {
4037 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4038 str, false, true));
4039}
4040
4041// Matches a string equal to str, ignoring case.
4042inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4043 StrCaseEq(const internal::wstring& str) {
4044 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4045 str, true, false));
4046}
4047
4048// Matches a string not equal to str, ignoring case.
4049inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4050 StrCaseNe(const internal::wstring& str) {
4051 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4052 str, false, false));
4053}
4054
4055// Creates a matcher that matches any wstring, std::wstring, or C wide string
4056// that contains the given substring.
4057inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
4058 HasSubstr(const internal::wstring& substring) {
4059 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
4060 substring));
4061}
4062
4063// Matches a string that starts with 'prefix' (case-sensitive).
4064inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
4065 StartsWith(const internal::wstring& prefix) {
4066 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
4067 prefix));
4068}
4069
4070// Matches a string that ends with 'suffix' (case-sensitive).
4071inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
4072 EndsWith(const internal::wstring& suffix) {
4073 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
4074 suffix));
4075}
4076
4077#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4078
4079// Creates a polymorphic matcher that matches a 2-tuple where the
4080// first field == the second field.
4081inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4082
4083// Creates a polymorphic matcher that matches a 2-tuple where the
4084// first field >= the second field.
4085inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4086
4087// Creates a polymorphic matcher that matches a 2-tuple where the
4088// first field > the second field.
4089inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4090
4091// Creates a polymorphic matcher that matches a 2-tuple where the
4092// first field <= the second field.
4093inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4094
4095// Creates a polymorphic matcher that matches a 2-tuple where the
4096// first field < the second field.
4097inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4098
4099// Creates a polymorphic matcher that matches a 2-tuple where the
4100// first field != the second field.
4101inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4102
4103// Creates a matcher that matches any value of type T that m doesn't
4104// match.
4105template <typename InnerMatcher>
4106inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4107 return internal::NotMatcher<InnerMatcher>(m);
4108}
4109
shiqiane35fdd92008-12-10 05:08:54 +00004110// Returns a matcher that matches anything that satisfies the given
4111// predicate. The predicate can be any unary function or functor
4112// whose return type can be implicitly converted to bool.
4113template <typename Predicate>
4114inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4115Truly(Predicate pred) {
4116 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4117}
4118
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004119// Returns a matcher that matches the container size. The container must
4120// support both size() and size_type which all STL-like containers provide.
4121// Note that the parameter 'size' can be a value of type size_type as well as
4122// matcher. For instance:
4123// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
4124// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
4125template <typename SizeMatcher>
4126inline internal::SizeIsMatcher<SizeMatcher>
4127SizeIs(const SizeMatcher& size_matcher) {
4128 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4129}
4130
kosakb6a34882014-03-12 21:06:46 +00004131// Returns a matcher that matches the distance between the container's begin()
4132// iterator and its end() iterator, i.e. the size of the container. This matcher
4133// can be used instead of SizeIs with containers such as std::forward_list which
4134// do not implement size(). The container must provide const_iterator (with
4135// valid iterator_traits), begin() and end().
4136template <typename DistanceMatcher>
4137inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4138BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4139 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4140}
4141
zhanyong.wan6a896b52009-01-16 01:13:50 +00004142// Returns a matcher that matches an equal container.
4143// This matcher behaves like Eq(), but in the event of mismatch lists the
4144// values that are included in one container but not the other. (Duplicate
4145// values and order differences are not explained.)
4146template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00004147inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00004148 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004149 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00004150 // This following line is for working around a bug in MSVC 8.0,
4151 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00004152 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00004153 return MakePolymorphicMatcher(
4154 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00004155}
4156
zhanyong.wan898725c2011-09-16 16:45:39 +00004157// Returns a matcher that matches a container that, when sorted using
4158// the given comparator, matches container_matcher.
4159template <typename Comparator, typename ContainerMatcher>
4160inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4161WhenSortedBy(const Comparator& comparator,
4162 const ContainerMatcher& container_matcher) {
4163 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4164 comparator, container_matcher);
4165}
4166
4167// Returns a matcher that matches a container that, when sorted using
4168// the < operator, matches container_matcher.
4169template <typename ContainerMatcher>
4170inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4171WhenSorted(const ContainerMatcher& container_matcher) {
4172 return
4173 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4174 internal::LessComparator(), container_matcher);
4175}
4176
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004177// Matches an STL-style container or a native array that contains the
4178// same number of elements as in rhs, where its i-th element and rhs's
4179// i-th element (as a pair) satisfy the given pair matcher, for all i.
4180// TupleMatcher must be able to be safely cast to Matcher<tuple<const
4181// T1&, const T2&> >, where T1 and T2 are the types of elements in the
4182// LHS container and the RHS container respectively.
4183template <typename TupleMatcher, typename Container>
4184inline internal::PointwiseMatcher<TupleMatcher,
4185 GTEST_REMOVE_CONST_(Container)>
4186Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4187 // This following line is for working around a bug in MSVC 8.0,
kosak2336e9c2014-07-28 22:57:30 +00004188 // which causes Container to be a const type sometimes (e.g. when
4189 // rhs is a const int[])..
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004190 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4191 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4192 tuple_matcher, rhs);
4193}
4194
kosak2336e9c2014-07-28 22:57:30 +00004195#if GTEST_HAS_STD_INITIALIZER_LIST_
4196
4197// Supports the Pointwise(m, {a, b, c}) syntax.
4198template <typename TupleMatcher, typename T>
4199inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4200 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4201 return Pointwise(tuple_matcher, std::vector<T>(rhs));
4202}
4203
4204#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4205
4206// UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4207// container or a native array that contains the same number of
4208// elements as in rhs, where in some permutation of the container, its
4209// i-th element and rhs's i-th element (as a pair) satisfy the given
4210// pair matcher, for all i. Tuple2Matcher must be able to be safely
4211// cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4212// the types of elements in the LHS container and the RHS container
4213// respectively.
4214//
4215// This is like Pointwise(pair_matcher, rhs), except that the element
4216// order doesn't matter.
4217template <typename Tuple2Matcher, typename RhsContainer>
4218inline internal::UnorderedElementsAreArrayMatcher<
4219 typename internal::BoundSecondMatcher<
4220 Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4221 RhsContainer)>::type::value_type> >
4222UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4223 const RhsContainer& rhs_container) {
4224 // This following line is for working around a bug in MSVC 8.0,
4225 // which causes RhsContainer to be a const type sometimes (e.g. when
4226 // rhs_container is a const int[]).
4227 typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4228
4229 // RhsView allows the same code to handle RhsContainer being a
4230 // STL-style container and it being a native C-style array.
4231 typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4232 typedef typename RhsView::type RhsStlContainer;
4233 typedef typename RhsStlContainer::value_type Second;
4234 const RhsStlContainer& rhs_stl_container =
4235 RhsView::ConstReference(rhs_container);
4236
4237 // Create a matcher for each element in rhs_container.
4238 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4239 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4240 it != rhs_stl_container.end(); ++it) {
4241 matchers.push_back(
4242 internal::MatcherBindSecond(tuple2_matcher, *it));
4243 }
4244
4245 // Delegate the work to UnorderedElementsAreArray().
4246 return UnorderedElementsAreArray(matchers);
4247}
4248
4249#if GTEST_HAS_STD_INITIALIZER_LIST_
4250
4251// Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4252template <typename Tuple2Matcher, typename T>
4253inline internal::UnorderedElementsAreArrayMatcher<
4254 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4255UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4256 std::initializer_list<T> rhs) {
4257 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4258}
4259
4260#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4261
zhanyong.wanb8243162009-06-04 05:48:20 +00004262// Matches an STL-style container or a native array that contains at
4263// least one element matching the given value or matcher.
4264//
4265// Examples:
4266// ::std::set<int> page_ids;
4267// page_ids.insert(3);
4268// page_ids.insert(1);
4269// EXPECT_THAT(page_ids, Contains(1));
4270// EXPECT_THAT(page_ids, Contains(Gt(2)));
4271// EXPECT_THAT(page_ids, Not(Contains(4)));
4272//
4273// ::std::map<int, size_t> page_lengths;
4274// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00004275// EXPECT_THAT(page_lengths,
4276// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004277//
4278// const char* user_ids[] = { "joe", "mike", "tom" };
4279// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4280template <typename M>
4281inline internal::ContainsMatcher<M> Contains(M matcher) {
4282 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004283}
4284
zhanyong.wan33605ba2010-04-22 23:37:47 +00004285// Matches an STL-style container or a native array that contains only
4286// elements matching the given value or matcher.
4287//
4288// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
4289// the messages are different.
4290//
4291// Examples:
4292// ::std::set<int> page_ids;
4293// // Each(m) matches an empty container, regardless of what m is.
4294// EXPECT_THAT(page_ids, Each(Eq(1)));
4295// EXPECT_THAT(page_ids, Each(Eq(77)));
4296//
4297// page_ids.insert(3);
4298// EXPECT_THAT(page_ids, Each(Gt(0)));
4299// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
4300// page_ids.insert(1);
4301// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
4302//
4303// ::std::map<int, size_t> page_lengths;
4304// page_lengths[1] = 100;
4305// page_lengths[2] = 200;
4306// page_lengths[3] = 300;
4307// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
4308// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
4309//
4310// const char* user_ids[] = { "joe", "mike", "tom" };
4311// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
4312template <typename M>
4313inline internal::EachMatcher<M> Each(M matcher) {
4314 return internal::EachMatcher<M>(matcher);
4315}
4316
zhanyong.wanb5937da2009-07-16 20:26:41 +00004317// Key(inner_matcher) matches an std::pair whose 'first' field matches
4318// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
4319// std::map that contains at least one element whose key is >= 5.
4320template <typename M>
4321inline internal::KeyMatcher<M> Key(M inner_matcher) {
4322 return internal::KeyMatcher<M>(inner_matcher);
4323}
4324
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00004325// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
4326// matches first_matcher and whose 'second' field matches second_matcher. For
4327// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
4328// to match a std::map<int, string> that contains exactly one element whose key
4329// is >= 5 and whose value equals "foo".
4330template <typename FirstMatcher, typename SecondMatcher>
4331inline internal::PairMatcher<FirstMatcher, SecondMatcher>
4332Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
4333 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
4334 first_matcher, second_matcher);
4335}
4336
shiqiane35fdd92008-12-10 05:08:54 +00004337// Returns a predicate that is satisfied by anything that matches the
4338// given matcher.
4339template <typename M>
4340inline internal::MatcherAsPredicate<M> Matches(M matcher) {
4341 return internal::MatcherAsPredicate<M>(matcher);
4342}
4343
zhanyong.wanb8243162009-06-04 05:48:20 +00004344// Returns true iff the value matches the matcher.
4345template <typename T, typename M>
4346inline bool Value(const T& value, M matcher) {
4347 return testing::Matches(matcher)(value);
4348}
4349
zhanyong.wan34b034c2010-03-05 21:23:23 +00004350// Matches the value against the given matcher and explains the match
4351// result to listener.
4352template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00004353inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00004354 M matcher, const T& value, MatchResultListener* listener) {
4355 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
4356}
4357
zhanyong.wan616180e2013-06-18 18:49:51 +00004358#if GTEST_LANG_CXX11
4359// Define variadic matcher versions. They are overloaded in
4360// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
4361template <typename... Args>
4362inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
4363 return internal::AllOfMatcher<Args...>(matchers...);
4364}
4365
4366template <typename... Args>
4367inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
4368 return internal::AnyOfMatcher<Args...>(matchers...);
4369}
4370
4371#endif // GTEST_LANG_CXX11
4372
zhanyong.wanbf550852009-06-09 06:09:53 +00004373// AllArgs(m) is a synonym of m. This is useful in
4374//
4375// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
4376//
4377// which is easier to read than
4378//
4379// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
4380template <typename InnerMatcher>
4381inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
4382
shiqiane35fdd92008-12-10 05:08:54 +00004383// These macros allow using matchers to check values in Google Test
4384// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
4385// succeed iff the value matches the matcher. If the assertion fails,
4386// the value and the description of the matcher will be printed.
4387#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
4388 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4389#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
4390 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4391
4392} // namespace testing
4393
4394#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
billydonahue1f5fdea2014-05-19 17:54:51 +00004395