1 // 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 // IWYU pragma: private, include "gmock/gmock.h"
39
40 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
41 #define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
42
43 #include <math.h>
44 #include <algorithm>
45 #include <iterator>
46 #include <limits>
47 #include <ostream> // NOLINT
48 #include <sstream>
49 #include <string>
50 #include <utility>
51 #include <vector>
52
53 #include "gmock/internal/gmock-internal-utils.h"
54 #include "gmock/internal/gmock-port.h"
55 #include "gtest/gtest.h"
56
57 #if GTEST_HAS_STD_INITIALIZER_LIST_
58 # include <initializer_list> // NOLINT -- must be after gtest.h
59 #endif
60
61 namespace testing {
62
63 // To implement a matcher Foo for type T, define:
64 // 1. a class FooMatcherImpl that implements the
65 // MatcherInterface<T> interface, and
66 // 2. a factory function that creates a Matcher<T> object from a
67 // FooMatcherImpl*.
68 //
69 // The two-level delegation design makes it possible to allow a user
70 // to write "v" instead of "Eq(v)" where a Matcher is expected, which
71 // is impossible if we pass matchers by pointers. It also eases
72 // ownership management as Matcher objects can now be copied like
73 // plain values.
74
75 // MatchResultListener is an abstract class. Its << operator can be
76 // used by a matcher to explain why a value matches or doesn't match.
77 //
78 // TODO(wan@google.com): add method
79 // bool InterestedInWhy(bool result) const;
80 // to indicate whether the listener is interested in why the match
81 // result is 'result'.
82 class MatchResultListener {
83 public:
84 // Creates a listener object with the given underlying ostream. The
85 // listener does not own the ostream, and does not dereference it
86 // in the constructor or destructor.
MatchResultListener(::std::ostream * os)87 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
88 virtual ~MatchResultListener() = 0; // Makes this class abstract.
89
90 // Streams x to the underlying ostream; does nothing if the ostream
91 // is NULL.
92 template <typename T>
93 MatchResultListener& operator<<(const T& x) {
94 if (stream_ != NULL)
95 *stream_ << x;
96 return *this;
97 }
98
99 // Returns the underlying ostream.
stream()100 ::std::ostream* stream() { return stream_; }
101
102 // Returns true iff the listener is interested in an explanation of
103 // the match result. A matcher's MatchAndExplain() method can use
104 // this information to avoid generating the explanation when no one
105 // intends to hear it.
IsInterested()106 bool IsInterested() const { return stream_ != NULL; }
107
108 private:
109 ::std::ostream* const stream_;
110
111 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
112 };
113
~MatchResultListener()114 inline MatchResultListener::~MatchResultListener() {
115 }
116
117 // An instance of a subclass of this knows how to describe itself as a
118 // matcher.
119 class MatcherDescriberInterface {
120 public:
~MatcherDescriberInterface()121 virtual ~MatcherDescriberInterface() {}
122
123 // Describes this matcher to an ostream. The function should print
124 // a verb phrase that describes the property a value matching this
125 // matcher should have. The subject of the verb phrase is the value
126 // being matched. For example, the DescribeTo() method of the Gt(7)
127 // matcher prints "is greater than 7".
128 virtual void DescribeTo(::std::ostream* os) const = 0;
129
130 // Describes the negation of this matcher to an ostream. For
131 // example, if the description of this matcher is "is greater than
132 // 7", the negated description could be "is not greater than 7".
133 // You are not required to override this when implementing
134 // MatcherInterface, but it is highly advised so that your matcher
135 // can produce good error messages.
DescribeNegationTo(::std::ostream * os)136 virtual void DescribeNegationTo(::std::ostream* os) const {
137 *os << "not (";
138 DescribeTo(os);
139 *os << ")";
140 }
141 };
142
143 // The implementation of a matcher.
144 template <typename T>
145 class MatcherInterface : public MatcherDescriberInterface {
146 public:
147 // Returns true iff the matcher matches x; also explains the match
148 // result to 'listener' if necessary (see the next paragraph), in
149 // the form of a non-restrictive relative clause ("which ...",
150 // "whose ...", etc) that describes x. For example, the
151 // MatchAndExplain() method of the Pointee(...) matcher should
152 // generate an explanation like "which points to ...".
153 //
154 // Implementations of MatchAndExplain() should add an explanation of
155 // the match result *if and only if* they can provide additional
156 // information that's not already present (or not obvious) in the
157 // print-out of x and the matcher's description. Whether the match
158 // succeeds is not a factor in deciding whether an explanation is
159 // needed, as sometimes the caller needs to print a failure message
160 // when the match succeeds (e.g. when the matcher is used inside
161 // Not()).
162 //
163 // For example, a "has at least 10 elements" matcher should explain
164 // what the actual element count is, regardless of the match result,
165 // as it is useful information to the reader; on the other hand, an
166 // "is empty" matcher probably only needs to explain what the actual
167 // size is when the match fails, as it's redundant to say that the
168 // size is 0 when the value is already known to be empty.
169 //
170 // You should override this method when defining a new matcher.
171 //
172 // It's the responsibility of the caller (Google Mock) to guarantee
173 // that 'listener' is not NULL. This helps to simplify a matcher's
174 // implementation when it doesn't care about the performance, as it
175 // can talk to 'listener' without checking its validity first.
176 // However, in order to implement dummy listeners efficiently,
177 // listener->stream() may be NULL.
178 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
179
180 // Inherits these methods from MatcherDescriberInterface:
181 // virtual void DescribeTo(::std::ostream* os) const = 0;
182 // virtual void DescribeNegationTo(::std::ostream* os) const;
183 };
184
185 // A match result listener that stores the explanation in a string.
186 class StringMatchResultListener : public MatchResultListener {
187 public:
StringMatchResultListener()188 StringMatchResultListener() : MatchResultListener(&ss_) {}
189
190 // Returns the explanation accumulated so far.
str()191 internal::string str() const { return ss_.str(); }
192
193 // Clears the explanation accumulated so far.
Clear()194 void Clear() { ss_.str(""); }
195
196 private:
197 ::std::stringstream ss_;
198
199 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
200 };
201
202 namespace internal {
203
204 struct AnyEq {
205 template <typename A, typename B>
operatorAnyEq206 bool operator()(const A& a, const B& b) const { return a == b; }
207 };
208 struct AnyNe {
209 template <typename A, typename B>
operatorAnyNe210 bool operator()(const A& a, const B& b) const { return a != b; }
211 };
212 struct AnyLt {
213 template <typename A, typename B>
operatorAnyLt214 bool operator()(const A& a, const B& b) const { return a < b; }
215 };
216 struct AnyGt {
217 template <typename A, typename B>
operatorAnyGt218 bool operator()(const A& a, const B& b) const { return a > b; }
219 };
220 struct AnyLe {
221 template <typename A, typename B>
operatorAnyLe222 bool operator()(const A& a, const B& b) const { return a <= b; }
223 };
224 struct AnyGe {
225 template <typename A, typename B>
operatorAnyGe226 bool operator()(const A& a, const B& b) const { return a >= b; }
227 };
228
229 // A match result listener that ignores the explanation.
230 class DummyMatchResultListener : public MatchResultListener {
231 public:
DummyMatchResultListener()232 DummyMatchResultListener() : MatchResultListener(NULL) {}
233
234 private:
235 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
236 };
237
238 // A match result listener that forwards the explanation to a given
239 // ostream. The difference between this and MatchResultListener is
240 // that the former is concrete.
241 class StreamMatchResultListener : public MatchResultListener {
242 public:
StreamMatchResultListener(::std::ostream * os)243 explicit StreamMatchResultListener(::std::ostream* os)
244 : MatchResultListener(os) {}
245
246 private:
247 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
248 };
249
250 // An internal class for implementing Matcher<T>, which will derive
251 // from it. We put functionalities common to all Matcher<T>
252 // specializations here to avoid code duplication.
253 template <typename T>
254 class MatcherBase {
255 public:
256 // Returns true iff the matcher matches x; also explains the match
257 // result to 'listener'.
MatchAndExplain(T x,MatchResultListener * listener)258 bool MatchAndExplain(T x, MatchResultListener* listener) const {
259 return impl_->MatchAndExplain(x, listener);
260 }
261
262 // Returns true iff this matcher matches x.
Matches(T x)263 bool Matches(T x) const {
264 DummyMatchResultListener dummy;
265 return MatchAndExplain(x, &dummy);
266 }
267
268 // Describes this matcher to an ostream.
DescribeTo(::std::ostream * os)269 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
270
271 // Describes the negation of this matcher to an ostream.
DescribeNegationTo(::std::ostream * os)272 void DescribeNegationTo(::std::ostream* os) const {
273 impl_->DescribeNegationTo(os);
274 }
275
276 // Explains why x matches, or doesn't match, the matcher.
ExplainMatchResultTo(T x,::std::ostream * os)277 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
278 StreamMatchResultListener listener(os);
279 MatchAndExplain(x, &listener);
280 }
281
282 // Returns the describer for this matcher object; retains ownership
283 // of the describer, which is only guaranteed to be alive when
284 // this matcher object is alive.
GetDescriber()285 const MatcherDescriberInterface* GetDescriber() const {
286 return impl_.get();
287 }
288
289 protected:
MatcherBase()290 MatcherBase() {}
291
292 // Constructs a matcher from its implementation.
MatcherBase(const MatcherInterface<T> * impl)293 explicit MatcherBase(const MatcherInterface<T>* impl)
294 : impl_(impl) {}
295
~MatcherBase()296 virtual ~MatcherBase() {}
297
298 private:
299 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
300 // interfaces. The former dynamically allocates a chunk of memory
301 // to hold the reference count, while the latter tracks all
302 // references using a circular linked list without allocating
303 // memory. It has been observed that linked_ptr performs better in
304 // typical scenarios. However, shared_ptr can out-perform
305 // linked_ptr when there are many more uses of the copy constructor
306 // than the default constructor.
307 //
308 // If performance becomes a problem, we should see if using
309 // shared_ptr helps.
310 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
311 };
312
313 } // namespace internal
314
315 // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
316 // object that can check whether a value of type T matches. The
317 // implementation of Matcher<T> is just a linked_ptr to const
318 // MatcherInterface<T>, so copying is fairly cheap. Don't inherit
319 // from Matcher!
320 template <typename T>
321 class Matcher : public internal::MatcherBase<T> {
322 public:
323 // Constructs a null matcher. Needed for storing Matcher objects in STL
324 // containers. A default-constructed matcher is not yet initialized. You
325 // cannot use it until a valid value has been assigned to it.
Matcher()326 explicit Matcher() {} // NOLINT
327
328 // Constructs a matcher from its implementation.
Matcher(const MatcherInterface<T> * impl)329 explicit Matcher(const MatcherInterface<T>* impl)
330 : internal::MatcherBase<T>(impl) {}
331
332 // Implicit constructor here allows people to write
333 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
334 Matcher(T value); // NOLINT
335 };
336
337 // The following two specializations allow the user to write str
338 // instead of Eq(str) and "foo" instead of Eq("foo") when a string
339 // matcher is expected.
340 template <>
341 class GTEST_API_ Matcher<const internal::string&>
342 : public internal::MatcherBase<const internal::string&> {
343 public:
Matcher()344 Matcher() {}
345
Matcher(const MatcherInterface<const internal::string &> * impl)346 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
347 : internal::MatcherBase<const internal::string&>(impl) {}
348
349 // Allows the user to write str instead of Eq(str) sometimes, where
350 // str is a string object.
351 Matcher(const internal::string& s); // NOLINT
352
353 // Allows the user to write "foo" instead of Eq("foo") sometimes.
354 Matcher(const char* s); // NOLINT
355 };
356
357 template <>
358 class GTEST_API_ Matcher<internal::string>
359 : public internal::MatcherBase<internal::string> {
360 public:
Matcher()361 Matcher() {}
362
Matcher(const MatcherInterface<internal::string> * impl)363 explicit Matcher(const MatcherInterface<internal::string>* impl)
364 : internal::MatcherBase<internal::string>(impl) {}
365
366 // Allows the user to write str instead of Eq(str) sometimes, where
367 // str is a string object.
368 Matcher(const internal::string& s); // NOLINT
369
370 // Allows the user to write "foo" instead of Eq("foo") sometimes.
371 Matcher(const char* s); // NOLINT
372 };
373
374 #if GTEST_HAS_STRING_PIECE_
375 // The following two specializations allow the user to write str
376 // instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece
377 // matcher is expected.
378 template <>
379 class GTEST_API_ Matcher<const StringPiece&>
380 : public internal::MatcherBase<const StringPiece&> {
381 public:
Matcher()382 Matcher() {}
383
Matcher(const MatcherInterface<const StringPiece &> * impl)384 explicit Matcher(const MatcherInterface<const StringPiece&>* impl)
385 : internal::MatcherBase<const StringPiece&>(impl) {}
386
387 // Allows the user to write str instead of Eq(str) sometimes, where
388 // str is a string object.
389 Matcher(const internal::string& s); // NOLINT
390
391 // Allows the user to write "foo" instead of Eq("foo") sometimes.
392 Matcher(const char* s); // NOLINT
393
394 // Allows the user to pass StringPieces directly.
395 Matcher(StringPiece s); // NOLINT
396 };
397
398 template <>
399 class GTEST_API_ Matcher<StringPiece>
400 : public internal::MatcherBase<StringPiece> {
401 public:
Matcher()402 Matcher() {}
403
Matcher(const MatcherInterface<StringPiece> * impl)404 explicit Matcher(const MatcherInterface<StringPiece>* impl)
405 : internal::MatcherBase<StringPiece>(impl) {}
406
407 // Allows the user to write str instead of Eq(str) sometimes, where
408 // str is a string object.
409 Matcher(const internal::string& s); // NOLINT
410
411 // Allows the user to write "foo" instead of Eq("foo") sometimes.
412 Matcher(const char* s); // NOLINT
413
414 // Allows the user to pass StringPieces directly.
415 Matcher(StringPiece s); // NOLINT
416 };
417 #endif // GTEST_HAS_STRING_PIECE_
418
419 // The PolymorphicMatcher class template makes it easy to implement a
420 // polymorphic matcher (i.e. a matcher that can match values of more
421 // than one type, e.g. Eq(n) and NotNull()).
422 //
423 // To define a polymorphic matcher, a user should provide an Impl
424 // class that has a DescribeTo() method and a DescribeNegationTo()
425 // method, and define a member function (or member function template)
426 //
427 // bool MatchAndExplain(const Value& value,
428 // MatchResultListener* listener) const;
429 //
430 // See the definition of NotNull() for a complete example.
431 template <class Impl>
432 class PolymorphicMatcher {
433 public:
PolymorphicMatcher(const Impl & an_impl)434 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
435
436 // Returns a mutable reference to the underlying matcher
437 // implementation object.
mutable_impl()438 Impl& mutable_impl() { return impl_; }
439
440 // Returns an immutable reference to the underlying matcher
441 // implementation object.
impl()442 const Impl& impl() const { return impl_; }
443
444 template <typename T>
445 operator Matcher<T>() const {
446 return Matcher<T>(new MonomorphicImpl<T>(impl_));
447 }
448
449 private:
450 template <typename T>
451 class MonomorphicImpl : public MatcherInterface<T> {
452 public:
MonomorphicImpl(const Impl & impl)453 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
454
DescribeTo(::std::ostream * os)455 virtual void DescribeTo(::std::ostream* os) const {
456 impl_.DescribeTo(os);
457 }
458
DescribeNegationTo(::std::ostream * os)459 virtual void DescribeNegationTo(::std::ostream* os) const {
460 impl_.DescribeNegationTo(os);
461 }
462
MatchAndExplain(T x,MatchResultListener * listener)463 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
464 return impl_.MatchAndExplain(x, listener);
465 }
466
467 private:
468 const Impl impl_;
469
470 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
471 };
472
473 Impl impl_;
474
475 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
476 };
477
478 // Creates a matcher from its implementation. This is easier to use
479 // than the Matcher<T> constructor as it doesn't require you to
480 // explicitly write the template argument, e.g.
481 //
482 // MakeMatcher(foo);
483 // vs
484 // Matcher<const string&>(foo);
485 template <typename T>
MakeMatcher(const MatcherInterface<T> * impl)486 inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
487 return Matcher<T>(impl);
488 }
489
490 // Creates a polymorphic matcher from its implementation. This is
491 // easier to use than the PolymorphicMatcher<Impl> constructor as it
492 // doesn't require you to explicitly write the template argument, e.g.
493 //
494 // MakePolymorphicMatcher(foo);
495 // vs
496 // PolymorphicMatcher<TypeOfFoo>(foo);
497 template <class Impl>
MakePolymorphicMatcher(const Impl & impl)498 inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
499 return PolymorphicMatcher<Impl>(impl);
500 }
501
502 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
503 // and MUST NOT BE USED IN USER CODE!!!
504 namespace internal {
505
506 // The MatcherCastImpl class template is a helper for implementing
507 // MatcherCast(). We need this helper in order to partially
508 // specialize the implementation of MatcherCast() (C++ allows
509 // class/struct templates to be partially specialized, but not
510 // function templates.).
511
512 // This general version is used when MatcherCast()'s argument is a
513 // polymorphic matcher (i.e. something that can be converted to a
514 // Matcher but is not one yet; for example, Eq(value)) or a value (for
515 // example, "hello").
516 template <typename T, typename M>
517 class MatcherCastImpl {
518 public:
Cast(const M & polymorphic_matcher_or_value)519 static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
520 // M can be a polymorhic matcher, in which case we want to use
521 // its conversion operator to create Matcher<T>. Or it can be a value
522 // that should be passed to the Matcher<T>'s constructor.
523 //
524 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
525 // polymorphic matcher because it'll be ambiguous if T has an implicit
526 // constructor from M (this usually happens when T has an implicit
527 // constructor from any type).
528 //
529 // It won't work to unconditionally implict_cast
530 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
531 // a user-defined conversion from M to T if one exists (assuming M is
532 // a value).
533 return CastImpl(
534 polymorphic_matcher_or_value,
535 BooleanConstant<
536 internal::ImplicitlyConvertible<M, Matcher<T> >::value>());
537 }
538
539 private:
CastImpl(const M & value,BooleanConstant<false>)540 static Matcher<T> CastImpl(const M& value, BooleanConstant<false>) {
541 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
542 // matcher. It must be a value then. Use direct initialization to create
543 // a matcher.
544 return Matcher<T>(ImplicitCast_<T>(value));
545 }
546
CastImpl(const M & polymorphic_matcher_or_value,BooleanConstant<true>)547 static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
548 BooleanConstant<true>) {
549 // M is implicitly convertible to Matcher<T>, which means that either
550 // M is a polymorhpic matcher or Matcher<T> has an implicit constructor
551 // from M. In both cases using the implicit conversion will produce a
552 // matcher.
553 //
554 // Even if T has an implicit constructor from M, it won't be called because
555 // creating Matcher<T> would require a chain of two user-defined conversions
556 // (first to create T from M and then to create Matcher<T> from T).
557 return polymorphic_matcher_or_value;
558 }
559 };
560
561 // This more specialized version is used when MatcherCast()'s argument
562 // is already a Matcher. This only compiles when type T can be
563 // statically converted to type U.
564 template <typename T, typename U>
565 class MatcherCastImpl<T, Matcher<U> > {
566 public:
Cast(const Matcher<U> & source_matcher)567 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
568 return Matcher<T>(new Impl(source_matcher));
569 }
570
571 private:
572 class Impl : public MatcherInterface<T> {
573 public:
Impl(const Matcher<U> & source_matcher)574 explicit Impl(const Matcher<U>& source_matcher)
575 : source_matcher_(source_matcher) {}
576
577 // We delegate the matching logic to the source matcher.
MatchAndExplain(T x,MatchResultListener * listener)578 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
579 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
580 }
581
DescribeTo(::std::ostream * os)582 virtual void DescribeTo(::std::ostream* os) const {
583 source_matcher_.DescribeTo(os);
584 }
585
DescribeNegationTo(::std::ostream * os)586 virtual void DescribeNegationTo(::std::ostream* os) const {
587 source_matcher_.DescribeNegationTo(os);
588 }
589
590 private:
591 const Matcher<U> source_matcher_;
592
593 GTEST_DISALLOW_ASSIGN_(Impl);
594 };
595 };
596
597 // This even more specialized version is used for efficiently casting
598 // a matcher to its own type.
599 template <typename T>
600 class MatcherCastImpl<T, Matcher<T> > {
601 public:
Cast(const Matcher<T> & matcher)602 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
603 };
604
605 } // namespace internal
606
607 // In order to be safe and clear, casting between different matcher
608 // types is done explicitly via MatcherCast<T>(m), which takes a
609 // matcher m and returns a Matcher<T>. It compiles only when T can be
610 // statically converted to the argument type of m.
611 template <typename T, typename M>
MatcherCast(const M & matcher)612 inline Matcher<T> MatcherCast(const M& matcher) {
613 return internal::MatcherCastImpl<T, M>::Cast(matcher);
614 }
615
616 // Implements SafeMatcherCast().
617 //
618 // We use an intermediate class to do the actual safe casting as Nokia's
619 // Symbian compiler cannot decide between
620 // template <T, M> ... (M) and
621 // template <T, U> ... (const Matcher<U>&)
622 // for function templates but can for member function templates.
623 template <typename T>
624 class SafeMatcherCastImpl {
625 public:
626 // This overload handles polymorphic matchers and values only since
627 // monomorphic matchers are handled by the next one.
628 template <typename M>
Cast(const M & polymorphic_matcher_or_value)629 static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
630 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
631 }
632
633 // This overload handles monomorphic matchers.
634 //
635 // In general, if type T can be implicitly converted to type U, we can
636 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
637 // contravariant): just keep a copy of the original Matcher<U>, convert the
638 // argument from type T to U, and then pass it to the underlying Matcher<U>.
639 // The only exception is when U is a reference and T is not, as the
640 // underlying Matcher<U> may be interested in the argument's address, which
641 // is not preserved in the conversion from T to U.
642 template <typename U>
Cast(const Matcher<U> & matcher)643 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
644 // Enforce that T can be implicitly converted to U.
645 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
646 T_must_be_implicitly_convertible_to_U);
647 // Enforce that we are not converting a non-reference type T to a reference
648 // type U.
649 GTEST_COMPILE_ASSERT_(
650 internal::is_reference<T>::value || !internal::is_reference<U>::value,
651 cannot_convert_non_referentce_arg_to_reference);
652 // In case both T and U are arithmetic types, enforce that the
653 // conversion is not lossy.
654 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
655 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
656 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
657 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
658 GTEST_COMPILE_ASSERT_(
659 kTIsOther || kUIsOther ||
660 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
661 conversion_of_arithmetic_types_must_be_lossless);
662 return MatcherCast<T>(matcher);
663 }
664 };
665
666 template <typename T, typename M>
SafeMatcherCast(const M & polymorphic_matcher)667 inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
668 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
669 }
670
671 // A<T>() returns a matcher that matches any value of type T.
672 template <typename T>
673 Matcher<T> A();
674
675 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
676 // and MUST NOT BE USED IN USER CODE!!!
677 namespace internal {
678
679 // If the explanation is not empty, prints it to the ostream.
PrintIfNotEmpty(const internal::string & explanation,::std::ostream * os)680 inline void PrintIfNotEmpty(const internal::string& explanation,
681 ::std::ostream* os) {
682 if (explanation != "" && os != NULL) {
683 *os << ", " << explanation;
684 }
685 }
686
687 // Returns true if the given type name is easy to read by a human.
688 // This is used to decide whether printing the type of a value might
689 // be helpful.
IsReadableTypeName(const string & type_name)690 inline bool IsReadableTypeName(const string& type_name) {
691 // We consider a type name readable if it's short or doesn't contain
692 // a template or function type.
693 return (type_name.length() <= 20 ||
694 type_name.find_first_of("<(") == string::npos);
695 }
696
697 // Matches the value against the given matcher, prints the value and explains
698 // the match result to the listener. Returns the match result.
699 // 'listener' must not be NULL.
700 // Value cannot be passed by const reference, because some matchers take a
701 // non-const argument.
702 template <typename Value, typename T>
MatchPrintAndExplain(Value & value,const Matcher<T> & matcher,MatchResultListener * listener)703 bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
704 MatchResultListener* listener) {
705 if (!listener->IsInterested()) {
706 // If the listener is not interested, we do not need to construct the
707 // inner explanation.
708 return matcher.Matches(value);
709 }
710
711 StringMatchResultListener inner_listener;
712 const bool match = matcher.MatchAndExplain(value, &inner_listener);
713
714 UniversalPrint(value, listener->stream());
715 #if GTEST_HAS_RTTI
716 const string& type_name = GetTypeName<Value>();
717 if (IsReadableTypeName(type_name))
718 *listener->stream() << " (of type " << type_name << ")";
719 #endif
720 PrintIfNotEmpty(inner_listener.str(), listener->stream());
721
722 return match;
723 }
724
725 // An internal helper class for doing compile-time loop on a tuple's
726 // fields.
727 template <size_t N>
728 class TuplePrefix {
729 public:
730 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
731 // iff the first N fields of matcher_tuple matches the first N
732 // fields of value_tuple, respectively.
733 template <typename MatcherTuple, typename ValueTuple>
Matches(const MatcherTuple & matcher_tuple,const ValueTuple & value_tuple)734 static bool Matches(const MatcherTuple& matcher_tuple,
735 const ValueTuple& value_tuple) {
736 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
737 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
738 }
739
740 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
741 // describes failures in matching the first N fields of matchers
742 // against the first N fields of values. If there is no failure,
743 // nothing will be streamed to os.
744 template <typename MatcherTuple, typename ValueTuple>
ExplainMatchFailuresTo(const MatcherTuple & matchers,const ValueTuple & values,::std::ostream * os)745 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
746 const ValueTuple& values,
747 ::std::ostream* os) {
748 // First, describes failures in the first N - 1 fields.
749 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
750
751 // Then describes the failure (if any) in the (N - 1)-th (0-based)
752 // field.
753 typename tuple_element<N - 1, MatcherTuple>::type matcher =
754 get<N - 1>(matchers);
755 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
756 Value value = get<N - 1>(values);
757 StringMatchResultListener listener;
758 if (!matcher.MatchAndExplain(value, &listener)) {
759 // TODO(wan): include in the message the name of the parameter
760 // as used in MOCK_METHOD*() when possible.
761 *os << " Expected arg #" << N - 1 << ": ";
762 get<N - 1>(matchers).DescribeTo(os);
763 *os << "\n Actual: ";
764 // We remove the reference in type Value to prevent the
765 // universal printer from printing the address of value, which
766 // isn't interesting to the user most of the time. The
767 // matcher's MatchAndExplain() method handles the case when
768 // the address is interesting.
769 internal::UniversalPrint(value, os);
770 PrintIfNotEmpty(listener.str(), os);
771 *os << "\n";
772 }
773 }
774 };
775
776 // The base case.
777 template <>
778 class TuplePrefix<0> {
779 public:
780 template <typename MatcherTuple, typename ValueTuple>
Matches(const MatcherTuple &,const ValueTuple &)781 static bool Matches(const MatcherTuple& /* matcher_tuple */,
782 const ValueTuple& /* value_tuple */) {
783 return true;
784 }
785
786 template <typename MatcherTuple, typename ValueTuple>
ExplainMatchFailuresTo(const MatcherTuple &,const ValueTuple &,::std::ostream *)787 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
788 const ValueTuple& /* values */,
789 ::std::ostream* /* os */) {}
790 };
791
792 // TupleMatches(matcher_tuple, value_tuple) returns true iff all
793 // matchers in matcher_tuple match the corresponding fields in
794 // value_tuple. It is a compiler error if matcher_tuple and
795 // value_tuple have different number of fields or incompatible field
796 // types.
797 template <typename MatcherTuple, typename ValueTuple>
TupleMatches(const MatcherTuple & matcher_tuple,const ValueTuple & value_tuple)798 bool TupleMatches(const MatcherTuple& matcher_tuple,
799 const ValueTuple& value_tuple) {
800 // Makes sure that matcher_tuple and value_tuple have the same
801 // number of fields.
802 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
803 tuple_size<ValueTuple>::value,
804 matcher_and_value_have_different_numbers_of_fields);
805 return TuplePrefix<tuple_size<ValueTuple>::value>::
806 Matches(matcher_tuple, value_tuple);
807 }
808
809 // Describes failures in matching matchers against values. If there
810 // is no failure, nothing will be streamed to os.
811 template <typename MatcherTuple, typename ValueTuple>
ExplainMatchFailureTupleTo(const MatcherTuple & matchers,const ValueTuple & values,::std::ostream * os)812 void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
813 const ValueTuple& values,
814 ::std::ostream* os) {
815 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
816 matchers, values, os);
817 }
818
819 // TransformTupleValues and its helper.
820 //
821 // TransformTupleValuesHelper hides the internal machinery that
822 // TransformTupleValues uses to implement a tuple traversal.
823 template <typename Tuple, typename Func, typename OutIter>
824 class TransformTupleValuesHelper {
825 private:
826 typedef ::testing::tuple_size<Tuple> TupleSize;
827
828 public:
829 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
830 // Returns the final value of 'out' in case the caller needs it.
Run(Func f,const Tuple & t,OutIter out)831 static OutIter Run(Func f, const Tuple& t, OutIter out) {
832 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
833 }
834
835 private:
836 template <typename Tup, size_t kRemainingSize>
837 struct IterateOverTuple {
operatorIterateOverTuple838 OutIter operator() (Func f, const Tup& t, OutIter out) const {
839 *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
840 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
841 }
842 };
843 template <typename Tup>
844 struct IterateOverTuple<Tup, 0> {
845 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
846 return out;
847 }
848 };
849 };
850
851 // Successively invokes 'f(element)' on each element of the tuple 't',
852 // appending each result to the 'out' iterator. Returns the final value
853 // of 'out'.
854 template <typename Tuple, typename Func, typename OutIter>
855 OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
856 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
857 }
858
859 // Implements A<T>().
860 template <typename T>
861 class AnyMatcherImpl : public MatcherInterface<T> {
862 public:
863 virtual bool MatchAndExplain(
864 T /* x */, MatchResultListener* /* listener */) const { return true; }
865 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
866 virtual void DescribeNegationTo(::std::ostream* os) const {
867 // This is mostly for completeness' safe, as it's not very useful
868 // to write Not(A<bool>()). However we cannot completely rule out
869 // such a possibility, and it doesn't hurt to be prepared.
870 *os << "never matches";
871 }
872 };
873
874 // Implements _, a matcher that matches any value of any
875 // type. This is a polymorphic matcher, so we need a template type
876 // conversion operator to make it appearing as a Matcher<T> for any
877 // type T.
878 class AnythingMatcher {
879 public:
880 template <typename T>
881 operator Matcher<T>() const { return A<T>(); }
882 };
883
884 // Implements a matcher that compares a given value with a
885 // pre-supplied value using one of the ==, <=, <, etc, operators. The
886 // two values being compared don't have to have the same type.
887 //
888 // The matcher defined here is polymorphic (for example, Eq(5) can be
889 // used to match an int, a short, a double, etc). Therefore we use
890 // a template type conversion operator in the implementation.
891 //
892 // The following template definition assumes that the Rhs parameter is
893 // a "bare" type (i.e. neither 'const T' nor 'T&').
894 template <typename D, typename Rhs, typename Op>
895 class ComparisonBase {
896 public:
897 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
898 template <typename Lhs>
899 operator Matcher<Lhs>() const {
900 return MakeMatcher(new Impl<Lhs>(rhs_));
901 }
902
903 private:
904 template <typename Lhs>
905 class Impl : public MatcherInterface<Lhs> {
906 public:
907 explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
908 virtual bool MatchAndExplain(
909 Lhs lhs, MatchResultListener* /* listener */) const {
910 return Op()(lhs, rhs_);
911 }
912 virtual void DescribeTo(::std::ostream* os) const {
913 *os << D::Desc() << " ";
914 UniversalPrint(rhs_, os);
915 }
916 virtual void DescribeNegationTo(::std::ostream* os) const {
917 *os << D::NegatedDesc() << " ";
918 UniversalPrint(rhs_, os);
919 }
920 private:
921 Rhs rhs_;
922 GTEST_DISALLOW_ASSIGN_(Impl);
923 };
924 Rhs rhs_;
925 GTEST_DISALLOW_ASSIGN_(ComparisonBase);
926 };
927
928 template <typename Rhs>
929 class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
930 public:
931 explicit EqMatcher(const Rhs& rhs)
932 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
933 static const char* Desc() { return "is equal to"; }
934 static const char* NegatedDesc() { return "isn't equal to"; }
935 };
936 template <typename Rhs>
937 class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
938 public:
939 explicit NeMatcher(const Rhs& rhs)
940 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
941 static const char* Desc() { return "isn't equal to"; }
942 static const char* NegatedDesc() { return "is equal to"; }
943 };
944 template <typename Rhs>
945 class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
946 public:
947 explicit LtMatcher(const Rhs& rhs)
948 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
949 static const char* Desc() { return "is <"; }
950 static const char* NegatedDesc() { return "isn't <"; }
951 };
952 template <typename Rhs>
953 class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
954 public:
955 explicit GtMatcher(const Rhs& rhs)
956 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
957 static const char* Desc() { return "is >"; }
958 static const char* NegatedDesc() { return "isn't >"; }
959 };
960 template <typename Rhs>
961 class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
962 public:
963 explicit LeMatcher(const Rhs& rhs)
964 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
965 static const char* Desc() { return "is <="; }
966 static const char* NegatedDesc() { return "isn't <="; }
967 };
968 template <typename Rhs>
969 class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
970 public:
971 explicit GeMatcher(const Rhs& rhs)
972 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
973 static const char* Desc() { return "is >="; }
974 static const char* NegatedDesc() { return "isn't >="; }
975 };
976
977 // Implements the polymorphic IsNull() matcher, which matches any raw or smart
978 // pointer that is NULL.
979 class IsNullMatcher {
980 public:
981 template <typename Pointer>
982 bool MatchAndExplain(const Pointer& p,
983 MatchResultListener* /* listener */) const {
984 #if GTEST_LANG_CXX11
985 return p == nullptr;
986 #else // GTEST_LANG_CXX11
987 return GetRawPointer(p) == NULL;
988 #endif // GTEST_LANG_CXX11
989 }
990
991 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
992 void DescribeNegationTo(::std::ostream* os) const {
993 *os << "isn't NULL";
994 }
995 };
996
997 // Implements the polymorphic NotNull() matcher, which matches any raw or smart
998 // pointer that is not NULL.
999 class NotNullMatcher {
1000 public:
1001 template <typename Pointer>
1002 bool MatchAndExplain(const Pointer& p,
1003 MatchResultListener* /* listener */) const {
1004 #if GTEST_LANG_CXX11
1005 return p != nullptr;
1006 #else // GTEST_LANG_CXX11
1007 return GetRawPointer(p) != NULL;
1008 #endif // GTEST_LANG_CXX11
1009 }
1010
1011 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
1012 void DescribeNegationTo(::std::ostream* os) const {
1013 *os << "is NULL";
1014 }
1015 };
1016
1017 // Ref(variable) matches any argument that is a reference to
1018 // 'variable'. This matcher is polymorphic as it can match any
1019 // super type of the type of 'variable'.
1020 //
1021 // The RefMatcher template class implements Ref(variable). It can
1022 // only be instantiated with a reference type. This prevents a user
1023 // from mistakenly using Ref(x) to match a non-reference function
1024 // argument. For example, the following will righteously cause a
1025 // compiler error:
1026 //
1027 // int n;
1028 // Matcher<int> m1 = Ref(n); // This won't compile.
1029 // Matcher<int&> m2 = Ref(n); // This will compile.
1030 template <typename T>
1031 class RefMatcher;
1032
1033 template <typename T>
1034 class RefMatcher<T&> {
1035 // Google Mock is a generic framework and thus needs to support
1036 // mocking any function types, including those that take non-const
1037 // reference arguments. Therefore the template parameter T (and
1038 // Super below) can be instantiated to either a const type or a
1039 // non-const type.
1040 public:
1041 // RefMatcher() takes a T& instead of const T&, as we want the
1042 // compiler to catch using Ref(const_value) as a matcher for a
1043 // non-const reference.
1044 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
1045
1046 template <typename Super>
1047 operator Matcher<Super&>() const {
1048 // By passing object_ (type T&) to Impl(), which expects a Super&,
1049 // we make sure that Super is a super type of T. In particular,
1050 // this catches using Ref(const_value) as a matcher for a
1051 // non-const reference, as you cannot implicitly convert a const
1052 // reference to a non-const reference.
1053 return MakeMatcher(new Impl<Super>(object_));
1054 }
1055
1056 private:
1057 template <typename Super>
1058 class Impl : public MatcherInterface<Super&> {
1059 public:
1060 explicit Impl(Super& x) : object_(x) {} // NOLINT
1061
1062 // MatchAndExplain() takes a Super& (as opposed to const Super&)
1063 // in order to match the interface MatcherInterface<Super&>.
1064 virtual bool MatchAndExplain(
1065 Super& x, MatchResultListener* listener) const {
1066 *listener << "which is located @" << static_cast<const void*>(&x);
1067 return &x == &object_;
1068 }
1069
1070 virtual void DescribeTo(::std::ostream* os) const {
1071 *os << "references the variable ";
1072 UniversalPrinter<Super&>::Print(object_, os);
1073 }
1074
1075 virtual void DescribeNegationTo(::std::ostream* os) const {
1076 *os << "does not reference the variable ";
1077 UniversalPrinter<Super&>::Print(object_, os);
1078 }
1079
1080 private:
1081 const Super& object_;
1082
1083 GTEST_DISALLOW_ASSIGN_(Impl);
1084 };
1085
1086 T& object_;
1087
1088 GTEST_DISALLOW_ASSIGN_(RefMatcher);
1089 };
1090
1091 // Polymorphic helper functions for narrow and wide string matchers.
1092 inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1093 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1094 }
1095
1096 inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1097 const wchar_t* rhs) {
1098 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1099 }
1100
1101 // String comparison for narrow or wide strings that can have embedded NUL
1102 // characters.
1103 template <typename StringType>
1104 bool CaseInsensitiveStringEquals(const StringType& s1,
1105 const StringType& s2) {
1106 // Are the heads equal?
1107 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1108 return false;
1109 }
1110
1111 // Skip the equal heads.
1112 const typename StringType::value_type nul = 0;
1113 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1114
1115 // Are we at the end of either s1 or s2?
1116 if (i1 == StringType::npos || i2 == StringType::npos) {
1117 return i1 == i2;
1118 }
1119
1120 // Are the tails equal?
1121 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1122 }
1123
1124 // String matchers.
1125
1126 // Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1127 template <typename StringType>
1128 class StrEqualityMatcher {
1129 public:
1130 StrEqualityMatcher(const StringType& str, bool expect_eq,
1131 bool case_sensitive)
1132 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1133
1134 // Accepts pointer types, particularly:
1135 // const char*
1136 // char*
1137 // const wchar_t*
1138 // wchar_t*
1139 template <typename CharType>
1140 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1141 if (s == NULL) {
1142 return !expect_eq_;
1143 }
1144 return MatchAndExplain(StringType(s), listener);
1145 }
1146
1147 // Matches anything that can convert to StringType.
1148 //
1149 // This is a template, not just a plain function with const StringType&,
1150 // because StringPiece has some interfering non-explicit constructors.
1151 template <typename MatcheeStringType>
1152 bool MatchAndExplain(const MatcheeStringType& s,
1153 MatchResultListener* /* listener */) const {
1154 const StringType& s2(s);
1155 const bool eq = case_sensitive_ ? s2 == string_ :
1156 CaseInsensitiveStringEquals(s2, string_);
1157 return expect_eq_ == eq;
1158 }
1159
1160 void DescribeTo(::std::ostream* os) const {
1161 DescribeToHelper(expect_eq_, os);
1162 }
1163
1164 void DescribeNegationTo(::std::ostream* os) const {
1165 DescribeToHelper(!expect_eq_, os);
1166 }
1167
1168 private:
1169 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
1170 *os << (expect_eq ? "is " : "isn't ");
1171 *os << "equal to ";
1172 if (!case_sensitive_) {
1173 *os << "(ignoring case) ";
1174 }
1175 UniversalPrint(string_, os);
1176 }
1177
1178 const StringType string_;
1179 const bool expect_eq_;
1180 const bool case_sensitive_;
1181
1182 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
1183 };
1184
1185 // Implements the polymorphic HasSubstr(substring) matcher, which
1186 // can be used as a Matcher<T> as long as T can be converted to a
1187 // string.
1188 template <typename StringType>
1189 class HasSubstrMatcher {
1190 public:
1191 explicit HasSubstrMatcher(const StringType& substring)
1192 : substring_(substring) {}
1193
1194 // Accepts pointer types, particularly:
1195 // const char*
1196 // char*
1197 // const wchar_t*
1198 // wchar_t*
1199 template <typename CharType>
1200 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1201 return s != NULL && MatchAndExplain(StringType(s), listener);
1202 }
1203
1204 // Matches anything that can convert to StringType.
1205 //
1206 // This is a template, not just a plain function with const StringType&,
1207 // because StringPiece has some interfering non-explicit constructors.
1208 template <typename MatcheeStringType>
1209 bool MatchAndExplain(const MatcheeStringType& s,
1210 MatchResultListener* /* listener */) const {
1211 const StringType& s2(s);
1212 return s2.find(substring_) != StringType::npos;
1213 }
1214
1215 // Describes what this matcher matches.
1216 void DescribeTo(::std::ostream* os) const {
1217 *os << "has substring ";
1218 UniversalPrint(substring_, os);
1219 }
1220
1221 void DescribeNegationTo(::std::ostream* os) const {
1222 *os << "has no substring ";
1223 UniversalPrint(substring_, os);
1224 }
1225
1226 private:
1227 const StringType substring_;
1228
1229 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
1230 };
1231
1232 // Implements the polymorphic StartsWith(substring) matcher, which
1233 // can be used as a Matcher<T> as long as T can be converted to a
1234 // string.
1235 template <typename StringType>
1236 class StartsWithMatcher {
1237 public:
1238 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1239 }
1240
1241 // Accepts pointer types, particularly:
1242 // const char*
1243 // char*
1244 // const wchar_t*
1245 // wchar_t*
1246 template <typename CharType>
1247 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1248 return s != NULL && MatchAndExplain(StringType(s), listener);
1249 }
1250
1251 // Matches anything that can convert to StringType.
1252 //
1253 // This is a template, not just a plain function with const StringType&,
1254 // because StringPiece has some interfering non-explicit constructors.
1255 template <typename MatcheeStringType>
1256 bool MatchAndExplain(const MatcheeStringType& s,
1257 MatchResultListener* /* listener */) const {
1258 const StringType& s2(s);
1259 return s2.length() >= prefix_.length() &&
1260 s2.substr(0, prefix_.length()) == prefix_;
1261 }
1262
1263 void DescribeTo(::std::ostream* os) const {
1264 *os << "starts with ";
1265 UniversalPrint(prefix_, os);
1266 }
1267
1268 void DescribeNegationTo(::std::ostream* os) const {
1269 *os << "doesn't start with ";
1270 UniversalPrint(prefix_, os);
1271 }
1272
1273 private:
1274 const StringType prefix_;
1275
1276 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
1277 };
1278
1279 // Implements the polymorphic EndsWith(substring) matcher, which
1280 // can be used as a Matcher<T> as long as T can be converted to a
1281 // string.
1282 template <typename StringType>
1283 class EndsWithMatcher {
1284 public:
1285 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1286
1287 // Accepts pointer types, particularly:
1288 // const char*
1289 // char*
1290 // const wchar_t*
1291 // wchar_t*
1292 template <typename CharType>
1293 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1294 return s != NULL && MatchAndExplain(StringType(s), listener);
1295 }
1296
1297 // Matches anything that can convert to StringType.
1298 //
1299 // This is a template, not just a plain function with const StringType&,
1300 // because StringPiece has some interfering non-explicit constructors.
1301 template <typename MatcheeStringType>
1302 bool MatchAndExplain(const MatcheeStringType& s,
1303 MatchResultListener* /* listener */) const {
1304 const StringType& s2(s);
1305 return s2.length() >= suffix_.length() &&
1306 s2.substr(s2.length() - suffix_.length()) == suffix_;
1307 }
1308
1309 void DescribeTo(::std::ostream* os) const {
1310 *os << "ends with ";
1311 UniversalPrint(suffix_, os);
1312 }
1313
1314 void DescribeNegationTo(::std::ostream* os) const {
1315 *os << "doesn't end with ";
1316 UniversalPrint(suffix_, os);
1317 }
1318
1319 private:
1320 const StringType suffix_;
1321
1322 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
1323 };
1324
1325 // Implements polymorphic matchers MatchesRegex(regex) and
1326 // ContainsRegex(regex), which can be used as a Matcher<T> as long as
1327 // T can be converted to a string.
1328 class MatchesRegexMatcher {
1329 public:
1330 MatchesRegexMatcher(const RE* regex, bool full_match)
1331 : regex_(regex), full_match_(full_match) {}
1332
1333 // Accepts pointer types, particularly:
1334 // const char*
1335 // char*
1336 // const wchar_t*
1337 // wchar_t*
1338 template <typename CharType>
1339 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1340 return s != NULL && MatchAndExplain(internal::string(s), listener);
1341 }
1342
1343 // Matches anything that can convert to internal::string.
1344 //
1345 // This is a template, not just a plain function with const internal::string&,
1346 // because StringPiece has some interfering non-explicit constructors.
1347 template <class MatcheeStringType>
1348 bool MatchAndExplain(const MatcheeStringType& s,
1349 MatchResultListener* /* listener */) const {
1350 const internal::string& s2(s);
1351 return full_match_ ? RE::FullMatch(s2, *regex_) :
1352 RE::PartialMatch(s2, *regex_);
1353 }
1354
1355 void DescribeTo(::std::ostream* os) const {
1356 *os << (full_match_ ? "matches" : "contains")
1357 << " regular expression ";
1358 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1359 }
1360
1361 void DescribeNegationTo(::std::ostream* os) const {
1362 *os << "doesn't " << (full_match_ ? "match" : "contain")
1363 << " regular expression ";
1364 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1365 }
1366
1367 private:
1368 const internal::linked_ptr<const RE> regex_;
1369 const bool full_match_;
1370
1371 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
1372 };
1373
1374 // Implements a matcher that compares the two fields of a 2-tuple
1375 // using one of the ==, <=, <, etc, operators. The two fields being
1376 // compared don't have to have the same type.
1377 //
1378 // The matcher defined here is polymorphic (for example, Eq() can be
1379 // used to match a tuple<int, short>, a tuple<const long&, double>,
1380 // etc). Therefore we use a template type conversion operator in the
1381 // implementation.
1382 template <typename D, typename Op>
1383 class PairMatchBase {
1384 public:
1385 template <typename T1, typename T2>
1386 operator Matcher< ::testing::tuple<T1, T2> >() const {
1387 return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >);
1388 }
1389 template <typename T1, typename T2>
1390 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
1391 return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>);
1392 }
1393
1394 private:
1395 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
1396 return os << D::Desc();
1397 }
1398
1399 template <typename Tuple>
1400 class Impl : public MatcherInterface<Tuple> {
1401 public:
1402 virtual bool MatchAndExplain(
1403 Tuple args,
1404 MatchResultListener* /* listener */) const {
1405 return Op()(::testing::get<0>(args), ::testing::get<1>(args));
1406 }
1407 virtual void DescribeTo(::std::ostream* os) const {
1408 *os << "are " << GetDesc;
1409 }
1410 virtual void DescribeNegationTo(::std::ostream* os) const {
1411 *os << "aren't " << GetDesc;
1412 }
1413 };
1414 };
1415
1416 class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
1417 public:
1418 static const char* Desc() { return "an equal pair"; }
1419 };
1420 class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
1421 public:
1422 static const char* Desc() { return "an unequal pair"; }
1423 };
1424 class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
1425 public:
1426 static const char* Desc() { return "a pair where the first < the second"; }
1427 };
1428 class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
1429 public:
1430 static const char* Desc() { return "a pair where the first > the second"; }
1431 };
1432 class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
1433 public:
1434 static const char* Desc() { return "a pair where the first <= the second"; }
1435 };
1436 class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
1437 public:
1438 static const char* Desc() { return "a pair where the first >= the second"; }
1439 };
1440
1441 // Implements the Not(...) matcher for a particular argument type T.
1442 // We do not nest it inside the NotMatcher class template, as that
1443 // will prevent different instantiations of NotMatcher from sharing
1444 // the same NotMatcherImpl<T> class.
1445 template <typename T>
1446 class NotMatcherImpl : public MatcherInterface<T> {
1447 public:
1448 explicit NotMatcherImpl(const Matcher<T>& matcher)
1449 : matcher_(matcher) {}
1450
1451 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1452 return !matcher_.MatchAndExplain(x, listener);
1453 }
1454
1455 virtual void DescribeTo(::std::ostream* os) const {
1456 matcher_.DescribeNegationTo(os);
1457 }
1458
1459 virtual void DescribeNegationTo(::std::ostream* os) const {
1460 matcher_.DescribeTo(os);
1461 }
1462
1463 private:
1464 const Matcher<T> matcher_;
1465
1466 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
1467 };
1468
1469 // Implements the Not(m) matcher, which matches a value that doesn't
1470 // match matcher m.
1471 template <typename InnerMatcher>
1472 class NotMatcher {
1473 public:
1474 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1475
1476 // This template type conversion operator allows Not(m) to be used
1477 // to match any type m can match.
1478 template <typename T>
1479 operator Matcher<T>() const {
1480 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
1481 }
1482
1483 private:
1484 InnerMatcher matcher_;
1485
1486 GTEST_DISALLOW_ASSIGN_(NotMatcher);
1487 };
1488
1489 // Implements the AllOf(m1, m2) matcher for a particular argument type
1490 // T. We do not nest it inside the BothOfMatcher class template, as
1491 // that will prevent different instantiations of BothOfMatcher from
1492 // sharing the same BothOfMatcherImpl<T> class.
1493 template <typename T>
1494 class BothOfMatcherImpl : public MatcherInterface<T> {
1495 public:
1496 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1497 : matcher1_(matcher1), matcher2_(matcher2) {}
1498
1499 virtual void DescribeTo(::std::ostream* os) const {
1500 *os << "(";
1501 matcher1_.DescribeTo(os);
1502 *os << ") and (";
1503 matcher2_.DescribeTo(os);
1504 *os << ")";
1505 }
1506
1507 virtual void DescribeNegationTo(::std::ostream* os) const {
1508 *os << "(";
1509 matcher1_.DescribeNegationTo(os);
1510 *os << ") or (";
1511 matcher2_.DescribeNegationTo(os);
1512 *os << ")";
1513 }
1514
1515 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1516 // If either matcher1_ or matcher2_ doesn't match x, we only need
1517 // to explain why one of them fails.
1518 StringMatchResultListener listener1;
1519 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1520 *listener << listener1.str();
1521 return false;
1522 }
1523
1524 StringMatchResultListener listener2;
1525 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1526 *listener << listener2.str();
1527 return false;
1528 }
1529
1530 // Otherwise we need to explain why *both* of them match.
1531 const internal::string s1 = listener1.str();
1532 const internal::string s2 = listener2.str();
1533
1534 if (s1 == "") {
1535 *listener << s2;
1536 } else {
1537 *listener << s1;
1538 if (s2 != "") {
1539 *listener << ", and " << s2;
1540 }
1541 }
1542 return true;
1543 }
1544
1545 private:
1546 const Matcher<T> matcher1_;
1547 const Matcher<T> matcher2_;
1548
1549 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
1550 };
1551
1552 #if GTEST_LANG_CXX11
1553 // MatcherList provides mechanisms for storing a variable number of matchers in
1554 // a list structure (ListType) and creating a combining matcher from such a
1555 // list.
1556 // The template is defined recursively using the following template paramters:
1557 // * kSize is the length of the MatcherList.
1558 // * Head is the type of the first matcher of the list.
1559 // * Tail denotes the types of the remaining matchers of the list.
1560 template <int kSize, typename Head, typename... Tail>
1561 struct MatcherList {
1562 typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
1563 typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
1564
1565 // BuildList stores variadic type values in a nested pair structure.
1566 // Example:
1567 // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
1568 // the corresponding result of type pair<int, pair<string, float>>.
1569 static ListType BuildList(const Head& matcher, const Tail&... tail) {
1570 return ListType(matcher, MatcherListTail::BuildList(tail...));
1571 }
1572
1573 // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
1574 // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
1575 // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
1576 // constructor taking two Matcher<T>s as input.
1577 template <typename T, template <typename /* T */> class CombiningMatcher>
1578 static Matcher<T> CreateMatcher(const ListType& matchers) {
1579 return Matcher<T>(new CombiningMatcher<T>(
1580 SafeMatcherCast<T>(matchers.first),
1581 MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
1582 matchers.second)));
1583 }
1584 };
1585
1586 // The following defines the base case for the recursive definition of
1587 // MatcherList.
1588 template <typename Matcher1, typename Matcher2>
1589 struct MatcherList<2, Matcher1, Matcher2> {
1590 typedef ::std::pair<Matcher1, Matcher2> ListType;
1591
1592 static ListType BuildList(const Matcher1& matcher1,
1593 const Matcher2& matcher2) {
1594 return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
1595 }
1596
1597 template <typename T, template <typename /* T */> class CombiningMatcher>
1598 static Matcher<T> CreateMatcher(const ListType& matchers) {
1599 return Matcher<T>(new CombiningMatcher<T>(
1600 SafeMatcherCast<T>(matchers.first),
1601 SafeMatcherCast<T>(matchers.second)));
1602 }
1603 };
1604
1605 // VariadicMatcher is used for the variadic implementation of
1606 // AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1607 // CombiningMatcher<T> is used to recursively combine the provided matchers
1608 // (of type Args...).
1609 template <template <typename T> class CombiningMatcher, typename... Args>
1610 class VariadicMatcher {
1611 public:
1612 VariadicMatcher(const Args&... matchers) // NOLINT
1613 : matchers_(MatcherListType::BuildList(matchers...)) {}
1614
1615 // This template type conversion operator allows an
1616 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1617 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1618 template <typename T>
1619 operator Matcher<T>() const {
1620 return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
1621 matchers_);
1622 }
1623
1624 private:
1625 typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
1626
1627 const typename MatcherListType::ListType matchers_;
1628
1629 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1630 };
1631
1632 template <typename... Args>
1633 using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
1634
1635 #endif // GTEST_LANG_CXX11
1636
1637 // Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1638 // matches a value that matches all of the matchers m_1, ..., and m_n.
1639 template <typename Matcher1, typename Matcher2>
1640 class BothOfMatcher {
1641 public:
1642 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1643 : matcher1_(matcher1), matcher2_(matcher2) {}
1644
1645 // This template type conversion operator allows a
1646 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1647 // both Matcher1 and Matcher2 can match.
1648 template <typename T>
1649 operator Matcher<T>() const {
1650 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1651 SafeMatcherCast<T>(matcher2_)));
1652 }
1653
1654 private:
1655 Matcher1 matcher1_;
1656 Matcher2 matcher2_;
1657
1658 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
1659 };
1660
1661 // Implements the AnyOf(m1, m2) matcher for a particular argument type
1662 // T. We do not nest it inside the AnyOfMatcher class template, as
1663 // that will prevent different instantiations of AnyOfMatcher from
1664 // sharing the same EitherOfMatcherImpl<T> class.
1665 template <typename T>
1666 class EitherOfMatcherImpl : public MatcherInterface<T> {
1667 public:
1668 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1669 : matcher1_(matcher1), matcher2_(matcher2) {}
1670
1671 virtual void DescribeTo(::std::ostream* os) const {
1672 *os << "(";
1673 matcher1_.DescribeTo(os);
1674 *os << ") or (";
1675 matcher2_.DescribeTo(os);
1676 *os << ")";
1677 }
1678
1679 virtual void DescribeNegationTo(::std::ostream* os) const {
1680 *os << "(";
1681 matcher1_.DescribeNegationTo(os);
1682 *os << ") and (";
1683 matcher2_.DescribeNegationTo(os);
1684 *os << ")";
1685 }
1686
1687 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1688 // If either matcher1_ or matcher2_ matches x, we just need to
1689 // explain why *one* of them matches.
1690 StringMatchResultListener listener1;
1691 if (matcher1_.MatchAndExplain(x, &listener1)) {
1692 *listener << listener1.str();
1693 return true;
1694 }
1695
1696 StringMatchResultListener listener2;
1697 if (matcher2_.MatchAndExplain(x, &listener2)) {
1698 *listener << listener2.str();
1699 return true;
1700 }
1701
1702 // Otherwise we need to explain why *both* of them fail.
1703 const internal::string s1 = listener1.str();
1704 const internal::string s2 = listener2.str();
1705
1706 if (s1 == "") {
1707 *listener << s2;
1708 } else {
1709 *listener << s1;
1710 if (s2 != "") {
1711 *listener << ", and " << s2;
1712 }
1713 }
1714 return false;
1715 }
1716
1717 private:
1718 const Matcher<T> matcher1_;
1719 const Matcher<T> matcher2_;
1720
1721 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
1722 };
1723
1724 #if GTEST_LANG_CXX11
1725 // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1726 template <typename... Args>
1727 using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
1728
1729 #endif // GTEST_LANG_CXX11
1730
1731 // Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1732 // matches a value that matches at least one of the matchers m_1, ...,
1733 // and m_n.
1734 template <typename Matcher1, typename Matcher2>
1735 class EitherOfMatcher {
1736 public:
1737 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1738 : matcher1_(matcher1), matcher2_(matcher2) {}
1739
1740 // This template type conversion operator allows a
1741 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1742 // both Matcher1 and Matcher2 can match.
1743 template <typename T>
1744 operator Matcher<T>() const {
1745 return Matcher<T>(new EitherOfMatcherImpl<T>(
1746 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
1747 }
1748
1749 private:
1750 Matcher1 matcher1_;
1751 Matcher2 matcher2_;
1752
1753 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
1754 };
1755
1756 // Used for implementing Truly(pred), which turns a predicate into a
1757 // matcher.
1758 template <typename Predicate>
1759 class TrulyMatcher {
1760 public:
1761 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1762
1763 // This method template allows Truly(pred) to be used as a matcher
1764 // for type T where T is the argument type of predicate 'pred'. The
1765 // argument is passed by reference as the predicate may be
1766 // interested in the address of the argument.
1767 template <typename T>
1768 bool MatchAndExplain(T& x, // NOLINT
1769 MatchResultListener* /* listener */) const {
1770 // Without the if-statement, MSVC sometimes warns about converting
1771 // a value to bool (warning 4800).
1772 //
1773 // We cannot write 'return !!predicate_(x);' as that doesn't work
1774 // when predicate_(x) returns a class convertible to bool but
1775 // having no operator!().
1776 if (predicate_(x))
1777 return true;
1778 return false;
1779 }
1780
1781 void DescribeTo(::std::ostream* os) const {
1782 *os << "satisfies the given predicate";
1783 }
1784
1785 void DescribeNegationTo(::std::ostream* os) const {
1786 *os << "doesn't satisfy the given predicate";
1787 }
1788
1789 private:
1790 Predicate predicate_;
1791
1792 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
1793 };
1794
1795 // Used for implementing Matches(matcher), which turns a matcher into
1796 // a predicate.
1797 template <typename M>
1798 class MatcherAsPredicate {
1799 public:
1800 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1801
1802 // This template operator() allows Matches(m) to be used as a
1803 // predicate on type T where m is a matcher on type T.
1804 //
1805 // The argument x is passed by reference instead of by value, as
1806 // some matcher may be interested in its address (e.g. as in
1807 // Matches(Ref(n))(x)).
1808 template <typename T>
1809 bool operator()(const T& x) const {
1810 // We let matcher_ commit to a particular type here instead of
1811 // when the MatcherAsPredicate object was constructed. This
1812 // allows us to write Matches(m) where m is a polymorphic matcher
1813 // (e.g. Eq(5)).
1814 //
1815 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1816 // compile when matcher_ has type Matcher<const T&>; if we write
1817 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1818 // when matcher_ has type Matcher<T>; if we just write
1819 // matcher_.Matches(x), it won't compile when matcher_ is
1820 // polymorphic, e.g. Eq(5).
1821 //
1822 // MatcherCast<const T&>() is necessary for making the code work
1823 // in all of the above situations.
1824 return MatcherCast<const T&>(matcher_).Matches(x);
1825 }
1826
1827 private:
1828 M matcher_;
1829
1830 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
1831 };
1832
1833 // For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1834 // argument M must be a type that can be converted to a matcher.
1835 template <typename M>
1836 class PredicateFormatterFromMatcher {
1837 public:
1838 explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {}
1839
1840 // This template () operator allows a PredicateFormatterFromMatcher
1841 // object to act as a predicate-formatter suitable for using with
1842 // Google Test's EXPECT_PRED_FORMAT1() macro.
1843 template <typename T>
1844 AssertionResult operator()(const char* value_text, const T& x) const {
1845 // We convert matcher_ to a Matcher<const T&> *now* instead of
1846 // when the PredicateFormatterFromMatcher object was constructed,
1847 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1848 // know which type to instantiate it to until we actually see the
1849 // type of x here.
1850 //
1851 // We write SafeMatcherCast<const T&>(matcher_) instead of
1852 // Matcher<const T&>(matcher_), as the latter won't compile when
1853 // matcher_ has type Matcher<T> (e.g. An<int>()).
1854 // We don't write MatcherCast<const T&> either, as that allows
1855 // potentially unsafe downcasting of the matcher argument.
1856 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
1857 StringMatchResultListener listener;
1858 if (MatchPrintAndExplain(x, matcher, &listener))
1859 return AssertionSuccess();
1860
1861 ::std::stringstream ss;
1862 ss << "Value of: " << value_text << "\n"
1863 << "Expected: ";
1864 matcher.DescribeTo(&ss);
1865 ss << "\n Actual: " << listener.str();
1866 return AssertionFailure() << ss.str();
1867 }
1868
1869 private:
1870 const M matcher_;
1871
1872 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
1873 };
1874
1875 // A helper function for converting a matcher to a predicate-formatter
1876 // without the user needing to explicitly write the type. This is
1877 // used for implementing ASSERT_THAT() and EXPECT_THAT().
1878 // Implementation detail: 'matcher' is received by-value to force decaying.
1879 template <typename M>
1880 inline PredicateFormatterFromMatcher<M>
1881 MakePredicateFormatterFromMatcher(M matcher) {
1882 return PredicateFormatterFromMatcher<M>(internal::move(matcher));
1883 }
1884
1885 // Implements the polymorphic floating point equality matcher, which matches
1886 // two float values using ULP-based approximation or, optionally, a
1887 // user-specified epsilon. The template is meant to be instantiated with
1888 // FloatType being either float or double.
1889 template <typename FloatType>
1890 class FloatingEqMatcher {
1891 public:
1892 // Constructor for FloatingEqMatcher.
1893 // The matcher's input will be compared with expected. The matcher treats two
1894 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1895 // equality comparisons between NANs will always return false. We specify a
1896 // negative max_abs_error_ term to indicate that ULP-based approximation will
1897 // be used for comparison.
1898 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
1899 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
1900 }
1901
1902 // Constructor that supports a user-specified max_abs_error that will be used
1903 // for comparison instead of ULP-based approximation. The max absolute
1904 // should be non-negative.
1905 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
1906 FloatType max_abs_error)
1907 : expected_(expected),
1908 nan_eq_nan_(nan_eq_nan),
1909 max_abs_error_(max_abs_error) {
1910 GTEST_CHECK_(max_abs_error >= 0)
1911 << ", where max_abs_error is" << max_abs_error;
1912 }
1913
1914 // Implements floating point equality matcher as a Matcher<T>.
1915 template <typename T>
1916 class Impl : public MatcherInterface<T> {
1917 public:
1918 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
1919 : expected_(expected),
1920 nan_eq_nan_(nan_eq_nan),
1921 max_abs_error_(max_abs_error) {}
1922
1923 virtual bool MatchAndExplain(T value,
1924 MatchResultListener* listener) const {
1925 const FloatingPoint<FloatType> actual(value), expected(expected_);
1926
1927 // Compares NaNs first, if nan_eq_nan_ is true.
1928 if (actual.is_nan() || expected.is_nan()) {
1929 if (actual.is_nan() && expected.is_nan()) {
1930 return nan_eq_nan_;
1931 }
1932 // One is nan; the other is not nan.
1933 return false;
1934 }
1935 if (HasMaxAbsError()) {
1936 // We perform an equality check so that inf will match inf, regardless
1937 // of error bounds. If the result of value - expected_ would result in
1938 // overflow or if either value is inf, the default result is infinity,
1939 // which should only match if max_abs_error_ is also infinity.
1940 if (value == expected_) {
1941 return true;
1942 }
1943
1944 const FloatType diff = value - expected_;
1945 if (fabs(diff) <= max_abs_error_) {
1946 return true;
1947 }
1948
1949 if (listener->IsInterested()) {
1950 *listener << "which is " << diff << " from " << expected_;
1951 }
1952 return false;
1953 } else {
1954 return actual.AlmostEquals(expected);
1955 }
1956 }
1957
1958 virtual void DescribeTo(::std::ostream* os) const {
1959 // os->precision() returns the previously set precision, which we
1960 // store to restore the ostream to its original configuration
1961 // after outputting.
1962 const ::std::streamsize old_precision = os->precision(
1963 ::std::numeric_limits<FloatType>::digits10 + 2);
1964 if (FloatingPoint<FloatType>(expected_).is_nan()) {
1965 if (nan_eq_nan_) {
1966 *os << "is NaN";
1967 } else {
1968 *os << "never matches";
1969 }
1970 } else {
1971 *os << "is approximately " << expected_;
1972 if (HasMaxAbsError()) {
1973 *os << " (absolute error <= " << max_abs_error_ << ")";
1974 }
1975 }
1976 os->precision(old_precision);
1977 }
1978
1979 virtual void DescribeNegationTo(::std::ostream* os) const {
1980 // As before, get original precision.
1981 const ::std::streamsize old_precision = os->precision(
1982 ::std::numeric_limits<FloatType>::digits10 + 2);
1983 if (FloatingPoint<FloatType>(expected_).is_nan()) {
1984 if (nan_eq_nan_) {
1985 *os << "isn't NaN";
1986 } else {
1987 *os << "is anything";
1988 }
1989 } else {
1990 *os << "isn't approximately " << expected_;
1991 if (HasMaxAbsError()) {
1992 *os << " (absolute error > " << max_abs_error_ << ")";
1993 }
1994 }
1995 // Restore original precision.
1996 os->precision(old_precision);
1997 }
1998
1999 private:
2000 bool HasMaxAbsError() const {
2001 return max_abs_error_ >= 0;
2002 }
2003
2004 const FloatType expected_;
2005 const bool nan_eq_nan_;
2006 // max_abs_error will be used for value comparison when >= 0.
2007 const FloatType max_abs_error_;
2008
2009 GTEST_DISALLOW_ASSIGN_(Impl);
2010 };
2011
2012 // The following 3 type conversion operators allow FloatEq(expected) and
2013 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
2014 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
2015 // (While Google's C++ coding style doesn't allow arguments passed
2016 // by non-const reference, we may see them in code not conforming to
2017 // the style. Therefore Google Mock needs to support them.)
2018 operator Matcher<FloatType>() const {
2019 return MakeMatcher(
2020 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
2021 }
2022
2023 operator Matcher<const FloatType&>() const {
2024 return MakeMatcher(
2025 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
2026 }
2027
2028 operator Matcher<FloatType&>() const {
2029 return MakeMatcher(
2030 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
2031 }
2032
2033 private:
2034 const FloatType expected_;
2035 const bool nan_eq_nan_;
2036 // max_abs_error will be used for value comparison when >= 0.
2037 const FloatType max_abs_error_;
2038
2039 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
2040 };
2041
2042 // Implements the Pointee(m) matcher for matching a pointer whose
2043 // pointee matches matcher m. The pointer can be either raw or smart.
2044 template <typename InnerMatcher>
2045 class PointeeMatcher {
2046 public:
2047 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
2048
2049 // This type conversion operator template allows Pointee(m) to be
2050 // used as a matcher for any pointer type whose pointee type is
2051 // compatible with the inner matcher, where type Pointer can be
2052 // either a raw pointer or a smart pointer.
2053 //
2054 // The reason we do this instead of relying on
2055 // MakePolymorphicMatcher() is that the latter is not flexible
2056 // enough for implementing the DescribeTo() method of Pointee().
2057 template <typename Pointer>
2058 operator Matcher<Pointer>() const {
2059 return MakeMatcher(new Impl<Pointer>(matcher_));
2060 }
2061
2062 private:
2063 // The monomorphic implementation that works for a particular pointer type.
2064 template <typename Pointer>
2065 class Impl : public MatcherInterface<Pointer> {
2066 public:
2067 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
2068 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
2069
2070 explicit Impl(const InnerMatcher& matcher)
2071 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
2072
2073 virtual void DescribeTo(::std::ostream* os) const {
2074 *os << "points to a value that ";
2075 matcher_.DescribeTo(os);
2076 }
2077
2078 virtual void DescribeNegationTo(::std::ostream* os) const {
2079 *os << "does not point to a value that ";
2080 matcher_.DescribeTo(os);
2081 }
2082
2083 virtual bool MatchAndExplain(Pointer pointer,
2084 MatchResultListener* listener) const {
2085 if (GetRawPointer(pointer) == NULL)
2086 return false;
2087
2088 *listener << "which points to ";
2089 return MatchPrintAndExplain(*pointer, matcher_, listener);
2090 }
2091
2092 private:
2093 const Matcher<const Pointee&> matcher_;
2094
2095 GTEST_DISALLOW_ASSIGN_(Impl);
2096 };
2097
2098 const InnerMatcher matcher_;
2099
2100 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
2101 };
2102
2103 // Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2104 // reference that matches inner_matcher when dynamic_cast<T> is applied.
2105 // The result of dynamic_cast<To> is forwarded to the inner matcher.
2106 // If To is a pointer and the cast fails, the inner matcher will receive NULL.
2107 // If To is a reference and the cast fails, this matcher returns false
2108 // immediately.
2109 template <typename To>
2110 class WhenDynamicCastToMatcherBase {
2111 public:
2112 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2113 : matcher_(matcher) {}
2114
2115 void DescribeTo(::std::ostream* os) const {
2116 GetCastTypeDescription(os);
2117 matcher_.DescribeTo(os);
2118 }
2119
2120 void DescribeNegationTo(::std::ostream* os) const {
2121 GetCastTypeDescription(os);
2122 matcher_.DescribeNegationTo(os);
2123 }
2124
2125 protected:
2126 const Matcher<To> matcher_;
2127
2128 static string GetToName() {
2129 #if GTEST_HAS_RTTI
2130 return GetTypeName<To>();
2131 #else // GTEST_HAS_RTTI
2132 return "the target type";
2133 #endif // GTEST_HAS_RTTI
2134 }
2135
2136 private:
2137 static void GetCastTypeDescription(::std::ostream* os) {
2138 *os << "when dynamic_cast to " << GetToName() << ", ";
2139 }
2140
2141 GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2142 };
2143
2144 // Primary template.
2145 // To is a pointer. Cast and forward the result.
2146 template <typename To>
2147 class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2148 public:
2149 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2150 : WhenDynamicCastToMatcherBase<To>(matcher) {}
2151
2152 template <typename From>
2153 bool MatchAndExplain(From from, MatchResultListener* listener) const {
2154 // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail?
2155 To to = dynamic_cast<To>(from);
2156 return MatchPrintAndExplain(to, this->matcher_, listener);
2157 }
2158 };
2159
2160 // Specialize for references.
2161 // In this case we return false if the dynamic_cast fails.
2162 template <typename To>
2163 class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2164 public:
2165 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2166 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2167
2168 template <typename From>
2169 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2170 // We don't want an std::bad_cast here, so do the cast with pointers.
2171 To* to = dynamic_cast<To*>(&from);
2172 if (to == NULL) {
2173 *listener << "which cannot be dynamic_cast to " << this->GetToName();
2174 return false;
2175 }
2176 return MatchPrintAndExplain(*to, this->matcher_, listener);
2177 }
2178 };
2179
2180 // Implements the Field() matcher for matching a field (i.e. member
2181 // variable) of an object.
2182 template <typename Class, typename FieldType>
2183 class FieldMatcher {
2184 public:
2185 FieldMatcher(FieldType Class::*field,
2186 const Matcher<const FieldType&>& matcher)
2187 : field_(field), matcher_(matcher) {}
2188
2189 void DescribeTo(::std::ostream* os) const {
2190 *os << "is an object whose given field ";
2191 matcher_.DescribeTo(os);
2192 }
2193
2194 void DescribeNegationTo(::std::ostream* os) const {
2195 *os << "is an object whose given field ";
2196 matcher_.DescribeNegationTo(os);
2197 }
2198
2199 template <typename T>
2200 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2201 return MatchAndExplainImpl(
2202 typename ::testing::internal::
2203 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
2204 value, listener);
2205 }
2206
2207 private:
2208 // The first argument of MatchAndExplainImpl() is needed to help
2209 // Symbian's C++ compiler choose which overload to use. Its type is
2210 // true_type iff the Field() matcher is used to match a pointer.
2211 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2212 MatchResultListener* listener) const {
2213 *listener << "whose given field is ";
2214 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
2215 }
2216
2217 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2218 MatchResultListener* listener) const {
2219 if (p == NULL)
2220 return false;
2221
2222 *listener << "which points to an object ";
2223 // Since *p has a field, it must be a class/struct/union type and
2224 // thus cannot be a pointer. Therefore we pass false_type() as
2225 // the first argument.
2226 return MatchAndExplainImpl(false_type(), *p, listener);
2227 }
2228
2229 const FieldType Class::*field_;
2230 const Matcher<const FieldType&> matcher_;
2231
2232 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
2233 };
2234
2235 // Implements the Property() matcher for matching a property
2236 // (i.e. return value of a getter method) of an object.
2237 template <typename Class, typename PropertyType>
2238 class PropertyMatcher {
2239 public:
2240 // The property may have a reference type, so 'const PropertyType&'
2241 // may cause double references and fail to compile. That's why we
2242 // need GTEST_REFERENCE_TO_CONST, which works regardless of
2243 // PropertyType being a reference or not.
2244 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
2245
2246 PropertyMatcher(PropertyType (Class::*property)() const,
2247 const Matcher<RefToConstProperty>& matcher)
2248 : property_(property), matcher_(matcher) {}
2249
2250 void DescribeTo(::std::ostream* os) const {
2251 *os << "is an object whose given property ";
2252 matcher_.DescribeTo(os);
2253 }
2254
2255 void DescribeNegationTo(::std::ostream* os) const {
2256 *os << "is an object whose given property ";
2257 matcher_.DescribeNegationTo(os);
2258 }
2259
2260 template <typename T>
2261 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2262 return MatchAndExplainImpl(
2263 typename ::testing::internal::
2264 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
2265 value, listener);
2266 }
2267
2268 private:
2269 // The first argument of MatchAndExplainImpl() is needed to help
2270 // 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.
2272 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2273 MatchResultListener* listener) const {
2274 *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.
2277 #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
2283 RefToConstProperty result = (obj.*property_)();
2284 return MatchPrintAndExplain(result, matcher_, listener);
2285 #endif
2286 }
2287
2288 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2289 MatchResultListener* listener) const {
2290 if (p == NULL)
2291 return false;
2292
2293 *listener << "which points to an object ";
2294 // 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.
2297 return MatchAndExplainImpl(false_type(), *p, listener);
2298 }
2299
2300 PropertyType (Class::*property_)() const;
2301 const Matcher<RefToConstProperty> matcher_;
2302
2303 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
2304 };
2305
2306 // 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.
2310 template <typename Functor>
2311 struct CallableTraits {
2312 typedef typename Functor::result_type ResultType;
2313 typedef Functor StorageType;
2314
2315 static void CheckIsValid(Functor /* functor */) {}
2316 template <typename T>
2317 static ResultType Invoke(Functor f, T arg) { return f(arg); }
2318 };
2319
2320 // Specialization for function pointers.
2321 template <typename ArgType, typename ResType>
2322 struct CallableTraits<ResType(*)(ArgType)> {
2323 typedef ResType ResultType;
2324 typedef ResType(*StorageType)(ArgType);
2325
2326 static void CheckIsValid(ResType(*f)(ArgType)) {
2327 GTEST_CHECK_(f != NULL)
2328 << "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.
2338 template <typename Callable>
2339 class 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) {}
2361
2362 virtual void DescribeTo(::std::ostream* os) const {
2363 *os << "is mapped by the given callable to a value that ";
2364 matcher_.DescribeTo(os);
2365 }
2366
2367 virtual void DescribeNegationTo(::std::ostream* os) const {
2368 *os << "is mapped by the given callable to a value that ";
2369 matcher_.DescribeNegationTo(os);
2370 }
2371
2372 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
2373 *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);
2379 }
2380
2381 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_;
2389
2390 GTEST_DISALLOW_ASSIGN_(Impl);
2391 }; // class Impl
2392
2393 const CallableStorageType callable_;
2394 const Matcher<ResultType> matcher_;
2395
2396 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
2397 };
2398
2399 // Implements a matcher that checks the size of an STL-style container.
2400 template <typename SizeMatcher>
2401 class 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
2451 // Implements a matcher that checks the begin()..end() distance of an STL-style
2452 // container.
2453 template <typename DistanceMatcher>
2454 class 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 GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
2468 typedef internal::StlContainerView<RawContainer> View;
2469 typedef typename View::type StlContainer;
2470 typedef typename View::const_reference StlContainerReference;
2471 typedef decltype(std::begin(
2472 std::declval<StlContainerReference>())) StlContainerConstIterator;
2473 typedef typename std::iterator_traits<
2474 StlContainerConstIterator>::difference_type DistanceType;
2475 explicit Impl(const DistanceMatcher& distance_matcher)
2476 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2477
2478 virtual void DescribeTo(::std::ostream* os) const {
2479 *os << "distance between begin() and end() ";
2480 distance_matcher_.DescribeTo(os);
2481 }
2482 virtual void DescribeNegationTo(::std::ostream* os) const {
2483 *os << "distance between begin() and end() ";
2484 distance_matcher_.DescribeNegationTo(os);
2485 }
2486
2487 virtual bool MatchAndExplain(Container container,
2488 MatchResultListener* listener) const {
2489 #if GTEST_HAS_STD_BEGIN_AND_END_
2490 using std::begin;
2491 using std::end;
2492 DistanceType distance = std::distance(begin(container), end(container));
2493 #else
2494 DistanceType distance = std::distance(container.begin(), container.end());
2495 #endif
2496 StringMatchResultListener distance_listener;
2497 const bool result =
2498 distance_matcher_.MatchAndExplain(distance, &distance_listener);
2499 *listener << "whose distance between begin() and end() " << distance
2500 << (result ? " matches" : " doesn't match");
2501 PrintIfNotEmpty(distance_listener.str(), listener->stream());
2502 return result;
2503 }
2504
2505 private:
2506 const Matcher<DistanceType> distance_matcher_;
2507 GTEST_DISALLOW_ASSIGN_(Impl);
2508 };
2509
2510 private:
2511 const DistanceMatcher distance_matcher_;
2512 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2513 };
2514
2515 // Implements an equality matcher for any STL-style container whose elements
2516 // support ==. This matcher is like Eq(), but its failure explanations provide
2517 // more detailed information that is useful when the container is used as a set.
2518 // The failure message reports elements that are in one of the operands but not
2519 // the other. The failure messages do not report duplicate or out-of-order
2520 // elements in the containers (which don't properly matter to sets, but can
2521 // occur if the containers are vectors or lists, for example).
2522 //
2523 // Uses the container's const_iterator, value_type, operator ==,
2524 // begin(), and end().
2525 template <typename Container>
2526 class ContainerEqMatcher {
2527 public:
2528 typedef internal::StlContainerView<Container> View;
2529 typedef typename View::type StlContainer;
2530 typedef typename View::const_reference StlContainerReference;
2531
2532 // We make a copy of expected in case the elements in it are modified
2533 // after this matcher is created.
2534 explicit ContainerEqMatcher(const Container& expected)
2535 : expected_(View::Copy(expected)) {
2536 // Makes sure the user doesn't instantiate this class template
2537 // with a const or reference type.
2538 (void)testing::StaticAssertTypeEq<Container,
2539 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
2540 }
2541
2542 void DescribeTo(::std::ostream* os) const {
2543 *os << "equals ";
2544 UniversalPrint(expected_, os);
2545 }
2546 void DescribeNegationTo(::std::ostream* os) const {
2547 *os << "does not equal ";
2548 UniversalPrint(expected_, os);
2549 }
2550
2551 template <typename LhsContainer>
2552 bool MatchAndExplain(const LhsContainer& lhs,
2553 MatchResultListener* listener) const {
2554 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
2555 // that causes LhsContainer to be a const type sometimes.
2556 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
2557 LhsView;
2558 typedef typename LhsView::type LhsStlContainer;
2559 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2560 if (lhs_stl_container == expected_)
2561 return true;
2562
2563 ::std::ostream* const os = listener->stream();
2564 if (os != NULL) {
2565 // Something is different. Check for extra values first.
2566 bool printed_header = false;
2567 for (typename LhsStlContainer::const_iterator it =
2568 lhs_stl_container.begin();
2569 it != lhs_stl_container.end(); ++it) {
2570 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
2571 expected_.end()) {
2572 if (printed_header) {
2573 *os << ", ";
2574 } else {
2575 *os << "which has these unexpected elements: ";
2576 printed_header = true;
2577 }
2578 UniversalPrint(*it, os);
2579 }
2580 }
2581
2582 // Now check for missing values.
2583 bool printed_header2 = false;
2584 for (typename StlContainer::const_iterator it = expected_.begin();
2585 it != expected_.end(); ++it) {
2586 if (internal::ArrayAwareFind(
2587 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2588 lhs_stl_container.end()) {
2589 if (printed_header2) {
2590 *os << ", ";
2591 } else {
2592 *os << (printed_header ? ",\nand" : "which")
2593 << " doesn't have these expected elements: ";
2594 printed_header2 = true;
2595 }
2596 UniversalPrint(*it, os);
2597 }
2598 }
2599 }
2600
2601 return false;
2602 }
2603
2604 private:
2605 const StlContainer expected_;
2606
2607 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
2608 };
2609
2610 // A comparator functor that uses the < operator to compare two values.
2611 struct LessComparator {
2612 template <typename T, typename U>
2613 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2614 };
2615
2616 // Implements WhenSortedBy(comparator, container_matcher).
2617 template <typename Comparator, typename ContainerMatcher>
2618 class WhenSortedByMatcher {
2619 public:
2620 WhenSortedByMatcher(const Comparator& comparator,
2621 const ContainerMatcher& matcher)
2622 : comparator_(comparator), matcher_(matcher) {}
2623
2624 template <typename LhsContainer>
2625 operator Matcher<LhsContainer>() const {
2626 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2627 }
2628
2629 template <typename LhsContainer>
2630 class Impl : public MatcherInterface<LhsContainer> {
2631 public:
2632 typedef internal::StlContainerView<
2633 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2634 typedef typename LhsView::type LhsStlContainer;
2635 typedef typename LhsView::const_reference LhsStlContainerReference;
2636 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2637 // so that we can match associative containers.
2638 typedef typename RemoveConstFromKey<
2639 typename LhsStlContainer::value_type>::type LhsValue;
2640
2641 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2642 : comparator_(comparator), matcher_(matcher) {}
2643
2644 virtual void DescribeTo(::std::ostream* os) const {
2645 *os << "(when sorted) ";
2646 matcher_.DescribeTo(os);
2647 }
2648
2649 virtual void DescribeNegationTo(::std::ostream* os) const {
2650 *os << "(when sorted) ";
2651 matcher_.DescribeNegationTo(os);
2652 }
2653
2654 virtual bool MatchAndExplain(LhsContainer lhs,
2655 MatchResultListener* listener) const {
2656 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2657 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2658 lhs_stl_container.end());
2659 ::std::sort(
2660 sorted_container.begin(), sorted_container.end(), comparator_);
2661
2662 if (!listener->IsInterested()) {
2663 // If the listener is not interested, we do not need to
2664 // construct the inner explanation.
2665 return matcher_.Matches(sorted_container);
2666 }
2667
2668 *listener << "which is ";
2669 UniversalPrint(sorted_container, listener->stream());
2670 *listener << " when sorted";
2671
2672 StringMatchResultListener inner_listener;
2673 const bool match = matcher_.MatchAndExplain(sorted_container,
2674 &inner_listener);
2675 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2676 return match;
2677 }
2678
2679 private:
2680 const Comparator comparator_;
2681 const Matcher<const ::std::vector<LhsValue>&> matcher_;
2682
2683 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2684 };
2685
2686 private:
2687 const Comparator comparator_;
2688 const ContainerMatcher matcher_;
2689
2690 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2691 };
2692
2693 // Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2694 // must be able to be safely cast to Matcher<tuple<const T1&, const
2695 // T2&> >, where T1 and T2 are the types of elements in the LHS
2696 // container and the RHS container respectively.
2697 template <typename TupleMatcher, typename RhsContainer>
2698 class PointwiseMatcher {
2699 public:
2700 typedef internal::StlContainerView<RhsContainer> RhsView;
2701 typedef typename RhsView::type RhsStlContainer;
2702 typedef typename RhsStlContainer::value_type RhsValue;
2703
2704 // Like ContainerEq, we make a copy of rhs in case the elements in
2705 // it are modified after this matcher is created.
2706 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2707 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2708 // Makes sure the user doesn't instantiate this class template
2709 // with a const or reference type.
2710 (void)testing::StaticAssertTypeEq<RhsContainer,
2711 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2712 }
2713
2714 template <typename LhsContainer>
2715 operator Matcher<LhsContainer>() const {
2716 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2717 }
2718
2719 template <typename LhsContainer>
2720 class Impl : public MatcherInterface<LhsContainer> {
2721 public:
2722 typedef internal::StlContainerView<
2723 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2724 typedef typename LhsView::type LhsStlContainer;
2725 typedef typename LhsView::const_reference LhsStlContainerReference;
2726 typedef typename LhsStlContainer::value_type LhsValue;
2727 // We pass the LHS value and the RHS value to the inner matcher by
2728 // reference, as they may be expensive to copy. We must use tuple
2729 // instead of pair here, as a pair cannot hold references (C++ 98,
2730 // 20.2.2 [lib.pairs]).
2731 typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
2732
2733 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2734 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2735 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2736 rhs_(rhs) {}
2737
2738 virtual void DescribeTo(::std::ostream* os) const {
2739 *os << "contains " << rhs_.size()
2740 << " values, where each value and its corresponding value in ";
2741 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2742 *os << " ";
2743 mono_tuple_matcher_.DescribeTo(os);
2744 }
2745 virtual void DescribeNegationTo(::std::ostream* os) const {
2746 *os << "doesn't contain exactly " << rhs_.size()
2747 << " values, or contains a value x at some index i"
2748 << " where x and the i-th value of ";
2749 UniversalPrint(rhs_, os);
2750 *os << " ";
2751 mono_tuple_matcher_.DescribeNegationTo(os);
2752 }
2753
2754 virtual bool MatchAndExplain(LhsContainer lhs,
2755 MatchResultListener* listener) const {
2756 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2757 const size_t actual_size = lhs_stl_container.size();
2758 if (actual_size != rhs_.size()) {
2759 *listener << "which contains " << actual_size << " values";
2760 return false;
2761 }
2762
2763 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2764 typename RhsStlContainer::const_iterator right = rhs_.begin();
2765 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2766 const InnerMatcherArg value_pair(*left, *right);
2767
2768 if (listener->IsInterested()) {
2769 StringMatchResultListener inner_listener;
2770 if (!mono_tuple_matcher_.MatchAndExplain(
2771 value_pair, &inner_listener)) {
2772 *listener << "where the value pair (";
2773 UniversalPrint(*left, listener->stream());
2774 *listener << ", ";
2775 UniversalPrint(*right, listener->stream());
2776 *listener << ") at index #" << i << " don't match";
2777 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2778 return false;
2779 }
2780 } else {
2781 if (!mono_tuple_matcher_.Matches(value_pair))
2782 return false;
2783 }
2784 }
2785
2786 return true;
2787 }
2788
2789 private:
2790 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2791 const RhsStlContainer rhs_;
2792
2793 GTEST_DISALLOW_ASSIGN_(Impl);
2794 };
2795
2796 private:
2797 const TupleMatcher tuple_matcher_;
2798 const RhsStlContainer rhs_;
2799
2800 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2801 };
2802
2803 // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
2804 template <typename Container>
2805 class QuantifierMatcherImpl : public MatcherInterface<Container> {
2806 public:
2807 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
2808 typedef StlContainerView<RawContainer> View;
2809 typedef typename View::type StlContainer;
2810 typedef typename View::const_reference StlContainerReference;
2811 typedef typename StlContainer::value_type Element;
2812
2813 template <typename InnerMatcher>
2814 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
2815 : inner_matcher_(
2816 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
2817
2818 // Checks whether:
2819 // * All elements in the container match, if all_elements_should_match.
2820 // * Any element in the container matches, if !all_elements_should_match.
2821 bool MatchAndExplainImpl(bool all_elements_should_match,
2822 Container container,
2823 MatchResultListener* listener) const {
2824 StlContainerReference stl_container = View::ConstReference(container);
2825 size_t i = 0;
2826 for (typename StlContainer::const_iterator it = stl_container.begin();
2827 it != stl_container.end(); ++it, ++i) {
2828 StringMatchResultListener inner_listener;
2829 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2830
2831 if (matches != all_elements_should_match) {
2832 *listener << "whose element #" << i
2833 << (matches ? " matches" : " doesn't match");
2834 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2835 return !all_elements_should_match;
2836 }
2837 }
2838 return all_elements_should_match;
2839 }
2840
2841 protected:
2842 const Matcher<const Element&> inner_matcher_;
2843
2844 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2845 };
2846
2847 // Implements Contains(element_matcher) for the given argument type Container.
2848 // Symmetric to EachMatcherImpl.
2849 template <typename Container>
2850 class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2851 public:
2852 template <typename InnerMatcher>
2853 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2854 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2855
2856 // Describes what this matcher does.
2857 virtual void DescribeTo(::std::ostream* os) const {
2858 *os << "contains at least one element that ";
2859 this->inner_matcher_.DescribeTo(os);
2860 }
2861
2862 virtual void DescribeNegationTo(::std::ostream* os) const {
2863 *os << "doesn't contain any element that ";
2864 this->inner_matcher_.DescribeTo(os);
2865 }
2866
2867 virtual bool MatchAndExplain(Container container,
2868 MatchResultListener* listener) const {
2869 return this->MatchAndExplainImpl(false, container, listener);
2870 }
2871
2872 private:
2873 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
2874 };
2875
2876 // Implements Each(element_matcher) for the given argument type Container.
2877 // Symmetric to ContainsMatcherImpl.
2878 template <typename Container>
2879 class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2880 public:
2881 template <typename InnerMatcher>
2882 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2883 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2884
2885 // Describes what this matcher does.
2886 virtual void DescribeTo(::std::ostream* os) const {
2887 *os << "only contains elements that ";
2888 this->inner_matcher_.DescribeTo(os);
2889 }
2890
2891 virtual void DescribeNegationTo(::std::ostream* os) const {
2892 *os << "contains some element that ";
2893 this->inner_matcher_.DescribeNegationTo(os);
2894 }
2895
2896 virtual bool MatchAndExplain(Container container,
2897 MatchResultListener* listener) const {
2898 return this->MatchAndExplainImpl(true, container, listener);
2899 }
2900
2901 private:
2902 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2903 };
2904
2905 // Implements polymorphic Contains(element_matcher).
2906 template <typename M>
2907 class ContainsMatcher {
2908 public:
2909 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2910
2911 template <typename Container>
2912 operator Matcher<Container>() const {
2913 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2914 }
2915
2916 private:
2917 const M inner_matcher_;
2918
2919 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
2920 };
2921
2922 // Implements polymorphic Each(element_matcher).
2923 template <typename M>
2924 class EachMatcher {
2925 public:
2926 explicit EachMatcher(M m) : inner_matcher_(m) {}
2927
2928 template <typename Container>
2929 operator Matcher<Container>() const {
2930 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2931 }
2932
2933 private:
2934 const M inner_matcher_;
2935
2936 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2937 };
2938
2939 // Implements Key(inner_matcher) for the given argument pair type.
2940 // Key(inner_matcher) matches an std::pair whose 'first' field matches
2941 // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2942 // std::map that contains at least one element whose key is >= 5.
2943 template <typename PairType>
2944 class KeyMatcherImpl : public MatcherInterface<PairType> {
2945 public:
2946 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
2947 typedef typename RawPairType::first_type KeyType;
2948
2949 template <typename InnerMatcher>
2950 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2951 : inner_matcher_(
2952 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2953 }
2954
2955 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
2956 virtual bool MatchAndExplain(PairType key_value,
2957 MatchResultListener* listener) const {
2958 StringMatchResultListener inner_listener;
2959 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2960 &inner_listener);
2961 const internal::string explanation = inner_listener.str();
2962 if (explanation != "") {
2963 *listener << "whose first field is a value " << explanation;
2964 }
2965 return match;
2966 }
2967
2968 // Describes what this matcher does.
2969 virtual void DescribeTo(::std::ostream* os) const {
2970 *os << "has a key that ";
2971 inner_matcher_.DescribeTo(os);
2972 }
2973
2974 // Describes what the negation of this matcher does.
2975 virtual void DescribeNegationTo(::std::ostream* os) const {
2976 *os << "doesn't have a key that ";
2977 inner_matcher_.DescribeTo(os);
2978 }
2979
2980 private:
2981 const Matcher<const KeyType&> inner_matcher_;
2982
2983 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
2984 };
2985
2986 // Implements polymorphic Key(matcher_for_key).
2987 template <typename M>
2988 class KeyMatcher {
2989 public:
2990 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2991
2992 template <typename PairType>
2993 operator Matcher<PairType>() const {
2994 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2995 }
2996
2997 private:
2998 const M matcher_for_key_;
2999
3000 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
3001 };
3002
3003 // Implements Pair(first_matcher, second_matcher) for the given argument pair
3004 // type with its two matchers. See Pair() function below.
3005 template <typename PairType>
3006 class PairMatcherImpl : public MatcherInterface<PairType> {
3007 public:
3008 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
3009 typedef typename RawPairType::first_type FirstType;
3010 typedef typename RawPairType::second_type SecondType;
3011
3012 template <typename FirstMatcher, typename SecondMatcher>
3013 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
3014 : first_matcher_(
3015 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
3016 second_matcher_(
3017 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
3018 }
3019
3020 // Describes what this matcher does.
3021 virtual void DescribeTo(::std::ostream* os) const {
3022 *os << "has a first field that ";
3023 first_matcher_.DescribeTo(os);
3024 *os << ", and has a second field that ";
3025 second_matcher_.DescribeTo(os);
3026 }
3027
3028 // Describes what the negation of this matcher does.
3029 virtual void DescribeNegationTo(::std::ostream* os) const {
3030 *os << "has a first field that ";
3031 first_matcher_.DescribeNegationTo(os);
3032 *os << ", or has a second field that ";
3033 second_matcher_.DescribeNegationTo(os);
3034 }
3035
3036 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3037 // matches second_matcher.
3038 virtual bool MatchAndExplain(PairType a_pair,
3039 MatchResultListener* listener) const {
3040 if (!listener->IsInterested()) {
3041 // If the listener is not interested, we don't need to construct the
3042 // explanation.
3043 return first_matcher_.Matches(a_pair.first) &&
3044 second_matcher_.Matches(a_pair.second);
3045 }
3046 StringMatchResultListener first_inner_listener;
3047 if (!first_matcher_.MatchAndExplain(a_pair.first,
3048 &first_inner_listener)) {
3049 *listener << "whose first field does not match";
3050 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
3051 return false;
3052 }
3053 StringMatchResultListener second_inner_listener;
3054 if (!second_matcher_.MatchAndExplain(a_pair.second,
3055 &second_inner_listener)) {
3056 *listener << "whose second field does not match";
3057 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
3058 return false;
3059 }
3060 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3061 listener);
3062 return true;
3063 }
3064
3065 private:
3066 void ExplainSuccess(const internal::string& first_explanation,
3067 const internal::string& second_explanation,
3068 MatchResultListener* listener) const {
3069 *listener << "whose both fields match";
3070 if (first_explanation != "") {
3071 *listener << ", where the first field is a value " << first_explanation;
3072 }
3073 if (second_explanation != "") {
3074 *listener << ", ";
3075 if (first_explanation != "") {
3076 *listener << "and ";
3077 } else {
3078 *listener << "where ";
3079 }
3080 *listener << "the second field is a value " << second_explanation;
3081 }
3082 }
3083
3084 const Matcher<const FirstType&> first_matcher_;
3085 const Matcher<const SecondType&> second_matcher_;
3086
3087 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
3088 };
3089
3090 // Implements polymorphic Pair(first_matcher, second_matcher).
3091 template <typename FirstMatcher, typename SecondMatcher>
3092 class PairMatcher {
3093 public:
3094 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3095 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3096
3097 template <typename PairType>
3098 operator Matcher<PairType> () const {
3099 return MakeMatcher(
3100 new PairMatcherImpl<PairType>(
3101 first_matcher_, second_matcher_));
3102 }
3103
3104 private:
3105 const FirstMatcher first_matcher_;
3106 const SecondMatcher second_matcher_;
3107
3108 GTEST_DISALLOW_ASSIGN_(PairMatcher);
3109 };
3110
3111 // Implements ElementsAre() and ElementsAreArray().
3112 template <typename Container>
3113 class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3114 public:
3115 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3116 typedef internal::StlContainerView<RawContainer> View;
3117 typedef typename View::type StlContainer;
3118 typedef typename View::const_reference StlContainerReference;
3119 typedef decltype(std::begin(
3120 std::declval<StlContainerReference>())) StlContainerConstIterator;
3121 typedef std::remove_reference_t<decltype(
3122 *std::declval<StlContainerConstIterator &>())>
3123 Element;
3124
3125 // Constructs the matcher from a sequence of element values or
3126 // element matchers.
3127 template <typename InputIter>
3128 ElementsAreMatcherImpl(InputIter first, InputIter last) {
3129 while (first != last) {
3130 matchers_.push_back(MatcherCast<const Element&>(*first++));
3131 }
3132 }
3133
3134 // Describes what this matcher does.
3135 virtual void DescribeTo(::std::ostream* os) const {
3136 if (count() == 0) {
3137 *os << "is empty";
3138 } else if (count() == 1) {
3139 *os << "has 1 element that ";
3140 matchers_[0].DescribeTo(os);
3141 } else {
3142 *os << "has " << Elements(count()) << " where\n";
3143 for (size_t i = 0; i != count(); ++i) {
3144 *os << "element #" << i << " ";
3145 matchers_[i].DescribeTo(os);
3146 if (i + 1 < count()) {
3147 *os << ",\n";
3148 }
3149 }
3150 }
3151 }
3152
3153 // Describes what the negation of this matcher does.
3154 virtual void DescribeNegationTo(::std::ostream* os) const {
3155 if (count() == 0) {
3156 *os << "isn't empty";
3157 return;
3158 }
3159
3160 *os << "doesn't have " << Elements(count()) << ", or\n";
3161 for (size_t i = 0; i != count(); ++i) {
3162 *os << "element #" << i << " ";
3163 matchers_[i].DescribeNegationTo(os);
3164 if (i + 1 < count()) {
3165 *os << ", or\n";
3166 }
3167 }
3168 }
3169
3170 virtual bool MatchAndExplain(Container container,
3171 MatchResultListener* listener) const {
3172 // To work with stream-like "containers", we must only walk
3173 // through the elements in one pass.
3174
3175 const bool listener_interested = listener->IsInterested();
3176
3177 // explanations[i] is the explanation of the element at index i.
3178 ::std::vector<internal::string> explanations(count());
3179 StlContainerReference stl_container = View::ConstReference(container);
3180 StlContainerConstIterator it = stl_container.begin();
3181 size_t exam_pos = 0;
3182 bool mismatch_found = false; // Have we found a mismatched element yet?
3183
3184 // Go through the elements and matchers in pairs, until we reach
3185 // the end of either the elements or the matchers, or until we find a
3186 // mismatch.
3187 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3188 bool match; // Does the current element match the current matcher?
3189 if (listener_interested) {
3190 StringMatchResultListener s;
3191 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3192 explanations[exam_pos] = s.str();
3193 } else {
3194 match = matchers_[exam_pos].Matches(*it);
3195 }
3196
3197 if (!match) {
3198 mismatch_found = true;
3199 break;
3200 }
3201 }
3202 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3203
3204 // Find how many elements the actual container has. We avoid
3205 // calling size() s.t. this code works for stream-like "containers"
3206 // that don't define size().
3207 size_t actual_count = exam_pos;
3208 for (; it != stl_container.end(); ++it) {
3209 ++actual_count;
3210 }
3211
3212 if (actual_count != count()) {
3213 // The element count doesn't match. If the container is empty,
3214 // there's no need to explain anything as Google Mock already
3215 // prints the empty container. Otherwise we just need to show
3216 // how many elements there actually are.
3217 if (listener_interested && (actual_count != 0)) {
3218 *listener << "which has " << Elements(actual_count);
3219 }
3220 return false;
3221 }
3222
3223 if (mismatch_found) {
3224 // The element count matches, but the exam_pos-th element doesn't match.
3225 if (listener_interested) {
3226 *listener << "whose element #" << exam_pos << " doesn't match";
3227 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
3228 }
3229 return false;
3230 }
3231
3232 // Every element matches its expectation. We need to explain why
3233 // (the obvious ones can be skipped).
3234 if (listener_interested) {
3235 bool reason_printed = false;
3236 for (size_t i = 0; i != count(); ++i) {
3237 const internal::string& s = explanations[i];
3238 if (!s.empty()) {
3239 if (reason_printed) {
3240 *listener << ",\nand ";
3241 }
3242 *listener << "whose element #" << i << " matches, " << s;
3243 reason_printed = true;
3244 }
3245 }
3246 }
3247 return true;
3248 }
3249
3250 private:
3251 static Message Elements(size_t count) {
3252 return Message() << count << (count == 1 ? " element" : " elements");
3253 }
3254
3255 size_t count() const { return matchers_.size(); }
3256
3257 ::std::vector<Matcher<const Element&> > matchers_;
3258
3259 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
3260 };
3261
3262 // Connectivity matrix of (elements X matchers), in element-major order.
3263 // Initially, there are no edges.
3264 // Use NextGraph() to iterate over all possible edge configurations.
3265 // Use Randomize() to generate a random edge configuration.
3266 class GTEST_API_ MatchMatrix {
3267 public:
3268 MatchMatrix(size_t num_elements, size_t num_matchers)
3269 : num_elements_(num_elements),
3270 num_matchers_(num_matchers),
3271 matched_(num_elements_* num_matchers_, 0) {
3272 }
3273
3274 size_t LhsSize() const { return num_elements_; }
3275 size_t RhsSize() const { return num_matchers_; }
3276 bool HasEdge(size_t ilhs, size_t irhs) const {
3277 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3278 }
3279 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3280 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3281 }
3282
3283 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3284 // adds 1 to that number; returns false if incrementing the graph left it
3285 // empty.
3286 bool NextGraph();
3287
3288 void Randomize();
3289
3290 string DebugString() const;
3291
3292 private:
3293 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3294 return ilhs * num_matchers_ + irhs;
3295 }
3296
3297 size_t num_elements_;
3298 size_t num_matchers_;
3299
3300 // Each element is a char interpreted as bool. They are stored as a
3301 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3302 // a (ilhs, irhs) matrix coordinate into an offset.
3303 ::std::vector<char> matched_;
3304 };
3305
3306 typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3307 typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3308
3309 // Returns a maximum bipartite matching for the specified graph 'g'.
3310 // The matching is represented as a vector of {element, matcher} pairs.
3311 GTEST_API_ ElementMatcherPairs
3312 FindMaxBipartiteMatching(const MatchMatrix& g);
3313
3314 GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
3315 MatchResultListener* listener);
3316
3317 // Untyped base class for implementing UnorderedElementsAre. By
3318 // putting logic that's not specific to the element type here, we
3319 // reduce binary bloat and increase compilation speed.
3320 class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3321 protected:
3322 // A vector of matcher describers, one for each element matcher.
3323 // Does not own the describers (and thus can be used only when the
3324 // element matchers are alive).
3325 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3326
3327 // Describes this UnorderedElementsAre matcher.
3328 void DescribeToImpl(::std::ostream* os) const;
3329
3330 // Describes the negation of this UnorderedElementsAre matcher.
3331 void DescribeNegationToImpl(::std::ostream* os) const;
3332
3333 bool VerifyAllElementsAndMatchersAreMatched(
3334 const ::std::vector<string>& element_printouts,
3335 const MatchMatrix& matrix,
3336 MatchResultListener* listener) const;
3337
3338 MatcherDescriberVec& matcher_describers() {
3339 return matcher_describers_;
3340 }
3341
3342 static Message Elements(size_t n) {
3343 return Message() << n << " element" << (n == 1 ? "" : "s");
3344 }
3345
3346 private:
3347 MatcherDescriberVec matcher_describers_;
3348
3349 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3350 };
3351
3352 // Implements unordered ElementsAre and unordered ElementsAreArray.
3353 template <typename Container>
3354 class UnorderedElementsAreMatcherImpl
3355 : public MatcherInterface<Container>,
3356 public UnorderedElementsAreMatcherImplBase {
3357 public:
3358 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3359 typedef internal::StlContainerView<RawContainer> View;
3360 typedef typename View::type StlContainer;
3361 typedef typename View::const_reference StlContainerReference;
3362 typedef decltype(std::begin(
3363 std::declval<StlContainerReference>())) StlContainerConstIterator;
3364 typedef std::remove_reference_t<decltype(
3365 *std::declval<StlContainerConstIterator &>())>
3366 Element;
3367
3368 // Constructs the matcher from a sequence of element values or
3369 // element matchers.
3370 template <typename InputIter>
3371 UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) {
3372 for (; first != last; ++first) {
3373 matchers_.push_back(MatcherCast<const Element&>(*first));
3374 matcher_describers().push_back(matchers_.back().GetDescriber());
3375 }
3376 }
3377
3378 // Describes what this matcher does.
3379 virtual void DescribeTo(::std::ostream* os) const {
3380 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3381 }
3382
3383 // Describes what the negation of this matcher does.
3384 virtual void DescribeNegationTo(::std::ostream* os) const {
3385 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3386 }
3387
3388 virtual bool MatchAndExplain(Container container,
3389 MatchResultListener* listener) const {
3390 StlContainerReference stl_container = View::ConstReference(container);
3391 ::std::vector<string> element_printouts;
3392 MatchMatrix matrix = AnalyzeElements(stl_container.begin(),
3393 stl_container.end(),
3394 &element_printouts,
3395 listener);
3396
3397 const size_t actual_count = matrix.LhsSize();
3398 if (actual_count == 0 && matchers_.empty()) {
3399 return true;
3400 }
3401 if (actual_count != matchers_.size()) {
3402 // The element count doesn't match. If the container is empty,
3403 // there's no need to explain anything as Google Mock already
3404 // prints the empty container. Otherwise we just need to show
3405 // how many elements there actually are.
3406 if (actual_count != 0 && listener->IsInterested()) {
3407 *listener << "which has " << Elements(actual_count);
3408 }
3409 return false;
3410 }
3411
3412 return VerifyAllElementsAndMatchersAreMatched(element_printouts,
3413 matrix, listener) &&
3414 FindPairing(matrix, listener);
3415 }
3416
3417 private:
3418 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3419
3420 template <typename ElementIter>
3421 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
3422 ::std::vector<string>* element_printouts,
3423 MatchResultListener* listener) const {
3424 element_printouts->clear();
3425 ::std::vector<char> did_match;
3426 size_t num_elements = 0;
3427 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3428 if (listener->IsInterested()) {
3429 element_printouts->push_back(PrintToString(*elem_first));
3430 }
3431 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3432 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3433 }
3434 }
3435
3436 MatchMatrix matrix(num_elements, matchers_.size());
3437 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3438 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3439 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3440 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3441 }
3442 }
3443 return matrix;
3444 }
3445
3446 MatcherVec matchers_;
3447
3448 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3449 };
3450
3451 // Functor for use in TransformTuple.
3452 // Performs MatcherCast<Target> on an input argument of any type.
3453 template <typename Target>
3454 struct CastAndAppendTransform {
3455 template <typename Arg>
3456 Matcher<Target> operator()(const Arg& a) const {
3457 return MatcherCast<Target>(a);
3458 }
3459 };
3460
3461 // Implements UnorderedElementsAre.
3462 template <typename MatcherTuple>
3463 class UnorderedElementsAreMatcher {
3464 public:
3465 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3466 : matchers_(args) {}
3467
3468 template <typename Container>
3469 operator Matcher<Container>() const {
3470 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3471 typedef internal::StlContainerView<RawContainer> View;
3472 typedef typename View::const_reference StlContainerReference;
3473 typedef decltype(std::begin(
3474 std::declval<StlContainerReference>())) StlContainerConstIterator;
3475 typedef std::remove_reference_t<decltype(
3476 *std::declval<StlContainerConstIterator &>())>
3477 Element;
3478 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3479 MatcherVec matchers;
3480 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
3481 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3482 ::std::back_inserter(matchers));
3483 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3484 matchers.begin(), matchers.end()));
3485 }
3486
3487 private:
3488 const MatcherTuple matchers_;
3489 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3490 };
3491
3492 // Implements ElementsAre.
3493 template <typename MatcherTuple>
3494 class ElementsAreMatcher {
3495 public:
3496 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3497
3498 template <typename Container>
3499 operator Matcher<Container>() const {
3500 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3501 typedef internal::StlContainerView<RawContainer> View;
3502 typedef typename View::const_reference StlContainerReference;
3503 typedef decltype(std::begin(
3504 std::declval<StlContainerReference>())) StlContainerConstIterator;
3505 typedef std::remove_reference_t<decltype(
3506 *std::declval<StlContainerConstIterator &>())>
3507 Element;
3508 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3509 MatcherVec matchers;
3510 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
3511 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3512 ::std::back_inserter(matchers));
3513 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3514 matchers.begin(), matchers.end()));
3515 }
3516
3517 private:
3518 const MatcherTuple matchers_;
3519 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3520 };
3521
3522 // Implements UnorderedElementsAreArray().
3523 template <typename T>
3524 class UnorderedElementsAreArrayMatcher {
3525 public:
3526 UnorderedElementsAreArrayMatcher() {}
3527
3528 template <typename Iter>
3529 UnorderedElementsAreArrayMatcher(Iter first, Iter last)
3530 : matchers_(first, last) {}
3531
3532 template <typename Container>
3533 operator Matcher<Container>() const {
3534 return MakeMatcher(
3535 new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(),
3536 matchers_.end()));
3537 }
3538
3539 private:
3540 ::std::vector<T> matchers_;
3541
3542 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
3543 };
3544
3545 // Implements ElementsAreArray().
3546 template <typename T>
3547 class ElementsAreArrayMatcher {
3548 public:
3549 template <typename Iter>
3550 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
3551
3552 template <typename Container>
3553 operator Matcher<Container>() const {
3554 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3555 matchers_.begin(), matchers_.end()));
3556 }
3557
3558 private:
3559 const ::std::vector<T> matchers_;
3560
3561 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
3562 };
3563
3564 // Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3565 // of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3566 // second) is a polymorphic matcher that matches a value x iff tm
3567 // matches tuple (x, second). Useful for implementing
3568 // UnorderedPointwise() in terms of UnorderedElementsAreArray().
3569 //
3570 // BoundSecondMatcher is copyable and assignable, as we need to put
3571 // instances of this class in a vector when implementing
3572 // UnorderedPointwise().
3573 template <typename Tuple2Matcher, typename Second>
3574 class BoundSecondMatcher {
3575 public:
3576 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3577 : tuple2_matcher_(tm), second_value_(second) {}
3578
3579 template <typename T>
3580 operator Matcher<T>() const {
3581 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3582 }
3583
3584 // We have to define this for UnorderedPointwise() to compile in
3585 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3586 // which requires the elements to be assignable in C++98. The
3587 // compiler cannot generate the operator= for us, as Tuple2Matcher
3588 // and Second may not be assignable.
3589 //
3590 // However, this should never be called, so the implementation just
3591 // need to assert.
3592 void operator=(const BoundSecondMatcher& /*rhs*/) {
3593 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3594 }
3595
3596 BoundSecondMatcher(const BoundSecondMatcher &) = default;
3597
3598 private:
3599 template <typename T>
3600 class Impl : public MatcherInterface<T> {
3601 public:
3602 typedef ::testing::tuple<T, Second> ArgTuple;
3603
3604 Impl(const Tuple2Matcher& tm, const Second& second)
3605 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3606 second_value_(second) {}
3607
3608 virtual void DescribeTo(::std::ostream* os) const {
3609 *os << "and ";
3610 UniversalPrint(second_value_, os);
3611 *os << " ";
3612 mono_tuple2_matcher_.DescribeTo(os);
3613 }
3614
3615 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3616 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3617 listener);
3618 }
3619
3620 private:
3621 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3622 const Second second_value_;
3623
3624 GTEST_DISALLOW_ASSIGN_(Impl);
3625 };
3626
3627 const Tuple2Matcher tuple2_matcher_;
3628 const Second second_value_;
3629 };
3630
3631 // Given a 2-tuple matcher tm and a value second,
3632 // MatcherBindSecond(tm, second) returns a matcher that matches a
3633 // value x iff tm matches tuple (x, second). Useful for implementing
3634 // UnorderedPointwise() in terms of UnorderedElementsAreArray().
3635 template <typename Tuple2Matcher, typename Second>
3636 BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
3637 const Tuple2Matcher& tm, const Second& second) {
3638 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
3639 }
3640
3641 // Returns the description for a matcher defined using the MATCHER*()
3642 // macro where the user-supplied description string is "", if
3643 // 'negation' is false; otherwise returns the description of the
3644 // negation of the matcher. 'param_values' contains a list of strings
3645 // that are the print-out of the matcher's parameters.
3646 GTEST_API_ string FormatMatcherDescription(bool negation,
3647 const char* matcher_name,
3648 const Strings& param_values);
3649
3650 } // namespace internal
3651
3652 // ElementsAreArray(first, last)
3653 // ElementsAreArray(pointer, count)
3654 // ElementsAreArray(array)
3655 // ElementsAreArray(container)
3656 // ElementsAreArray({ e1, e2, ..., en })
3657 //
3658 // The ElementsAreArray() functions are like ElementsAre(...), except
3659 // that they are given a homogeneous sequence rather than taking each
3660 // element as a function argument. The sequence can be specified as an
3661 // array, a pointer and count, a vector, an initializer list, or an
3662 // STL iterator range. In each of these cases, the underlying sequence
3663 // can be either a sequence of values or a sequence of matchers.
3664 //
3665 // All forms of ElementsAreArray() make a copy of the input matcher sequence.
3666
3667 template <typename Iter>
3668 inline internal::ElementsAreArrayMatcher<
3669 typename ::std::iterator_traits<Iter>::value_type>
3670 ElementsAreArray(Iter first, Iter last) {
3671 typedef typename ::std::iterator_traits<Iter>::value_type T;
3672 return internal::ElementsAreArrayMatcher<T>(first, last);
3673 }
3674
3675 template <typename T>
3676 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3677 const T* pointer, size_t count) {
3678 return ElementsAreArray(pointer, pointer + count);
3679 }
3680
3681 template <typename T, size_t N>
3682 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3683 const T (&array)[N]) {
3684 return ElementsAreArray(array, N);
3685 }
3686
3687 template <typename Container>
3688 inline internal::ElementsAreArrayMatcher<typename Container::value_type>
3689 ElementsAreArray(const Container& container) {
3690 return ElementsAreArray(container.begin(), container.end());
3691 }
3692
3693 #if GTEST_HAS_STD_INITIALIZER_LIST_
3694 template <typename T>
3695 inline internal::ElementsAreArrayMatcher<T>
3696 ElementsAreArray(::std::initializer_list<T> xs) {
3697 return ElementsAreArray(xs.begin(), xs.end());
3698 }
3699 #endif
3700
3701 // UnorderedElementsAreArray(first, last)
3702 // UnorderedElementsAreArray(pointer, count)
3703 // UnorderedElementsAreArray(array)
3704 // UnorderedElementsAreArray(container)
3705 // UnorderedElementsAreArray({ e1, e2, ..., en })
3706 //
3707 // The UnorderedElementsAreArray() functions are like
3708 // ElementsAreArray(...), but allow matching the elements in any order.
3709 template <typename Iter>
3710 inline internal::UnorderedElementsAreArrayMatcher<
3711 typename ::std::iterator_traits<Iter>::value_type>
3712 UnorderedElementsAreArray(Iter first, Iter last) {
3713 typedef typename ::std::iterator_traits<Iter>::value_type T;
3714 return internal::UnorderedElementsAreArrayMatcher<T>(first, last);
3715 }
3716
3717 template <typename T>
3718 inline internal::UnorderedElementsAreArrayMatcher<T>
3719 UnorderedElementsAreArray(const T* pointer, size_t count) {
3720 return UnorderedElementsAreArray(pointer, pointer + count);
3721 }
3722
3723 template <typename T, size_t N>
3724 inline internal::UnorderedElementsAreArrayMatcher<T>
3725 UnorderedElementsAreArray(const T (&array)[N]) {
3726 return UnorderedElementsAreArray(array, N);
3727 }
3728
3729 template <typename Container>
3730 inline internal::UnorderedElementsAreArrayMatcher<
3731 typename Container::value_type>
3732 UnorderedElementsAreArray(const Container& container) {
3733 return UnorderedElementsAreArray(container.begin(), container.end());
3734 }
3735
3736 #if GTEST_HAS_STD_INITIALIZER_LIST_
3737 template <typename T>
3738 inline internal::UnorderedElementsAreArrayMatcher<T>
3739 UnorderedElementsAreArray(::std::initializer_list<T> xs) {
3740 return UnorderedElementsAreArray(xs.begin(), xs.end());
3741 }
3742 #endif
3743
3744 // _ is a matcher that matches anything of any type.
3745 //
3746 // This definition is fine as:
3747 //
3748 // 1. The C++ standard permits using the name _ in a namespace that
3749 // is not the global namespace or ::std.
3750 // 2. The AnythingMatcher class has no data member or constructor,
3751 // so it's OK to create global variables of this type.
3752 // 3. c-style has approved of using _ in this case.
3753 const internal::AnythingMatcher _ = {};
3754 // Creates a matcher that matches any value of the given type T.
3755 template <typename T>
3756 inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
3757
3758 // Creates a matcher that matches any value of the given type T.
3759 template <typename T>
3760 inline Matcher<T> An() { return A<T>(); }
3761
3762 // Creates a polymorphic matcher that matches anything equal to x.
3763 // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
3764 // wouldn't compile.
3765 template <typename T>
3766 inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
3767
3768 // Constructs a Matcher<T> from a 'value' of type T. The constructed
3769 // matcher matches any value that's equal to 'value'.
3770 template <typename T>
3771 Matcher<T>::Matcher(T value) { *this = Eq(value); }
3772
3773 // Creates a monomorphic matcher that matches anything with type Lhs
3774 // and equal to rhs. A user may need to use this instead of Eq(...)
3775 // in order to resolve an overloading ambiguity.
3776 //
3777 // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
3778 // or Matcher<T>(x), but more readable than the latter.
3779 //
3780 // We could define similar monomorphic matchers for other comparison
3781 // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
3782 // it yet as those are used much less than Eq() in practice. A user
3783 // can always write Matcher<T>(Lt(5)) to be explicit about the type,
3784 // for example.
3785 template <typename Lhs, typename Rhs>
3786 inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
3787
3788 // Creates a polymorphic matcher that matches anything >= x.
3789 template <typename Rhs>
3790 inline internal::GeMatcher<Rhs> Ge(Rhs x) {
3791 return internal::GeMatcher<Rhs>(x);
3792 }
3793
3794 // Creates a polymorphic matcher that matches anything > x.
3795 template <typename Rhs>
3796 inline internal::GtMatcher<Rhs> Gt(Rhs x) {
3797 return internal::GtMatcher<Rhs>(x);
3798 }
3799
3800 // Creates a polymorphic matcher that matches anything <= x.
3801 template <typename Rhs>
3802 inline internal::LeMatcher<Rhs> Le(Rhs x) {
3803 return internal::LeMatcher<Rhs>(x);
3804 }
3805
3806 // Creates a polymorphic matcher that matches anything < x.
3807 template <typename Rhs>
3808 inline internal::LtMatcher<Rhs> Lt(Rhs x) {
3809 return internal::LtMatcher<Rhs>(x);
3810 }
3811
3812 // Creates a polymorphic matcher that matches anything != x.
3813 template <typename Rhs>
3814 inline internal::NeMatcher<Rhs> Ne(Rhs x) {
3815 return internal::NeMatcher<Rhs>(x);
3816 }
3817
3818 // Creates a polymorphic matcher that matches any NULL pointer.
3819 inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
3820 return MakePolymorphicMatcher(internal::IsNullMatcher());
3821 }
3822
3823 // Creates a polymorphic matcher that matches any non-NULL pointer.
3824 // This is convenient as Not(NULL) doesn't compile (the compiler
3825 // thinks that that expression is comparing a pointer with an integer).
3826 inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
3827 return MakePolymorphicMatcher(internal::NotNullMatcher());
3828 }
3829
3830 // Creates a polymorphic matcher that matches any argument that
3831 // references variable x.
3832 template <typename T>
3833 inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
3834 return internal::RefMatcher<T&>(x);
3835 }
3836
3837 // Creates a matcher that matches any double argument approximately
3838 // equal to rhs, where two NANs are considered unequal.
3839 inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
3840 return internal::FloatingEqMatcher<double>(rhs, false);
3841 }
3842
3843 // Creates a matcher that matches any double argument approximately
3844 // equal to rhs, including NaN values when rhs is NaN.
3845 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
3846 return internal::FloatingEqMatcher<double>(rhs, true);
3847 }
3848
3849 // Creates a matcher that matches any double argument approximately equal to
3850 // rhs, up to the specified max absolute error bound, where two NANs are
3851 // considered unequal. The max absolute error bound must be non-negative.
3852 inline internal::FloatingEqMatcher<double> DoubleNear(
3853 double rhs, double max_abs_error) {
3854 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
3855 }
3856
3857 // Creates a matcher that matches any double argument approximately equal to
3858 // rhs, up to the specified max absolute error bound, including NaN values when
3859 // rhs is NaN. The max absolute error bound must be non-negative.
3860 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
3861 double rhs, double max_abs_error) {
3862 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
3863 }
3864
3865 // Creates a matcher that matches any float argument approximately
3866 // equal to rhs, where two NANs are considered unequal.
3867 inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
3868 return internal::FloatingEqMatcher<float>(rhs, false);
3869 }
3870
3871 // Creates a matcher that matches any float argument approximately
3872 // equal to rhs, including NaN values when rhs is NaN.
3873 inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
3874 return internal::FloatingEqMatcher<float>(rhs, true);
3875 }
3876
3877 // Creates a matcher that matches any float argument approximately equal to
3878 // rhs, up to the specified max absolute error bound, where two NANs are
3879 // considered unequal. The max absolute error bound must be non-negative.
3880 inline internal::FloatingEqMatcher<float> FloatNear(
3881 float rhs, float max_abs_error) {
3882 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
3883 }
3884
3885 // Creates a matcher that matches any float argument approximately equal to
3886 // rhs, up to the specified max absolute error bound, including NaN values when
3887 // rhs is NaN. The max absolute error bound must be non-negative.
3888 inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
3889 float rhs, float max_abs_error) {
3890 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
3891 }
3892
3893 // Creates a matcher that matches a pointer (raw or smart) that points
3894 // to a value that matches inner_matcher.
3895 template <typename InnerMatcher>
3896 inline internal::PointeeMatcher<InnerMatcher> Pointee(
3897 const InnerMatcher& inner_matcher) {
3898 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
3899 }
3900
3901 // Creates a matcher that matches a pointer or reference that matches
3902 // inner_matcher when dynamic_cast<To> is applied.
3903 // The result of dynamic_cast<To> is forwarded to the inner matcher.
3904 // If To is a pointer and the cast fails, the inner matcher will receive NULL.
3905 // If To is a reference and the cast fails, this matcher returns false
3906 // immediately.
3907 template <typename To>
3908 inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
3909 WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
3910 return MakePolymorphicMatcher(
3911 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
3912 }
3913
3914 // Creates a matcher that matches an object whose given field matches
3915 // 'matcher'. For example,
3916 // Field(&Foo::number, Ge(5))
3917 // matches a Foo object x iff x.number >= 5.
3918 template <typename Class, typename FieldType, typename FieldMatcher>
3919 inline PolymorphicMatcher<
3920 internal::FieldMatcher<Class, FieldType> > Field(
3921 FieldType Class::*field, const FieldMatcher& matcher) {
3922 return MakePolymorphicMatcher(
3923 internal::FieldMatcher<Class, FieldType>(
3924 field, MatcherCast<const FieldType&>(matcher)));
3925 // The call to MatcherCast() is required for supporting inner
3926 // matchers of compatible types. For example, it allows
3927 // Field(&Foo::bar, m)
3928 // to compile where bar is an int32 and m is a matcher for int64.
3929 }
3930
3931 // Creates a matcher that matches an object whose given property
3932 // matches 'matcher'. For example,
3933 // Property(&Foo::str, StartsWith("hi"))
3934 // matches a Foo object x iff x.str() starts with "hi".
3935 template <typename Class, typename PropertyType, typename PropertyMatcher>
3936 inline PolymorphicMatcher<
3937 internal::PropertyMatcher<Class, PropertyType> > Property(
3938 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
3939 return MakePolymorphicMatcher(
3940 internal::PropertyMatcher<Class, PropertyType>(
3941 property,
3942 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
3943 // The call to MatcherCast() is required for supporting inner
3944 // matchers of compatible types. For example, it allows
3945 // Property(&Foo::bar, m)
3946 // to compile where bar() returns an int32 and m is a matcher for int64.
3947 }
3948
3949 // Creates a matcher that matches an object iff the result of applying
3950 // a callable to x matches 'matcher'.
3951 // For example,
3952 // ResultOf(f, StartsWith("hi"))
3953 // matches a Foo object x iff f(x) starts with "hi".
3954 // callable parameter can be a function, function pointer, or a functor.
3955 // Callable has to satisfy the following conditions:
3956 // * It is required to keep no state affecting the results of
3957 // the calls on it and make no assumptions about how many calls
3958 // will be made. Any state it keeps must be protected from the
3959 // concurrent access.
3960 // * If it is a function object, it has to define type result_type.
3961 // We recommend deriving your functor classes from std::unary_function.
3962 template <typename Callable, typename ResultOfMatcher>
3963 internal::ResultOfMatcher<Callable> ResultOf(
3964 Callable callable, const ResultOfMatcher& matcher) {
3965 return internal::ResultOfMatcher<Callable>(
3966 callable,
3967 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
3968 matcher));
3969 // The call to MatcherCast() is required for supporting inner
3970 // matchers of compatible types. For example, it allows
3971 // ResultOf(Function, m)
3972 // to compile where Function() returns an int32 and m is a matcher for int64.
3973 }
3974
3975 // String matchers.
3976
3977 // Matches a string equal to str.
3978 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3979 StrEq(const internal::string& str) {
3980 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3981 str, true, true));
3982 }
3983
3984 // Matches a string not equal to str.
3985 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3986 StrNe(const internal::string& str) {
3987 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3988 str, false, true));
3989 }
3990
3991 // Matches a string equal to str, ignoring case.
3992 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3993 StrCaseEq(const internal::string& str) {
3994 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3995 str, true, false));
3996 }
3997
3998 // Matches a string not equal to str, ignoring case.
3999 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
4000 StrCaseNe(const internal::string& str) {
4001 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
4002 str, false, false));
4003 }
4004
4005 // Creates a matcher that matches any string, std::string, or C string
4006 // that contains the given substring.
4007 inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
4008 HasSubstr(const internal::string& substring) {
4009 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
4010 substring));
4011 }
4012
4013 // Matches a string that starts with 'prefix' (case-sensitive).
4014 inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
4015 StartsWith(const internal::string& prefix) {
4016 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
4017 prefix));
4018 }
4019
4020 // Matches a string that ends with 'suffix' (case-sensitive).
4021 inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
4022 EndsWith(const internal::string& suffix) {
4023 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
4024 suffix));
4025 }
4026
4027 // Matches a string that fully matches regular expression 'regex'.
4028 // The matcher takes ownership of 'regex'.
4029 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4030 const internal::RE* regex) {
4031 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
4032 }
4033 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4034 const internal::string& regex) {
4035 return MatchesRegex(new internal::RE(regex));
4036 }
4037
4038 // Matches a string that contains regular expression 'regex'.
4039 // The matcher takes ownership of 'regex'.
4040 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4041 const internal::RE* regex) {
4042 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4043 }
4044 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4045 const internal::string& regex) {
4046 return ContainsRegex(new internal::RE(regex));
4047 }
4048
4049 #if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4050 // Wide string matchers.
4051
4052 // Matches a string equal to str.
4053 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4054 StrEq(const internal::wstring& str) {
4055 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4056 str, true, true));
4057 }
4058
4059 // Matches a string not equal to str.
4060 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4061 StrNe(const internal::wstring& str) {
4062 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4063 str, false, true));
4064 }
4065
4066 // Matches a string equal to str, ignoring case.
4067 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4068 StrCaseEq(const internal::wstring& str) {
4069 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4070 str, true, false));
4071 }
4072
4073 // Matches a string not equal to str, ignoring case.
4074 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4075 StrCaseNe(const internal::wstring& str) {
4076 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4077 str, false, false));
4078 }
4079
4080 // Creates a matcher that matches any wstring, std::wstring, or C wide string
4081 // that contains the given substring.
4082 inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
4083 HasSubstr(const internal::wstring& substring) {
4084 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
4085 substring));
4086 }
4087
4088 // Matches a string that starts with 'prefix' (case-sensitive).
4089 inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
4090 StartsWith(const internal::wstring& prefix) {
4091 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
4092 prefix));
4093 }
4094
4095 // Matches a string that ends with 'suffix' (case-sensitive).
4096 inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
4097 EndsWith(const internal::wstring& suffix) {
4098 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
4099 suffix));
4100 }
4101
4102 #endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4103
4104 // Creates a polymorphic matcher that matches a 2-tuple where the
4105 // first field == the second field.
4106 inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4107
4108 // Creates a polymorphic matcher that matches a 2-tuple where the
4109 // first field >= the second field.
4110 inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4111
4112 // Creates a polymorphic matcher that matches a 2-tuple where the
4113 // first field > the second field.
4114 inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4115
4116 // Creates a polymorphic matcher that matches a 2-tuple where the
4117 // first field <= the second field.
4118 inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4119
4120 // Creates a polymorphic matcher that matches a 2-tuple where the
4121 // first field < the second field.
4122 inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4123
4124 // Creates a polymorphic matcher that matches a 2-tuple where the
4125 // first field != the second field.
4126 inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4127
4128 // Creates a matcher that matches any value of type T that m doesn't
4129 // match.
4130 template <typename InnerMatcher>
4131 inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4132 return internal::NotMatcher<InnerMatcher>(m);
4133 }
4134
4135 // Returns a matcher that matches anything that satisfies the given
4136 // predicate. The predicate can be any unary function or functor
4137 // whose return type can be implicitly converted to bool.
4138 template <typename Predicate>
4139 inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4140 Truly(Predicate pred) {
4141 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4142 }
4143
4144 // Returns a matcher that matches the container size. The container must
4145 // support both size() and size_type which all STL-like containers provide.
4146 // Note that the parameter 'size' can be a value of type size_type as well as
4147 // matcher. For instance:
4148 // EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
4149 // EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
4150 template <typename SizeMatcher>
4151 inline internal::SizeIsMatcher<SizeMatcher>
4152 SizeIs(const SizeMatcher& size_matcher) {
4153 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4154 }
4155
4156 // Returns a matcher that matches the distance between the container's begin()
4157 // iterator and its end() iterator, i.e. the size of the container. This matcher
4158 // can be used instead of SizeIs with containers such as std::forward_list which
4159 // do not implement size(). The container must provide const_iterator (with
4160 // valid iterator_traits), begin() and end().
4161 template <typename DistanceMatcher>
4162 inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4163 BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4164 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4165 }
4166
4167 // Returns a matcher that matches an equal container.
4168 // This matcher behaves like Eq(), but in the event of mismatch lists the
4169 // values that are included in one container but not the other. (Duplicate
4170 // values and order differences are not explained.)
4171 template <typename Container>
4172 inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
4173 GTEST_REMOVE_CONST_(Container)> >
4174 ContainerEq(const Container& rhs) {
4175 // This following line is for working around a bug in MSVC 8.0,
4176 // which causes Container to be a const type sometimes.
4177 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4178 return MakePolymorphicMatcher(
4179 internal::ContainerEqMatcher<RawContainer>(rhs));
4180 }
4181
4182 // Returns a matcher that matches a container that, when sorted using
4183 // the given comparator, matches container_matcher.
4184 template <typename Comparator, typename ContainerMatcher>
4185 inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4186 WhenSortedBy(const Comparator& comparator,
4187 const ContainerMatcher& container_matcher) {
4188 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4189 comparator, container_matcher);
4190 }
4191
4192 // Returns a matcher that matches a container that, when sorted using
4193 // the < operator, matches container_matcher.
4194 template <typename ContainerMatcher>
4195 inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4196 WhenSorted(const ContainerMatcher& container_matcher) {
4197 return
4198 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4199 internal::LessComparator(), container_matcher);
4200 }
4201
4202 // Matches an STL-style container or a native array that contains the
4203 // same number of elements as in rhs, where its i-th element and rhs's
4204 // i-th element (as a pair) satisfy the given pair matcher, for all i.
4205 // TupleMatcher must be able to be safely cast to Matcher<tuple<const
4206 // T1&, const T2&> >, where T1 and T2 are the types of elements in the
4207 // LHS container and the RHS container respectively.
4208 template <typename TupleMatcher, typename Container>
4209 inline internal::PointwiseMatcher<TupleMatcher,
4210 GTEST_REMOVE_CONST_(Container)>
4211 Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4212 // This following line is for working around a bug in MSVC 8.0,
4213 // which causes Container to be a const type sometimes (e.g. when
4214 // rhs is a const int[])..
4215 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4216 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4217 tuple_matcher, rhs);
4218 }
4219
4220 #if GTEST_HAS_STD_INITIALIZER_LIST_
4221
4222 // Supports the Pointwise(m, {a, b, c}) syntax.
4223 template <typename TupleMatcher, typename T>
4224 inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4225 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4226 return Pointwise(tuple_matcher, std::vector<T>(rhs));
4227 }
4228
4229 #endif // GTEST_HAS_STD_INITIALIZER_LIST_
4230
4231 // UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4232 // container or a native array that contains the same number of
4233 // elements as in rhs, where in some permutation of the container, its
4234 // i-th element and rhs's i-th element (as a pair) satisfy the given
4235 // pair matcher, for all i. Tuple2Matcher must be able to be safely
4236 // cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4237 // the types of elements in the LHS container and the RHS container
4238 // respectively.
4239 //
4240 // This is like Pointwise(pair_matcher, rhs), except that the element
4241 // order doesn't matter.
4242 template <typename Tuple2Matcher, typename RhsContainer>
4243 inline internal::UnorderedElementsAreArrayMatcher<
4244 typename internal::BoundSecondMatcher<
4245 Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4246 RhsContainer)>::type::value_type> >
4247 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4248 const RhsContainer& rhs_container) {
4249 // This following line is for working around a bug in MSVC 8.0,
4250 // which causes RhsContainer to be a const type sometimes (e.g. when
4251 // rhs_container is a const int[]).
4252 typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4253
4254 // RhsView allows the same code to handle RhsContainer being a
4255 // STL-style container and it being a native C-style array.
4256 typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4257 typedef typename RhsView::type RhsStlContainer;
4258 typedef typename RhsStlContainer::value_type Second;
4259 const RhsStlContainer& rhs_stl_container =
4260 RhsView::ConstReference(rhs_container);
4261
4262 // Create a matcher for each element in rhs_container.
4263 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4264 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4265 it != rhs_stl_container.end(); ++it) {
4266 matchers.push_back(
4267 internal::MatcherBindSecond(tuple2_matcher, *it));
4268 }
4269
4270 // Delegate the work to UnorderedElementsAreArray().
4271 return UnorderedElementsAreArray(matchers);
4272 }
4273
4274 #if GTEST_HAS_STD_INITIALIZER_LIST_
4275
4276 // Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4277 template <typename Tuple2Matcher, typename T>
4278 inline internal::UnorderedElementsAreArrayMatcher<
4279 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4280 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4281 std::initializer_list<T> rhs) {
4282 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4283 }
4284
4285 #endif // GTEST_HAS_STD_INITIALIZER_LIST_
4286
4287 // Matches an STL-style container or a native array that contains at
4288 // least one element matching the given value or matcher.
4289 //
4290 // Examples:
4291 // ::std::set<int> page_ids;
4292 // page_ids.insert(3);
4293 // page_ids.insert(1);
4294 // EXPECT_THAT(page_ids, Contains(1));
4295 // EXPECT_THAT(page_ids, Contains(Gt(2)));
4296 // EXPECT_THAT(page_ids, Not(Contains(4)));
4297 //
4298 // ::std::map<int, size_t> page_lengths;
4299 // page_lengths[1] = 100;
4300 // EXPECT_THAT(page_lengths,
4301 // Contains(::std::pair<const int, size_t>(1, 100)));
4302 //
4303 // const char* user_ids[] = { "joe", "mike", "tom" };
4304 // EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4305 template <typename M>
4306 inline internal::ContainsMatcher<M> Contains(M matcher) {
4307 return internal::ContainsMatcher<M>(matcher);
4308 }
4309
4310 // Matches an STL-style container or a native array that contains only
4311 // elements matching the given value or matcher.
4312 //
4313 // Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
4314 // the messages are different.
4315 //
4316 // Examples:
4317 // ::std::set<int> page_ids;
4318 // // Each(m) matches an empty container, regardless of what m is.
4319 // EXPECT_THAT(page_ids, Each(Eq(1)));
4320 // EXPECT_THAT(page_ids, Each(Eq(77)));
4321 //
4322 // page_ids.insert(3);
4323 // EXPECT_THAT(page_ids, Each(Gt(0)));
4324 // EXPECT_THAT(page_ids, Not(Each(Gt(4))));
4325 // page_ids.insert(1);
4326 // EXPECT_THAT(page_ids, Not(Each(Lt(2))));
4327 //
4328 // ::std::map<int, size_t> page_lengths;
4329 // page_lengths[1] = 100;
4330 // page_lengths[2] = 200;
4331 // page_lengths[3] = 300;
4332 // EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
4333 // EXPECT_THAT(page_lengths, Each(Key(Le(3))));
4334 //
4335 // const char* user_ids[] = { "joe", "mike", "tom" };
4336 // EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
4337 template <typename M>
4338 inline internal::EachMatcher<M> Each(M matcher) {
4339 return internal::EachMatcher<M>(matcher);
4340 }
4341
4342 // Key(inner_matcher) matches an std::pair whose 'first' field matches
4343 // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
4344 // std::map that contains at least one element whose key is >= 5.
4345 template <typename M>
4346 inline internal::KeyMatcher<M> Key(M inner_matcher) {
4347 return internal::KeyMatcher<M>(inner_matcher);
4348 }
4349
4350 // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
4351 // matches first_matcher and whose 'second' field matches second_matcher. For
4352 // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
4353 // to match a std::map<int, string> that contains exactly one element whose key
4354 // is >= 5 and whose value equals "foo".
4355 template <typename FirstMatcher, typename SecondMatcher>
4356 inline internal::PairMatcher<FirstMatcher, SecondMatcher>
4357 Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
4358 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
4359 first_matcher, second_matcher);
4360 }
4361
4362 // Returns a predicate that is satisfied by anything that matches the
4363 // given matcher.
4364 template <typename M>
4365 inline internal::MatcherAsPredicate<M> Matches(M matcher) {
4366 return internal::MatcherAsPredicate<M>(matcher);
4367 }
4368
4369 // Returns true iff the value matches the matcher.
4370 template <typename T, typename M>
4371 inline bool Value(const T& value, M matcher) {
4372 return testing::Matches(matcher)(value);
4373 }
4374
4375 // Matches the value against the given matcher and explains the match
4376 // result to listener.
4377 template <typename T, typename M>
4378 inline bool ExplainMatchResult(
4379 M matcher, const T& value, MatchResultListener* listener) {
4380 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
4381 }
4382
4383 #if GTEST_LANG_CXX11
4384 // Define variadic matcher versions. They are overloaded in
4385 // gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
4386 template <typename... Args>
4387 inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
4388 return internal::AllOfMatcher<Args...>(matchers...);
4389 }
4390
4391 template <typename... Args>
4392 inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
4393 return internal::AnyOfMatcher<Args...>(matchers...);
4394 }
4395
4396 #endif // GTEST_LANG_CXX11
4397
4398 // AllArgs(m) is a synonym of m. This is useful in
4399 //
4400 // EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
4401 //
4402 // which is easier to read than
4403 //
4404 // EXPECT_CALL(foo, Bar(_, _)).With(Eq());
4405 template <typename InnerMatcher>
4406 inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
4407
4408 // These macros allow using matchers to check values in Google Test
4409 // tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
4410 // succeed iff the value matches the matcher. If the assertion fails,
4411 // the value and the description of the matcher will be printed.
4412 #define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
4413 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4414 #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
4415 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4416
4417 } // namespace testing
4418
4419 // Include any custom callback matchers added by the local installation.
4420 // We must include this header at the end to make sure it can use the
4421 // declarations from this file.
4422 #include "gmock/internal/custom/gmock-matchers.h"
4423 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
4424