blob: 3367a0b578a6d21f0789c9737f94a41d0311c533 [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.
Nico Weber09fd5b32017-05-15 17:07:03 -0400189 std::string str() const { return ss_.str(); }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000190
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.
kosakd86a7232015-07-13 21:19:43 +0000324 explicit Matcher() {} // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000325
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,
Hector Dearman24054ff2017-06-19 18:27:33 +0100649 cannot_convert_non_reference_arg_to_reference);
zhanyong.wan95b12332009-09-25 18:55:50 +0000650 // 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.
Nico Weber09fd5b32017-05-15 17:07:03 -0400678inline void PrintIfNotEmpty(const std::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.
Nico Weber09fd5b32017-05-15 17:07:03 -0400688inline bool IsReadableTypeName(const std::string& type_name) {
zhanyong.wan736baa82010-09-27 17:44:16 +0000689 // 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 ||
Nico Weber09fd5b32017-05-15 17:07:03 -0400692 type_name.find_first_of("<(") == std::string::npos);
zhanyong.wan736baa82010-09-27 17:44:16 +0000693}
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
Nico Weber09fd5b32017-05-15 17:07:03 -0400714 const std::string& type_name = GetTypeName<Value>();
zhanyong.wan736baa82010-09-27 17:44:16 +0000715 if (IsReadableTypeName(type_name))
716 *listener->stream() << " (of type " << type_name << ")";
717#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000718 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000719
720 return match;
721}
722
shiqiane35fdd92008-12-10 05:08:54 +0000723// An internal helper class for doing compile-time loop on a tuple's
724// fields.
725template <size_t N>
726class TuplePrefix {
727 public:
728 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
729 // iff the first N fields of matcher_tuple matches the first N
730 // fields of value_tuple, respectively.
731 template <typename MatcherTuple, typename ValueTuple>
732 static bool Matches(const MatcherTuple& matcher_tuple,
733 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000734 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
735 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
736 }
737
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000738 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000739 // describes failures in matching the first N fields of matchers
740 // against the first N fields of values. If there is no failure,
741 // nothing will be streamed to os.
742 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000743 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
744 const ValueTuple& values,
745 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000746 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000747 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000748
749 // Then describes the failure (if any) in the (N - 1)-th (0-based)
750 // field.
751 typename tuple_element<N - 1, MatcherTuple>::type matcher =
752 get<N - 1>(matchers);
753 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
754 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000755 StringMatchResultListener listener;
756 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000757 // TODO(wan): include in the message the name of the parameter
758 // as used in MOCK_METHOD*() when possible.
759 *os << " Expected arg #" << N - 1 << ": ";
760 get<N - 1>(matchers).DescribeTo(os);
761 *os << "\n Actual: ";
762 // We remove the reference in type Value to prevent the
763 // universal printer from printing the address of value, which
764 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000765 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000766 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000767 internal::UniversalPrint(value, os);
768 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000769 *os << "\n";
770 }
771 }
772};
773
774// The base case.
775template <>
776class TuplePrefix<0> {
777 public:
778 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000779 static bool Matches(const MatcherTuple& /* matcher_tuple */,
780 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000781 return true;
782 }
783
784 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000785 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
786 const ValueTuple& /* values */,
787 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000788};
789
790// TupleMatches(matcher_tuple, value_tuple) returns true iff all
791// matchers in matcher_tuple match the corresponding fields in
792// value_tuple. It is a compiler error if matcher_tuple and
793// value_tuple have different number of fields or incompatible field
794// types.
795template <typename MatcherTuple, typename ValueTuple>
796bool TupleMatches(const MatcherTuple& matcher_tuple,
797 const ValueTuple& value_tuple) {
shiqiane35fdd92008-12-10 05:08:54 +0000798 // Makes sure that matcher_tuple and value_tuple have the same
799 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000800 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000801 tuple_size<ValueTuple>::value,
802 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000803 return TuplePrefix<tuple_size<ValueTuple>::value>::
804 Matches(matcher_tuple, value_tuple);
805}
806
807// Describes failures in matching matchers against values. If there
808// is no failure, nothing will be streamed to os.
809template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000810void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
811 const ValueTuple& values,
812 ::std::ostream* os) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000813 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000814 matchers, values, os);
815}
816
zhanyong.wanfb25d532013-07-28 08:24:00 +0000817// TransformTupleValues and its helper.
818//
819// TransformTupleValuesHelper hides the internal machinery that
820// TransformTupleValues uses to implement a tuple traversal.
821template <typename Tuple, typename Func, typename OutIter>
822class TransformTupleValuesHelper {
823 private:
kosakbd018832014-04-02 20:30:00 +0000824 typedef ::testing::tuple_size<Tuple> TupleSize;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000825
826 public:
827 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
828 // Returns the final value of 'out' in case the caller needs it.
829 static OutIter Run(Func f, const Tuple& t, OutIter out) {
830 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
831 }
832
833 private:
834 template <typename Tup, size_t kRemainingSize>
835 struct IterateOverTuple {
836 OutIter operator() (Func f, const Tup& t, OutIter out) const {
kosakbd018832014-04-02 20:30:00 +0000837 *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
zhanyong.wanfb25d532013-07-28 08:24:00 +0000838 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
839 }
840 };
841 template <typename Tup>
842 struct IterateOverTuple<Tup, 0> {
843 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
844 return out;
845 }
846 };
847};
848
849// Successively invokes 'f(element)' on each element of the tuple 't',
850// appending each result to the 'out' iterator. Returns the final value
851// of 'out'.
852template <typename Tuple, typename Func, typename OutIter>
853OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
854 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
855}
856
shiqiane35fdd92008-12-10 05:08:54 +0000857// Implements A<T>().
858template <typename T>
859class AnyMatcherImpl : public MatcherInterface<T> {
860 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000861 virtual bool MatchAndExplain(
862 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000863 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
864 virtual void DescribeNegationTo(::std::ostream* os) const {
865 // This is mostly for completeness' safe, as it's not very useful
866 // to write Not(A<bool>()). However we cannot completely rule out
867 // such a possibility, and it doesn't hurt to be prepared.
868 *os << "never matches";
869 }
870};
871
872// Implements _, a matcher that matches any value of any
873// type. This is a polymorphic matcher, so we need a template type
874// conversion operator to make it appearing as a Matcher<T> for any
875// type T.
876class AnythingMatcher {
877 public:
878 template <typename T>
879 operator Matcher<T>() const { return A<T>(); }
880};
881
882// Implements a matcher that compares a given value with a
883// pre-supplied value using one of the ==, <=, <, etc, operators. The
884// two values being compared don't have to have the same type.
885//
886// The matcher defined here is polymorphic (for example, Eq(5) can be
887// used to match an int, a short, a double, etc). Therefore we use
888// a template type conversion operator in the implementation.
889//
shiqiane35fdd92008-12-10 05:08:54 +0000890// The following template definition assumes that the Rhs parameter is
891// a "bare" type (i.e. neither 'const T' nor 'T&').
kosak506340a2014-11-17 01:47:54 +0000892template <typename D, typename Rhs, typename Op>
893class ComparisonBase {
894 public:
895 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
896 template <typename Lhs>
897 operator Matcher<Lhs>() const {
898 return MakeMatcher(new Impl<Lhs>(rhs_));
shiqiane35fdd92008-12-10 05:08:54 +0000899 }
900
kosak506340a2014-11-17 01:47:54 +0000901 private:
902 template <typename Lhs>
903 class Impl : public MatcherInterface<Lhs> {
904 public:
905 explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
906 virtual bool MatchAndExplain(
907 Lhs lhs, MatchResultListener* /* listener */) const {
908 return Op()(lhs, rhs_);
909 }
910 virtual void DescribeTo(::std::ostream* os) const {
911 *os << D::Desc() << " ";
912 UniversalPrint(rhs_, os);
913 }
914 virtual void DescribeNegationTo(::std::ostream* os) const {
915 *os << D::NegatedDesc() << " ";
916 UniversalPrint(rhs_, os);
917 }
918 private:
919 Rhs rhs_;
920 GTEST_DISALLOW_ASSIGN_(Impl);
921 };
922 Rhs rhs_;
923 GTEST_DISALLOW_ASSIGN_(ComparisonBase);
924};
shiqiane35fdd92008-12-10 05:08:54 +0000925
kosak506340a2014-11-17 01:47:54 +0000926template <typename Rhs>
927class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
928 public:
929 explicit EqMatcher(const Rhs& rhs)
930 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
931 static const char* Desc() { return "is equal to"; }
932 static const char* NegatedDesc() { return "isn't equal to"; }
933};
934template <typename Rhs>
935class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
936 public:
937 explicit NeMatcher(const Rhs& rhs)
938 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
939 static const char* Desc() { return "isn't equal to"; }
940 static const char* NegatedDesc() { return "is equal to"; }
941};
942template <typename Rhs>
943class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
944 public:
945 explicit LtMatcher(const Rhs& rhs)
946 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
947 static const char* Desc() { return "is <"; }
948 static const char* NegatedDesc() { return "isn't <"; }
949};
950template <typename Rhs>
951class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
952 public:
953 explicit GtMatcher(const Rhs& rhs)
954 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
955 static const char* Desc() { return "is >"; }
956 static const char* NegatedDesc() { return "isn't >"; }
957};
958template <typename Rhs>
959class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
960 public:
961 explicit LeMatcher(const Rhs& rhs)
962 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
963 static const char* Desc() { return "is <="; }
964 static const char* NegatedDesc() { return "isn't <="; }
965};
966template <typename Rhs>
967class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
968 public:
969 explicit GeMatcher(const Rhs& rhs)
970 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
971 static const char* Desc() { return "is >="; }
972 static const char* NegatedDesc() { return "isn't >="; }
973};
shiqiane35fdd92008-12-10 05:08:54 +0000974
vladlosev79b83502009-11-18 00:43:37 +0000975// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000976// pointer that is NULL.
977class IsNullMatcher {
978 public:
vladlosev79b83502009-11-18 00:43:37 +0000979 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000980 bool MatchAndExplain(const Pointer& p,
981 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +0000982#if GTEST_LANG_CXX11
983 return p == nullptr;
984#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +0000985 return GetRawPointer(p) == NULL;
kosak6305ff52015-04-28 22:36:31 +0000986#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +0000987 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000988
989 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
990 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000991 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000992 }
993};
994
vladlosev79b83502009-11-18 00:43:37 +0000995// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000996// pointer that is not NULL.
997class NotNullMatcher {
998 public:
vladlosev79b83502009-11-18 00:43:37 +0000999 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +00001000 bool MatchAndExplain(const Pointer& p,
1001 MatchResultListener* /* listener */) const {
kosak6305ff52015-04-28 22:36:31 +00001002#if GTEST_LANG_CXX11
1003 return p != nullptr;
1004#else // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001005 return GetRawPointer(p) != NULL;
kosak6305ff52015-04-28 22:36:31 +00001006#endif // GTEST_LANG_CXX11
zhanyong.wandb22c222010-01-28 21:52:29 +00001007 }
shiqiane35fdd92008-12-10 05:08:54 +00001008
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001009 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +00001010 void DescribeNegationTo(::std::ostream* os) const {
1011 *os << "is NULL";
1012 }
1013};
1014
1015// Ref(variable) matches any argument that is a reference to
1016// 'variable'. This matcher is polymorphic as it can match any
1017// super type of the type of 'variable'.
1018//
1019// The RefMatcher template class implements Ref(variable). It can
1020// only be instantiated with a reference type. This prevents a user
1021// from mistakenly using Ref(x) to match a non-reference function
1022// argument. For example, the following will righteously cause a
1023// compiler error:
1024//
1025// int n;
1026// Matcher<int> m1 = Ref(n); // This won't compile.
1027// Matcher<int&> m2 = Ref(n); // This will compile.
1028template <typename T>
1029class RefMatcher;
1030
1031template <typename T>
1032class RefMatcher<T&> {
1033 // Google Mock is a generic framework and thus needs to support
1034 // mocking any function types, including those that take non-const
1035 // reference arguments. Therefore the template parameter T (and
1036 // Super below) can be instantiated to either a const type or a
1037 // non-const type.
1038 public:
1039 // RefMatcher() takes a T& instead of const T&, as we want the
1040 // compiler to catch using Ref(const_value) as a matcher for a
1041 // non-const reference.
1042 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
1043
1044 template <typename Super>
1045 operator Matcher<Super&>() const {
1046 // By passing object_ (type T&) to Impl(), which expects a Super&,
1047 // we make sure that Super is a super type of T. In particular,
1048 // this catches using Ref(const_value) as a matcher for a
1049 // non-const reference, as you cannot implicitly convert a const
1050 // reference to a non-const reference.
1051 return MakeMatcher(new Impl<Super>(object_));
1052 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001053
shiqiane35fdd92008-12-10 05:08:54 +00001054 private:
1055 template <typename Super>
1056 class Impl : public MatcherInterface<Super&> {
1057 public:
1058 explicit Impl(Super& x) : object_(x) {} // NOLINT
1059
zhanyong.wandb22c222010-01-28 21:52:29 +00001060 // MatchAndExplain() takes a Super& (as opposed to const Super&)
1061 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +00001062 virtual bool MatchAndExplain(
1063 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001064 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +00001065 return &x == &object_;
1066 }
shiqiane35fdd92008-12-10 05:08:54 +00001067
1068 virtual void DescribeTo(::std::ostream* os) const {
1069 *os << "references the variable ";
1070 UniversalPrinter<Super&>::Print(object_, os);
1071 }
1072
1073 virtual void DescribeNegationTo(::std::ostream* os) const {
1074 *os << "does not reference the variable ";
1075 UniversalPrinter<Super&>::Print(object_, os);
1076 }
1077
shiqiane35fdd92008-12-10 05:08:54 +00001078 private:
1079 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001080
1081 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001082 };
1083
1084 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001085
1086 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001087};
1088
1089// Polymorphic helper functions for narrow and wide string matchers.
1090inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1091 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1092}
1093
1094inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1095 const wchar_t* rhs) {
1096 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1097}
1098
1099// String comparison for narrow or wide strings that can have embedded NUL
1100// characters.
1101template <typename StringType>
1102bool CaseInsensitiveStringEquals(const StringType& s1,
1103 const StringType& s2) {
1104 // Are the heads equal?
1105 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1106 return false;
1107 }
1108
1109 // Skip the equal heads.
1110 const typename StringType::value_type nul = 0;
1111 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1112
1113 // Are we at the end of either s1 or s2?
1114 if (i1 == StringType::npos || i2 == StringType::npos) {
1115 return i1 == i2;
1116 }
1117
1118 // Are the tails equal?
1119 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1120}
1121
1122// String matchers.
1123
1124// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1125template <typename StringType>
1126class StrEqualityMatcher {
1127 public:
shiqiane35fdd92008-12-10 05:08:54 +00001128 StrEqualityMatcher(const StringType& str, bool expect_eq,
1129 bool case_sensitive)
1130 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1131
jgm38513a82012-11-15 15:50:36 +00001132 // Accepts pointer types, particularly:
1133 // const char*
1134 // char*
1135 // const wchar_t*
1136 // wchar_t*
1137 template <typename CharType>
1138 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001139 if (s == NULL) {
1140 return !expect_eq_;
1141 }
zhanyong.wandb22c222010-01-28 21:52:29 +00001142 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001143 }
1144
jgm38513a82012-11-15 15:50:36 +00001145 // Matches anything that can convert to StringType.
1146 //
1147 // This is a template, not just a plain function with const StringType&,
1148 // because StringPiece has some interfering non-explicit constructors.
1149 template <typename MatcheeStringType>
1150 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001151 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001152 const StringType& s2(s);
1153 const bool eq = case_sensitive_ ? s2 == string_ :
1154 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +00001155 return expect_eq_ == eq;
1156 }
1157
1158 void DescribeTo(::std::ostream* os) const {
1159 DescribeToHelper(expect_eq_, os);
1160 }
1161
1162 void DescribeNegationTo(::std::ostream* os) const {
1163 DescribeToHelper(!expect_eq_, os);
1164 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001165
shiqiane35fdd92008-12-10 05:08:54 +00001166 private:
1167 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001168 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +00001169 *os << "equal to ";
1170 if (!case_sensitive_) {
1171 *os << "(ignoring case) ";
1172 }
vladloseve2e8ba42010-05-13 18:16:03 +00001173 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001174 }
1175
1176 const StringType string_;
1177 const bool expect_eq_;
1178 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001179
1180 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001181};
1182
1183// Implements the polymorphic HasSubstr(substring) matcher, which
1184// can be used as a Matcher<T> as long as T can be converted to a
1185// string.
1186template <typename StringType>
1187class HasSubstrMatcher {
1188 public:
shiqiane35fdd92008-12-10 05:08:54 +00001189 explicit HasSubstrMatcher(const StringType& substring)
1190 : substring_(substring) {}
1191
jgm38513a82012-11-15 15:50:36 +00001192 // Accepts pointer types, particularly:
1193 // const char*
1194 // char*
1195 // const wchar_t*
1196 // wchar_t*
1197 template <typename CharType>
1198 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001199 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001200 }
1201
jgm38513a82012-11-15 15:50:36 +00001202 // Matches anything that can convert to StringType.
1203 //
1204 // This is a template, not just a plain function with const StringType&,
1205 // because StringPiece has some interfering non-explicit constructors.
1206 template <typename MatcheeStringType>
1207 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001208 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001209 const StringType& s2(s);
1210 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001211 }
1212
1213 // Describes what this matcher matches.
1214 void DescribeTo(::std::ostream* os) const {
1215 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001216 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001217 }
1218
1219 void DescribeNegationTo(::std::ostream* os) const {
1220 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001221 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001222 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001223
shiqiane35fdd92008-12-10 05:08:54 +00001224 private:
1225 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001226
1227 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001228};
1229
1230// Implements the polymorphic StartsWith(substring) matcher, which
1231// can be used as a Matcher<T> as long as T can be converted to a
1232// string.
1233template <typename StringType>
1234class StartsWithMatcher {
1235 public:
shiqiane35fdd92008-12-10 05:08:54 +00001236 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1237 }
1238
jgm38513a82012-11-15 15:50:36 +00001239 // Accepts pointer types, particularly:
1240 // const char*
1241 // char*
1242 // const wchar_t*
1243 // wchar_t*
1244 template <typename CharType>
1245 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001246 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001247 }
1248
jgm38513a82012-11-15 15:50:36 +00001249 // Matches anything that can convert to StringType.
1250 //
1251 // This is a template, not just a plain function with const StringType&,
1252 // because StringPiece has some interfering non-explicit constructors.
1253 template <typename MatcheeStringType>
1254 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001255 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001256 const StringType& s2(s);
1257 return s2.length() >= prefix_.length() &&
1258 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001259 }
1260
1261 void DescribeTo(::std::ostream* os) const {
1262 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001263 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001264 }
1265
1266 void DescribeNegationTo(::std::ostream* os) const {
1267 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001268 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001269 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001270
shiqiane35fdd92008-12-10 05:08:54 +00001271 private:
1272 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001273
1274 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001275};
1276
1277// Implements the polymorphic EndsWith(substring) matcher, which
1278// can be used as a Matcher<T> as long as T can be converted to a
1279// string.
1280template <typename StringType>
1281class EndsWithMatcher {
1282 public:
shiqiane35fdd92008-12-10 05:08:54 +00001283 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1284
jgm38513a82012-11-15 15:50:36 +00001285 // Accepts pointer types, particularly:
1286 // const char*
1287 // char*
1288 // const wchar_t*
1289 // wchar_t*
1290 template <typename CharType>
1291 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001292 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001293 }
1294
jgm38513a82012-11-15 15:50:36 +00001295 // Matches anything that can convert to StringType.
1296 //
1297 // This is a template, not just a plain function with const StringType&,
1298 // because StringPiece has some interfering non-explicit constructors.
1299 template <typename MatcheeStringType>
1300 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001301 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001302 const StringType& s2(s);
1303 return s2.length() >= suffix_.length() &&
1304 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001305 }
1306
1307 void DescribeTo(::std::ostream* os) const {
1308 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001309 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001310 }
1311
1312 void DescribeNegationTo(::std::ostream* os) const {
1313 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001314 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001315 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001316
shiqiane35fdd92008-12-10 05:08:54 +00001317 private:
1318 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001319
1320 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001321};
1322
shiqiane35fdd92008-12-10 05:08:54 +00001323// Implements polymorphic matchers MatchesRegex(regex) and
1324// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1325// T can be converted to a string.
1326class MatchesRegexMatcher {
1327 public:
1328 MatchesRegexMatcher(const RE* regex, bool full_match)
1329 : regex_(regex), full_match_(full_match) {}
1330
jgm38513a82012-11-15 15:50:36 +00001331 // Accepts pointer types, particularly:
1332 // const char*
1333 // char*
1334 // const wchar_t*
1335 // wchar_t*
1336 template <typename CharType>
1337 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001338 return s != NULL && MatchAndExplain(std::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001339 }
1340
Nico Weber09fd5b32017-05-15 17:07:03 -04001341 // Matches anything that can convert to std::string.
jgm38513a82012-11-15 15:50:36 +00001342 //
Nico Weber09fd5b32017-05-15 17:07:03 -04001343 // This is a template, not just a plain function with const std::string&,
jgm38513a82012-11-15 15:50:36 +00001344 // because StringPiece has some interfering non-explicit constructors.
1345 template <class MatcheeStringType>
1346 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001347 MatchResultListener* /* listener */) const {
Nico Weber09fd5b32017-05-15 17:07:03 -04001348 const std::string& s2(s);
jgm38513a82012-11-15 15:50:36 +00001349 return full_match_ ? RE::FullMatch(s2, *regex_) :
1350 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001351 }
1352
1353 void DescribeTo(::std::ostream* os) const {
1354 *os << (full_match_ ? "matches" : "contains")
1355 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001356 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001357 }
1358
1359 void DescribeNegationTo(::std::ostream* os) const {
1360 *os << "doesn't " << (full_match_ ? "match" : "contain")
1361 << " regular expression ";
Nico Weber09fd5b32017-05-15 17:07:03 -04001362 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001363 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001364
shiqiane35fdd92008-12-10 05:08:54 +00001365 private:
1366 const internal::linked_ptr<const RE> regex_;
1367 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001368
1369 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001370};
1371
shiqiane35fdd92008-12-10 05:08:54 +00001372// Implements a matcher that compares the two fields of a 2-tuple
1373// using one of the ==, <=, <, etc, operators. The two fields being
1374// compared don't have to have the same type.
1375//
1376// The matcher defined here is polymorphic (for example, Eq() can be
1377// used to match a tuple<int, short>, a tuple<const long&, double>,
1378// etc). Therefore we use a template type conversion operator in the
1379// implementation.
kosak506340a2014-11-17 01:47:54 +00001380template <typename D, typename Op>
1381class PairMatchBase {
1382 public:
1383 template <typename T1, typename T2>
1384 operator Matcher< ::testing::tuple<T1, T2> >() const {
1385 return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >);
1386 }
1387 template <typename T1, typename T2>
1388 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
1389 return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>);
shiqiane35fdd92008-12-10 05:08:54 +00001390 }
1391
kosak506340a2014-11-17 01:47:54 +00001392 private:
1393 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
1394 return os << D::Desc();
1395 }
shiqiane35fdd92008-12-10 05:08:54 +00001396
kosak506340a2014-11-17 01:47:54 +00001397 template <typename Tuple>
1398 class Impl : public MatcherInterface<Tuple> {
1399 public:
1400 virtual bool MatchAndExplain(
1401 Tuple args,
1402 MatchResultListener* /* listener */) const {
1403 return Op()(::testing::get<0>(args), ::testing::get<1>(args));
1404 }
1405 virtual void DescribeTo(::std::ostream* os) const {
1406 *os << "are " << GetDesc;
1407 }
1408 virtual void DescribeNegationTo(::std::ostream* os) const {
1409 *os << "aren't " << GetDesc;
1410 }
1411 };
1412};
1413
1414class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
1415 public:
1416 static const char* Desc() { return "an equal pair"; }
1417};
1418class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
1419 public:
1420 static const char* Desc() { return "an unequal pair"; }
1421};
1422class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
1423 public:
1424 static const char* Desc() { return "a pair where the first < the second"; }
1425};
1426class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
1427 public:
1428 static const char* Desc() { return "a pair where the first > the second"; }
1429};
1430class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
1431 public:
1432 static const char* Desc() { return "a pair where the first <= the second"; }
1433};
1434class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
1435 public:
1436 static const char* Desc() { return "a pair where the first >= the second"; }
1437};
shiqiane35fdd92008-12-10 05:08:54 +00001438
zhanyong.wanc6a41232009-05-13 23:38:40 +00001439// Implements the Not(...) matcher for a particular argument type T.
1440// We do not nest it inside the NotMatcher class template, as that
1441// will prevent different instantiations of NotMatcher from sharing
1442// the same NotMatcherImpl<T> class.
1443template <typename T>
1444class NotMatcherImpl : public MatcherInterface<T> {
1445 public:
1446 explicit NotMatcherImpl(const Matcher<T>& matcher)
1447 : matcher_(matcher) {}
1448
zhanyong.wan82113312010-01-08 21:55:40 +00001449 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1450 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001451 }
1452
1453 virtual void DescribeTo(::std::ostream* os) const {
1454 matcher_.DescribeNegationTo(os);
1455 }
1456
1457 virtual void DescribeNegationTo(::std::ostream* os) const {
1458 matcher_.DescribeTo(os);
1459 }
1460
zhanyong.wanc6a41232009-05-13 23:38:40 +00001461 private:
1462 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001463
1464 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001465};
1466
shiqiane35fdd92008-12-10 05:08:54 +00001467// Implements the Not(m) matcher, which matches a value that doesn't
1468// match matcher m.
1469template <typename InnerMatcher>
1470class NotMatcher {
1471 public:
1472 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1473
1474 // This template type conversion operator allows Not(m) to be used
1475 // to match any type m can match.
1476 template <typename T>
1477 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001478 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001479 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001480
shiqiane35fdd92008-12-10 05:08:54 +00001481 private:
shiqiane35fdd92008-12-10 05:08:54 +00001482 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001483
1484 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001485};
1486
zhanyong.wanc6a41232009-05-13 23:38:40 +00001487// Implements the AllOf(m1, m2) matcher for a particular argument type
1488// T. We do not nest it inside the BothOfMatcher class template, as
1489// that will prevent different instantiations of BothOfMatcher from
1490// sharing the same BothOfMatcherImpl<T> class.
1491template <typename T>
1492class BothOfMatcherImpl : public MatcherInterface<T> {
1493 public:
1494 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1495 : matcher1_(matcher1), matcher2_(matcher2) {}
1496
zhanyong.wanc6a41232009-05-13 23:38:40 +00001497 virtual void DescribeTo(::std::ostream* os) const {
1498 *os << "(";
1499 matcher1_.DescribeTo(os);
1500 *os << ") and (";
1501 matcher2_.DescribeTo(os);
1502 *os << ")";
1503 }
1504
1505 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001506 *os << "(";
1507 matcher1_.DescribeNegationTo(os);
1508 *os << ") or (";
1509 matcher2_.DescribeNegationTo(os);
1510 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001511 }
1512
zhanyong.wan82113312010-01-08 21:55:40 +00001513 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1514 // If either matcher1_ or matcher2_ doesn't match x, we only need
1515 // to explain why one of them fails.
1516 StringMatchResultListener listener1;
1517 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1518 *listener << listener1.str();
1519 return false;
1520 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001521
zhanyong.wan82113312010-01-08 21:55:40 +00001522 StringMatchResultListener listener2;
1523 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1524 *listener << listener2.str();
1525 return false;
1526 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001527
zhanyong.wan82113312010-01-08 21:55:40 +00001528 // Otherwise we need to explain why *both* of them match.
Nico Weber09fd5b32017-05-15 17:07:03 -04001529 const std::string s1 = listener1.str();
1530 const std::string s2 = listener2.str();
zhanyong.wan82113312010-01-08 21:55:40 +00001531
1532 if (s1 == "") {
1533 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001534 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001535 *listener << s1;
1536 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001537 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001538 }
1539 }
zhanyong.wan82113312010-01-08 21:55:40 +00001540 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001541 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001542
zhanyong.wanc6a41232009-05-13 23:38:40 +00001543 private:
1544 const Matcher<T> matcher1_;
1545 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001546
1547 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001548};
1549
zhanyong.wan616180e2013-06-18 18:49:51 +00001550#if GTEST_LANG_CXX11
1551// MatcherList provides mechanisms for storing a variable number of matchers in
1552// a list structure (ListType) and creating a combining matcher from such a
1553// list.
1554// The template is defined recursively using the following template paramters:
1555// * kSize is the length of the MatcherList.
1556// * Head is the type of the first matcher of the list.
1557// * Tail denotes the types of the remaining matchers of the list.
1558template <int kSize, typename Head, typename... Tail>
1559struct MatcherList {
1560 typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
zhanyong.wan29897032013-06-20 18:59:15 +00001561 typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001562
1563 // BuildList stores variadic type values in a nested pair structure.
1564 // Example:
1565 // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
1566 // the corresponding result of type pair<int, pair<string, float>>.
1567 static ListType BuildList(const Head& matcher, const Tail&... tail) {
1568 return ListType(matcher, MatcherListTail::BuildList(tail...));
1569 }
1570
1571 // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
1572 // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
1573 // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
1574 // constructor taking two Matcher<T>s as input.
1575 template <typename T, template <typename /* T */> class CombiningMatcher>
1576 static Matcher<T> CreateMatcher(const ListType& matchers) {
1577 return Matcher<T>(new CombiningMatcher<T>(
1578 SafeMatcherCast<T>(matchers.first),
1579 MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
1580 matchers.second)));
1581 }
1582};
1583
1584// The following defines the base case for the recursive definition of
1585// MatcherList.
1586template <typename Matcher1, typename Matcher2>
1587struct MatcherList<2, Matcher1, Matcher2> {
zhanyong.wan29897032013-06-20 18:59:15 +00001588 typedef ::std::pair<Matcher1, Matcher2> ListType;
zhanyong.wan616180e2013-06-18 18:49:51 +00001589
1590 static ListType BuildList(const Matcher1& matcher1,
1591 const Matcher2& matcher2) {
zhanyong.wan29897032013-06-20 18:59:15 +00001592 return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
zhanyong.wan616180e2013-06-18 18:49:51 +00001593 }
1594
1595 template <typename T, template <typename /* T */> class CombiningMatcher>
1596 static Matcher<T> CreateMatcher(const ListType& matchers) {
1597 return Matcher<T>(new CombiningMatcher<T>(
1598 SafeMatcherCast<T>(matchers.first),
1599 SafeMatcherCast<T>(matchers.second)));
1600 }
1601};
1602
1603// VariadicMatcher is used for the variadic implementation of
1604// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1605// CombiningMatcher<T> is used to recursively combine the provided matchers
1606// (of type Args...).
1607template <template <typename T> class CombiningMatcher, typename... Args>
1608class VariadicMatcher {
1609 public:
1610 VariadicMatcher(const Args&... matchers) // NOLINT
1611 : matchers_(MatcherListType::BuildList(matchers...)) {}
1612
1613 // This template type conversion operator allows an
1614 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1615 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1616 template <typename T>
1617 operator Matcher<T>() const {
1618 return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
1619 matchers_);
1620 }
1621
1622 private:
1623 typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
1624
1625 const typename MatcherListType::ListType matchers_;
1626
1627 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1628};
1629
1630template <typename... Args>
1631using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
1632
1633#endif // GTEST_LANG_CXX11
1634
shiqiane35fdd92008-12-10 05:08:54 +00001635// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1636// matches a value that matches all of the matchers m_1, ..., and m_n.
1637template <typename Matcher1, typename Matcher2>
1638class BothOfMatcher {
1639 public:
1640 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1641 : matcher1_(matcher1), matcher2_(matcher2) {}
1642
1643 // This template type conversion operator allows a
1644 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1645 // both Matcher1 and Matcher2 can match.
1646 template <typename T>
1647 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001648 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1649 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001650 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001651
shiqiane35fdd92008-12-10 05:08:54 +00001652 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001653 Matcher1 matcher1_;
1654 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001655
1656 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001657};
shiqiane35fdd92008-12-10 05:08:54 +00001658
zhanyong.wanc6a41232009-05-13 23:38:40 +00001659// Implements the AnyOf(m1, m2) matcher for a particular argument type
1660// T. We do not nest it inside the AnyOfMatcher class template, as
1661// that will prevent different instantiations of AnyOfMatcher from
1662// sharing the same EitherOfMatcherImpl<T> class.
1663template <typename T>
1664class EitherOfMatcherImpl : public MatcherInterface<T> {
1665 public:
1666 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1667 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001668
zhanyong.wanc6a41232009-05-13 23:38:40 +00001669 virtual void DescribeTo(::std::ostream* os) const {
1670 *os << "(";
1671 matcher1_.DescribeTo(os);
1672 *os << ") or (";
1673 matcher2_.DescribeTo(os);
1674 *os << ")";
1675 }
shiqiane35fdd92008-12-10 05:08:54 +00001676
zhanyong.wanc6a41232009-05-13 23:38:40 +00001677 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001678 *os << "(";
1679 matcher1_.DescribeNegationTo(os);
1680 *os << ") and (";
1681 matcher2_.DescribeNegationTo(os);
1682 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001683 }
shiqiane35fdd92008-12-10 05:08:54 +00001684
zhanyong.wan82113312010-01-08 21:55:40 +00001685 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1686 // If either matcher1_ or matcher2_ matches x, we just need to
1687 // explain why *one* of them matches.
1688 StringMatchResultListener listener1;
1689 if (matcher1_.MatchAndExplain(x, &listener1)) {
1690 *listener << listener1.str();
1691 return true;
1692 }
1693
1694 StringMatchResultListener listener2;
1695 if (matcher2_.MatchAndExplain(x, &listener2)) {
1696 *listener << listener2.str();
1697 return true;
1698 }
1699
1700 // Otherwise we need to explain why *both* of them fail.
Nico Weber09fd5b32017-05-15 17:07:03 -04001701 const std::string s1 = listener1.str();
1702 const std::string s2 = listener2.str();
zhanyong.wan82113312010-01-08 21:55:40 +00001703
1704 if (s1 == "") {
1705 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001706 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001707 *listener << s1;
1708 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001709 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001710 }
1711 }
zhanyong.wan82113312010-01-08 21:55:40 +00001712 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001713 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001714
zhanyong.wanc6a41232009-05-13 23:38:40 +00001715 private:
1716 const Matcher<T> matcher1_;
1717 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001718
1719 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001720};
1721
zhanyong.wan616180e2013-06-18 18:49:51 +00001722#if GTEST_LANG_CXX11
1723// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1724template <typename... Args>
1725using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
1726
1727#endif // GTEST_LANG_CXX11
1728
shiqiane35fdd92008-12-10 05:08:54 +00001729// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1730// matches a value that matches at least one of the matchers m_1, ...,
1731// and m_n.
1732template <typename Matcher1, typename Matcher2>
1733class EitherOfMatcher {
1734 public:
1735 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1736 : matcher1_(matcher1), matcher2_(matcher2) {}
1737
1738 // This template type conversion operator allows a
1739 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1740 // both Matcher1 and Matcher2 can match.
1741 template <typename T>
1742 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001743 return Matcher<T>(new EitherOfMatcherImpl<T>(
1744 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001745 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001746
shiqiane35fdd92008-12-10 05:08:54 +00001747 private:
shiqiane35fdd92008-12-10 05:08:54 +00001748 Matcher1 matcher1_;
1749 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001750
1751 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001752};
1753
1754// Used for implementing Truly(pred), which turns a predicate into a
1755// matcher.
1756template <typename Predicate>
1757class TrulyMatcher {
1758 public:
1759 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1760
1761 // This method template allows Truly(pred) to be used as a matcher
1762 // for type T where T is the argument type of predicate 'pred'. The
1763 // argument is passed by reference as the predicate may be
1764 // interested in the address of the argument.
1765 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001766 bool MatchAndExplain(T& x, // NOLINT
1767 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001768 // Without the if-statement, MSVC sometimes warns about converting
1769 // a value to bool (warning 4800).
1770 //
1771 // We cannot write 'return !!predicate_(x);' as that doesn't work
1772 // when predicate_(x) returns a class convertible to bool but
1773 // having no operator!().
1774 if (predicate_(x))
1775 return true;
1776 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001777 }
1778
1779 void DescribeTo(::std::ostream* os) const {
1780 *os << "satisfies the given predicate";
1781 }
1782
1783 void DescribeNegationTo(::std::ostream* os) const {
1784 *os << "doesn't satisfy the given predicate";
1785 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001786
shiqiane35fdd92008-12-10 05:08:54 +00001787 private:
1788 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001789
1790 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001791};
1792
1793// Used for implementing Matches(matcher), which turns a matcher into
1794// a predicate.
1795template <typename M>
1796class MatcherAsPredicate {
1797 public:
1798 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1799
1800 // This template operator() allows Matches(m) to be used as a
1801 // predicate on type T where m is a matcher on type T.
1802 //
1803 // The argument x is passed by reference instead of by value, as
1804 // some matcher may be interested in its address (e.g. as in
1805 // Matches(Ref(n))(x)).
1806 template <typename T>
1807 bool operator()(const T& x) const {
1808 // We let matcher_ commit to a particular type here instead of
1809 // when the MatcherAsPredicate object was constructed. This
1810 // allows us to write Matches(m) where m is a polymorphic matcher
1811 // (e.g. Eq(5)).
1812 //
1813 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1814 // compile when matcher_ has type Matcher<const T&>; if we write
1815 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1816 // when matcher_ has type Matcher<T>; if we just write
1817 // matcher_.Matches(x), it won't compile when matcher_ is
1818 // polymorphic, e.g. Eq(5).
1819 //
1820 // MatcherCast<const T&>() is necessary for making the code work
1821 // in all of the above situations.
1822 return MatcherCast<const T&>(matcher_).Matches(x);
1823 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001824
shiqiane35fdd92008-12-10 05:08:54 +00001825 private:
1826 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001827
1828 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001829};
1830
1831// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1832// argument M must be a type that can be converted to a matcher.
1833template <typename M>
1834class PredicateFormatterFromMatcher {
1835 public:
kosak9b1a9442015-04-28 23:06:58 +00001836 explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {}
shiqiane35fdd92008-12-10 05:08:54 +00001837
1838 // This template () operator allows a PredicateFormatterFromMatcher
1839 // object to act as a predicate-formatter suitable for using with
1840 // Google Test's EXPECT_PRED_FORMAT1() macro.
1841 template <typename T>
1842 AssertionResult operator()(const char* value_text, const T& x) const {
1843 // We convert matcher_ to a Matcher<const T&> *now* instead of
1844 // when the PredicateFormatterFromMatcher object was constructed,
1845 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1846 // know which type to instantiate it to until we actually see the
1847 // type of x here.
1848 //
zhanyong.wanf4274522013-04-24 02:49:43 +00001849 // We write SafeMatcherCast<const T&>(matcher_) instead of
shiqiane35fdd92008-12-10 05:08:54 +00001850 // Matcher<const T&>(matcher_), as the latter won't compile when
1851 // matcher_ has type Matcher<T> (e.g. An<int>()).
zhanyong.wanf4274522013-04-24 02:49:43 +00001852 // We don't write MatcherCast<const T&> either, as that allows
1853 // potentially unsafe downcasting of the matcher argument.
1854 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001855 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001856 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001857 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001858
1859 ::std::stringstream ss;
1860 ss << "Value of: " << value_text << "\n"
1861 << "Expected: ";
1862 matcher.DescribeTo(&ss);
1863 ss << "\n Actual: " << listener.str();
1864 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001865 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001866
shiqiane35fdd92008-12-10 05:08:54 +00001867 private:
1868 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001869
1870 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001871};
1872
1873// A helper function for converting a matcher to a predicate-formatter
1874// without the user needing to explicitly write the type. This is
1875// used for implementing ASSERT_THAT() and EXPECT_THAT().
kosak9b1a9442015-04-28 23:06:58 +00001876// Implementation detail: 'matcher' is received by-value to force decaying.
shiqiane35fdd92008-12-10 05:08:54 +00001877template <typename M>
1878inline PredicateFormatterFromMatcher<M>
kosak9b1a9442015-04-28 23:06:58 +00001879MakePredicateFormatterFromMatcher(M matcher) {
1880 return PredicateFormatterFromMatcher<M>(internal::move(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00001881}
1882
zhanyong.wan616180e2013-06-18 18:49:51 +00001883// Implements the polymorphic floating point equality matcher, which matches
1884// two float values using ULP-based approximation or, optionally, a
1885// user-specified epsilon. The template is meant to be instantiated with
1886// FloatType being either float or double.
shiqiane35fdd92008-12-10 05:08:54 +00001887template <typename FloatType>
1888class FloatingEqMatcher {
1889 public:
1890 // Constructor for FloatingEqMatcher.
kosak6b817802015-01-08 02:38:14 +00001891 // The matcher's input will be compared with expected. The matcher treats two
shiqiane35fdd92008-12-10 05:08:54 +00001892 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
zhanyong.wan616180e2013-06-18 18:49:51 +00001893 // equality comparisons between NANs will always return false. We specify a
1894 // negative max_abs_error_ term to indicate that ULP-based approximation will
1895 // be used for comparison.
kosak6b817802015-01-08 02:38:14 +00001896 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
1897 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001898 }
1899
1900 // Constructor that supports a user-specified max_abs_error that will be used
1901 // for comparison instead of ULP-based approximation. The max absolute
1902 // should be non-negative.
kosak6b817802015-01-08 02:38:14 +00001903 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
1904 FloatType max_abs_error)
1905 : expected_(expected),
1906 nan_eq_nan_(nan_eq_nan),
1907 max_abs_error_(max_abs_error) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001908 GTEST_CHECK_(max_abs_error >= 0)
1909 << ", where max_abs_error is" << max_abs_error;
1910 }
shiqiane35fdd92008-12-10 05:08:54 +00001911
1912 // Implements floating point equality matcher as a Matcher<T>.
1913 template <typename T>
1914 class Impl : public MatcherInterface<T> {
1915 public:
kosak6b817802015-01-08 02:38:14 +00001916 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
1917 : expected_(expected),
1918 nan_eq_nan_(nan_eq_nan),
1919 max_abs_error_(max_abs_error) {}
shiqiane35fdd92008-12-10 05:08:54 +00001920
zhanyong.wan82113312010-01-08 21:55:40 +00001921 virtual bool MatchAndExplain(T value,
kosak6b817802015-01-08 02:38:14 +00001922 MatchResultListener* listener) const {
1923 const FloatingPoint<FloatType> actual(value), expected(expected_);
shiqiane35fdd92008-12-10 05:08:54 +00001924
1925 // Compares NaNs first, if nan_eq_nan_ is true.
kosak6b817802015-01-08 02:38:14 +00001926 if (actual.is_nan() || expected.is_nan()) {
1927 if (actual.is_nan() && expected.is_nan()) {
zhanyong.wan616180e2013-06-18 18:49:51 +00001928 return nan_eq_nan_;
1929 }
1930 // One is nan; the other is not nan.
1931 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001932 }
zhanyong.wan616180e2013-06-18 18:49:51 +00001933 if (HasMaxAbsError()) {
1934 // We perform an equality check so that inf will match inf, regardless
kosak6b817802015-01-08 02:38:14 +00001935 // of error bounds. If the result of value - expected_ would result in
zhanyong.wan616180e2013-06-18 18:49:51 +00001936 // overflow or if either value is inf, the default result is infinity,
1937 // which should only match if max_abs_error_ is also infinity.
kosak6b817802015-01-08 02:38:14 +00001938 if (value == expected_) {
1939 return true;
1940 }
1941
1942 const FloatType diff = value - expected_;
1943 if (fabs(diff) <= max_abs_error_) {
1944 return true;
1945 }
1946
1947 if (listener->IsInterested()) {
1948 *listener << "which is " << diff << " from " << expected_;
1949 }
1950 return false;
zhanyong.wan616180e2013-06-18 18:49:51 +00001951 } else {
kosak6b817802015-01-08 02:38:14 +00001952 return actual.AlmostEquals(expected);
zhanyong.wan616180e2013-06-18 18:49:51 +00001953 }
shiqiane35fdd92008-12-10 05:08:54 +00001954 }
1955
1956 virtual void DescribeTo(::std::ostream* os) const {
1957 // os->precision() returns the previously set precision, which we
1958 // store to restore the ostream to its original configuration
1959 // after outputting.
1960 const ::std::streamsize old_precision = os->precision(
1961 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00001962 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00001963 if (nan_eq_nan_) {
1964 *os << "is NaN";
1965 } else {
1966 *os << "never matches";
1967 }
1968 } else {
kosak6b817802015-01-08 02:38:14 +00001969 *os << "is approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001970 if (HasMaxAbsError()) {
1971 *os << " (absolute error <= " << max_abs_error_ << ")";
1972 }
shiqiane35fdd92008-12-10 05:08:54 +00001973 }
1974 os->precision(old_precision);
1975 }
1976
1977 virtual void DescribeNegationTo(::std::ostream* os) const {
1978 // As before, get original precision.
1979 const ::std::streamsize old_precision = os->precision(
1980 ::std::numeric_limits<FloatType>::digits10 + 2);
kosak6b817802015-01-08 02:38:14 +00001981 if (FloatingPoint<FloatType>(expected_).is_nan()) {
shiqiane35fdd92008-12-10 05:08:54 +00001982 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001983 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00001984 } else {
1985 *os << "is anything";
1986 }
1987 } else {
kosak6b817802015-01-08 02:38:14 +00001988 *os << "isn't approximately " << expected_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001989 if (HasMaxAbsError()) {
1990 *os << " (absolute error > " << max_abs_error_ << ")";
1991 }
shiqiane35fdd92008-12-10 05:08:54 +00001992 }
1993 // Restore original precision.
1994 os->precision(old_precision);
1995 }
1996
1997 private:
zhanyong.wan616180e2013-06-18 18:49:51 +00001998 bool HasMaxAbsError() const {
1999 return max_abs_error_ >= 0;
2000 }
2001
kosak6b817802015-01-08 02:38:14 +00002002 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002003 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002004 // max_abs_error will be used for value comparison when >= 0.
2005 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002006
2007 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002008 };
2009
kosak6b817802015-01-08 02:38:14 +00002010 // The following 3 type conversion operators allow FloatEq(expected) and
2011 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
shiqiane35fdd92008-12-10 05:08:54 +00002012 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
2013 // (While Google's C++ coding style doesn't allow arguments passed
2014 // by non-const reference, we may see them in code not conforming to
2015 // the style. Therefore Google Mock needs to support them.)
2016 operator Matcher<FloatType>() const {
kosak6b817802015-01-08 02:38:14 +00002017 return MakeMatcher(
2018 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002019 }
2020
2021 operator Matcher<const FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00002022 return MakeMatcher(
kosak6b817802015-01-08 02:38:14 +00002023 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002024 }
2025
2026 operator Matcher<FloatType&>() const {
kosak6b817802015-01-08 02:38:14 +00002027 return MakeMatcher(
2028 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00002029 }
jgm79a367e2012-04-10 16:02:11 +00002030
shiqiane35fdd92008-12-10 05:08:54 +00002031 private:
kosak6b817802015-01-08 02:38:14 +00002032 const FloatType expected_;
shiqiane35fdd92008-12-10 05:08:54 +00002033 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00002034 // max_abs_error will be used for value comparison when >= 0.
2035 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002036
2037 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002038};
2039
2040// Implements the Pointee(m) matcher for matching a pointer whose
2041// pointee matches matcher m. The pointer can be either raw or smart.
2042template <typename InnerMatcher>
2043class PointeeMatcher {
2044 public:
2045 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
2046
2047 // This type conversion operator template allows Pointee(m) to be
2048 // used as a matcher for any pointer type whose pointee type is
2049 // compatible with the inner matcher, where type Pointer can be
2050 // either a raw pointer or a smart pointer.
2051 //
2052 // The reason we do this instead of relying on
2053 // MakePolymorphicMatcher() is that the latter is not flexible
2054 // enough for implementing the DescribeTo() method of Pointee().
2055 template <typename Pointer>
2056 operator Matcher<Pointer>() const {
2057 return MakeMatcher(new Impl<Pointer>(matcher_));
2058 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002059
shiqiane35fdd92008-12-10 05:08:54 +00002060 private:
2061 // The monomorphic implementation that works for a particular pointer type.
2062 template <typename Pointer>
2063 class Impl : public MatcherInterface<Pointer> {
2064 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00002065 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
2066 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00002067
2068 explicit Impl(const InnerMatcher& matcher)
2069 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
2070
shiqiane35fdd92008-12-10 05:08:54 +00002071 virtual void DescribeTo(::std::ostream* os) const {
2072 *os << "points to a value that ";
2073 matcher_.DescribeTo(os);
2074 }
2075
2076 virtual void DescribeNegationTo(::std::ostream* os) const {
2077 *os << "does not point to a value that ";
2078 matcher_.DescribeTo(os);
2079 }
2080
zhanyong.wan82113312010-01-08 21:55:40 +00002081 virtual bool MatchAndExplain(Pointer pointer,
2082 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00002083 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00002084 return false;
shiqiane35fdd92008-12-10 05:08:54 +00002085
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002086 *listener << "which points to ";
2087 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002088 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002089
shiqiane35fdd92008-12-10 05:08:54 +00002090 private:
2091 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002092
2093 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002094 };
2095
2096 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002097
2098 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002099};
2100
billydonahue1f5fdea2014-05-19 17:54:51 +00002101// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2102// reference that matches inner_matcher when dynamic_cast<T> is applied.
2103// The result of dynamic_cast<To> is forwarded to the inner matcher.
2104// If To is a pointer and the cast fails, the inner matcher will receive NULL.
2105// If To is a reference and the cast fails, this matcher returns false
2106// immediately.
2107template <typename To>
2108class WhenDynamicCastToMatcherBase {
2109 public:
2110 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2111 : matcher_(matcher) {}
2112
2113 void DescribeTo(::std::ostream* os) const {
2114 GetCastTypeDescription(os);
2115 matcher_.DescribeTo(os);
2116 }
2117
2118 void DescribeNegationTo(::std::ostream* os) const {
2119 GetCastTypeDescription(os);
2120 matcher_.DescribeNegationTo(os);
2121 }
2122
2123 protected:
2124 const Matcher<To> matcher_;
2125
Nico Weber09fd5b32017-05-15 17:07:03 -04002126 static std::string GetToName() {
billydonahue1f5fdea2014-05-19 17:54:51 +00002127#if GTEST_HAS_RTTI
2128 return GetTypeName<To>();
2129#else // GTEST_HAS_RTTI
2130 return "the target type";
2131#endif // GTEST_HAS_RTTI
2132 }
2133
2134 private:
2135 static void GetCastTypeDescription(::std::ostream* os) {
2136 *os << "when dynamic_cast to " << GetToName() << ", ";
2137 }
2138
2139 GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2140};
2141
2142// Primary template.
2143// To is a pointer. Cast and forward the result.
2144template <typename To>
2145class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2146 public:
2147 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2148 : WhenDynamicCastToMatcherBase<To>(matcher) {}
2149
2150 template <typename From>
2151 bool MatchAndExplain(From from, MatchResultListener* listener) const {
2152 // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail?
2153 To to = dynamic_cast<To>(from);
2154 return MatchPrintAndExplain(to, this->matcher_, listener);
2155 }
2156};
2157
2158// Specialize for references.
2159// In this case we return false if the dynamic_cast fails.
2160template <typename To>
2161class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2162 public:
2163 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2164 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2165
2166 template <typename From>
2167 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2168 // We don't want an std::bad_cast here, so do the cast with pointers.
2169 To* to = dynamic_cast<To*>(&from);
2170 if (to == NULL) {
2171 *listener << "which cannot be dynamic_cast to " << this->GetToName();
2172 return false;
2173 }
2174 return MatchPrintAndExplain(*to, this->matcher_, listener);
2175 }
2176};
2177
shiqiane35fdd92008-12-10 05:08:54 +00002178// Implements the Field() matcher for matching a field (i.e. member
2179// variable) of an object.
2180template <typename Class, typename FieldType>
2181class FieldMatcher {
2182 public:
2183 FieldMatcher(FieldType Class::*field,
2184 const Matcher<const FieldType&>& matcher)
2185 : field_(field), matcher_(matcher) {}
2186
shiqiane35fdd92008-12-10 05:08:54 +00002187 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002188 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002189 matcher_.DescribeTo(os);
2190 }
2191
2192 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002193 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00002194 matcher_.DescribeNegationTo(os);
2195 }
2196
zhanyong.wandb22c222010-01-28 21:52:29 +00002197 template <typename T>
2198 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2199 return MatchAndExplainImpl(
2200 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002201 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002202 value, listener);
2203 }
2204
2205 private:
2206 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002207 // Symbian's C++ compiler choose which overload to use. Its type is
2208 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002209 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2210 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002211 *listener << "whose given field is ";
2212 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002213 }
2214
zhanyong.wandb22c222010-01-28 21:52:29 +00002215 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2216 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002217 if (p == NULL)
2218 return false;
2219
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002220 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002221 // Since *p has a field, it must be a class/struct/union type and
2222 // thus cannot be a pointer. Therefore we pass false_type() as
2223 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002224 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002225 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002226
shiqiane35fdd92008-12-10 05:08:54 +00002227 const FieldType Class::*field_;
2228 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002229
2230 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002231};
2232
shiqiane35fdd92008-12-10 05:08:54 +00002233// Implements the Property() matcher for matching a property
2234// (i.e. return value of a getter method) of an object.
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002235//
2236// Property is a const-qualified member function of Class returning
2237// PropertyType.
2238template <typename Class, typename PropertyType, typename Property>
shiqiane35fdd92008-12-10 05:08:54 +00002239class PropertyMatcher {
2240 public:
2241 // The property may have a reference type, so 'const PropertyType&'
2242 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00002243 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00002244 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00002245 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00002246
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002247 PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)
shiqiane35fdd92008-12-10 05:08:54 +00002248 : property_(property), matcher_(matcher) {}
2249
shiqiane35fdd92008-12-10 05:08:54 +00002250 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002251 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002252 matcher_.DescribeTo(os);
2253 }
2254
2255 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002256 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002257 matcher_.DescribeNegationTo(os);
2258 }
2259
zhanyong.wandb22c222010-01-28 21:52:29 +00002260 template <typename T>
2261 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2262 return MatchAndExplainImpl(
2263 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002264 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002265 value, listener);
2266 }
2267
2268 private:
2269 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002270 // Symbian's C++ compiler choose which overload to use. Its type is
2271 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002272 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2273 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002274 *listener << "whose given property is ";
2275 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2276 // which takes a non-const reference as argument.
kosak02d64792015-02-14 02:22:21 +00002277#if defined(_PREFAST_ ) && _MSC_VER == 1800
2278 // Workaround bug in VC++ 2013's /analyze parser.
2279 // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move
2280 posix::Abort(); // To make sure it is never run.
2281 return false;
2282#else
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002283 RefToConstProperty result = (obj.*property_)();
2284 return MatchPrintAndExplain(result, matcher_, listener);
kosak02d64792015-02-14 02:22:21 +00002285#endif
shiqiane35fdd92008-12-10 05:08:54 +00002286 }
2287
zhanyong.wandb22c222010-01-28 21:52:29 +00002288 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2289 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002290 if (p == NULL)
2291 return false;
2292
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002293 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002294 // Since *p has a property method, it must be a class/struct/union
2295 // type and thus cannot be a pointer. Therefore we pass
2296 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002297 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002298 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002299
Roman Perepelitsa966b5492017-08-22 16:06:26 +02002300 Property property_;
shiqiane35fdd92008-12-10 05:08:54 +00002301 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002302
2303 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002304};
2305
shiqiane35fdd92008-12-10 05:08:54 +00002306// Type traits specifying various features of different functors for ResultOf.
2307// The default template specifies features for functor objects.
2308// Functor classes have to typedef argument_type and result_type
2309// to be compatible with ResultOf.
2310template <typename Functor>
2311struct CallableTraits {
2312 typedef typename Functor::result_type ResultType;
2313 typedef Functor StorageType;
2314
zhanyong.wan32de5f52009-12-23 00:13:23 +00002315 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00002316 template <typename T>
2317 static ResultType Invoke(Functor f, T arg) { return f(arg); }
2318};
2319
2320// Specialization for function pointers.
2321template <typename ArgType, typename ResType>
2322struct CallableTraits<ResType(*)(ArgType)> {
2323 typedef ResType ResultType;
2324 typedef ResType(*StorageType)(ArgType);
2325
2326 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002327 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00002328 << "NULL function pointer is passed into ResultOf().";
2329 }
2330 template <typename T>
2331 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2332 return (*f)(arg);
2333 }
2334};
2335
2336// Implements the ResultOf() matcher for matching a return value of a
2337// unary function of an object.
2338template <typename Callable>
2339class ResultOfMatcher {
2340 public:
2341 typedef typename CallableTraits<Callable>::ResultType ResultType;
2342
2343 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
2344 : callable_(callable), matcher_(matcher) {
2345 CallableTraits<Callable>::CheckIsValid(callable_);
2346 }
2347
2348 template <typename T>
2349 operator Matcher<T>() const {
2350 return Matcher<T>(new Impl<T>(callable_, matcher_));
2351 }
2352
2353 private:
2354 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2355
2356 template <typename T>
2357 class Impl : public MatcherInterface<T> {
2358 public:
2359 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
2360 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00002361
2362 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002363 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002364 matcher_.DescribeTo(os);
2365 }
2366
2367 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002368 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002369 matcher_.DescribeNegationTo(os);
2370 }
2371
zhanyong.wan82113312010-01-08 21:55:40 +00002372 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002373 *listener << "which is mapped by the given callable to ";
2374 // Cannot pass the return value (for example, int) to
2375 // MatchPrintAndExplain, which takes a non-const reference as argument.
2376 ResultType result =
2377 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2378 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002379 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002380
shiqiane35fdd92008-12-10 05:08:54 +00002381 private:
2382 // Functors often define operator() as non-const method even though
2383 // they are actualy stateless. But we need to use them even when
2384 // 'this' is a const pointer. It's the user's responsibility not to
2385 // use stateful callables with ResultOf(), which does't guarantee
2386 // how many times the callable will be invoked.
2387 mutable CallableStorageType callable_;
2388 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002389
2390 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002391 }; // class Impl
2392
2393 const CallableStorageType callable_;
2394 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002395
2396 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002397};
2398
zhanyong.wana31d9ce2013-03-01 01:50:17 +00002399// Implements a matcher that checks the size of an STL-style container.
2400template <typename SizeMatcher>
2401class SizeIsMatcher {
2402 public:
2403 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2404 : size_matcher_(size_matcher) {
2405 }
2406
2407 template <typename Container>
2408 operator Matcher<Container>() const {
2409 return MakeMatcher(new Impl<Container>(size_matcher_));
2410 }
2411
2412 template <typename Container>
2413 class Impl : public MatcherInterface<Container> {
2414 public:
2415 typedef internal::StlContainerView<
2416 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2417 typedef typename ContainerView::type::size_type SizeType;
2418 explicit Impl(const SizeMatcher& size_matcher)
2419 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2420
2421 virtual void DescribeTo(::std::ostream* os) const {
2422 *os << "size ";
2423 size_matcher_.DescribeTo(os);
2424 }
2425 virtual void DescribeNegationTo(::std::ostream* os) const {
2426 *os << "size ";
2427 size_matcher_.DescribeNegationTo(os);
2428 }
2429
2430 virtual bool MatchAndExplain(Container container,
2431 MatchResultListener* listener) const {
2432 SizeType size = container.size();
2433 StringMatchResultListener size_listener;
2434 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2435 *listener
2436 << "whose size " << size << (result ? " matches" : " doesn't match");
2437 PrintIfNotEmpty(size_listener.str(), listener->stream());
2438 return result;
2439 }
2440
2441 private:
2442 const Matcher<SizeType> size_matcher_;
2443 GTEST_DISALLOW_ASSIGN_(Impl);
2444 };
2445
2446 private:
2447 const SizeMatcher size_matcher_;
2448 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2449};
2450
kosakb6a34882014-03-12 21:06:46 +00002451// Implements a matcher that checks the begin()..end() distance of an STL-style
2452// container.
2453template <typename DistanceMatcher>
2454class BeginEndDistanceIsMatcher {
2455 public:
2456 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2457 : distance_matcher_(distance_matcher) {}
2458
2459 template <typename Container>
2460 operator Matcher<Container>() const {
2461 return MakeMatcher(new Impl<Container>(distance_matcher_));
2462 }
2463
2464 template <typename Container>
2465 class Impl : public MatcherInterface<Container> {
2466 public:
2467 typedef internal::StlContainerView<
2468 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2469 typedef typename std::iterator_traits<
2470 typename ContainerView::type::const_iterator>::difference_type
2471 DistanceType;
2472 explicit Impl(const DistanceMatcher& distance_matcher)
2473 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2474
2475 virtual void DescribeTo(::std::ostream* os) const {
2476 *os << "distance between begin() and end() ";
2477 distance_matcher_.DescribeTo(os);
2478 }
2479 virtual void DescribeNegationTo(::std::ostream* os) const {
2480 *os << "distance between begin() and end() ";
2481 distance_matcher_.DescribeNegationTo(os);
2482 }
2483
2484 virtual bool MatchAndExplain(Container container,
2485 MatchResultListener* listener) const {
kosak5b9cbbb2014-11-17 00:28:55 +00002486#if GTEST_HAS_STD_BEGIN_AND_END_
kosakb6a34882014-03-12 21:06:46 +00002487 using std::begin;
2488 using std::end;
2489 DistanceType distance = std::distance(begin(container), end(container));
2490#else
2491 DistanceType distance = std::distance(container.begin(), container.end());
2492#endif
2493 StringMatchResultListener distance_listener;
2494 const bool result =
2495 distance_matcher_.MatchAndExplain(distance, &distance_listener);
2496 *listener << "whose distance between begin() and end() " << distance
2497 << (result ? " matches" : " doesn't match");
2498 PrintIfNotEmpty(distance_listener.str(), listener->stream());
2499 return result;
2500 }
2501
2502 private:
2503 const Matcher<DistanceType> distance_matcher_;
2504 GTEST_DISALLOW_ASSIGN_(Impl);
2505 };
2506
2507 private:
2508 const DistanceMatcher distance_matcher_;
2509 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2510};
2511
zhanyong.wan6a896b52009-01-16 01:13:50 +00002512// Implements an equality matcher for any STL-style container whose elements
2513// support ==. This matcher is like Eq(), but its failure explanations provide
2514// more detailed information that is useful when the container is used as a set.
2515// The failure message reports elements that are in one of the operands but not
2516// the other. The failure messages do not report duplicate or out-of-order
2517// elements in the containers (which don't properly matter to sets, but can
2518// occur if the containers are vectors or lists, for example).
2519//
2520// Uses the container's const_iterator, value_type, operator ==,
2521// begin(), and end().
2522template <typename Container>
2523class ContainerEqMatcher {
2524 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002525 typedef internal::StlContainerView<Container> View;
2526 typedef typename View::type StlContainer;
2527 typedef typename View::const_reference StlContainerReference;
2528
kosak6b817802015-01-08 02:38:14 +00002529 // We make a copy of expected in case the elements in it are modified
zhanyong.wanb8243162009-06-04 05:48:20 +00002530 // after this matcher is created.
kosak6b817802015-01-08 02:38:14 +00002531 explicit ContainerEqMatcher(const Container& expected)
2532 : expected_(View::Copy(expected)) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002533 // Makes sure the user doesn't instantiate this class template
2534 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002535 (void)testing::StaticAssertTypeEq<Container,
2536 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002537 }
2538
zhanyong.wan6a896b52009-01-16 01:13:50 +00002539 void DescribeTo(::std::ostream* os) const {
2540 *os << "equals ";
kosak6b817802015-01-08 02:38:14 +00002541 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002542 }
2543 void DescribeNegationTo(::std::ostream* os) const {
2544 *os << "does not equal ";
kosak6b817802015-01-08 02:38:14 +00002545 UniversalPrint(expected_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002546 }
2547
zhanyong.wanb8243162009-06-04 05:48:20 +00002548 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002549 bool MatchAndExplain(const LhsContainer& lhs,
2550 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002551 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002552 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002553 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002554 LhsView;
2555 typedef typename LhsView::type LhsStlContainer;
2556 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
kosak6b817802015-01-08 02:38:14 +00002557 if (lhs_stl_container == expected_)
zhanyong.wane122e452010-01-12 09:03:52 +00002558 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002559
zhanyong.wane122e452010-01-12 09:03:52 +00002560 ::std::ostream* const os = listener->stream();
2561 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002562 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002563 bool printed_header = false;
2564 for (typename LhsStlContainer::const_iterator it =
2565 lhs_stl_container.begin();
2566 it != lhs_stl_container.end(); ++it) {
kosak6b817802015-01-08 02:38:14 +00002567 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
2568 expected_.end()) {
zhanyong.wane122e452010-01-12 09:03:52 +00002569 if (printed_header) {
2570 *os << ", ";
2571 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002572 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002573 printed_header = true;
2574 }
vladloseve2e8ba42010-05-13 18:16:03 +00002575 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002576 }
zhanyong.wane122e452010-01-12 09:03:52 +00002577 }
2578
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002579 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002580 bool printed_header2 = false;
kosak6b817802015-01-08 02:38:14 +00002581 for (typename StlContainer::const_iterator it = expected_.begin();
2582 it != expected_.end(); ++it) {
zhanyong.wane122e452010-01-12 09:03:52 +00002583 if (internal::ArrayAwareFind(
2584 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2585 lhs_stl_container.end()) {
2586 if (printed_header2) {
2587 *os << ", ";
2588 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002589 *os << (printed_header ? ",\nand" : "which")
2590 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002591 printed_header2 = true;
2592 }
vladloseve2e8ba42010-05-13 18:16:03 +00002593 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002594 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002595 }
2596 }
2597
zhanyong.wane122e452010-01-12 09:03:52 +00002598 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002599 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002600
zhanyong.wan6a896b52009-01-16 01:13:50 +00002601 private:
kosak6b817802015-01-08 02:38:14 +00002602 const StlContainer expected_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002603
2604 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002605};
2606
zhanyong.wan898725c2011-09-16 16:45:39 +00002607// A comparator functor that uses the < operator to compare two values.
2608struct LessComparator {
2609 template <typename T, typename U>
2610 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2611};
2612
2613// Implements WhenSortedBy(comparator, container_matcher).
2614template <typename Comparator, typename ContainerMatcher>
2615class WhenSortedByMatcher {
2616 public:
2617 WhenSortedByMatcher(const Comparator& comparator,
2618 const ContainerMatcher& matcher)
2619 : comparator_(comparator), matcher_(matcher) {}
2620
2621 template <typename LhsContainer>
2622 operator Matcher<LhsContainer>() const {
2623 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2624 }
2625
2626 template <typename LhsContainer>
2627 class Impl : public MatcherInterface<LhsContainer> {
2628 public:
2629 typedef internal::StlContainerView<
2630 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2631 typedef typename LhsView::type LhsStlContainer;
2632 typedef typename LhsView::const_reference LhsStlContainerReference;
zhanyong.wana9a59e02013-03-27 16:14:55 +00002633 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2634 // so that we can match associative containers.
2635 typedef typename RemoveConstFromKey<
2636 typename LhsStlContainer::value_type>::type LhsValue;
zhanyong.wan898725c2011-09-16 16:45:39 +00002637
2638 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2639 : comparator_(comparator), matcher_(matcher) {}
2640
2641 virtual void DescribeTo(::std::ostream* os) const {
2642 *os << "(when sorted) ";
2643 matcher_.DescribeTo(os);
2644 }
2645
2646 virtual void DescribeNegationTo(::std::ostream* os) const {
2647 *os << "(when sorted) ";
2648 matcher_.DescribeNegationTo(os);
2649 }
2650
2651 virtual bool MatchAndExplain(LhsContainer lhs,
2652 MatchResultListener* listener) const {
2653 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wanfb25d532013-07-28 08:24:00 +00002654 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2655 lhs_stl_container.end());
2656 ::std::sort(
2657 sorted_container.begin(), sorted_container.end(), comparator_);
zhanyong.wan898725c2011-09-16 16:45:39 +00002658
2659 if (!listener->IsInterested()) {
2660 // If the listener is not interested, we do not need to
2661 // construct the inner explanation.
2662 return matcher_.Matches(sorted_container);
2663 }
2664
2665 *listener << "which is ";
2666 UniversalPrint(sorted_container, listener->stream());
2667 *listener << " when sorted";
2668
2669 StringMatchResultListener inner_listener;
2670 const bool match = matcher_.MatchAndExplain(sorted_container,
2671 &inner_listener);
2672 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2673 return match;
2674 }
2675
2676 private:
2677 const Comparator comparator_;
zhanyong.wanfb25d532013-07-28 08:24:00 +00002678 const Matcher<const ::std::vector<LhsValue>&> matcher_;
zhanyong.wan898725c2011-09-16 16:45:39 +00002679
2680 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2681 };
2682
2683 private:
2684 const Comparator comparator_;
2685 const ContainerMatcher matcher_;
2686
2687 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2688};
2689
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002690// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2691// must be able to be safely cast to Matcher<tuple<const T1&, const
2692// T2&> >, where T1 and T2 are the types of elements in the LHS
2693// container and the RHS container respectively.
2694template <typename TupleMatcher, typename RhsContainer>
2695class PointwiseMatcher {
2696 public:
2697 typedef internal::StlContainerView<RhsContainer> RhsView;
2698 typedef typename RhsView::type RhsStlContainer;
2699 typedef typename RhsStlContainer::value_type RhsValue;
2700
2701 // Like ContainerEq, we make a copy of rhs in case the elements in
2702 // it are modified after this matcher is created.
2703 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2704 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2705 // Makes sure the user doesn't instantiate this class template
2706 // with a const or reference type.
2707 (void)testing::StaticAssertTypeEq<RhsContainer,
2708 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2709 }
2710
2711 template <typename LhsContainer>
2712 operator Matcher<LhsContainer>() const {
2713 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2714 }
2715
2716 template <typename LhsContainer>
2717 class Impl : public MatcherInterface<LhsContainer> {
2718 public:
2719 typedef internal::StlContainerView<
2720 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2721 typedef typename LhsView::type LhsStlContainer;
2722 typedef typename LhsView::const_reference LhsStlContainerReference;
2723 typedef typename LhsStlContainer::value_type LhsValue;
2724 // We pass the LHS value and the RHS value to the inner matcher by
2725 // reference, as they may be expensive to copy. We must use tuple
2726 // instead of pair here, as a pair cannot hold references (C++ 98,
2727 // 20.2.2 [lib.pairs]).
kosakbd018832014-04-02 20:30:00 +00002728 typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002729
2730 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2731 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2732 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2733 rhs_(rhs) {}
2734
2735 virtual void DescribeTo(::std::ostream* os) const {
2736 *os << "contains " << rhs_.size()
2737 << " values, where each value and its corresponding value in ";
2738 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2739 *os << " ";
2740 mono_tuple_matcher_.DescribeTo(os);
2741 }
2742 virtual void DescribeNegationTo(::std::ostream* os) const {
2743 *os << "doesn't contain exactly " << rhs_.size()
2744 << " values, or contains a value x at some index i"
2745 << " where x and the i-th value of ";
2746 UniversalPrint(rhs_, os);
2747 *os << " ";
2748 mono_tuple_matcher_.DescribeNegationTo(os);
2749 }
2750
2751 virtual bool MatchAndExplain(LhsContainer lhs,
2752 MatchResultListener* listener) const {
2753 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2754 const size_t actual_size = lhs_stl_container.size();
2755 if (actual_size != rhs_.size()) {
2756 *listener << "which contains " << actual_size << " values";
2757 return false;
2758 }
2759
2760 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2761 typename RhsStlContainer::const_iterator right = rhs_.begin();
2762 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2763 const InnerMatcherArg value_pair(*left, *right);
2764
2765 if (listener->IsInterested()) {
2766 StringMatchResultListener inner_listener;
2767 if (!mono_tuple_matcher_.MatchAndExplain(
2768 value_pair, &inner_listener)) {
2769 *listener << "where the value pair (";
2770 UniversalPrint(*left, listener->stream());
2771 *listener << ", ";
2772 UniversalPrint(*right, listener->stream());
2773 *listener << ") at index #" << i << " don't match";
2774 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2775 return false;
2776 }
2777 } else {
2778 if (!mono_tuple_matcher_.Matches(value_pair))
2779 return false;
2780 }
2781 }
2782
2783 return true;
2784 }
2785
2786 private:
2787 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2788 const RhsStlContainer rhs_;
2789
2790 GTEST_DISALLOW_ASSIGN_(Impl);
2791 };
2792
2793 private:
2794 const TupleMatcher tuple_matcher_;
2795 const RhsStlContainer rhs_;
2796
2797 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2798};
2799
zhanyong.wan33605ba2010-04-22 23:37:47 +00002800// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002801template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002802class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002803 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002804 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002805 typedef StlContainerView<RawContainer> View;
2806 typedef typename View::type StlContainer;
2807 typedef typename View::const_reference StlContainerReference;
2808 typedef typename StlContainer::value_type Element;
2809
2810 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002811 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002812 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002813 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002814
zhanyong.wan33605ba2010-04-22 23:37:47 +00002815 // Checks whether:
2816 // * All elements in the container match, if all_elements_should_match.
2817 // * Any element in the container matches, if !all_elements_should_match.
2818 bool MatchAndExplainImpl(bool all_elements_should_match,
2819 Container container,
2820 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002821 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002822 size_t i = 0;
2823 for (typename StlContainer::const_iterator it = stl_container.begin();
2824 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002825 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002826 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2827
2828 if (matches != all_elements_should_match) {
2829 *listener << "whose element #" << i
2830 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002831 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002832 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002833 }
2834 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002835 return all_elements_should_match;
2836 }
2837
2838 protected:
2839 const Matcher<const Element&> inner_matcher_;
2840
2841 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2842};
2843
2844// Implements Contains(element_matcher) for the given argument type Container.
2845// Symmetric to EachMatcherImpl.
2846template <typename Container>
2847class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2848 public:
2849 template <typename InnerMatcher>
2850 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2851 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2852
2853 // Describes what this matcher does.
2854 virtual void DescribeTo(::std::ostream* os) const {
2855 *os << "contains at least one element that ";
2856 this->inner_matcher_.DescribeTo(os);
2857 }
2858
2859 virtual void DescribeNegationTo(::std::ostream* os) const {
2860 *os << "doesn't contain any element that ";
2861 this->inner_matcher_.DescribeTo(os);
2862 }
2863
2864 virtual bool MatchAndExplain(Container container,
2865 MatchResultListener* listener) const {
2866 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002867 }
2868
2869 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002870 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002871};
2872
zhanyong.wan33605ba2010-04-22 23:37:47 +00002873// Implements Each(element_matcher) for the given argument type Container.
2874// Symmetric to ContainsMatcherImpl.
2875template <typename Container>
2876class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2877 public:
2878 template <typename InnerMatcher>
2879 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2880 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2881
2882 // Describes what this matcher does.
2883 virtual void DescribeTo(::std::ostream* os) const {
2884 *os << "only contains elements that ";
2885 this->inner_matcher_.DescribeTo(os);
2886 }
2887
2888 virtual void DescribeNegationTo(::std::ostream* os) const {
2889 *os << "contains some element that ";
2890 this->inner_matcher_.DescribeNegationTo(os);
2891 }
2892
2893 virtual bool MatchAndExplain(Container container,
2894 MatchResultListener* listener) const {
2895 return this->MatchAndExplainImpl(true, container, listener);
2896 }
2897
2898 private:
2899 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2900};
2901
zhanyong.wanb8243162009-06-04 05:48:20 +00002902// Implements polymorphic Contains(element_matcher).
2903template <typename M>
2904class ContainsMatcher {
2905 public:
2906 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2907
2908 template <typename Container>
2909 operator Matcher<Container>() const {
2910 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2911 }
2912
2913 private:
2914 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002915
2916 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002917};
2918
zhanyong.wan33605ba2010-04-22 23:37:47 +00002919// Implements polymorphic Each(element_matcher).
2920template <typename M>
2921class EachMatcher {
2922 public:
2923 explicit EachMatcher(M m) : inner_matcher_(m) {}
2924
2925 template <typename Container>
2926 operator Matcher<Container>() const {
2927 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2928 }
2929
2930 private:
2931 const M inner_matcher_;
2932
2933 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2934};
2935
zhanyong.wanb5937da2009-07-16 20:26:41 +00002936// Implements Key(inner_matcher) for the given argument pair type.
2937// Key(inner_matcher) matches an std::pair whose 'first' field matches
2938// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2939// std::map that contains at least one element whose key is >= 5.
2940template <typename PairType>
2941class KeyMatcherImpl : public MatcherInterface<PairType> {
2942 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002943 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002944 typedef typename RawPairType::first_type KeyType;
2945
2946 template <typename InnerMatcher>
2947 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2948 : inner_matcher_(
2949 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2950 }
2951
2952 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002953 virtual bool MatchAndExplain(PairType key_value,
2954 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002955 StringMatchResultListener inner_listener;
2956 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2957 &inner_listener);
Nico Weber09fd5b32017-05-15 17:07:03 -04002958 const std::string explanation = inner_listener.str();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002959 if (explanation != "") {
2960 *listener << "whose first field is a value " << explanation;
2961 }
2962 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002963 }
2964
2965 // Describes what this matcher does.
2966 virtual void DescribeTo(::std::ostream* os) const {
2967 *os << "has a key that ";
2968 inner_matcher_.DescribeTo(os);
2969 }
2970
2971 // Describes what the negation of this matcher does.
2972 virtual void DescribeNegationTo(::std::ostream* os) const {
2973 *os << "doesn't have a key that ";
2974 inner_matcher_.DescribeTo(os);
2975 }
2976
zhanyong.wanb5937da2009-07-16 20:26:41 +00002977 private:
2978 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002979
2980 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002981};
2982
2983// Implements polymorphic Key(matcher_for_key).
2984template <typename M>
2985class KeyMatcher {
2986 public:
2987 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2988
2989 template <typename PairType>
2990 operator Matcher<PairType>() const {
2991 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2992 }
2993
2994 private:
2995 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002996
2997 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002998};
2999
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003000// Implements Pair(first_matcher, second_matcher) for the given argument pair
3001// type with its two matchers. See Pair() function below.
3002template <typename PairType>
3003class PairMatcherImpl : public MatcherInterface<PairType> {
3004 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003005 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003006 typedef typename RawPairType::first_type FirstType;
3007 typedef typename RawPairType::second_type SecondType;
3008
3009 template <typename FirstMatcher, typename SecondMatcher>
3010 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
3011 : first_matcher_(
3012 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
3013 second_matcher_(
3014 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
3015 }
3016
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003017 // Describes what this matcher does.
3018 virtual void DescribeTo(::std::ostream* os) const {
3019 *os << "has a first field that ";
3020 first_matcher_.DescribeTo(os);
3021 *os << ", and has a second field that ";
3022 second_matcher_.DescribeTo(os);
3023 }
3024
3025 // Describes what the negation of this matcher does.
3026 virtual void DescribeNegationTo(::std::ostream* os) const {
3027 *os << "has a first field that ";
3028 first_matcher_.DescribeNegationTo(os);
3029 *os << ", or has a second field that ";
3030 second_matcher_.DescribeNegationTo(os);
3031 }
3032
zhanyong.wan82113312010-01-08 21:55:40 +00003033 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3034 // matches second_matcher.
3035 virtual bool MatchAndExplain(PairType a_pair,
3036 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003037 if (!listener->IsInterested()) {
3038 // If the listener is not interested, we don't need to construct the
3039 // explanation.
3040 return first_matcher_.Matches(a_pair.first) &&
3041 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00003042 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003043 StringMatchResultListener first_inner_listener;
3044 if (!first_matcher_.MatchAndExplain(a_pair.first,
3045 &first_inner_listener)) {
3046 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003047 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003048 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003049 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003050 StringMatchResultListener second_inner_listener;
3051 if (!second_matcher_.MatchAndExplain(a_pair.second,
3052 &second_inner_listener)) {
3053 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003054 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00003055 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003056 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003057 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3058 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00003059 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003060 }
3061
3062 private:
Nico Weber09fd5b32017-05-15 17:07:03 -04003063 void ExplainSuccess(const std::string& first_explanation,
3064 const std::string& second_explanation,
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003065 MatchResultListener* listener) const {
3066 *listener << "whose both fields match";
3067 if (first_explanation != "") {
3068 *listener << ", where the first field is a value " << first_explanation;
3069 }
3070 if (second_explanation != "") {
3071 *listener << ", ";
3072 if (first_explanation != "") {
3073 *listener << "and ";
3074 } else {
3075 *listener << "where ";
3076 }
3077 *listener << "the second field is a value " << second_explanation;
3078 }
3079 }
3080
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003081 const Matcher<const FirstType&> first_matcher_;
3082 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003083
3084 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003085};
3086
3087// Implements polymorphic Pair(first_matcher, second_matcher).
3088template <typename FirstMatcher, typename SecondMatcher>
3089class PairMatcher {
3090 public:
3091 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3092 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3093
3094 template <typename PairType>
3095 operator Matcher<PairType> () const {
3096 return MakeMatcher(
3097 new PairMatcherImpl<PairType>(
3098 first_matcher_, second_matcher_));
3099 }
3100
3101 private:
3102 const FirstMatcher first_matcher_;
3103 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003104
3105 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003106};
3107
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003108// Implements ElementsAre() and ElementsAreArray().
3109template <typename Container>
3110class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3111 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003112 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003113 typedef internal::StlContainerView<RawContainer> View;
3114 typedef typename View::type StlContainer;
3115 typedef typename View::const_reference StlContainerReference;
3116 typedef typename StlContainer::value_type Element;
3117
3118 // Constructs the matcher from a sequence of element values or
3119 // element matchers.
3120 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00003121 ElementsAreMatcherImpl(InputIter first, InputIter last) {
3122 while (first != last) {
3123 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003124 }
3125 }
3126
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003127 // Describes what this matcher does.
3128 virtual void DescribeTo(::std::ostream* os) const {
3129 if (count() == 0) {
3130 *os << "is empty";
3131 } else if (count() == 1) {
3132 *os << "has 1 element that ";
3133 matchers_[0].DescribeTo(os);
3134 } else {
3135 *os << "has " << Elements(count()) << " where\n";
3136 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003137 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003138 matchers_[i].DescribeTo(os);
3139 if (i + 1 < count()) {
3140 *os << ",\n";
3141 }
3142 }
3143 }
3144 }
3145
3146 // Describes what the negation of this matcher does.
3147 virtual void DescribeNegationTo(::std::ostream* os) const {
3148 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003149 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003150 return;
3151 }
3152
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003153 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003154 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003155 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003156 matchers_[i].DescribeNegationTo(os);
3157 if (i + 1 < count()) {
3158 *os << ", or\n";
3159 }
3160 }
3161 }
3162
zhanyong.wan82113312010-01-08 21:55:40 +00003163 virtual bool MatchAndExplain(Container container,
3164 MatchResultListener* listener) const {
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003165 // To work with stream-like "containers", we must only walk
3166 // through the elements in one pass.
3167
3168 const bool listener_interested = listener->IsInterested();
3169
3170 // explanations[i] is the explanation of the element at index i.
Nico Weber09fd5b32017-05-15 17:07:03 -04003171 ::std::vector<std::string> explanations(count());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003172 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003173 typename StlContainer::const_iterator it = stl_container.begin();
3174 size_t exam_pos = 0;
3175 bool mismatch_found = false; // Have we found a mismatched element yet?
3176
3177 // Go through the elements and matchers in pairs, until we reach
3178 // the end of either the elements or the matchers, or until we find a
3179 // mismatch.
3180 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3181 bool match; // Does the current element match the current matcher?
3182 if (listener_interested) {
3183 StringMatchResultListener s;
3184 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3185 explanations[exam_pos] = s.str();
3186 } else {
3187 match = matchers_[exam_pos].Matches(*it);
3188 }
3189
3190 if (!match) {
3191 mismatch_found = true;
3192 break;
3193 }
3194 }
3195 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3196
3197 // Find how many elements the actual container has. We avoid
3198 // calling size() s.t. this code works for stream-like "containers"
3199 // that don't define size().
3200 size_t actual_count = exam_pos;
3201 for (; it != stl_container.end(); ++it) {
3202 ++actual_count;
3203 }
3204
zhanyong.wan82113312010-01-08 21:55:40 +00003205 if (actual_count != count()) {
3206 // The element count doesn't match. If the container is empty,
3207 // there's no need to explain anything as Google Mock already
3208 // prints the empty container. Otherwise we just need to show
3209 // how many elements there actually are.
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003210 if (listener_interested && (actual_count != 0)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003211 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003212 }
zhanyong.wan82113312010-01-08 21:55:40 +00003213 return false;
3214 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003215
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003216 if (mismatch_found) {
3217 // The element count matches, but the exam_pos-th element doesn't match.
3218 if (listener_interested) {
3219 *listener << "whose element #" << exam_pos << " doesn't match";
3220 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003221 }
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003222 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003223 }
zhanyong.wan82113312010-01-08 21:55:40 +00003224
3225 // Every element matches its expectation. We need to explain why
3226 // (the obvious ones can be skipped).
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003227 if (listener_interested) {
3228 bool reason_printed = false;
3229 for (size_t i = 0; i != count(); ++i) {
Nico Weber09fd5b32017-05-15 17:07:03 -04003230 const std::string& s = explanations[i];
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003231 if (!s.empty()) {
3232 if (reason_printed) {
3233 *listener << ",\nand ";
3234 }
3235 *listener << "whose element #" << i << " matches, " << s;
3236 reason_printed = true;
zhanyong.wan82113312010-01-08 21:55:40 +00003237 }
zhanyong.wan82113312010-01-08 21:55:40 +00003238 }
3239 }
zhanyong.wan82113312010-01-08 21:55:40 +00003240 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003241 }
3242
3243 private:
3244 static Message Elements(size_t count) {
3245 return Message() << count << (count == 1 ? " element" : " elements");
3246 }
3247
3248 size_t count() const { return matchers_.size(); }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003249
3250 ::std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003251
3252 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003253};
3254
zhanyong.wanfb25d532013-07-28 08:24:00 +00003255// Connectivity matrix of (elements X matchers), in element-major order.
3256// Initially, there are no edges.
3257// Use NextGraph() to iterate over all possible edge configurations.
3258// Use Randomize() to generate a random edge configuration.
3259class GTEST_API_ MatchMatrix {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003260 public:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003261 MatchMatrix(size_t num_elements, size_t num_matchers)
3262 : num_elements_(num_elements),
3263 num_matchers_(num_matchers),
3264 matched_(num_elements_* num_matchers_, 0) {
3265 }
3266
3267 size_t LhsSize() const { return num_elements_; }
3268 size_t RhsSize() const { return num_matchers_; }
3269 bool HasEdge(size_t ilhs, size_t irhs) const {
3270 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3271 }
3272 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3273 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3274 }
3275
3276 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3277 // adds 1 to that number; returns false if incrementing the graph left it
3278 // empty.
3279 bool NextGraph();
3280
3281 void Randomize();
3282
Nico Weber09fd5b32017-05-15 17:07:03 -04003283 std::string DebugString() const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003284
3285 private:
3286 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3287 return ilhs * num_matchers_ + irhs;
3288 }
3289
3290 size_t num_elements_;
3291 size_t num_matchers_;
3292
3293 // Each element is a char interpreted as bool. They are stored as a
3294 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3295 // a (ilhs, irhs) matrix coordinate into an offset.
3296 ::std::vector<char> matched_;
3297};
3298
3299typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3300typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3301
3302// Returns a maximum bipartite matching for the specified graph 'g'.
3303// The matching is represented as a vector of {element, matcher} pairs.
3304GTEST_API_ ElementMatcherPairs
3305FindMaxBipartiteMatching(const MatchMatrix& g);
3306
3307GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
3308 MatchResultListener* listener);
3309
3310// Untyped base class for implementing UnorderedElementsAre. By
3311// putting logic that's not specific to the element type here, we
3312// reduce binary bloat and increase compilation speed.
3313class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3314 protected:
3315 // A vector of matcher describers, one for each element matcher.
3316 // Does not own the describers (and thus can be used only when the
3317 // element matchers are alive).
3318 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3319
3320 // Describes this UnorderedElementsAre matcher.
3321 void DescribeToImpl(::std::ostream* os) const;
3322
3323 // Describes the negation of this UnorderedElementsAre matcher.
3324 void DescribeNegationToImpl(::std::ostream* os) const;
3325
3326 bool VerifyAllElementsAndMatchersAreMatched(
Nico Weber09fd5b32017-05-15 17:07:03 -04003327 const ::std::vector<std::string>& element_printouts,
3328 const MatchMatrix& matrix, MatchResultListener* listener) const;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003329
3330 MatcherDescriberVec& matcher_describers() {
3331 return matcher_describers_;
3332 }
3333
3334 static Message Elements(size_t n) {
3335 return Message() << n << " element" << (n == 1 ? "" : "s");
3336 }
3337
3338 private:
3339 MatcherDescriberVec matcher_describers_;
3340
3341 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3342};
3343
3344// Implements unordered ElementsAre and unordered ElementsAreArray.
3345template <typename Container>
3346class UnorderedElementsAreMatcherImpl
3347 : public MatcherInterface<Container>,
3348 public UnorderedElementsAreMatcherImplBase {
3349 public:
3350 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3351 typedef internal::StlContainerView<RawContainer> View;
3352 typedef typename View::type StlContainer;
3353 typedef typename View::const_reference StlContainerReference;
3354 typedef typename StlContainer::const_iterator StlContainerConstIterator;
3355 typedef typename StlContainer::value_type Element;
3356
3357 // Constructs the matcher from a sequence of element values or
3358 // element matchers.
3359 template <typename InputIter>
3360 UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) {
3361 for (; first != last; ++first) {
3362 matchers_.push_back(MatcherCast<const Element&>(*first));
3363 matcher_describers().push_back(matchers_.back().GetDescriber());
3364 }
3365 }
3366
3367 // Describes what this matcher does.
3368 virtual void DescribeTo(::std::ostream* os) const {
3369 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3370 }
3371
3372 // Describes what the negation of this matcher does.
3373 virtual void DescribeNegationTo(::std::ostream* os) const {
3374 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3375 }
3376
3377 virtual bool MatchAndExplain(Container container,
3378 MatchResultListener* listener) const {
3379 StlContainerReference stl_container = View::ConstReference(container);
Nico Weber09fd5b32017-05-15 17:07:03 -04003380 ::std::vector<std::string> element_printouts;
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003381 MatchMatrix matrix = AnalyzeElements(stl_container.begin(),
3382 stl_container.end(),
3383 &element_printouts,
3384 listener);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003385
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003386 const size_t actual_count = matrix.LhsSize();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003387 if (actual_count == 0 && matchers_.empty()) {
3388 return true;
3389 }
3390 if (actual_count != matchers_.size()) {
3391 // The element count doesn't match. If the container is empty,
3392 // there's no need to explain anything as Google Mock already
3393 // prints the empty container. Otherwise we just need to show
3394 // how many elements there actually are.
3395 if (actual_count != 0 && listener->IsInterested()) {
3396 *listener << "which has " << Elements(actual_count);
3397 }
3398 return false;
3399 }
3400
zhanyong.wanfb25d532013-07-28 08:24:00 +00003401 return VerifyAllElementsAndMatchersAreMatched(element_printouts,
3402 matrix, listener) &&
3403 FindPairing(matrix, listener);
3404 }
3405
3406 private:
3407 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3408
3409 template <typename ElementIter>
3410 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
Nico Weber09fd5b32017-05-15 17:07:03 -04003411 ::std::vector<std::string>* element_printouts,
zhanyong.wanfb25d532013-07-28 08:24:00 +00003412 MatchResultListener* listener) const {
zhanyong.wan5579c1a2013-07-30 06:16:21 +00003413 element_printouts->clear();
zhanyong.wanfb25d532013-07-28 08:24:00 +00003414 ::std::vector<char> did_match;
3415 size_t num_elements = 0;
3416 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3417 if (listener->IsInterested()) {
3418 element_printouts->push_back(PrintToString(*elem_first));
3419 }
3420 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3421 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3422 }
3423 }
3424
3425 MatchMatrix matrix(num_elements, matchers_.size());
3426 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3427 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3428 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3429 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3430 }
3431 }
3432 return matrix;
3433 }
3434
3435 MatcherVec matchers_;
3436
3437 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3438};
3439
3440// Functor for use in TransformTuple.
3441// Performs MatcherCast<Target> on an input argument of any type.
3442template <typename Target>
3443struct CastAndAppendTransform {
3444 template <typename Arg>
3445 Matcher<Target> operator()(const Arg& a) const {
3446 return MatcherCast<Target>(a);
3447 }
3448};
3449
3450// Implements UnorderedElementsAre.
3451template <typename MatcherTuple>
3452class UnorderedElementsAreMatcher {
3453 public:
3454 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3455 : matchers_(args) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003456
3457 template <typename Container>
3458 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003459 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanfb25d532013-07-28 08:24:00 +00003460 typedef typename internal::StlContainerView<RawContainer>::type View;
3461 typedef typename View::value_type Element;
3462 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3463 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003464 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003465 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3466 ::std::back_inserter(matchers));
3467 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3468 matchers.begin(), matchers.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003469 }
zhanyong.wanfb25d532013-07-28 08:24:00 +00003470
3471 private:
3472 const MatcherTuple matchers_;
3473 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3474};
3475
3476// Implements ElementsAre.
3477template <typename MatcherTuple>
3478class ElementsAreMatcher {
3479 public:
3480 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3481
3482 template <typename Container>
3483 operator Matcher<Container>() const {
3484 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3485 typedef typename internal::StlContainerView<RawContainer>::type View;
3486 typedef typename View::value_type Element;
3487 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3488 MatcherVec matchers;
kosakbd018832014-04-02 20:30:00 +00003489 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
zhanyong.wanfb25d532013-07-28 08:24:00 +00003490 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3491 ::std::back_inserter(matchers));
3492 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3493 matchers.begin(), matchers.end()));
3494 }
3495
3496 private:
3497 const MatcherTuple matchers_;
3498 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3499};
3500
3501// Implements UnorderedElementsAreArray().
3502template <typename T>
3503class UnorderedElementsAreArrayMatcher {
3504 public:
3505 UnorderedElementsAreArrayMatcher() {}
3506
3507 template <typename Iter>
3508 UnorderedElementsAreArrayMatcher(Iter first, Iter last)
3509 : matchers_(first, last) {}
3510
3511 template <typename Container>
3512 operator Matcher<Container>() const {
3513 return MakeMatcher(
3514 new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(),
3515 matchers_.end()));
3516 }
3517
3518 private:
3519 ::std::vector<T> matchers_;
3520
3521 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003522};
3523
3524// Implements ElementsAreArray().
3525template <typename T>
3526class ElementsAreArrayMatcher {
3527 public:
jgm38513a82012-11-15 15:50:36 +00003528 template <typename Iter>
3529 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003530
3531 template <typename Container>
3532 operator Matcher<Container>() const {
jgm38513a82012-11-15 15:50:36 +00003533 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3534 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003535 }
3536
3537 private:
zhanyong.wanfb25d532013-07-28 08:24:00 +00003538 const ::std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003539
3540 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003541};
3542
kosak2336e9c2014-07-28 22:57:30 +00003543// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3544// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3545// second) is a polymorphic matcher that matches a value x iff tm
3546// matches tuple (x, second). Useful for implementing
3547// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3548//
3549// BoundSecondMatcher is copyable and assignable, as we need to put
3550// instances of this class in a vector when implementing
3551// UnorderedPointwise().
3552template <typename Tuple2Matcher, typename Second>
3553class BoundSecondMatcher {
3554 public:
3555 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3556 : tuple2_matcher_(tm), second_value_(second) {}
3557
3558 template <typename T>
3559 operator Matcher<T>() const {
3560 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3561 }
3562
3563 // We have to define this for UnorderedPointwise() to compile in
3564 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3565 // which requires the elements to be assignable in C++98. The
3566 // compiler cannot generate the operator= for us, as Tuple2Matcher
3567 // and Second may not be assignable.
3568 //
3569 // However, this should never be called, so the implementation just
3570 // need to assert.
3571 void operator=(const BoundSecondMatcher& /*rhs*/) {
3572 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3573 }
3574
3575 private:
3576 template <typename T>
3577 class Impl : public MatcherInterface<T> {
3578 public:
3579 typedef ::testing::tuple<T, Second> ArgTuple;
3580
3581 Impl(const Tuple2Matcher& tm, const Second& second)
3582 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3583 second_value_(second) {}
3584
3585 virtual void DescribeTo(::std::ostream* os) const {
3586 *os << "and ";
3587 UniversalPrint(second_value_, os);
3588 *os << " ";
3589 mono_tuple2_matcher_.DescribeTo(os);
3590 }
3591
3592 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3593 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3594 listener);
3595 }
3596
3597 private:
3598 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3599 const Second second_value_;
3600
3601 GTEST_DISALLOW_ASSIGN_(Impl);
3602 };
3603
3604 const Tuple2Matcher tuple2_matcher_;
3605 const Second second_value_;
3606};
3607
3608// Given a 2-tuple matcher tm and a value second,
3609// MatcherBindSecond(tm, second) returns a matcher that matches a
3610// value x iff tm matches tuple (x, second). Useful for implementing
3611// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3612template <typename Tuple2Matcher, typename Second>
3613BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
3614 const Tuple2Matcher& tm, const Second& second) {
3615 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
3616}
3617
David Benjaminb3d9be52017-02-10 19:19:54 -05003618// Joins a vector of strings as if they are fields of a tuple; returns
3619// the joined string. This function is exported for testing.
3620GTEST_API_ string JoinAsTuple(const Strings& fields);
3621
zhanyong.wanb4140802010-06-08 22:53:57 +00003622// Returns the description for a matcher defined using the MATCHER*()
3623// macro where the user-supplied description string is "", if
3624// 'negation' is false; otherwise returns the description of the
3625// negation of the matcher. 'param_values' contains a list of strings
3626// that are the print-out of the matcher's parameters.
Nico Weber09fd5b32017-05-15 17:07:03 -04003627GTEST_API_ std::string FormatMatcherDescription(bool negation,
3628 const char* matcher_name,
3629 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00003630
shiqiane35fdd92008-12-10 05:08:54 +00003631} // namespace internal
3632
zhanyong.wanfb25d532013-07-28 08:24:00 +00003633// ElementsAreArray(first, last)
3634// ElementsAreArray(pointer, count)
3635// ElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00003636// ElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003637// ElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00003638//
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003639// The ElementsAreArray() functions are like ElementsAre(...), except
3640// that they are given a homogeneous sequence rather than taking each
3641// element as a function argument. The sequence can be specified as an
3642// array, a pointer and count, a vector, an initializer list, or an
3643// STL iterator range. In each of these cases, the underlying sequence
3644// can be either a sequence of values or a sequence of matchers.
zhanyong.wanfb25d532013-07-28 08:24:00 +00003645//
3646// All forms of ElementsAreArray() make a copy of the input matcher sequence.
3647
3648template <typename Iter>
3649inline internal::ElementsAreArrayMatcher<
3650 typename ::std::iterator_traits<Iter>::value_type>
3651ElementsAreArray(Iter first, Iter last) {
3652 typedef typename ::std::iterator_traits<Iter>::value_type T;
3653 return internal::ElementsAreArrayMatcher<T>(first, last);
3654}
3655
3656template <typename T>
3657inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3658 const T* pointer, size_t count) {
3659 return ElementsAreArray(pointer, pointer + count);
3660}
3661
3662template <typename T, size_t N>
3663inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3664 const T (&array)[N]) {
3665 return ElementsAreArray(array, N);
3666}
3667
kosak06678922014-07-28 20:01:28 +00003668template <typename Container>
3669inline internal::ElementsAreArrayMatcher<typename Container::value_type>
3670ElementsAreArray(const Container& container) {
3671 return ElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00003672}
3673
kosak18489fa2013-12-04 23:49:07 +00003674#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003675template <typename T>
3676inline internal::ElementsAreArrayMatcher<T>
3677ElementsAreArray(::std::initializer_list<T> xs) {
3678 return ElementsAreArray(xs.begin(), xs.end());
3679}
3680#endif
3681
zhanyong.wanfb25d532013-07-28 08:24:00 +00003682// UnorderedElementsAreArray(first, last)
3683// UnorderedElementsAreArray(pointer, count)
3684// UnorderedElementsAreArray(array)
kosak06678922014-07-28 20:01:28 +00003685// UnorderedElementsAreArray(container)
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003686// UnorderedElementsAreArray({ e1, e2, ..., en })
zhanyong.wanfb25d532013-07-28 08:24:00 +00003687//
3688// The UnorderedElementsAreArray() functions are like
3689// ElementsAreArray(...), but allow matching the elements in any order.
3690template <typename Iter>
3691inline internal::UnorderedElementsAreArrayMatcher<
3692 typename ::std::iterator_traits<Iter>::value_type>
3693UnorderedElementsAreArray(Iter first, Iter last) {
3694 typedef typename ::std::iterator_traits<Iter>::value_type T;
3695 return internal::UnorderedElementsAreArrayMatcher<T>(first, last);
3696}
3697
3698template <typename T>
3699inline internal::UnorderedElementsAreArrayMatcher<T>
3700UnorderedElementsAreArray(const T* pointer, size_t count) {
3701 return UnorderedElementsAreArray(pointer, pointer + count);
3702}
3703
3704template <typename T, size_t N>
3705inline internal::UnorderedElementsAreArrayMatcher<T>
3706UnorderedElementsAreArray(const T (&array)[N]) {
3707 return UnorderedElementsAreArray(array, N);
3708}
3709
kosak06678922014-07-28 20:01:28 +00003710template <typename Container>
3711inline internal::UnorderedElementsAreArrayMatcher<
3712 typename Container::value_type>
3713UnorderedElementsAreArray(const Container& container) {
3714 return UnorderedElementsAreArray(container.begin(), container.end());
zhanyong.wanfb25d532013-07-28 08:24:00 +00003715}
3716
kosak18489fa2013-12-04 23:49:07 +00003717#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00003718template <typename T>
3719inline internal::UnorderedElementsAreArrayMatcher<T>
3720UnorderedElementsAreArray(::std::initializer_list<T> xs) {
3721 return UnorderedElementsAreArray(xs.begin(), xs.end());
3722}
3723#endif
zhanyong.wanfb25d532013-07-28 08:24:00 +00003724
shiqiane35fdd92008-12-10 05:08:54 +00003725// _ is a matcher that matches anything of any type.
3726//
3727// This definition is fine as:
3728//
3729// 1. The C++ standard permits using the name _ in a namespace that
3730// is not the global namespace or ::std.
3731// 2. The AnythingMatcher class has no data member or constructor,
3732// so it's OK to create global variables of this type.
3733// 3. c-style has approved of using _ in this case.
3734const internal::AnythingMatcher _ = {};
3735// Creates a matcher that matches any value of the given type T.
3736template <typename T>
3737inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
3738
3739// Creates a matcher that matches any value of the given type T.
3740template <typename T>
3741inline Matcher<T> An() { return A<T>(); }
3742
3743// Creates a polymorphic matcher that matches anything equal to x.
3744// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
3745// wouldn't compile.
3746template <typename T>
3747inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
3748
3749// Constructs a Matcher<T> from a 'value' of type T. The constructed
3750// matcher matches any value that's equal to 'value'.
3751template <typename T>
3752Matcher<T>::Matcher(T value) { *this = Eq(value); }
3753
3754// Creates a monomorphic matcher that matches anything with type Lhs
3755// and equal to rhs. A user may need to use this instead of Eq(...)
3756// in order to resolve an overloading ambiguity.
3757//
3758// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
3759// or Matcher<T>(x), but more readable than the latter.
3760//
3761// We could define similar monomorphic matchers for other comparison
3762// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
3763// it yet as those are used much less than Eq() in practice. A user
3764// can always write Matcher<T>(Lt(5)) to be explicit about the type,
3765// for example.
3766template <typename Lhs, typename Rhs>
3767inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
3768
3769// Creates a polymorphic matcher that matches anything >= x.
3770template <typename Rhs>
3771inline internal::GeMatcher<Rhs> Ge(Rhs x) {
3772 return internal::GeMatcher<Rhs>(x);
3773}
3774
3775// Creates a polymorphic matcher that matches anything > x.
3776template <typename Rhs>
3777inline internal::GtMatcher<Rhs> Gt(Rhs x) {
3778 return internal::GtMatcher<Rhs>(x);
3779}
3780
3781// Creates a polymorphic matcher that matches anything <= x.
3782template <typename Rhs>
3783inline internal::LeMatcher<Rhs> Le(Rhs x) {
3784 return internal::LeMatcher<Rhs>(x);
3785}
3786
3787// Creates a polymorphic matcher that matches anything < x.
3788template <typename Rhs>
3789inline internal::LtMatcher<Rhs> Lt(Rhs x) {
3790 return internal::LtMatcher<Rhs>(x);
3791}
3792
3793// Creates a polymorphic matcher that matches anything != x.
3794template <typename Rhs>
3795inline internal::NeMatcher<Rhs> Ne(Rhs x) {
3796 return internal::NeMatcher<Rhs>(x);
3797}
3798
zhanyong.wan2d970ee2009-09-24 21:41:36 +00003799// Creates a polymorphic matcher that matches any NULL pointer.
3800inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
3801 return MakePolymorphicMatcher(internal::IsNullMatcher());
3802}
3803
shiqiane35fdd92008-12-10 05:08:54 +00003804// Creates a polymorphic matcher that matches any non-NULL pointer.
3805// This is convenient as Not(NULL) doesn't compile (the compiler
3806// thinks that that expression is comparing a pointer with an integer).
3807inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
3808 return MakePolymorphicMatcher(internal::NotNullMatcher());
3809}
3810
3811// Creates a polymorphic matcher that matches any argument that
3812// references variable x.
3813template <typename T>
3814inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
3815 return internal::RefMatcher<T&>(x);
3816}
3817
3818// Creates a matcher that matches any double argument approximately
3819// equal to rhs, where two NANs are considered unequal.
3820inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
3821 return internal::FloatingEqMatcher<double>(rhs, false);
3822}
3823
3824// Creates a matcher that matches any double argument approximately
3825// equal to rhs, including NaN values when rhs is NaN.
3826inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
3827 return internal::FloatingEqMatcher<double>(rhs, true);
3828}
3829
zhanyong.wan616180e2013-06-18 18:49:51 +00003830// Creates a matcher that matches any double argument approximately equal to
3831// rhs, up to the specified max absolute error bound, where two NANs are
3832// considered unequal. The max absolute error bound must be non-negative.
3833inline internal::FloatingEqMatcher<double> DoubleNear(
3834 double rhs, double max_abs_error) {
3835 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
3836}
3837
3838// Creates a matcher that matches any double argument approximately equal to
3839// rhs, up to the specified max absolute error bound, including NaN values when
3840// rhs is NaN. The max absolute error bound must be non-negative.
3841inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
3842 double rhs, double max_abs_error) {
3843 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
3844}
3845
shiqiane35fdd92008-12-10 05:08:54 +00003846// Creates a matcher that matches any float argument approximately
3847// equal to rhs, where two NANs are considered unequal.
3848inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
3849 return internal::FloatingEqMatcher<float>(rhs, false);
3850}
3851
zhanyong.wan616180e2013-06-18 18:49:51 +00003852// Creates a matcher that matches any float argument approximately
shiqiane35fdd92008-12-10 05:08:54 +00003853// equal to rhs, including NaN values when rhs is NaN.
3854inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
3855 return internal::FloatingEqMatcher<float>(rhs, true);
3856}
3857
zhanyong.wan616180e2013-06-18 18:49:51 +00003858// Creates a matcher that matches any float argument approximately equal to
3859// rhs, up to the specified max absolute error bound, where two NANs are
3860// considered unequal. The max absolute error bound must be non-negative.
3861inline internal::FloatingEqMatcher<float> FloatNear(
3862 float rhs, float max_abs_error) {
3863 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
3864}
3865
3866// Creates a matcher that matches any float argument approximately equal to
3867// rhs, up to the specified max absolute error bound, including NaN values when
3868// rhs is NaN. The max absolute error bound must be non-negative.
3869inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
3870 float rhs, float max_abs_error) {
3871 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
3872}
3873
shiqiane35fdd92008-12-10 05:08:54 +00003874// Creates a matcher that matches a pointer (raw or smart) that points
3875// to a value that matches inner_matcher.
3876template <typename InnerMatcher>
3877inline internal::PointeeMatcher<InnerMatcher> Pointee(
3878 const InnerMatcher& inner_matcher) {
3879 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
3880}
3881
billydonahue1f5fdea2014-05-19 17:54:51 +00003882// Creates a matcher that matches a pointer or reference that matches
3883// inner_matcher when dynamic_cast<To> is applied.
3884// The result of dynamic_cast<To> is forwarded to the inner matcher.
3885// If To is a pointer and the cast fails, the inner matcher will receive NULL.
3886// If To is a reference and the cast fails, this matcher returns false
3887// immediately.
3888template <typename To>
3889inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
3890WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
3891 return MakePolymorphicMatcher(
3892 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
3893}
3894
shiqiane35fdd92008-12-10 05:08:54 +00003895// Creates a matcher that matches an object whose given field matches
3896// 'matcher'. For example,
3897// Field(&Foo::number, Ge(5))
3898// matches a Foo object x iff x.number >= 5.
3899template <typename Class, typename FieldType, typename FieldMatcher>
3900inline PolymorphicMatcher<
3901 internal::FieldMatcher<Class, FieldType> > Field(
3902 FieldType Class::*field, const FieldMatcher& matcher) {
3903 return MakePolymorphicMatcher(
3904 internal::FieldMatcher<Class, FieldType>(
3905 field, MatcherCast<const FieldType&>(matcher)));
3906 // The call to MatcherCast() is required for supporting inner
3907 // matchers of compatible types. For example, it allows
3908 // Field(&Foo::bar, m)
3909 // to compile where bar is an int32 and m is a matcher for int64.
3910}
3911
3912// Creates a matcher that matches an object whose given property
3913// matches 'matcher'. For example,
3914// Property(&Foo::str, StartsWith("hi"))
3915// matches a Foo object x iff x.str() starts with "hi".
3916template <typename Class, typename PropertyType, typename PropertyMatcher>
Roman Perepelitsa966b5492017-08-22 16:06:26 +02003917inline PolymorphicMatcher<internal::PropertyMatcher<
3918 Class, PropertyType, PropertyType (Class::*)() const> >
3919Property(PropertyType (Class::*property)() const,
3920 const PropertyMatcher& matcher) {
shiqiane35fdd92008-12-10 05:08:54 +00003921 return MakePolymorphicMatcher(
Roman Perepelitsa966b5492017-08-22 16:06:26 +02003922 internal::PropertyMatcher<Class, PropertyType,
3923 PropertyType (Class::*)() const>(
shiqiane35fdd92008-12-10 05:08:54 +00003924 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00003925 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00003926 // The call to MatcherCast() is required for supporting inner
3927 // matchers of compatible types. For example, it allows
3928 // Property(&Foo::bar, m)
3929 // to compile where bar() returns an int32 and m is a matcher for int64.
3930}
3931
Roman Perepelitsa966b5492017-08-22 16:06:26 +02003932#if GTEST_LANG_CXX11
3933// The same as above but for reference-qualified member functions.
3934template <typename Class, typename PropertyType, typename PropertyMatcher>
3935inline PolymorphicMatcher<internal::PropertyMatcher<
3936 Class, PropertyType, PropertyType (Class::*)() const &> >
3937Property(PropertyType (Class::*property)() const &,
3938 const PropertyMatcher& matcher) {
3939 return MakePolymorphicMatcher(
3940 internal::PropertyMatcher<Class, PropertyType,
3941 PropertyType (Class::*)() const &>(
3942 property,
3943 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
3944}
3945#endif
3946
shiqiane35fdd92008-12-10 05:08:54 +00003947// Creates a matcher that matches an object iff the result of applying
3948// a callable to x matches 'matcher'.
3949// For example,
3950// ResultOf(f, StartsWith("hi"))
3951// matches a Foo object x iff f(x) starts with "hi".
3952// callable parameter can be a function, function pointer, or a functor.
3953// Callable has to satisfy the following conditions:
3954// * It is required to keep no state affecting the results of
3955// the calls on it and make no assumptions about how many calls
3956// will be made. Any state it keeps must be protected from the
3957// concurrent access.
3958// * If it is a function object, it has to define type result_type.
3959// We recommend deriving your functor classes from std::unary_function.
3960template <typename Callable, typename ResultOfMatcher>
3961internal::ResultOfMatcher<Callable> ResultOf(
3962 Callable callable, const ResultOfMatcher& matcher) {
3963 return internal::ResultOfMatcher<Callable>(
3964 callable,
3965 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
3966 matcher));
3967 // The call to MatcherCast() is required for supporting inner
3968 // matchers of compatible types. For example, it allows
3969 // ResultOf(Function, m)
3970 // to compile where Function() returns an int32 and m is a matcher for int64.
3971}
3972
3973// String matchers.
3974
3975// Matches a string equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04003976inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
3977 const std::string& str) {
3978 return MakePolymorphicMatcher(
3979 internal::StrEqualityMatcher<std::string>(str, true, true));
shiqiane35fdd92008-12-10 05:08:54 +00003980}
3981
3982// Matches a string not equal to str.
Nico Weber09fd5b32017-05-15 17:07:03 -04003983inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
3984 const std::string& str) {
3985 return MakePolymorphicMatcher(
3986 internal::StrEqualityMatcher<std::string>(str, false, true));
shiqiane35fdd92008-12-10 05:08:54 +00003987}
3988
3989// Matches a string equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04003990inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
3991 const std::string& str) {
3992 return MakePolymorphicMatcher(
3993 internal::StrEqualityMatcher<std::string>(str, true, false));
shiqiane35fdd92008-12-10 05:08:54 +00003994}
3995
3996// Matches a string not equal to str, ignoring case.
Nico Weber09fd5b32017-05-15 17:07:03 -04003997inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
3998 const std::string& str) {
3999 return MakePolymorphicMatcher(
4000 internal::StrEqualityMatcher<std::string>(str, false, false));
shiqiane35fdd92008-12-10 05:08:54 +00004001}
4002
4003// Creates a matcher that matches any string, std::string, or C string
4004// that contains the given substring.
Nico Weber09fd5b32017-05-15 17:07:03 -04004005inline PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
4006 const std::string& substring) {
4007 return MakePolymorphicMatcher(
4008 internal::HasSubstrMatcher<std::string>(substring));
shiqiane35fdd92008-12-10 05:08:54 +00004009}
4010
4011// Matches a string that starts with 'prefix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004012inline PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
4013 const std::string& prefix) {
4014 return MakePolymorphicMatcher(
4015 internal::StartsWithMatcher<std::string>(prefix));
shiqiane35fdd92008-12-10 05:08:54 +00004016}
4017
4018// Matches a string that ends with 'suffix' (case-sensitive).
Nico Weber09fd5b32017-05-15 17:07:03 -04004019inline PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
4020 const std::string& suffix) {
4021 return MakePolymorphicMatcher(internal::EndsWithMatcher<std::string>(suffix));
shiqiane35fdd92008-12-10 05:08:54 +00004022}
4023
shiqiane35fdd92008-12-10 05:08:54 +00004024// Matches a string that fully matches regular expression 'regex'.
4025// The matcher takes ownership of 'regex'.
4026inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4027 const internal::RE* regex) {
4028 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
4029}
4030inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004031 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004032 return MatchesRegex(new internal::RE(regex));
4033}
4034
4035// Matches a string that contains regular expression 'regex'.
4036// The matcher takes ownership of 'regex'.
4037inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4038 const internal::RE* regex) {
4039 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4040}
4041inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
Nico Weber09fd5b32017-05-15 17:07:03 -04004042 const std::string& regex) {
shiqiane35fdd92008-12-10 05:08:54 +00004043 return ContainsRegex(new internal::RE(regex));
4044}
4045
shiqiane35fdd92008-12-10 05:08:54 +00004046#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4047// Wide string matchers.
4048
4049// Matches a string equal to str.
4050inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4051 StrEq(const internal::wstring& str) {
4052 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4053 str, true, true));
4054}
4055
4056// Matches a string not equal to str.
4057inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4058 StrNe(const internal::wstring& str) {
4059 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4060 str, false, true));
4061}
4062
4063// Matches a string equal to str, ignoring case.
4064inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4065 StrCaseEq(const internal::wstring& str) {
4066 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4067 str, true, false));
4068}
4069
4070// Matches a string not equal to str, ignoring case.
4071inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4072 StrCaseNe(const internal::wstring& str) {
4073 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4074 str, false, false));
4075}
4076
4077// Creates a matcher that matches any wstring, std::wstring, or C wide string
4078// that contains the given substring.
4079inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
4080 HasSubstr(const internal::wstring& substring) {
4081 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
4082 substring));
4083}
4084
4085// Matches a string that starts with 'prefix' (case-sensitive).
4086inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
4087 StartsWith(const internal::wstring& prefix) {
4088 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
4089 prefix));
4090}
4091
4092// Matches a string that ends with 'suffix' (case-sensitive).
4093inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
4094 EndsWith(const internal::wstring& suffix) {
4095 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
4096 suffix));
4097}
4098
4099#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4100
4101// Creates a polymorphic matcher that matches a 2-tuple where the
4102// first field == the second field.
4103inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4104
4105// Creates a polymorphic matcher that matches a 2-tuple where the
4106// first field >= the second field.
4107inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4108
4109// Creates a polymorphic matcher that matches a 2-tuple where the
4110// first field > the second field.
4111inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4112
4113// Creates a polymorphic matcher that matches a 2-tuple where the
4114// first field <= the second field.
4115inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4116
4117// Creates a polymorphic matcher that matches a 2-tuple where the
4118// first field < the second field.
4119inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4120
4121// Creates a polymorphic matcher that matches a 2-tuple where the
4122// first field != the second field.
4123inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4124
4125// Creates a matcher that matches any value of type T that m doesn't
4126// match.
4127template <typename InnerMatcher>
4128inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4129 return internal::NotMatcher<InnerMatcher>(m);
4130}
4131
shiqiane35fdd92008-12-10 05:08:54 +00004132// Returns a matcher that matches anything that satisfies the given
4133// predicate. The predicate can be any unary function or functor
4134// whose return type can be implicitly converted to bool.
4135template <typename Predicate>
4136inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4137Truly(Predicate pred) {
4138 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4139}
4140
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004141// Returns a matcher that matches the container size. The container must
4142// support both size() and size_type which all STL-like containers provide.
4143// Note that the parameter 'size' can be a value of type size_type as well as
4144// matcher. For instance:
4145// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
4146// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
4147template <typename SizeMatcher>
4148inline internal::SizeIsMatcher<SizeMatcher>
4149SizeIs(const SizeMatcher& size_matcher) {
4150 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4151}
4152
kosakb6a34882014-03-12 21:06:46 +00004153// Returns a matcher that matches the distance between the container's begin()
4154// iterator and its end() iterator, i.e. the size of the container. This matcher
4155// can be used instead of SizeIs with containers such as std::forward_list which
4156// do not implement size(). The container must provide const_iterator (with
4157// valid iterator_traits), begin() and end().
4158template <typename DistanceMatcher>
4159inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4160BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4161 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4162}
4163
zhanyong.wan6a896b52009-01-16 01:13:50 +00004164// Returns a matcher that matches an equal container.
4165// This matcher behaves like Eq(), but in the event of mismatch lists the
4166// values that are included in one container but not the other. (Duplicate
4167// values and order differences are not explained.)
4168template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00004169inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00004170 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004171 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00004172 // This following line is for working around a bug in MSVC 8.0,
4173 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00004174 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00004175 return MakePolymorphicMatcher(
4176 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00004177}
4178
zhanyong.wan898725c2011-09-16 16:45:39 +00004179// Returns a matcher that matches a container that, when sorted using
4180// the given comparator, matches container_matcher.
4181template <typename Comparator, typename ContainerMatcher>
4182inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4183WhenSortedBy(const Comparator& comparator,
4184 const ContainerMatcher& container_matcher) {
4185 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4186 comparator, container_matcher);
4187}
4188
4189// Returns a matcher that matches a container that, when sorted using
4190// the < operator, matches container_matcher.
4191template <typename ContainerMatcher>
4192inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4193WhenSorted(const ContainerMatcher& container_matcher) {
4194 return
4195 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4196 internal::LessComparator(), container_matcher);
4197}
4198
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004199// Matches an STL-style container or a native array that contains the
4200// same number of elements as in rhs, where its i-th element and rhs's
4201// i-th element (as a pair) satisfy the given pair matcher, for all i.
4202// TupleMatcher must be able to be safely cast to Matcher<tuple<const
4203// T1&, const T2&> >, where T1 and T2 are the types of elements in the
4204// LHS container and the RHS container respectively.
4205template <typename TupleMatcher, typename Container>
4206inline internal::PointwiseMatcher<TupleMatcher,
4207 GTEST_REMOVE_CONST_(Container)>
4208Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4209 // This following line is for working around a bug in MSVC 8.0,
kosak2336e9c2014-07-28 22:57:30 +00004210 // which causes Container to be a const type sometimes (e.g. when
4211 // rhs is a const int[])..
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004212 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4213 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4214 tuple_matcher, rhs);
4215}
4216
kosak2336e9c2014-07-28 22:57:30 +00004217#if GTEST_HAS_STD_INITIALIZER_LIST_
4218
4219// Supports the Pointwise(m, {a, b, c}) syntax.
4220template <typename TupleMatcher, typename T>
4221inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4222 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4223 return Pointwise(tuple_matcher, std::vector<T>(rhs));
4224}
4225
4226#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4227
4228// UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4229// container or a native array that contains the same number of
4230// elements as in rhs, where in some permutation of the container, its
4231// i-th element and rhs's i-th element (as a pair) satisfy the given
4232// pair matcher, for all i. Tuple2Matcher must be able to be safely
4233// cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4234// the types of elements in the LHS container and the RHS container
4235// respectively.
4236//
4237// This is like Pointwise(pair_matcher, rhs), except that the element
4238// order doesn't matter.
4239template <typename Tuple2Matcher, typename RhsContainer>
4240inline internal::UnorderedElementsAreArrayMatcher<
4241 typename internal::BoundSecondMatcher<
4242 Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4243 RhsContainer)>::type::value_type> >
4244UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4245 const RhsContainer& rhs_container) {
4246 // This following line is for working around a bug in MSVC 8.0,
4247 // which causes RhsContainer to be a const type sometimes (e.g. when
4248 // rhs_container is a const int[]).
4249 typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4250
4251 // RhsView allows the same code to handle RhsContainer being a
4252 // STL-style container and it being a native C-style array.
4253 typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4254 typedef typename RhsView::type RhsStlContainer;
4255 typedef typename RhsStlContainer::value_type Second;
4256 const RhsStlContainer& rhs_stl_container =
4257 RhsView::ConstReference(rhs_container);
4258
4259 // Create a matcher for each element in rhs_container.
4260 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4261 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4262 it != rhs_stl_container.end(); ++it) {
4263 matchers.push_back(
4264 internal::MatcherBindSecond(tuple2_matcher, *it));
4265 }
4266
4267 // Delegate the work to UnorderedElementsAreArray().
4268 return UnorderedElementsAreArray(matchers);
4269}
4270
4271#if GTEST_HAS_STD_INITIALIZER_LIST_
4272
4273// Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4274template <typename Tuple2Matcher, typename T>
4275inline internal::UnorderedElementsAreArrayMatcher<
4276 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4277UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4278 std::initializer_list<T> rhs) {
4279 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4280}
4281
4282#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4283
zhanyong.wanb8243162009-06-04 05:48:20 +00004284// Matches an STL-style container or a native array that contains at
4285// least one element matching the given value or matcher.
4286//
4287// Examples:
4288// ::std::set<int> page_ids;
4289// page_ids.insert(3);
4290// page_ids.insert(1);
4291// EXPECT_THAT(page_ids, Contains(1));
4292// EXPECT_THAT(page_ids, Contains(Gt(2)));
4293// EXPECT_THAT(page_ids, Not(Contains(4)));
4294//
4295// ::std::map<int, size_t> page_lengths;
4296// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00004297// EXPECT_THAT(page_lengths,
4298// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004299//
4300// const char* user_ids[] = { "joe", "mike", "tom" };
4301// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4302template <typename M>
4303inline internal::ContainsMatcher<M> Contains(M matcher) {
4304 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004305}
4306
zhanyong.wan33605ba2010-04-22 23:37:47 +00004307// Matches an STL-style container or a native array that contains only
4308// elements matching the given value or matcher.
4309//
4310// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
4311// the messages are different.
4312//
4313// Examples:
4314// ::std::set<int> page_ids;
4315// // Each(m) matches an empty container, regardless of what m is.
4316// EXPECT_THAT(page_ids, Each(Eq(1)));
4317// EXPECT_THAT(page_ids, Each(Eq(77)));
4318//
4319// page_ids.insert(3);
4320// EXPECT_THAT(page_ids, Each(Gt(0)));
4321// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
4322// page_ids.insert(1);
4323// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
4324//
4325// ::std::map<int, size_t> page_lengths;
4326// page_lengths[1] = 100;
4327// page_lengths[2] = 200;
4328// page_lengths[3] = 300;
4329// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
4330// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
4331//
4332// const char* user_ids[] = { "joe", "mike", "tom" };
4333// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
4334template <typename M>
4335inline internal::EachMatcher<M> Each(M matcher) {
4336 return internal::EachMatcher<M>(matcher);
4337}
4338
zhanyong.wanb5937da2009-07-16 20:26:41 +00004339// Key(inner_matcher) matches an std::pair whose 'first' field matches
4340// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
4341// std::map that contains at least one element whose key is >= 5.
4342template <typename M>
4343inline internal::KeyMatcher<M> Key(M inner_matcher) {
4344 return internal::KeyMatcher<M>(inner_matcher);
4345}
4346
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00004347// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
4348// matches first_matcher and whose 'second' field matches second_matcher. For
4349// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
4350// to match a std::map<int, string> that contains exactly one element whose key
4351// is >= 5 and whose value equals "foo".
4352template <typename FirstMatcher, typename SecondMatcher>
4353inline internal::PairMatcher<FirstMatcher, SecondMatcher>
4354Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
4355 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
4356 first_matcher, second_matcher);
4357}
4358
shiqiane35fdd92008-12-10 05:08:54 +00004359// Returns a predicate that is satisfied by anything that matches the
4360// given matcher.
4361template <typename M>
4362inline internal::MatcherAsPredicate<M> Matches(M matcher) {
4363 return internal::MatcherAsPredicate<M>(matcher);
4364}
4365
zhanyong.wanb8243162009-06-04 05:48:20 +00004366// Returns true iff the value matches the matcher.
4367template <typename T, typename M>
4368inline bool Value(const T& value, M matcher) {
4369 return testing::Matches(matcher)(value);
4370}
4371
zhanyong.wan34b034c2010-03-05 21:23:23 +00004372// Matches the value against the given matcher and explains the match
4373// result to listener.
4374template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00004375inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00004376 M matcher, const T& value, MatchResultListener* listener) {
4377 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
4378}
4379
zhanyong.wan616180e2013-06-18 18:49:51 +00004380#if GTEST_LANG_CXX11
4381// Define variadic matcher versions. They are overloaded in
4382// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
4383template <typename... Args>
4384inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
4385 return internal::AllOfMatcher<Args...>(matchers...);
4386}
4387
4388template <typename... Args>
4389inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
4390 return internal::AnyOfMatcher<Args...>(matchers...);
4391}
4392
4393#endif // GTEST_LANG_CXX11
4394
zhanyong.wanbf550852009-06-09 06:09:53 +00004395// AllArgs(m) is a synonym of m. This is useful in
4396//
4397// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
4398//
4399// which is easier to read than
4400//
4401// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
4402template <typename InnerMatcher>
4403inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
4404
shiqiane35fdd92008-12-10 05:08:54 +00004405// These macros allow using matchers to check values in Google Test
4406// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
4407// succeed iff the value matches the matcher. If the assertion fails,
4408// the value and the description of the matcher will be printed.
4409#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
4410 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4411#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
4412 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4413
4414} // namespace testing
4415
kosak6702b972015-07-27 23:05:57 +00004416// Include any custom callback matchers added by the local installation.
4417// We must include this header at the end to make sure it can use the
4418// declarations from this file.
4419#include "gmock/internal/custom/gmock-matchers.h"
shiqiane35fdd92008-12-10 05:08:54 +00004420#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_