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