blob: a7bcfc83ebd1e3c741ec43d9af647917f79ed19e [file] [log] [blame]
Austin Schuh0cbef622015-09-06 17:34:52 -07001// 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.
Austin Schuh889ac432018-10-29 22:57:02 -070029
Austin Schuh0cbef622015-09-06 17:34:52 -070030
31// Google Mock - a framework for writing C++ mock classes.
32//
33// This file implements some commonly used argument matchers. More
34// matchers can be defined by the user implementing the
35// MatcherInterface<T> interface if necessary.
36
Austin Schuh889ac432018-10-29 22:57:02 -070037// GOOGLETEST_CM0002 DO NOT DELETE
38
Austin Schuh0cbef622015-09-06 17:34:52 -070039#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
40#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
41
42#include <math.h>
43#include <algorithm>
44#include <iterator>
45#include <limits>
46#include <ostream> // NOLINT
47#include <sstream>
48#include <string>
49#include <utility>
50#include <vector>
Austin Schuh889ac432018-10-29 22:57:02 -070051#include "gtest/gtest.h"
Austin Schuh0cbef622015-09-06 17:34:52 -070052#include "gmock/internal/gmock-internal-utils.h"
53#include "gmock/internal/gmock-port.h"
Austin Schuh0cbef622015-09-06 17:34:52 -070054
55#if GTEST_HAS_STD_INITIALIZER_LIST_
56# include <initializer_list> // NOLINT -- must be after gtest.h
57#endif
58
Austin Schuh889ac432018-10-29 22:57:02 -070059GTEST_DISABLE_MSC_WARNINGS_PUSH_(
60 4251 5046 /* class A needs to have dll-interface to be used by clients of
61 class B */
62 /* Symbol involving type with internal linkage not defined */)
63
Austin Schuh0cbef622015-09-06 17:34:52 -070064namespace testing {
65
66// To implement a matcher Foo for type T, define:
67// 1. a class FooMatcherImpl that implements the
68// MatcherInterface<T> interface, and
69// 2. a factory function that creates a Matcher<T> object from a
70// FooMatcherImpl*.
71//
72// The two-level delegation design makes it possible to allow a user
73// to write "v" instead of "Eq(v)" where a Matcher is expected, which
74// is impossible if we pass matchers by pointers. It also eases
75// ownership management as Matcher objects can now be copied like
76// plain values.
77
78// MatchResultListener is an abstract class. Its << operator can be
79// used by a matcher to explain why a value matches or doesn't match.
80//
Austin Schuh889ac432018-10-29 22:57:02 -070081// FIXME: add method
Austin Schuh0cbef622015-09-06 17:34:52 -070082// bool InterestedInWhy(bool result) const;
83// to indicate whether the listener is interested in why the match
84// result is 'result'.
85class MatchResultListener {
86 public:
87 // Creates a listener object with the given underlying ostream. The
88 // listener does not own the ostream, and does not dereference it
89 // in the constructor or destructor.
90 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
91 virtual ~MatchResultListener() = 0; // Makes this class abstract.
92
93 // Streams x to the underlying ostream; does nothing if the ostream
94 // is NULL.
95 template <typename T>
96 MatchResultListener& operator<<(const T& x) {
97 if (stream_ != NULL)
98 *stream_ << x;
99 return *this;
100 }
101
102 // Returns the underlying ostream.
103 ::std::ostream* stream() { return stream_; }
104
105 // Returns true iff the listener is interested in an explanation of
106 // the match result. A matcher's MatchAndExplain() method can use
107 // this information to avoid generating the explanation when no one
108 // intends to hear it.
109 bool IsInterested() const { return stream_ != NULL; }
110
111 private:
112 ::std::ostream* const stream_;
113
114 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
115};
116
117inline MatchResultListener::~MatchResultListener() {
118}
119
120// An instance of a subclass of this knows how to describe itself as a
121// matcher.
122class MatcherDescriberInterface {
123 public:
124 virtual ~MatcherDescriberInterface() {}
125
126 // Describes this matcher to an ostream. The function should print
127 // a verb phrase that describes the property a value matching this
128 // matcher should have. The subject of the verb phrase is the value
129 // being matched. For example, the DescribeTo() method of the Gt(7)
130 // matcher prints "is greater than 7".
131 virtual void DescribeTo(::std::ostream* os) const = 0;
132
133 // Describes the negation of this matcher to an ostream. For
134 // example, if the description of this matcher is "is greater than
135 // 7", the negated description could be "is not greater than 7".
136 // You are not required to override this when implementing
137 // MatcherInterface, but it is highly advised so that your matcher
138 // can produce good error messages.
139 virtual void DescribeNegationTo(::std::ostream* os) const {
140 *os << "not (";
141 DescribeTo(os);
142 *os << ")";
143 }
144};
145
146// The implementation of a matcher.
147template <typename T>
148class MatcherInterface : public MatcherDescriberInterface {
149 public:
150 // Returns true iff the matcher matches x; also explains the match
151 // result to 'listener' if necessary (see the next paragraph), in
152 // the form of a non-restrictive relative clause ("which ...",
153 // "whose ...", etc) that describes x. For example, the
154 // MatchAndExplain() method of the Pointee(...) matcher should
155 // generate an explanation like "which points to ...".
156 //
157 // Implementations of MatchAndExplain() should add an explanation of
158 // the match result *if and only if* they can provide additional
159 // information that's not already present (or not obvious) in the
160 // print-out of x and the matcher's description. Whether the match
161 // succeeds is not a factor in deciding whether an explanation is
162 // needed, as sometimes the caller needs to print a failure message
163 // when the match succeeds (e.g. when the matcher is used inside
164 // Not()).
165 //
166 // For example, a "has at least 10 elements" matcher should explain
167 // what the actual element count is, regardless of the match result,
168 // as it is useful information to the reader; on the other hand, an
169 // "is empty" matcher probably only needs to explain what the actual
170 // size is when the match fails, as it's redundant to say that the
171 // size is 0 when the value is already known to be empty.
172 //
173 // You should override this method when defining a new matcher.
174 //
175 // It's the responsibility of the caller (Google Mock) to guarantee
176 // that 'listener' is not NULL. This helps to simplify a matcher's
177 // implementation when it doesn't care about the performance, as it
178 // can talk to 'listener' without checking its validity first.
179 // However, in order to implement dummy listeners efficiently,
180 // listener->stream() may be NULL.
181 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
182
183 // Inherits these methods from MatcherDescriberInterface:
184 // virtual void DescribeTo(::std::ostream* os) const = 0;
185 // virtual void DescribeNegationTo(::std::ostream* os) const;
186};
187
Austin Schuh889ac432018-10-29 22:57:02 -0700188namespace internal {
189
190// Converts a MatcherInterface<T> to a MatcherInterface<const T&>.
191template <typename T>
192class MatcherInterfaceAdapter : public MatcherInterface<const T&> {
193 public:
194 explicit MatcherInterfaceAdapter(const MatcherInterface<T>* impl)
195 : impl_(impl) {}
196 virtual ~MatcherInterfaceAdapter() { delete impl_; }
197
198 virtual void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
199
200 virtual void DescribeNegationTo(::std::ostream* os) const {
201 impl_->DescribeNegationTo(os);
202 }
203
204 virtual bool MatchAndExplain(const T& x,
205 MatchResultListener* listener) const {
206 return impl_->MatchAndExplain(x, listener);
207 }
208
209 private:
210 const MatcherInterface<T>* const impl_;
211
212 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatcherInterfaceAdapter);
213};
214
215} // namespace internal
216
Austin Schuh0cbef622015-09-06 17:34:52 -0700217// A match result listener that stores the explanation in a string.
218class StringMatchResultListener : public MatchResultListener {
219 public:
220 StringMatchResultListener() : MatchResultListener(&ss_) {}
221
222 // Returns the explanation accumulated so far.
Austin Schuh889ac432018-10-29 22:57:02 -0700223 std::string str() const { return ss_.str(); }
Austin Schuh0cbef622015-09-06 17:34:52 -0700224
225 // Clears the explanation accumulated so far.
226 void Clear() { ss_.str(""); }
227
228 private:
229 ::std::stringstream ss_;
230
231 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
232};
233
234namespace internal {
235
236struct AnyEq {
237 template <typename A, typename B>
238 bool operator()(const A& a, const B& b) const { return a == b; }
239};
240struct AnyNe {
241 template <typename A, typename B>
242 bool operator()(const A& a, const B& b) const { return a != b; }
243};
244struct AnyLt {
245 template <typename A, typename B>
246 bool operator()(const A& a, const B& b) const { return a < b; }
247};
248struct AnyGt {
249 template <typename A, typename B>
250 bool operator()(const A& a, const B& b) const { return a > b; }
251};
252struct AnyLe {
253 template <typename A, typename B>
254 bool operator()(const A& a, const B& b) const { return a <= b; }
255};
256struct AnyGe {
257 template <typename A, typename B>
258 bool operator()(const A& a, const B& b) const { return a >= b; }
259};
260
261// A match result listener that ignores the explanation.
262class DummyMatchResultListener : public MatchResultListener {
263 public:
264 DummyMatchResultListener() : MatchResultListener(NULL) {}
265
266 private:
267 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
268};
269
270// A match result listener that forwards the explanation to a given
271// ostream. The difference between this and MatchResultListener is
272// that the former is concrete.
273class StreamMatchResultListener : public MatchResultListener {
274 public:
275 explicit StreamMatchResultListener(::std::ostream* os)
276 : MatchResultListener(os) {}
277
278 private:
279 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
280};
281
282// An internal class for implementing Matcher<T>, which will derive
283// from it. We put functionalities common to all Matcher<T>
284// specializations here to avoid code duplication.
285template <typename T>
286class MatcherBase {
287 public:
288 // Returns true iff the matcher matches x; also explains the match
289 // result to 'listener'.
Austin Schuh889ac432018-10-29 22:57:02 -0700290 bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
291 MatchResultListener* listener) const {
Austin Schuh0cbef622015-09-06 17:34:52 -0700292 return impl_->MatchAndExplain(x, listener);
293 }
294
295 // Returns true iff this matcher matches x.
Austin Schuh889ac432018-10-29 22:57:02 -0700296 bool Matches(GTEST_REFERENCE_TO_CONST_(T) x) const {
Austin Schuh0cbef622015-09-06 17:34:52 -0700297 DummyMatchResultListener dummy;
298 return MatchAndExplain(x, &dummy);
299 }
300
301 // Describes this matcher to an ostream.
302 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
303
304 // Describes the negation of this matcher to an ostream.
305 void DescribeNegationTo(::std::ostream* os) const {
306 impl_->DescribeNegationTo(os);
307 }
308
309 // Explains why x matches, or doesn't match, the matcher.
Austin Schuh889ac432018-10-29 22:57:02 -0700310 void ExplainMatchResultTo(GTEST_REFERENCE_TO_CONST_(T) x,
311 ::std::ostream* os) const {
Austin Schuh0cbef622015-09-06 17:34:52 -0700312 StreamMatchResultListener listener(os);
313 MatchAndExplain(x, &listener);
314 }
315
316 // Returns the describer for this matcher object; retains ownership
317 // of the describer, which is only guaranteed to be alive when
318 // this matcher object is alive.
319 const MatcherDescriberInterface* GetDescriber() const {
320 return impl_.get();
321 }
322
323 protected:
324 MatcherBase() {}
325
326 // Constructs a matcher from its implementation.
Austin Schuh889ac432018-10-29 22:57:02 -0700327 explicit MatcherBase(
328 const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)>* impl)
Austin Schuh0cbef622015-09-06 17:34:52 -0700329 : impl_(impl) {}
330
Austin Schuh889ac432018-10-29 22:57:02 -0700331 template <typename U>
332 explicit MatcherBase(
333 const MatcherInterface<U>* impl,
334 typename internal::EnableIf<
335 !internal::IsSame<U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* =
336 NULL)
337 : impl_(new internal::MatcherInterfaceAdapter<U>(impl)) {}
338
Austin Schuh0cbef622015-09-06 17:34:52 -0700339 virtual ~MatcherBase() {}
340
341 private:
342 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
343 // interfaces. The former dynamically allocates a chunk of memory
344 // to hold the reference count, while the latter tracks all
345 // references using a circular linked list without allocating
346 // memory. It has been observed that linked_ptr performs better in
347 // typical scenarios. However, shared_ptr can out-perform
348 // linked_ptr when there are many more uses of the copy constructor
349 // than the default constructor.
350 //
351 // If performance becomes a problem, we should see if using
352 // shared_ptr helps.
Austin Schuh889ac432018-10-29 22:57:02 -0700353 ::testing::internal::linked_ptr<
354 const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> >
355 impl_;
Austin Schuh0cbef622015-09-06 17:34:52 -0700356};
357
358} // namespace internal
359
360// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
361// object that can check whether a value of type T matches. The
362// implementation of Matcher<T> is just a linked_ptr to const
363// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
364// from Matcher!
365template <typename T>
366class Matcher : public internal::MatcherBase<T> {
367 public:
368 // Constructs a null matcher. Needed for storing Matcher objects in STL
369 // containers. A default-constructed matcher is not yet initialized. You
370 // cannot use it until a valid value has been assigned to it.
371 explicit Matcher() {} // NOLINT
372
373 // Constructs a matcher from its implementation.
Austin Schuh889ac432018-10-29 22:57:02 -0700374 explicit Matcher(const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)>* impl)
375 : internal::MatcherBase<T>(impl) {}
376
377 template <typename U>
378 explicit Matcher(const MatcherInterface<U>* impl,
379 typename internal::EnableIf<!internal::IsSame<
380 U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* = NULL)
Austin Schuh0cbef622015-09-06 17:34:52 -0700381 : internal::MatcherBase<T>(impl) {}
382
383 // Implicit constructor here allows people to write
384 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
385 Matcher(T value); // NOLINT
386};
387
388// The following two specializations allow the user to write str
Austin Schuh889ac432018-10-29 22:57:02 -0700389// instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
Austin Schuh0cbef622015-09-06 17:34:52 -0700390// matcher is expected.
391template <>
Austin Schuh889ac432018-10-29 22:57:02 -0700392class GTEST_API_ Matcher<const std::string&>
393 : public internal::MatcherBase<const std::string&> {
Austin Schuh0cbef622015-09-06 17:34:52 -0700394 public:
395 Matcher() {}
396
Austin Schuh889ac432018-10-29 22:57:02 -0700397 explicit Matcher(const MatcherInterface<const std::string&>* impl)
398 : internal::MatcherBase<const std::string&>(impl) {}
Austin Schuh0cbef622015-09-06 17:34:52 -0700399
400 // Allows the user to write str instead of Eq(str) sometimes, where
Austin Schuh889ac432018-10-29 22:57:02 -0700401 // str is a std::string object.
402 Matcher(const std::string& s); // NOLINT
403
404#if GTEST_HAS_GLOBAL_STRING
405 // Allows the user to write str instead of Eq(str) sometimes, where
406 // str is a ::string object.
407 Matcher(const ::string& s); // NOLINT
408#endif // GTEST_HAS_GLOBAL_STRING
Austin Schuh0cbef622015-09-06 17:34:52 -0700409
410 // Allows the user to write "foo" instead of Eq("foo") sometimes.
411 Matcher(const char* s); // NOLINT
412};
413
414template <>
Austin Schuh889ac432018-10-29 22:57:02 -0700415class GTEST_API_ Matcher<std::string>
416 : public internal::MatcherBase<std::string> {
Austin Schuh0cbef622015-09-06 17:34:52 -0700417 public:
418 Matcher() {}
419
Austin Schuh889ac432018-10-29 22:57:02 -0700420 explicit Matcher(const MatcherInterface<const std::string&>* impl)
421 : internal::MatcherBase<std::string>(impl) {}
422 explicit Matcher(const MatcherInterface<std::string>* impl)
423 : internal::MatcherBase<std::string>(impl) {}
Austin Schuh0cbef622015-09-06 17:34:52 -0700424
425 // Allows the user to write str instead of Eq(str) sometimes, where
426 // str is a string object.
Austin Schuh889ac432018-10-29 22:57:02 -0700427 Matcher(const std::string& s); // NOLINT
428
429#if GTEST_HAS_GLOBAL_STRING
430 // Allows the user to write str instead of Eq(str) sometimes, where
431 // str is a ::string object.
432 Matcher(const ::string& s); // NOLINT
433#endif // GTEST_HAS_GLOBAL_STRING
Austin Schuh0cbef622015-09-06 17:34:52 -0700434
435 // Allows the user to write "foo" instead of Eq("foo") sometimes.
436 Matcher(const char* s); // NOLINT
437};
438
Austin Schuh889ac432018-10-29 22:57:02 -0700439#if GTEST_HAS_GLOBAL_STRING
Austin Schuh0cbef622015-09-06 17:34:52 -0700440// The following two specializations allow the user to write str
Austin Schuh889ac432018-10-29 22:57:02 -0700441// instead of Eq(str) and "foo" instead of Eq("foo") when a ::string
Austin Schuh0cbef622015-09-06 17:34:52 -0700442// matcher is expected.
443template <>
Austin Schuh889ac432018-10-29 22:57:02 -0700444class GTEST_API_ Matcher<const ::string&>
445 : public internal::MatcherBase<const ::string&> {
Austin Schuh0cbef622015-09-06 17:34:52 -0700446 public:
447 Matcher() {}
448
Austin Schuh889ac432018-10-29 22:57:02 -0700449 explicit Matcher(const MatcherInterface<const ::string&>* impl)
450 : internal::MatcherBase<const ::string&>(impl) {}
Austin Schuh0cbef622015-09-06 17:34:52 -0700451
452 // Allows the user to write str instead of Eq(str) sometimes, where
Austin Schuh889ac432018-10-29 22:57:02 -0700453 // str is a std::string object.
454 Matcher(const std::string& s); // NOLINT
455
456 // Allows the user to write str instead of Eq(str) sometimes, where
457 // str is a ::string object.
458 Matcher(const ::string& s); // NOLINT
Austin Schuh0cbef622015-09-06 17:34:52 -0700459
460 // Allows the user to write "foo" instead of Eq("foo") sometimes.
461 Matcher(const char* s); // NOLINT
Austin Schuh0cbef622015-09-06 17:34:52 -0700462};
463
464template <>
Austin Schuh889ac432018-10-29 22:57:02 -0700465class GTEST_API_ Matcher< ::string>
466 : public internal::MatcherBase< ::string> {
Austin Schuh0cbef622015-09-06 17:34:52 -0700467 public:
468 Matcher() {}
469
Austin Schuh889ac432018-10-29 22:57:02 -0700470 explicit Matcher(const MatcherInterface<const ::string&>* impl)
471 : internal::MatcherBase< ::string>(impl) {}
472 explicit Matcher(const MatcherInterface< ::string>* impl)
473 : internal::MatcherBase< ::string>(impl) {}
Austin Schuh0cbef622015-09-06 17:34:52 -0700474
475 // Allows the user to write str instead of Eq(str) sometimes, where
Austin Schuh889ac432018-10-29 22:57:02 -0700476 // str is a std::string object.
477 Matcher(const std::string& s); // NOLINT
478
479 // Allows the user to write str instead of Eq(str) sometimes, where
480 // str is a ::string object.
481 Matcher(const ::string& s); // NOLINT
482
483 // Allows the user to write "foo" instead of Eq("foo") sometimes.
484 Matcher(const char* s); // NOLINT
485};
486#endif // GTEST_HAS_GLOBAL_STRING
487
488#if GTEST_HAS_ABSL
489// The following two specializations allow the user to write str
490// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
491// matcher is expected.
492template <>
493class GTEST_API_ Matcher<const absl::string_view&>
494 : public internal::MatcherBase<const absl::string_view&> {
495 public:
496 Matcher() {}
497
498 explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
499 : internal::MatcherBase<const absl::string_view&>(impl) {}
500
501 // Allows the user to write str instead of Eq(str) sometimes, where
502 // str is a std::string object.
503 Matcher(const std::string& s); // NOLINT
504
505#if GTEST_HAS_GLOBAL_STRING
506 // Allows the user to write str instead of Eq(str) sometimes, where
507 // str is a ::string object.
508 Matcher(const ::string& s); // NOLINT
509#endif // GTEST_HAS_GLOBAL_STRING
Austin Schuh0cbef622015-09-06 17:34:52 -0700510
511 // Allows the user to write "foo" instead of Eq("foo") sometimes.
512 Matcher(const char* s); // NOLINT
513
Austin Schuh889ac432018-10-29 22:57:02 -0700514 // Allows the user to pass absl::string_views directly.
515 Matcher(absl::string_view s); // NOLINT
Austin Schuh0cbef622015-09-06 17:34:52 -0700516};
Austin Schuh889ac432018-10-29 22:57:02 -0700517
518template <>
519class GTEST_API_ Matcher<absl::string_view>
520 : public internal::MatcherBase<absl::string_view> {
521 public:
522 Matcher() {}
523
524 explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
525 : internal::MatcherBase<absl::string_view>(impl) {}
526 explicit Matcher(const MatcherInterface<absl::string_view>* impl)
527 : internal::MatcherBase<absl::string_view>(impl) {}
528
529 // Allows the user to write str instead of Eq(str) sometimes, where
530 // str is a std::string object.
531 Matcher(const std::string& s); // NOLINT
532
533#if GTEST_HAS_GLOBAL_STRING
534 // Allows the user to write str instead of Eq(str) sometimes, where
535 // str is a ::string object.
536 Matcher(const ::string& s); // NOLINT
537#endif // GTEST_HAS_GLOBAL_STRING
538
539 // Allows the user to write "foo" instead of Eq("foo") sometimes.
540 Matcher(const char* s); // NOLINT
541
542 // Allows the user to pass absl::string_views directly.
543 Matcher(absl::string_view s); // NOLINT
544};
545#endif // GTEST_HAS_ABSL
546
547// Prints a matcher in a human-readable format.
548template <typename T>
549std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
550 matcher.DescribeTo(&os);
551 return os;
552}
Austin Schuh0cbef622015-09-06 17:34:52 -0700553
554// The PolymorphicMatcher class template makes it easy to implement a
555// polymorphic matcher (i.e. a matcher that can match values of more
556// than one type, e.g. Eq(n) and NotNull()).
557//
558// To define a polymorphic matcher, a user should provide an Impl
559// class that has a DescribeTo() method and a DescribeNegationTo()
560// method, and define a member function (or member function template)
561//
562// bool MatchAndExplain(const Value& value,
563// MatchResultListener* listener) const;
564//
565// See the definition of NotNull() for a complete example.
566template <class Impl>
567class PolymorphicMatcher {
568 public:
569 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
570
571 // Returns a mutable reference to the underlying matcher
572 // implementation object.
573 Impl& mutable_impl() { return impl_; }
574
575 // Returns an immutable reference to the underlying matcher
576 // implementation object.
577 const Impl& impl() const { return impl_; }
578
579 template <typename T>
580 operator Matcher<T>() const {
Austin Schuh889ac432018-10-29 22:57:02 -0700581 return Matcher<T>(new MonomorphicImpl<GTEST_REFERENCE_TO_CONST_(T)>(impl_));
Austin Schuh0cbef622015-09-06 17:34:52 -0700582 }
583
584 private:
585 template <typename T>
586 class MonomorphicImpl : public MatcherInterface<T> {
587 public:
588 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
589
590 virtual void DescribeTo(::std::ostream* os) const {
591 impl_.DescribeTo(os);
592 }
593
594 virtual void DescribeNegationTo(::std::ostream* os) const {
595 impl_.DescribeNegationTo(os);
596 }
597
598 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
599 return impl_.MatchAndExplain(x, listener);
600 }
601
602 private:
603 const Impl impl_;
604
605 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
606 };
607
608 Impl impl_;
609
610 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
611};
612
613// Creates a matcher from its implementation. This is easier to use
614// than the Matcher<T> constructor as it doesn't require you to
615// explicitly write the template argument, e.g.
616//
617// MakeMatcher(foo);
618// vs
619// Matcher<const string&>(foo);
620template <typename T>
621inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
622 return Matcher<T>(impl);
623}
624
625// Creates a polymorphic matcher from its implementation. This is
626// easier to use than the PolymorphicMatcher<Impl> constructor as it
627// doesn't require you to explicitly write the template argument, e.g.
628//
629// MakePolymorphicMatcher(foo);
630// vs
631// PolymorphicMatcher<TypeOfFoo>(foo);
632template <class Impl>
633inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
634 return PolymorphicMatcher<Impl>(impl);
635}
636
637// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
638// and MUST NOT BE USED IN USER CODE!!!
639namespace internal {
640
641// The MatcherCastImpl class template is a helper for implementing
642// MatcherCast(). We need this helper in order to partially
643// specialize the implementation of MatcherCast() (C++ allows
644// class/struct templates to be partially specialized, but not
645// function templates.).
646
647// This general version is used when MatcherCast()'s argument is a
648// polymorphic matcher (i.e. something that can be converted to a
649// Matcher but is not one yet; for example, Eq(value)) or a value (for
650// example, "hello").
651template <typename T, typename M>
652class MatcherCastImpl {
653 public:
654 static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
Austin Schuh889ac432018-10-29 22:57:02 -0700655 // M can be a polymorphic matcher, in which case we want to use
Austin Schuh0cbef622015-09-06 17:34:52 -0700656 // its conversion operator to create Matcher<T>. Or it can be a value
657 // that should be passed to the Matcher<T>'s constructor.
658 //
659 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
660 // polymorphic matcher because it'll be ambiguous if T has an implicit
661 // constructor from M (this usually happens when T has an implicit
662 // constructor from any type).
663 //
664 // It won't work to unconditionally implict_cast
665 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
666 // a user-defined conversion from M to T if one exists (assuming M is
667 // a value).
668 return CastImpl(
669 polymorphic_matcher_or_value,
670 BooleanConstant<
Austin Schuh889ac432018-10-29 22:57:02 -0700671 internal::ImplicitlyConvertible<M, Matcher<T> >::value>(),
672 BooleanConstant<
673 internal::ImplicitlyConvertible<M, T>::value>());
Austin Schuh0cbef622015-09-06 17:34:52 -0700674 }
675
676 private:
Austin Schuh889ac432018-10-29 22:57:02 -0700677 template <bool Ignore>
Austin Schuh0cbef622015-09-06 17:34:52 -0700678 static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
Austin Schuh889ac432018-10-29 22:57:02 -0700679 BooleanConstant<true> /* convertible_to_matcher */,
680 BooleanConstant<Ignore>) {
Austin Schuh0cbef622015-09-06 17:34:52 -0700681 // M is implicitly convertible to Matcher<T>, which means that either
Austin Schuh889ac432018-10-29 22:57:02 -0700682 // M is a polymorphic matcher or Matcher<T> has an implicit constructor
Austin Schuh0cbef622015-09-06 17:34:52 -0700683 // from M. In both cases using the implicit conversion will produce a
684 // matcher.
685 //
686 // Even if T has an implicit constructor from M, it won't be called because
687 // creating Matcher<T> would require a chain of two user-defined conversions
688 // (first to create T from M and then to create Matcher<T> from T).
689 return polymorphic_matcher_or_value;
690 }
Austin Schuh889ac432018-10-29 22:57:02 -0700691
692 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
693 // matcher. It's a value of a type implicitly convertible to T. Use direct
694 // initialization to create a matcher.
695 static Matcher<T> CastImpl(
696 const M& value, BooleanConstant<false> /* convertible_to_matcher */,
697 BooleanConstant<true> /* convertible_to_T */) {
698 return Matcher<T>(ImplicitCast_<T>(value));
699 }
700
701 // M can't be implicitly converted to either Matcher<T> or T. Attempt to use
702 // polymorphic matcher Eq(value) in this case.
703 //
704 // Note that we first attempt to perform an implicit cast on the value and
705 // only fall back to the polymorphic Eq() matcher afterwards because the
706 // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end
707 // which might be undefined even when Rhs is implicitly convertible to Lhs
708 // (e.g. std::pair<const int, int> vs. std::pair<int, int>).
709 //
710 // We don't define this method inline as we need the declaration of Eq().
711 static Matcher<T> CastImpl(
712 const M& value, BooleanConstant<false> /* convertible_to_matcher */,
713 BooleanConstant<false> /* convertible_to_T */);
Austin Schuh0cbef622015-09-06 17:34:52 -0700714};
715
716// This more specialized version is used when MatcherCast()'s argument
717// is already a Matcher. This only compiles when type T can be
718// statically converted to type U.
719template <typename T, typename U>
720class MatcherCastImpl<T, Matcher<U> > {
721 public:
722 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
723 return Matcher<T>(new Impl(source_matcher));
724 }
725
726 private:
727 class Impl : public MatcherInterface<T> {
728 public:
729 explicit Impl(const Matcher<U>& source_matcher)
730 : source_matcher_(source_matcher) {}
731
732 // We delegate the matching logic to the source matcher.
733 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
Austin Schuh889ac432018-10-29 22:57:02 -0700734#if GTEST_LANG_CXX11
735 using FromType = typename std::remove_cv<typename std::remove_pointer<
736 typename std::remove_reference<T>::type>::type>::type;
737 using ToType = typename std::remove_cv<typename std::remove_pointer<
738 typename std::remove_reference<U>::type>::type>::type;
739 // Do not allow implicitly converting base*/& to derived*/&.
740 static_assert(
741 // Do not trigger if only one of them is a pointer. That implies a
742 // regular conversion and not a down_cast.
743 (std::is_pointer<typename std::remove_reference<T>::type>::value !=
744 std::is_pointer<typename std::remove_reference<U>::type>::value) ||
745 std::is_same<FromType, ToType>::value ||
746 !std::is_base_of<FromType, ToType>::value,
747 "Can't implicitly convert from <base> to <derived>");
748#endif // GTEST_LANG_CXX11
749
Austin Schuh0cbef622015-09-06 17:34:52 -0700750 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
751 }
752
753 virtual void DescribeTo(::std::ostream* os) const {
754 source_matcher_.DescribeTo(os);
755 }
756
757 virtual void DescribeNegationTo(::std::ostream* os) const {
758 source_matcher_.DescribeNegationTo(os);
759 }
760
761 private:
762 const Matcher<U> source_matcher_;
763
764 GTEST_DISALLOW_ASSIGN_(Impl);
765 };
766};
767
768// This even more specialized version is used for efficiently casting
769// a matcher to its own type.
770template <typename T>
771class MatcherCastImpl<T, Matcher<T> > {
772 public:
773 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
774};
775
776} // namespace internal
777
778// In order to be safe and clear, casting between different matcher
779// types is done explicitly via MatcherCast<T>(m), which takes a
780// matcher m and returns a Matcher<T>. It compiles only when T can be
781// statically converted to the argument type of m.
782template <typename T, typename M>
783inline Matcher<T> MatcherCast(const M& matcher) {
784 return internal::MatcherCastImpl<T, M>::Cast(matcher);
785}
786
787// Implements SafeMatcherCast().
788//
789// We use an intermediate class to do the actual safe casting as Nokia's
790// Symbian compiler cannot decide between
791// template <T, M> ... (M) and
792// template <T, U> ... (const Matcher<U>&)
793// for function templates but can for member function templates.
794template <typename T>
795class SafeMatcherCastImpl {
796 public:
797 // This overload handles polymorphic matchers and values only since
798 // monomorphic matchers are handled by the next one.
799 template <typename M>
800 static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
801 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
802 }
803
804 // This overload handles monomorphic matchers.
805 //
806 // In general, if type T can be implicitly converted to type U, we can
807 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
808 // contravariant): just keep a copy of the original Matcher<U>, convert the
809 // argument from type T to U, and then pass it to the underlying Matcher<U>.
810 // The only exception is when U is a reference and T is not, as the
811 // underlying Matcher<U> may be interested in the argument's address, which
812 // is not preserved in the conversion from T to U.
813 template <typename U>
814 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
815 // Enforce that T can be implicitly converted to U.
816 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
817 T_must_be_implicitly_convertible_to_U);
818 // Enforce that we are not converting a non-reference type T to a reference
819 // type U.
820 GTEST_COMPILE_ASSERT_(
821 internal::is_reference<T>::value || !internal::is_reference<U>::value,
Austin Schuh889ac432018-10-29 22:57:02 -0700822 cannot_convert_non_reference_arg_to_reference);
Austin Schuh0cbef622015-09-06 17:34:52 -0700823 // In case both T and U are arithmetic types, enforce that the
824 // conversion is not lossy.
825 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
826 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
827 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
828 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
829 GTEST_COMPILE_ASSERT_(
830 kTIsOther || kUIsOther ||
831 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
832 conversion_of_arithmetic_types_must_be_lossless);
833 return MatcherCast<T>(matcher);
834 }
835};
836
837template <typename T, typename M>
838inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
839 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
840}
841
842// A<T>() returns a matcher that matches any value of type T.
843template <typename T>
844Matcher<T> A();
845
846// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
847// and MUST NOT BE USED IN USER CODE!!!
848namespace internal {
849
850// If the explanation is not empty, prints it to the ostream.
Austin Schuh889ac432018-10-29 22:57:02 -0700851inline void PrintIfNotEmpty(const std::string& explanation,
Austin Schuh0cbef622015-09-06 17:34:52 -0700852 ::std::ostream* os) {
853 if (explanation != "" && os != NULL) {
854 *os << ", " << explanation;
855 }
856}
857
858// Returns true if the given type name is easy to read by a human.
859// This is used to decide whether printing the type of a value might
860// be helpful.
Austin Schuh889ac432018-10-29 22:57:02 -0700861inline bool IsReadableTypeName(const std::string& type_name) {
Austin Schuh0cbef622015-09-06 17:34:52 -0700862 // We consider a type name readable if it's short or doesn't contain
863 // a template or function type.
864 return (type_name.length() <= 20 ||
Austin Schuh889ac432018-10-29 22:57:02 -0700865 type_name.find_first_of("<(") == std::string::npos);
Austin Schuh0cbef622015-09-06 17:34:52 -0700866}
867
868// Matches the value against the given matcher, prints the value and explains
869// the match result to the listener. Returns the match result.
870// 'listener' must not be NULL.
871// Value cannot be passed by const reference, because some matchers take a
872// non-const argument.
873template <typename Value, typename T>
874bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
875 MatchResultListener* listener) {
876 if (!listener->IsInterested()) {
877 // If the listener is not interested, we do not need to construct the
878 // inner explanation.
879 return matcher.Matches(value);
880 }
881
882 StringMatchResultListener inner_listener;
883 const bool match = matcher.MatchAndExplain(value, &inner_listener);
884
885 UniversalPrint(value, listener->stream());
886#if GTEST_HAS_RTTI
Austin Schuh889ac432018-10-29 22:57:02 -0700887 const std::string& type_name = GetTypeName<Value>();
Austin Schuh0cbef622015-09-06 17:34:52 -0700888 if (IsReadableTypeName(type_name))
889 *listener->stream() << " (of type " << type_name << ")";
890#endif
891 PrintIfNotEmpty(inner_listener.str(), listener->stream());
892
893 return match;
894}
895
896// An internal helper class for doing compile-time loop on a tuple's
897// fields.
898template <size_t N>
899class TuplePrefix {
900 public:
901 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
902 // iff the first N fields of matcher_tuple matches the first N
903 // fields of value_tuple, respectively.
904 template <typename MatcherTuple, typename ValueTuple>
905 static bool Matches(const MatcherTuple& matcher_tuple,
906 const ValueTuple& value_tuple) {
907 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
908 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
909 }
910
911 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
912 // describes failures in matching the first N fields of matchers
913 // against the first N fields of values. If there is no failure,
914 // nothing will be streamed to os.
915 template <typename MatcherTuple, typename ValueTuple>
916 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
917 const ValueTuple& values,
918 ::std::ostream* os) {
919 // First, describes failures in the first N - 1 fields.
920 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
921
922 // Then describes the failure (if any) in the (N - 1)-th (0-based)
923 // field.
924 typename tuple_element<N - 1, MatcherTuple>::type matcher =
925 get<N - 1>(matchers);
926 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
Austin Schuh889ac432018-10-29 22:57:02 -0700927 GTEST_REFERENCE_TO_CONST_(Value) value = get<N - 1>(values);
Austin Schuh0cbef622015-09-06 17:34:52 -0700928 StringMatchResultListener listener;
929 if (!matcher.MatchAndExplain(value, &listener)) {
Austin Schuh889ac432018-10-29 22:57:02 -0700930 // FIXME: include in the message the name of the parameter
Austin Schuh0cbef622015-09-06 17:34:52 -0700931 // as used in MOCK_METHOD*() when possible.
932 *os << " Expected arg #" << N - 1 << ": ";
933 get<N - 1>(matchers).DescribeTo(os);
934 *os << "\n Actual: ";
935 // We remove the reference in type Value to prevent the
936 // universal printer from printing the address of value, which
937 // isn't interesting to the user most of the time. The
938 // matcher's MatchAndExplain() method handles the case when
939 // the address is interesting.
940 internal::UniversalPrint(value, os);
941 PrintIfNotEmpty(listener.str(), os);
942 *os << "\n";
943 }
944 }
945};
946
947// The base case.
948template <>
949class TuplePrefix<0> {
950 public:
951 template <typename MatcherTuple, typename ValueTuple>
952 static bool Matches(const MatcherTuple& /* matcher_tuple */,
953 const ValueTuple& /* value_tuple */) {
954 return true;
955 }
956
957 template <typename MatcherTuple, typename ValueTuple>
958 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
959 const ValueTuple& /* values */,
960 ::std::ostream* /* os */) {}
961};
962
963// TupleMatches(matcher_tuple, value_tuple) returns true iff all
964// matchers in matcher_tuple match the corresponding fields in
965// value_tuple. It is a compiler error if matcher_tuple and
966// value_tuple have different number of fields or incompatible field
967// types.
968template <typename MatcherTuple, typename ValueTuple>
969bool TupleMatches(const MatcherTuple& matcher_tuple,
970 const ValueTuple& value_tuple) {
971 // Makes sure that matcher_tuple and value_tuple have the same
972 // number of fields.
973 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
974 tuple_size<ValueTuple>::value,
975 matcher_and_value_have_different_numbers_of_fields);
976 return TuplePrefix<tuple_size<ValueTuple>::value>::
977 Matches(matcher_tuple, value_tuple);
978}
979
980// Describes failures in matching matchers against values. If there
981// is no failure, nothing will be streamed to os.
982template <typename MatcherTuple, typename ValueTuple>
983void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
984 const ValueTuple& values,
985 ::std::ostream* os) {
986 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
987 matchers, values, os);
988}
989
990// TransformTupleValues and its helper.
991//
992// TransformTupleValuesHelper hides the internal machinery that
993// TransformTupleValues uses to implement a tuple traversal.
994template <typename Tuple, typename Func, typename OutIter>
995class TransformTupleValuesHelper {
996 private:
997 typedef ::testing::tuple_size<Tuple> TupleSize;
998
999 public:
1000 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
1001 // Returns the final value of 'out' in case the caller needs it.
1002 static OutIter Run(Func f, const Tuple& t, OutIter out) {
1003 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
1004 }
1005
1006 private:
1007 template <typename Tup, size_t kRemainingSize>
1008 struct IterateOverTuple {
1009 OutIter operator() (Func f, const Tup& t, OutIter out) const {
1010 *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
1011 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
1012 }
1013 };
1014 template <typename Tup>
1015 struct IterateOverTuple<Tup, 0> {
1016 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
1017 return out;
1018 }
1019 };
1020};
1021
1022// Successively invokes 'f(element)' on each element of the tuple 't',
1023// appending each result to the 'out' iterator. Returns the final value
1024// of 'out'.
1025template <typename Tuple, typename Func, typename OutIter>
1026OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
1027 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
1028}
1029
1030// Implements A<T>().
1031template <typename T>
Austin Schuh889ac432018-10-29 22:57:02 -07001032class AnyMatcherImpl : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
Austin Schuh0cbef622015-09-06 17:34:52 -07001033 public:
Austin Schuh889ac432018-10-29 22:57:02 -07001034 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) /* x */,
1035 MatchResultListener* /* listener */) const {
1036 return true;
1037 }
Austin Schuh0cbef622015-09-06 17:34:52 -07001038 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
1039 virtual void DescribeNegationTo(::std::ostream* os) const {
1040 // This is mostly for completeness' safe, as it's not very useful
1041 // to write Not(A<bool>()). However we cannot completely rule out
1042 // such a possibility, and it doesn't hurt to be prepared.
1043 *os << "never matches";
1044 }
1045};
1046
1047// Implements _, a matcher that matches any value of any
1048// type. This is a polymorphic matcher, so we need a template type
1049// conversion operator to make it appearing as a Matcher<T> for any
1050// type T.
1051class AnythingMatcher {
1052 public:
1053 template <typename T>
1054 operator Matcher<T>() const { return A<T>(); }
1055};
1056
1057// Implements a matcher that compares a given value with a
1058// pre-supplied value using one of the ==, <=, <, etc, operators. The
1059// two values being compared don't have to have the same type.
1060//
1061// The matcher defined here is polymorphic (for example, Eq(5) can be
1062// used to match an int, a short, a double, etc). Therefore we use
1063// a template type conversion operator in the implementation.
1064//
1065// The following template definition assumes that the Rhs parameter is
1066// a "bare" type (i.e. neither 'const T' nor 'T&').
1067template <typename D, typename Rhs, typename Op>
1068class ComparisonBase {
1069 public:
1070 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
1071 template <typename Lhs>
1072 operator Matcher<Lhs>() const {
1073 return MakeMatcher(new Impl<Lhs>(rhs_));
1074 }
1075
1076 private:
1077 template <typename Lhs>
1078 class Impl : public MatcherInterface<Lhs> {
1079 public:
1080 explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
1081 virtual bool MatchAndExplain(
1082 Lhs lhs, MatchResultListener* /* listener */) const {
1083 return Op()(lhs, rhs_);
1084 }
1085 virtual void DescribeTo(::std::ostream* os) const {
1086 *os << D::Desc() << " ";
1087 UniversalPrint(rhs_, os);
1088 }
1089 virtual void DescribeNegationTo(::std::ostream* os) const {
1090 *os << D::NegatedDesc() << " ";
1091 UniversalPrint(rhs_, os);
1092 }
1093 private:
1094 Rhs rhs_;
1095 GTEST_DISALLOW_ASSIGN_(Impl);
1096 };
1097 Rhs rhs_;
1098 GTEST_DISALLOW_ASSIGN_(ComparisonBase);
1099};
1100
1101template <typename Rhs>
1102class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
1103 public:
1104 explicit EqMatcher(const Rhs& rhs)
1105 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
1106 static const char* Desc() { return "is equal to"; }
1107 static const char* NegatedDesc() { return "isn't equal to"; }
1108};
1109template <typename Rhs>
1110class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
1111 public:
1112 explicit NeMatcher(const Rhs& rhs)
1113 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
1114 static const char* Desc() { return "isn't equal to"; }
1115 static const char* NegatedDesc() { return "is equal to"; }
1116};
1117template <typename Rhs>
1118class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
1119 public:
1120 explicit LtMatcher(const Rhs& rhs)
1121 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
1122 static const char* Desc() { return "is <"; }
1123 static const char* NegatedDesc() { return "isn't <"; }
1124};
1125template <typename Rhs>
1126class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
1127 public:
1128 explicit GtMatcher(const Rhs& rhs)
1129 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
1130 static const char* Desc() { return "is >"; }
1131 static const char* NegatedDesc() { return "isn't >"; }
1132};
1133template <typename Rhs>
1134class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
1135 public:
1136 explicit LeMatcher(const Rhs& rhs)
1137 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
1138 static const char* Desc() { return "is <="; }
1139 static const char* NegatedDesc() { return "isn't <="; }
1140};
1141template <typename Rhs>
1142class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
1143 public:
1144 explicit GeMatcher(const Rhs& rhs)
1145 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
1146 static const char* Desc() { return "is >="; }
1147 static const char* NegatedDesc() { return "isn't >="; }
1148};
1149
1150// Implements the polymorphic IsNull() matcher, which matches any raw or smart
1151// pointer that is NULL.
1152class IsNullMatcher {
1153 public:
1154 template <typename Pointer>
1155 bool MatchAndExplain(const Pointer& p,
1156 MatchResultListener* /* listener */) const {
1157#if GTEST_LANG_CXX11
1158 return p == nullptr;
1159#else // GTEST_LANG_CXX11
1160 return GetRawPointer(p) == NULL;
1161#endif // GTEST_LANG_CXX11
1162 }
1163
1164 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
1165 void DescribeNegationTo(::std::ostream* os) const {
1166 *os << "isn't NULL";
1167 }
1168};
1169
1170// Implements the polymorphic NotNull() matcher, which matches any raw or smart
1171// pointer that is not NULL.
1172class NotNullMatcher {
1173 public:
1174 template <typename Pointer>
1175 bool MatchAndExplain(const Pointer& p,
1176 MatchResultListener* /* listener */) const {
1177#if GTEST_LANG_CXX11
1178 return p != nullptr;
1179#else // GTEST_LANG_CXX11
1180 return GetRawPointer(p) != NULL;
1181#endif // GTEST_LANG_CXX11
1182 }
1183
1184 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
1185 void DescribeNegationTo(::std::ostream* os) const {
1186 *os << "is NULL";
1187 }
1188};
1189
1190// Ref(variable) matches any argument that is a reference to
1191// 'variable'. This matcher is polymorphic as it can match any
1192// super type of the type of 'variable'.
1193//
1194// The RefMatcher template class implements Ref(variable). It can
1195// only be instantiated with a reference type. This prevents a user
1196// from mistakenly using Ref(x) to match a non-reference function
1197// argument. For example, the following will righteously cause a
1198// compiler error:
1199//
1200// int n;
1201// Matcher<int> m1 = Ref(n); // This won't compile.
1202// Matcher<int&> m2 = Ref(n); // This will compile.
1203template <typename T>
1204class RefMatcher;
1205
1206template <typename T>
1207class RefMatcher<T&> {
1208 // Google Mock is a generic framework and thus needs to support
1209 // mocking any function types, including those that take non-const
1210 // reference arguments. Therefore the template parameter T (and
1211 // Super below) can be instantiated to either a const type or a
1212 // non-const type.
1213 public:
1214 // RefMatcher() takes a T& instead of const T&, as we want the
1215 // compiler to catch using Ref(const_value) as a matcher for a
1216 // non-const reference.
1217 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
1218
1219 template <typename Super>
1220 operator Matcher<Super&>() const {
1221 // By passing object_ (type T&) to Impl(), which expects a Super&,
1222 // we make sure that Super is a super type of T. In particular,
1223 // this catches using Ref(const_value) as a matcher for a
1224 // non-const reference, as you cannot implicitly convert a const
1225 // reference to a non-const reference.
1226 return MakeMatcher(new Impl<Super>(object_));
1227 }
1228
1229 private:
1230 template <typename Super>
1231 class Impl : public MatcherInterface<Super&> {
1232 public:
1233 explicit Impl(Super& x) : object_(x) {} // NOLINT
1234
1235 // MatchAndExplain() takes a Super& (as opposed to const Super&)
1236 // in order to match the interface MatcherInterface<Super&>.
1237 virtual bool MatchAndExplain(
1238 Super& x, MatchResultListener* listener) const {
1239 *listener << "which is located @" << static_cast<const void*>(&x);
1240 return &x == &object_;
1241 }
1242
1243 virtual void DescribeTo(::std::ostream* os) const {
1244 *os << "references the variable ";
1245 UniversalPrinter<Super&>::Print(object_, os);
1246 }
1247
1248 virtual void DescribeNegationTo(::std::ostream* os) const {
1249 *os << "does not reference the variable ";
1250 UniversalPrinter<Super&>::Print(object_, os);
1251 }
1252
1253 private:
1254 const Super& object_;
1255
1256 GTEST_DISALLOW_ASSIGN_(Impl);
1257 };
1258
1259 T& object_;
1260
1261 GTEST_DISALLOW_ASSIGN_(RefMatcher);
1262};
1263
1264// Polymorphic helper functions for narrow and wide string matchers.
1265inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1266 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1267}
1268
1269inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1270 const wchar_t* rhs) {
1271 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1272}
1273
1274// String comparison for narrow or wide strings that can have embedded NUL
1275// characters.
1276template <typename StringType>
1277bool CaseInsensitiveStringEquals(const StringType& s1,
1278 const StringType& s2) {
1279 // Are the heads equal?
1280 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1281 return false;
1282 }
1283
1284 // Skip the equal heads.
1285 const typename StringType::value_type nul = 0;
1286 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1287
1288 // Are we at the end of either s1 or s2?
1289 if (i1 == StringType::npos || i2 == StringType::npos) {
1290 return i1 == i2;
1291 }
1292
1293 // Are the tails equal?
1294 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1295}
1296
1297// String matchers.
1298
1299// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1300template <typename StringType>
1301class StrEqualityMatcher {
1302 public:
1303 StrEqualityMatcher(const StringType& str, bool expect_eq,
1304 bool case_sensitive)
1305 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1306
Austin Schuh889ac432018-10-29 22:57:02 -07001307#if GTEST_HAS_ABSL
1308 bool MatchAndExplain(const absl::string_view& s,
1309 MatchResultListener* listener) const {
1310 if (s.data() == NULL) {
1311 return !expect_eq_;
1312 }
1313 // This should fail to compile if absl::string_view is used with wide
1314 // strings.
1315 const StringType& str = string(s);
1316 return MatchAndExplain(str, listener);
1317 }
1318#endif // GTEST_HAS_ABSL
1319
Austin Schuh0cbef622015-09-06 17:34:52 -07001320 // Accepts pointer types, particularly:
1321 // const char*
1322 // char*
1323 // const wchar_t*
1324 // wchar_t*
1325 template <typename CharType>
1326 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1327 if (s == NULL) {
1328 return !expect_eq_;
1329 }
1330 return MatchAndExplain(StringType(s), listener);
1331 }
1332
1333 // Matches anything that can convert to StringType.
1334 //
1335 // This is a template, not just a plain function with const StringType&,
Austin Schuh889ac432018-10-29 22:57:02 -07001336 // because absl::string_view has some interfering non-explicit constructors.
Austin Schuh0cbef622015-09-06 17:34:52 -07001337 template <typename MatcheeStringType>
1338 bool MatchAndExplain(const MatcheeStringType& s,
1339 MatchResultListener* /* listener */) const {
1340 const StringType& s2(s);
1341 const bool eq = case_sensitive_ ? s2 == string_ :
1342 CaseInsensitiveStringEquals(s2, string_);
1343 return expect_eq_ == eq;
1344 }
1345
1346 void DescribeTo(::std::ostream* os) const {
1347 DescribeToHelper(expect_eq_, os);
1348 }
1349
1350 void DescribeNegationTo(::std::ostream* os) const {
1351 DescribeToHelper(!expect_eq_, os);
1352 }
1353
1354 private:
1355 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
1356 *os << (expect_eq ? "is " : "isn't ");
1357 *os << "equal to ";
1358 if (!case_sensitive_) {
1359 *os << "(ignoring case) ";
1360 }
1361 UniversalPrint(string_, os);
1362 }
1363
1364 const StringType string_;
1365 const bool expect_eq_;
1366 const bool case_sensitive_;
1367
1368 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
1369};
1370
1371// Implements the polymorphic HasSubstr(substring) matcher, which
1372// can be used as a Matcher<T> as long as T can be converted to a
1373// string.
1374template <typename StringType>
1375class HasSubstrMatcher {
1376 public:
1377 explicit HasSubstrMatcher(const StringType& substring)
1378 : substring_(substring) {}
1379
Austin Schuh889ac432018-10-29 22:57:02 -07001380#if GTEST_HAS_ABSL
1381 bool MatchAndExplain(const absl::string_view& s,
1382 MatchResultListener* listener) const {
1383 if (s.data() == NULL) {
1384 return false;
1385 }
1386 // This should fail to compile if absl::string_view is used with wide
1387 // strings.
1388 const StringType& str = string(s);
1389 return MatchAndExplain(str, listener);
1390 }
1391#endif // GTEST_HAS_ABSL
1392
Austin Schuh0cbef622015-09-06 17:34:52 -07001393 // Accepts pointer types, particularly:
1394 // const char*
1395 // char*
1396 // const wchar_t*
1397 // wchar_t*
1398 template <typename CharType>
1399 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1400 return s != NULL && MatchAndExplain(StringType(s), listener);
1401 }
1402
1403 // Matches anything that can convert to StringType.
1404 //
1405 // This is a template, not just a plain function with const StringType&,
Austin Schuh889ac432018-10-29 22:57:02 -07001406 // because absl::string_view has some interfering non-explicit constructors.
Austin Schuh0cbef622015-09-06 17:34:52 -07001407 template <typename MatcheeStringType>
1408 bool MatchAndExplain(const MatcheeStringType& s,
1409 MatchResultListener* /* listener */) const {
1410 const StringType& s2(s);
1411 return s2.find(substring_) != StringType::npos;
1412 }
1413
1414 // Describes what this matcher matches.
1415 void DescribeTo(::std::ostream* os) const {
1416 *os << "has substring ";
1417 UniversalPrint(substring_, os);
1418 }
1419
1420 void DescribeNegationTo(::std::ostream* os) const {
1421 *os << "has no substring ";
1422 UniversalPrint(substring_, os);
1423 }
1424
1425 private:
1426 const StringType substring_;
1427
1428 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
1429};
1430
1431// Implements the polymorphic StartsWith(substring) matcher, which
1432// can be used as a Matcher<T> as long as T can be converted to a
1433// string.
1434template <typename StringType>
1435class StartsWithMatcher {
1436 public:
1437 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1438 }
1439
Austin Schuh889ac432018-10-29 22:57:02 -07001440#if GTEST_HAS_ABSL
1441 bool MatchAndExplain(const absl::string_view& s,
1442 MatchResultListener* listener) const {
1443 if (s.data() == NULL) {
1444 return false;
1445 }
1446 // This should fail to compile if absl::string_view is used with wide
1447 // strings.
1448 const StringType& str = string(s);
1449 return MatchAndExplain(str, listener);
1450 }
1451#endif // GTEST_HAS_ABSL
1452
Austin Schuh0cbef622015-09-06 17:34:52 -07001453 // Accepts pointer types, particularly:
1454 // const char*
1455 // char*
1456 // const wchar_t*
1457 // wchar_t*
1458 template <typename CharType>
1459 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1460 return s != NULL && MatchAndExplain(StringType(s), listener);
1461 }
1462
1463 // Matches anything that can convert to StringType.
1464 //
1465 // This is a template, not just a plain function with const StringType&,
Austin Schuh889ac432018-10-29 22:57:02 -07001466 // because absl::string_view has some interfering non-explicit constructors.
Austin Schuh0cbef622015-09-06 17:34:52 -07001467 template <typename MatcheeStringType>
1468 bool MatchAndExplain(const MatcheeStringType& s,
1469 MatchResultListener* /* listener */) const {
1470 const StringType& s2(s);
1471 return s2.length() >= prefix_.length() &&
1472 s2.substr(0, prefix_.length()) == prefix_;
1473 }
1474
1475 void DescribeTo(::std::ostream* os) const {
1476 *os << "starts with ";
1477 UniversalPrint(prefix_, os);
1478 }
1479
1480 void DescribeNegationTo(::std::ostream* os) const {
1481 *os << "doesn't start with ";
1482 UniversalPrint(prefix_, os);
1483 }
1484
1485 private:
1486 const StringType prefix_;
1487
1488 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
1489};
1490
1491// Implements the polymorphic EndsWith(substring) matcher, which
1492// can be used as a Matcher<T> as long as T can be converted to a
1493// string.
1494template <typename StringType>
1495class EndsWithMatcher {
1496 public:
1497 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1498
Austin Schuh889ac432018-10-29 22:57:02 -07001499#if GTEST_HAS_ABSL
1500 bool MatchAndExplain(const absl::string_view& s,
1501 MatchResultListener* listener) const {
1502 if (s.data() == NULL) {
1503 return false;
1504 }
1505 // This should fail to compile if absl::string_view is used with wide
1506 // strings.
1507 const StringType& str = string(s);
1508 return MatchAndExplain(str, listener);
1509 }
1510#endif // GTEST_HAS_ABSL
1511
Austin Schuh0cbef622015-09-06 17:34:52 -07001512 // Accepts pointer types, particularly:
1513 // const char*
1514 // char*
1515 // const wchar_t*
1516 // wchar_t*
1517 template <typename CharType>
1518 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1519 return s != NULL && MatchAndExplain(StringType(s), listener);
1520 }
1521
1522 // Matches anything that can convert to StringType.
1523 //
1524 // This is a template, not just a plain function with const StringType&,
Austin Schuh889ac432018-10-29 22:57:02 -07001525 // because absl::string_view has some interfering non-explicit constructors.
Austin Schuh0cbef622015-09-06 17:34:52 -07001526 template <typename MatcheeStringType>
1527 bool MatchAndExplain(const MatcheeStringType& s,
1528 MatchResultListener* /* listener */) const {
1529 const StringType& s2(s);
1530 return s2.length() >= suffix_.length() &&
1531 s2.substr(s2.length() - suffix_.length()) == suffix_;
1532 }
1533
1534 void DescribeTo(::std::ostream* os) const {
1535 *os << "ends with ";
1536 UniversalPrint(suffix_, os);
1537 }
1538
1539 void DescribeNegationTo(::std::ostream* os) const {
1540 *os << "doesn't end with ";
1541 UniversalPrint(suffix_, os);
1542 }
1543
1544 private:
1545 const StringType suffix_;
1546
1547 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
1548};
1549
1550// Implements polymorphic matchers MatchesRegex(regex) and
1551// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1552// T can be converted to a string.
1553class MatchesRegexMatcher {
1554 public:
1555 MatchesRegexMatcher(const RE* regex, bool full_match)
1556 : regex_(regex), full_match_(full_match) {}
1557
Austin Schuh889ac432018-10-29 22:57:02 -07001558#if GTEST_HAS_ABSL
1559 bool MatchAndExplain(const absl::string_view& s,
1560 MatchResultListener* listener) const {
1561 return s.data() && MatchAndExplain(string(s), listener);
1562 }
1563#endif // GTEST_HAS_ABSL
1564
Austin Schuh0cbef622015-09-06 17:34:52 -07001565 // Accepts pointer types, particularly:
1566 // const char*
1567 // char*
1568 // const wchar_t*
1569 // wchar_t*
1570 template <typename CharType>
1571 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
Austin Schuh889ac432018-10-29 22:57:02 -07001572 return s != NULL && MatchAndExplain(std::string(s), listener);
Austin Schuh0cbef622015-09-06 17:34:52 -07001573 }
1574
Austin Schuh889ac432018-10-29 22:57:02 -07001575 // Matches anything that can convert to std::string.
Austin Schuh0cbef622015-09-06 17:34:52 -07001576 //
Austin Schuh889ac432018-10-29 22:57:02 -07001577 // This is a template, not just a plain function with const std::string&,
1578 // because absl::string_view has some interfering non-explicit constructors.
Austin Schuh0cbef622015-09-06 17:34:52 -07001579 template <class MatcheeStringType>
1580 bool MatchAndExplain(const MatcheeStringType& s,
1581 MatchResultListener* /* listener */) const {
Austin Schuh889ac432018-10-29 22:57:02 -07001582 const std::string& s2(s);
Austin Schuh0cbef622015-09-06 17:34:52 -07001583 return full_match_ ? RE::FullMatch(s2, *regex_) :
1584 RE::PartialMatch(s2, *regex_);
1585 }
1586
1587 void DescribeTo(::std::ostream* os) const {
1588 *os << (full_match_ ? "matches" : "contains")
1589 << " regular expression ";
Austin Schuh889ac432018-10-29 22:57:02 -07001590 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
Austin Schuh0cbef622015-09-06 17:34:52 -07001591 }
1592
1593 void DescribeNegationTo(::std::ostream* os) const {
1594 *os << "doesn't " << (full_match_ ? "match" : "contain")
1595 << " regular expression ";
Austin Schuh889ac432018-10-29 22:57:02 -07001596 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
Austin Schuh0cbef622015-09-06 17:34:52 -07001597 }
1598
1599 private:
1600 const internal::linked_ptr<const RE> regex_;
1601 const bool full_match_;
1602
1603 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
1604};
1605
1606// Implements a matcher that compares the two fields of a 2-tuple
1607// using one of the ==, <=, <, etc, operators. The two fields being
1608// compared don't have to have the same type.
1609//
1610// The matcher defined here is polymorphic (for example, Eq() can be
1611// used to match a tuple<int, short>, a tuple<const long&, double>,
1612// etc). Therefore we use a template type conversion operator in the
1613// implementation.
1614template <typename D, typename Op>
1615class PairMatchBase {
1616 public:
1617 template <typename T1, typename T2>
1618 operator Matcher< ::testing::tuple<T1, T2> >() const {
1619 return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >);
1620 }
1621 template <typename T1, typename T2>
1622 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
1623 return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>);
1624 }
1625
1626 private:
1627 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
1628 return os << D::Desc();
1629 }
1630
1631 template <typename Tuple>
1632 class Impl : public MatcherInterface<Tuple> {
1633 public:
1634 virtual bool MatchAndExplain(
1635 Tuple args,
1636 MatchResultListener* /* listener */) const {
1637 return Op()(::testing::get<0>(args), ::testing::get<1>(args));
1638 }
1639 virtual void DescribeTo(::std::ostream* os) const {
1640 *os << "are " << GetDesc;
1641 }
1642 virtual void DescribeNegationTo(::std::ostream* os) const {
1643 *os << "aren't " << GetDesc;
1644 }
1645 };
1646};
1647
1648class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
1649 public:
1650 static const char* Desc() { return "an equal pair"; }
1651};
1652class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
1653 public:
1654 static const char* Desc() { return "an unequal pair"; }
1655};
1656class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
1657 public:
1658 static const char* Desc() { return "a pair where the first < the second"; }
1659};
1660class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
1661 public:
1662 static const char* Desc() { return "a pair where the first > the second"; }
1663};
1664class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
1665 public:
1666 static const char* Desc() { return "a pair where the first <= the second"; }
1667};
1668class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
1669 public:
1670 static const char* Desc() { return "a pair where the first >= the second"; }
1671};
1672
1673// Implements the Not(...) matcher for a particular argument type T.
1674// We do not nest it inside the NotMatcher class template, as that
1675// will prevent different instantiations of NotMatcher from sharing
1676// the same NotMatcherImpl<T> class.
1677template <typename T>
Austin Schuh889ac432018-10-29 22:57:02 -07001678class NotMatcherImpl : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
Austin Schuh0cbef622015-09-06 17:34:52 -07001679 public:
1680 explicit NotMatcherImpl(const Matcher<T>& matcher)
1681 : matcher_(matcher) {}
1682
Austin Schuh889ac432018-10-29 22:57:02 -07001683 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
1684 MatchResultListener* listener) const {
Austin Schuh0cbef622015-09-06 17:34:52 -07001685 return !matcher_.MatchAndExplain(x, listener);
1686 }
1687
1688 virtual void DescribeTo(::std::ostream* os) const {
1689 matcher_.DescribeNegationTo(os);
1690 }
1691
1692 virtual void DescribeNegationTo(::std::ostream* os) const {
1693 matcher_.DescribeTo(os);
1694 }
1695
1696 private:
1697 const Matcher<T> matcher_;
1698
1699 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
1700};
1701
1702// Implements the Not(m) matcher, which matches a value that doesn't
1703// match matcher m.
1704template <typename InnerMatcher>
1705class NotMatcher {
1706 public:
1707 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1708
1709 // This template type conversion operator allows Not(m) to be used
1710 // to match any type m can match.
1711 template <typename T>
1712 operator Matcher<T>() const {
1713 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
1714 }
1715
1716 private:
1717 InnerMatcher matcher_;
1718
1719 GTEST_DISALLOW_ASSIGN_(NotMatcher);
1720};
1721
1722// Implements the AllOf(m1, m2) matcher for a particular argument type
1723// T. We do not nest it inside the BothOfMatcher class template, as
1724// that will prevent different instantiations of BothOfMatcher from
1725// sharing the same BothOfMatcherImpl<T> class.
1726template <typename T>
Austin Schuh889ac432018-10-29 22:57:02 -07001727class AllOfMatcherImpl
1728 : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
Austin Schuh0cbef622015-09-06 17:34:52 -07001729 public:
Austin Schuh889ac432018-10-29 22:57:02 -07001730 explicit AllOfMatcherImpl(std::vector<Matcher<T> > matchers)
1731 : matchers_(internal::move(matchers)) {}
Austin Schuh0cbef622015-09-06 17:34:52 -07001732
1733 virtual void DescribeTo(::std::ostream* os) const {
1734 *os << "(";
Austin Schuh889ac432018-10-29 22:57:02 -07001735 for (size_t i = 0; i < matchers_.size(); ++i) {
1736 if (i != 0) *os << ") and (";
1737 matchers_[i].DescribeTo(os);
1738 }
Austin Schuh0cbef622015-09-06 17:34:52 -07001739 *os << ")";
1740 }
1741
1742 virtual void DescribeNegationTo(::std::ostream* os) const {
1743 *os << "(";
Austin Schuh889ac432018-10-29 22:57:02 -07001744 for (size_t i = 0; i < matchers_.size(); ++i) {
1745 if (i != 0) *os << ") or (";
1746 matchers_[i].DescribeNegationTo(os);
1747 }
Austin Schuh0cbef622015-09-06 17:34:52 -07001748 *os << ")";
1749 }
1750
Austin Schuh889ac432018-10-29 22:57:02 -07001751 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
1752 MatchResultListener* listener) const {
Austin Schuh0cbef622015-09-06 17:34:52 -07001753 // If either matcher1_ or matcher2_ doesn't match x, we only need
1754 // to explain why one of them fails.
Austin Schuh889ac432018-10-29 22:57:02 -07001755 std::string all_match_result;
Austin Schuh0cbef622015-09-06 17:34:52 -07001756
Austin Schuh889ac432018-10-29 22:57:02 -07001757 for (size_t i = 0; i < matchers_.size(); ++i) {
1758 StringMatchResultListener slistener;
1759 if (matchers_[i].MatchAndExplain(x, &slistener)) {
1760 if (all_match_result.empty()) {
1761 all_match_result = slistener.str();
1762 } else {
1763 std::string result = slistener.str();
1764 if (!result.empty()) {
1765 all_match_result += ", and ";
1766 all_match_result += result;
1767 }
1768 }
1769 } else {
1770 *listener << slistener.str();
1771 return false;
1772 }
Austin Schuh0cbef622015-09-06 17:34:52 -07001773 }
1774
1775 // Otherwise we need to explain why *both* of them match.
Austin Schuh889ac432018-10-29 22:57:02 -07001776 *listener << all_match_result;
Austin Schuh0cbef622015-09-06 17:34:52 -07001777 return true;
1778 }
1779
1780 private:
Austin Schuh889ac432018-10-29 22:57:02 -07001781 const std::vector<Matcher<T> > matchers_;
Austin Schuh0cbef622015-09-06 17:34:52 -07001782
Austin Schuh889ac432018-10-29 22:57:02 -07001783 GTEST_DISALLOW_ASSIGN_(AllOfMatcherImpl);
Austin Schuh0cbef622015-09-06 17:34:52 -07001784};
1785
1786#if GTEST_LANG_CXX11
Austin Schuh0cbef622015-09-06 17:34:52 -07001787// VariadicMatcher is used for the variadic implementation of
1788// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1789// CombiningMatcher<T> is used to recursively combine the provided matchers
1790// (of type Args...).
1791template <template <typename T> class CombiningMatcher, typename... Args>
1792class VariadicMatcher {
1793 public:
1794 VariadicMatcher(const Args&... matchers) // NOLINT
Austin Schuh889ac432018-10-29 22:57:02 -07001795 : matchers_(matchers...) {
1796 static_assert(sizeof...(Args) > 0, "Must have at least one matcher.");
1797 }
Austin Schuh0cbef622015-09-06 17:34:52 -07001798
1799 // This template type conversion operator allows an
1800 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1801 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1802 template <typename T>
1803 operator Matcher<T>() const {
Austin Schuh889ac432018-10-29 22:57:02 -07001804 std::vector<Matcher<T> > values;
1805 CreateVariadicMatcher<T>(&values, std::integral_constant<size_t, 0>());
1806 return Matcher<T>(new CombiningMatcher<T>(internal::move(values)));
Austin Schuh0cbef622015-09-06 17:34:52 -07001807 }
1808
1809 private:
Austin Schuh889ac432018-10-29 22:57:02 -07001810 template <typename T, size_t I>
1811 void CreateVariadicMatcher(std::vector<Matcher<T> >* values,
1812 std::integral_constant<size_t, I>) const {
1813 values->push_back(SafeMatcherCast<T>(std::get<I>(matchers_)));
1814 CreateVariadicMatcher<T>(values, std::integral_constant<size_t, I + 1>());
1815 }
Austin Schuh0cbef622015-09-06 17:34:52 -07001816
Austin Schuh889ac432018-10-29 22:57:02 -07001817 template <typename T>
1818 void CreateVariadicMatcher(
1819 std::vector<Matcher<T> >*,
1820 std::integral_constant<size_t, sizeof...(Args)>) const {}
1821
1822 tuple<Args...> matchers_;
Austin Schuh0cbef622015-09-06 17:34:52 -07001823
1824 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1825};
1826
1827template <typename... Args>
Austin Schuh889ac432018-10-29 22:57:02 -07001828using AllOfMatcher = VariadicMatcher<AllOfMatcherImpl, Args...>;
Austin Schuh0cbef622015-09-06 17:34:52 -07001829
1830#endif // GTEST_LANG_CXX11
1831
1832// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1833// matches a value that matches all of the matchers m_1, ..., and m_n.
1834template <typename Matcher1, typename Matcher2>
1835class BothOfMatcher {
1836 public:
1837 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1838 : matcher1_(matcher1), matcher2_(matcher2) {}
1839
1840 // This template type conversion operator allows a
1841 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1842 // both Matcher1 and Matcher2 can match.
1843 template <typename T>
1844 operator Matcher<T>() const {
Austin Schuh889ac432018-10-29 22:57:02 -07001845 std::vector<Matcher<T> > values;
1846 values.push_back(SafeMatcherCast<T>(matcher1_));
1847 values.push_back(SafeMatcherCast<T>(matcher2_));
1848 return Matcher<T>(new AllOfMatcherImpl<T>(internal::move(values)));
Austin Schuh0cbef622015-09-06 17:34:52 -07001849 }
1850
1851 private:
1852 Matcher1 matcher1_;
1853 Matcher2 matcher2_;
1854
1855 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
1856};
1857
1858// Implements the AnyOf(m1, m2) matcher for a particular argument type
1859// T. We do not nest it inside the AnyOfMatcher class template, as
1860// that will prevent different instantiations of AnyOfMatcher from
1861// sharing the same EitherOfMatcherImpl<T> class.
1862template <typename T>
Austin Schuh889ac432018-10-29 22:57:02 -07001863class AnyOfMatcherImpl
1864 : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
Austin Schuh0cbef622015-09-06 17:34:52 -07001865 public:
Austin Schuh889ac432018-10-29 22:57:02 -07001866 explicit AnyOfMatcherImpl(std::vector<Matcher<T> > matchers)
1867 : matchers_(internal::move(matchers)) {}
Austin Schuh0cbef622015-09-06 17:34:52 -07001868
1869 virtual void DescribeTo(::std::ostream* os) const {
1870 *os << "(";
Austin Schuh889ac432018-10-29 22:57:02 -07001871 for (size_t i = 0; i < matchers_.size(); ++i) {
1872 if (i != 0) *os << ") or (";
1873 matchers_[i].DescribeTo(os);
1874 }
Austin Schuh0cbef622015-09-06 17:34:52 -07001875 *os << ")";
1876 }
1877
1878 virtual void DescribeNegationTo(::std::ostream* os) const {
1879 *os << "(";
Austin Schuh889ac432018-10-29 22:57:02 -07001880 for (size_t i = 0; i < matchers_.size(); ++i) {
1881 if (i != 0) *os << ") and (";
1882 matchers_[i].DescribeNegationTo(os);
1883 }
Austin Schuh0cbef622015-09-06 17:34:52 -07001884 *os << ")";
1885 }
1886
Austin Schuh889ac432018-10-29 22:57:02 -07001887 virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
1888 MatchResultListener* listener) const {
1889 std::string no_match_result;
1890
Austin Schuh0cbef622015-09-06 17:34:52 -07001891 // If either matcher1_ or matcher2_ matches x, we just need to
1892 // explain why *one* of them matches.
Austin Schuh889ac432018-10-29 22:57:02 -07001893 for (size_t i = 0; i < matchers_.size(); ++i) {
1894 StringMatchResultListener slistener;
1895 if (matchers_[i].MatchAndExplain(x, &slistener)) {
1896 *listener << slistener.str();
1897 return true;
1898 } else {
1899 if (no_match_result.empty()) {
1900 no_match_result = slistener.str();
1901 } else {
1902 std::string result = slistener.str();
1903 if (!result.empty()) {
1904 no_match_result += ", and ";
1905 no_match_result += result;
1906 }
1907 }
1908 }
Austin Schuh0cbef622015-09-06 17:34:52 -07001909 }
1910
1911 // Otherwise we need to explain why *both* of them fail.
Austin Schuh889ac432018-10-29 22:57:02 -07001912 *listener << no_match_result;
Austin Schuh0cbef622015-09-06 17:34:52 -07001913 return false;
1914 }
1915
1916 private:
Austin Schuh889ac432018-10-29 22:57:02 -07001917 const std::vector<Matcher<T> > matchers_;
Austin Schuh0cbef622015-09-06 17:34:52 -07001918
Austin Schuh889ac432018-10-29 22:57:02 -07001919 GTEST_DISALLOW_ASSIGN_(AnyOfMatcherImpl);
Austin Schuh0cbef622015-09-06 17:34:52 -07001920};
1921
1922#if GTEST_LANG_CXX11
1923// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1924template <typename... Args>
Austin Schuh889ac432018-10-29 22:57:02 -07001925using AnyOfMatcher = VariadicMatcher<AnyOfMatcherImpl, Args...>;
Austin Schuh0cbef622015-09-06 17:34:52 -07001926
1927#endif // GTEST_LANG_CXX11
1928
1929// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1930// matches a value that matches at least one of the matchers m_1, ...,
1931// and m_n.
1932template <typename Matcher1, typename Matcher2>
1933class EitherOfMatcher {
1934 public:
1935 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1936 : matcher1_(matcher1), matcher2_(matcher2) {}
1937
1938 // This template type conversion operator allows a
1939 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1940 // both Matcher1 and Matcher2 can match.
1941 template <typename T>
1942 operator Matcher<T>() const {
Austin Schuh889ac432018-10-29 22:57:02 -07001943 std::vector<Matcher<T> > values;
1944 values.push_back(SafeMatcherCast<T>(matcher1_));
1945 values.push_back(SafeMatcherCast<T>(matcher2_));
1946 return Matcher<T>(new AnyOfMatcherImpl<T>(internal::move(values)));
Austin Schuh0cbef622015-09-06 17:34:52 -07001947 }
1948
1949 private:
1950 Matcher1 matcher1_;
1951 Matcher2 matcher2_;
1952
1953 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
1954};
1955
1956// Used for implementing Truly(pred), which turns a predicate into a
1957// matcher.
1958template <typename Predicate>
1959class TrulyMatcher {
1960 public:
1961 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1962
1963 // This method template allows Truly(pred) to be used as a matcher
1964 // for type T where T is the argument type of predicate 'pred'. The
1965 // argument is passed by reference as the predicate may be
1966 // interested in the address of the argument.
1967 template <typename T>
1968 bool MatchAndExplain(T& x, // NOLINT
1969 MatchResultListener* /* listener */) const {
1970 // Without the if-statement, MSVC sometimes warns about converting
1971 // a value to bool (warning 4800).
1972 //
1973 // We cannot write 'return !!predicate_(x);' as that doesn't work
1974 // when predicate_(x) returns a class convertible to bool but
1975 // having no operator!().
1976 if (predicate_(x))
1977 return true;
1978 return false;
1979 }
1980
1981 void DescribeTo(::std::ostream* os) const {
1982 *os << "satisfies the given predicate";
1983 }
1984
1985 void DescribeNegationTo(::std::ostream* os) const {
1986 *os << "doesn't satisfy the given predicate";
1987 }
1988
1989 private:
1990 Predicate predicate_;
1991
1992 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
1993};
1994
1995// Used for implementing Matches(matcher), which turns a matcher into
1996// a predicate.
1997template <typename M>
1998class MatcherAsPredicate {
1999 public:
2000 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
2001
2002 // This template operator() allows Matches(m) to be used as a
2003 // predicate on type T where m is a matcher on type T.
2004 //
2005 // The argument x is passed by reference instead of by value, as
2006 // some matcher may be interested in its address (e.g. as in
2007 // Matches(Ref(n))(x)).
2008 template <typename T>
2009 bool operator()(const T& x) const {
2010 // We let matcher_ commit to a particular type here instead of
2011 // when the MatcherAsPredicate object was constructed. This
2012 // allows us to write Matches(m) where m is a polymorphic matcher
2013 // (e.g. Eq(5)).
2014 //
2015 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
2016 // compile when matcher_ has type Matcher<const T&>; if we write
2017 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
2018 // when matcher_ has type Matcher<T>; if we just write
2019 // matcher_.Matches(x), it won't compile when matcher_ is
2020 // polymorphic, e.g. Eq(5).
2021 //
2022 // MatcherCast<const T&>() is necessary for making the code work
2023 // in all of the above situations.
2024 return MatcherCast<const T&>(matcher_).Matches(x);
2025 }
2026
2027 private:
2028 M matcher_;
2029
2030 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
2031};
2032
2033// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
2034// argument M must be a type that can be converted to a matcher.
2035template <typename M>
2036class PredicateFormatterFromMatcher {
2037 public:
2038 explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {}
2039
2040 // This template () operator allows a PredicateFormatterFromMatcher
2041 // object to act as a predicate-formatter suitable for using with
2042 // Google Test's EXPECT_PRED_FORMAT1() macro.
2043 template <typename T>
2044 AssertionResult operator()(const char* value_text, const T& x) const {
2045 // We convert matcher_ to a Matcher<const T&> *now* instead of
2046 // when the PredicateFormatterFromMatcher object was constructed,
2047 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
2048 // know which type to instantiate it to until we actually see the
2049 // type of x here.
2050 //
2051 // We write SafeMatcherCast<const T&>(matcher_) instead of
2052 // Matcher<const T&>(matcher_), as the latter won't compile when
2053 // matcher_ has type Matcher<T> (e.g. An<int>()).
2054 // We don't write MatcherCast<const T&> either, as that allows
2055 // potentially unsafe downcasting of the matcher argument.
2056 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
2057 StringMatchResultListener listener;
2058 if (MatchPrintAndExplain(x, matcher, &listener))
2059 return AssertionSuccess();
2060
2061 ::std::stringstream ss;
2062 ss << "Value of: " << value_text << "\n"
2063 << "Expected: ";
2064 matcher.DescribeTo(&ss);
2065 ss << "\n Actual: " << listener.str();
2066 return AssertionFailure() << ss.str();
2067 }
2068
2069 private:
2070 const M matcher_;
2071
2072 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
2073};
2074
2075// A helper function for converting a matcher to a predicate-formatter
2076// without the user needing to explicitly write the type. This is
2077// used for implementing ASSERT_THAT() and EXPECT_THAT().
2078// Implementation detail: 'matcher' is received by-value to force decaying.
2079template <typename M>
2080inline PredicateFormatterFromMatcher<M>
2081MakePredicateFormatterFromMatcher(M matcher) {
2082 return PredicateFormatterFromMatcher<M>(internal::move(matcher));
2083}
2084
2085// Implements the polymorphic floating point equality matcher, which matches
2086// two float values using ULP-based approximation or, optionally, a
2087// user-specified epsilon. The template is meant to be instantiated with
2088// FloatType being either float or double.
2089template <typename FloatType>
2090class FloatingEqMatcher {
2091 public:
2092 // Constructor for FloatingEqMatcher.
2093 // The matcher's input will be compared with expected. The matcher treats two
2094 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
2095 // equality comparisons between NANs will always return false. We specify a
2096 // negative max_abs_error_ term to indicate that ULP-based approximation will
2097 // be used for comparison.
2098 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
2099 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
2100 }
2101
2102 // Constructor that supports a user-specified max_abs_error that will be used
2103 // for comparison instead of ULP-based approximation. The max absolute
2104 // should be non-negative.
2105 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
2106 FloatType max_abs_error)
2107 : expected_(expected),
2108 nan_eq_nan_(nan_eq_nan),
2109 max_abs_error_(max_abs_error) {
2110 GTEST_CHECK_(max_abs_error >= 0)
2111 << ", where max_abs_error is" << max_abs_error;
2112 }
2113
2114 // Implements floating point equality matcher as a Matcher<T>.
2115 template <typename T>
2116 class Impl : public MatcherInterface<T> {
2117 public:
2118 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
2119 : expected_(expected),
2120 nan_eq_nan_(nan_eq_nan),
2121 max_abs_error_(max_abs_error) {}
2122
2123 virtual bool MatchAndExplain(T value,
2124 MatchResultListener* listener) const {
2125 const FloatingPoint<FloatType> actual(value), expected(expected_);
2126
2127 // Compares NaNs first, if nan_eq_nan_ is true.
2128 if (actual.is_nan() || expected.is_nan()) {
2129 if (actual.is_nan() && expected.is_nan()) {
2130 return nan_eq_nan_;
2131 }
2132 // One is nan; the other is not nan.
2133 return false;
2134 }
2135 if (HasMaxAbsError()) {
2136 // We perform an equality check so that inf will match inf, regardless
2137 // of error bounds. If the result of value - expected_ would result in
2138 // overflow or if either value is inf, the default result is infinity,
2139 // which should only match if max_abs_error_ is also infinity.
2140 if (value == expected_) {
2141 return true;
2142 }
2143
2144 const FloatType diff = value - expected_;
2145 if (fabs(diff) <= max_abs_error_) {
2146 return true;
2147 }
2148
2149 if (listener->IsInterested()) {
2150 *listener << "which is " << diff << " from " << expected_;
2151 }
2152 return false;
2153 } else {
2154 return actual.AlmostEquals(expected);
2155 }
2156 }
2157
2158 virtual void DescribeTo(::std::ostream* os) const {
2159 // os->precision() returns the previously set precision, which we
2160 // store to restore the ostream to its original configuration
2161 // after outputting.
2162 const ::std::streamsize old_precision = os->precision(
2163 ::std::numeric_limits<FloatType>::digits10 + 2);
2164 if (FloatingPoint<FloatType>(expected_).is_nan()) {
2165 if (nan_eq_nan_) {
2166 *os << "is NaN";
2167 } else {
2168 *os << "never matches";
2169 }
2170 } else {
2171 *os << "is approximately " << expected_;
2172 if (HasMaxAbsError()) {
2173 *os << " (absolute error <= " << max_abs_error_ << ")";
2174 }
2175 }
2176 os->precision(old_precision);
2177 }
2178
2179 virtual void DescribeNegationTo(::std::ostream* os) const {
2180 // As before, get original precision.
2181 const ::std::streamsize old_precision = os->precision(
2182 ::std::numeric_limits<FloatType>::digits10 + 2);
2183 if (FloatingPoint<FloatType>(expected_).is_nan()) {
2184 if (nan_eq_nan_) {
2185 *os << "isn't NaN";
2186 } else {
2187 *os << "is anything";
2188 }
2189 } else {
2190 *os << "isn't approximately " << expected_;
2191 if (HasMaxAbsError()) {
2192 *os << " (absolute error > " << max_abs_error_ << ")";
2193 }
2194 }
2195 // Restore original precision.
2196 os->precision(old_precision);
2197 }
2198
2199 private:
2200 bool HasMaxAbsError() const {
2201 return max_abs_error_ >= 0;
2202 }
2203
2204 const FloatType expected_;
2205 const bool nan_eq_nan_;
2206 // max_abs_error will be used for value comparison when >= 0.
2207 const FloatType max_abs_error_;
2208
2209 GTEST_DISALLOW_ASSIGN_(Impl);
2210 };
2211
2212 // The following 3 type conversion operators allow FloatEq(expected) and
2213 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
2214 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
2215 // (While Google's C++ coding style doesn't allow arguments passed
2216 // by non-const reference, we may see them in code not conforming to
2217 // the style. Therefore Google Mock needs to support them.)
2218 operator Matcher<FloatType>() const {
2219 return MakeMatcher(
2220 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
2221 }
2222
2223 operator Matcher<const FloatType&>() const {
2224 return MakeMatcher(
2225 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
2226 }
2227
2228 operator Matcher<FloatType&>() const {
2229 return MakeMatcher(
2230 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
2231 }
2232
2233 private:
2234 const FloatType expected_;
2235 const bool nan_eq_nan_;
2236 // max_abs_error will be used for value comparison when >= 0.
2237 const FloatType max_abs_error_;
2238
2239 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
2240};
2241
Austin Schuh889ac432018-10-29 22:57:02 -07002242// A 2-tuple ("binary") wrapper around FloatingEqMatcher:
2243// FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false)
2244// against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e)
2245// against y. The former implements "Eq", the latter "Near". At present, there
2246// is no version that compares NaNs as equal.
2247template <typename FloatType>
2248class FloatingEq2Matcher {
2249 public:
2250 FloatingEq2Matcher() { Init(-1, false); }
2251
2252 explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); }
2253
2254 explicit FloatingEq2Matcher(FloatType max_abs_error) {
2255 Init(max_abs_error, false);
2256 }
2257
2258 FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) {
2259 Init(max_abs_error, nan_eq_nan);
2260 }
2261
2262 template <typename T1, typename T2>
2263 operator Matcher< ::testing::tuple<T1, T2> >() const {
2264 return MakeMatcher(
2265 new Impl< ::testing::tuple<T1, T2> >(max_abs_error_, nan_eq_nan_));
2266 }
2267 template <typename T1, typename T2>
2268 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
2269 return MakeMatcher(
2270 new Impl<const ::testing::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_));
2271 }
2272
2273 private:
2274 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
2275 return os << "an almost-equal pair";
2276 }
2277
2278 template <typename Tuple>
2279 class Impl : public MatcherInterface<Tuple> {
2280 public:
2281 Impl(FloatType max_abs_error, bool nan_eq_nan) :
2282 max_abs_error_(max_abs_error),
2283 nan_eq_nan_(nan_eq_nan) {}
2284
2285 virtual bool MatchAndExplain(Tuple args,
2286 MatchResultListener* listener) const {
2287 if (max_abs_error_ == -1) {
2288 FloatingEqMatcher<FloatType> fm(::testing::get<0>(args), nan_eq_nan_);
2289 return static_cast<Matcher<FloatType> >(fm).MatchAndExplain(
2290 ::testing::get<1>(args), listener);
2291 } else {
2292 FloatingEqMatcher<FloatType> fm(::testing::get<0>(args), nan_eq_nan_,
2293 max_abs_error_);
2294 return static_cast<Matcher<FloatType> >(fm).MatchAndExplain(
2295 ::testing::get<1>(args), listener);
2296 }
2297 }
2298 virtual void DescribeTo(::std::ostream* os) const {
2299 *os << "are " << GetDesc;
2300 }
2301 virtual void DescribeNegationTo(::std::ostream* os) const {
2302 *os << "aren't " << GetDesc;
2303 }
2304
2305 private:
2306 FloatType max_abs_error_;
2307 const bool nan_eq_nan_;
2308 };
2309
2310 void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) {
2311 max_abs_error_ = max_abs_error_val;
2312 nan_eq_nan_ = nan_eq_nan_val;
2313 }
2314 FloatType max_abs_error_;
2315 bool nan_eq_nan_;
2316};
2317
Austin Schuh0cbef622015-09-06 17:34:52 -07002318// Implements the Pointee(m) matcher for matching a pointer whose
2319// pointee matches matcher m. The pointer can be either raw or smart.
2320template <typename InnerMatcher>
2321class PointeeMatcher {
2322 public:
2323 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
2324
2325 // This type conversion operator template allows Pointee(m) to be
2326 // used as a matcher for any pointer type whose pointee type is
2327 // compatible with the inner matcher, where type Pointer can be
2328 // either a raw pointer or a smart pointer.
2329 //
2330 // The reason we do this instead of relying on
2331 // MakePolymorphicMatcher() is that the latter is not flexible
2332 // enough for implementing the DescribeTo() method of Pointee().
2333 template <typename Pointer>
2334 operator Matcher<Pointer>() const {
Austin Schuh889ac432018-10-29 22:57:02 -07002335 return Matcher<Pointer>(
2336 new Impl<GTEST_REFERENCE_TO_CONST_(Pointer)>(matcher_));
Austin Schuh0cbef622015-09-06 17:34:52 -07002337 }
2338
2339 private:
2340 // The monomorphic implementation that works for a particular pointer type.
2341 template <typename Pointer>
2342 class Impl : public MatcherInterface<Pointer> {
2343 public:
2344 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
2345 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
2346
2347 explicit Impl(const InnerMatcher& matcher)
2348 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
2349
2350 virtual void DescribeTo(::std::ostream* os) const {
2351 *os << "points to a value that ";
2352 matcher_.DescribeTo(os);
2353 }
2354
2355 virtual void DescribeNegationTo(::std::ostream* os) const {
2356 *os << "does not point to a value that ";
2357 matcher_.DescribeTo(os);
2358 }
2359
2360 virtual bool MatchAndExplain(Pointer pointer,
2361 MatchResultListener* listener) const {
2362 if (GetRawPointer(pointer) == NULL)
2363 return false;
2364
2365 *listener << "which points to ";
2366 return MatchPrintAndExplain(*pointer, matcher_, listener);
2367 }
2368
2369 private:
2370 const Matcher<const Pointee&> matcher_;
2371
2372 GTEST_DISALLOW_ASSIGN_(Impl);
2373 };
2374
2375 const InnerMatcher matcher_;
2376
2377 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
2378};
2379
Austin Schuh889ac432018-10-29 22:57:02 -07002380#if GTEST_HAS_RTTI
Austin Schuh0cbef622015-09-06 17:34:52 -07002381// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2382// reference that matches inner_matcher when dynamic_cast<T> is applied.
2383// The result of dynamic_cast<To> is forwarded to the inner matcher.
2384// If To is a pointer and the cast fails, the inner matcher will receive NULL.
2385// If To is a reference and the cast fails, this matcher returns false
2386// immediately.
2387template <typename To>
2388class WhenDynamicCastToMatcherBase {
2389 public:
2390 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2391 : matcher_(matcher) {}
2392
2393 void DescribeTo(::std::ostream* os) const {
2394 GetCastTypeDescription(os);
2395 matcher_.DescribeTo(os);
2396 }
2397
2398 void DescribeNegationTo(::std::ostream* os) const {
2399 GetCastTypeDescription(os);
2400 matcher_.DescribeNegationTo(os);
2401 }
2402
2403 protected:
2404 const Matcher<To> matcher_;
2405
Austin Schuh889ac432018-10-29 22:57:02 -07002406 static std::string GetToName() {
Austin Schuh0cbef622015-09-06 17:34:52 -07002407 return GetTypeName<To>();
Austin Schuh0cbef622015-09-06 17:34:52 -07002408 }
2409
2410 private:
2411 static void GetCastTypeDescription(::std::ostream* os) {
2412 *os << "when dynamic_cast to " << GetToName() << ", ";
2413 }
2414
2415 GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2416};
2417
2418// Primary template.
2419// To is a pointer. Cast and forward the result.
2420template <typename To>
2421class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2422 public:
2423 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2424 : WhenDynamicCastToMatcherBase<To>(matcher) {}
2425
2426 template <typename From>
2427 bool MatchAndExplain(From from, MatchResultListener* listener) const {
Austin Schuh889ac432018-10-29 22:57:02 -07002428 // FIXME: Add more detail on failures. ie did the dyn_cast fail?
Austin Schuh0cbef622015-09-06 17:34:52 -07002429 To to = dynamic_cast<To>(from);
2430 return MatchPrintAndExplain(to, this->matcher_, listener);
2431 }
2432};
2433
2434// Specialize for references.
2435// In this case we return false if the dynamic_cast fails.
2436template <typename To>
2437class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2438 public:
2439 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2440 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2441
2442 template <typename From>
2443 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2444 // We don't want an std::bad_cast here, so do the cast with pointers.
2445 To* to = dynamic_cast<To*>(&from);
2446 if (to == NULL) {
2447 *listener << "which cannot be dynamic_cast to " << this->GetToName();
2448 return false;
2449 }
2450 return MatchPrintAndExplain(*to, this->matcher_, listener);
2451 }
2452};
Austin Schuh889ac432018-10-29 22:57:02 -07002453#endif // GTEST_HAS_RTTI
Austin Schuh0cbef622015-09-06 17:34:52 -07002454
2455// Implements the Field() matcher for matching a field (i.e. member
2456// variable) of an object.
2457template <typename Class, typename FieldType>
2458class FieldMatcher {
2459 public:
2460 FieldMatcher(FieldType Class::*field,
2461 const Matcher<const FieldType&>& matcher)
Austin Schuh889ac432018-10-29 22:57:02 -07002462 : field_(field), matcher_(matcher), whose_field_("whose given field ") {}
2463
2464 FieldMatcher(const std::string& field_name, FieldType Class::*field,
2465 const Matcher<const FieldType&>& matcher)
2466 : field_(field),
2467 matcher_(matcher),
2468 whose_field_("whose field `" + field_name + "` ") {}
Austin Schuh0cbef622015-09-06 17:34:52 -07002469
2470 void DescribeTo(::std::ostream* os) const {
Austin Schuh889ac432018-10-29 22:57:02 -07002471 *os << "is an object " << whose_field_;
Austin Schuh0cbef622015-09-06 17:34:52 -07002472 matcher_.DescribeTo(os);
2473 }
2474
2475 void DescribeNegationTo(::std::ostream* os) const {
Austin Schuh889ac432018-10-29 22:57:02 -07002476 *os << "is an object " << whose_field_;
Austin Schuh0cbef622015-09-06 17:34:52 -07002477 matcher_.DescribeNegationTo(os);
2478 }
2479
2480 template <typename T>
2481 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2482 return MatchAndExplainImpl(
2483 typename ::testing::internal::
2484 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
2485 value, listener);
2486 }
2487
2488 private:
2489 // The first argument of MatchAndExplainImpl() is needed to help
2490 // Symbian's C++ compiler choose which overload to use. Its type is
2491 // true_type iff the Field() matcher is used to match a pointer.
2492 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2493 MatchResultListener* listener) const {
Austin Schuh889ac432018-10-29 22:57:02 -07002494 *listener << whose_field_ << "is ";
Austin Schuh0cbef622015-09-06 17:34:52 -07002495 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
2496 }
2497
2498 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2499 MatchResultListener* listener) const {
2500 if (p == NULL)
2501 return false;
2502
2503 *listener << "which points to an object ";
2504 // Since *p has a field, it must be a class/struct/union type and
2505 // thus cannot be a pointer. Therefore we pass false_type() as
2506 // the first argument.
2507 return MatchAndExplainImpl(false_type(), *p, listener);
2508 }
2509
2510 const FieldType Class::*field_;
2511 const Matcher<const FieldType&> matcher_;
2512
Austin Schuh889ac432018-10-29 22:57:02 -07002513 // Contains either "whose given field " if the name of the field is unknown
2514 // or "whose field `name_of_field` " if the name is known.
2515 const std::string whose_field_;
2516
Austin Schuh0cbef622015-09-06 17:34:52 -07002517 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
2518};
2519
2520// Implements the Property() matcher for matching a property
2521// (i.e. return value of a getter method) of an object.
Austin Schuh889ac432018-10-29 22:57:02 -07002522//
2523// Property is a const-qualified member function of Class returning
2524// PropertyType.
2525template <typename Class, typename PropertyType, typename Property>
Austin Schuh0cbef622015-09-06 17:34:52 -07002526class PropertyMatcher {
2527 public:
2528 // The property may have a reference type, so 'const PropertyType&'
2529 // may cause double references and fail to compile. That's why we
2530 // need GTEST_REFERENCE_TO_CONST, which works regardless of
2531 // PropertyType being a reference or not.
2532 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
2533
Austin Schuh889ac432018-10-29 22:57:02 -07002534 PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)
2535 : property_(property),
2536 matcher_(matcher),
2537 whose_property_("whose given property ") {}
2538
2539 PropertyMatcher(const std::string& property_name, Property property,
Austin Schuh0cbef622015-09-06 17:34:52 -07002540 const Matcher<RefToConstProperty>& matcher)
Austin Schuh889ac432018-10-29 22:57:02 -07002541 : property_(property),
2542 matcher_(matcher),
2543 whose_property_("whose property `" + property_name + "` ") {}
Austin Schuh0cbef622015-09-06 17:34:52 -07002544
2545 void DescribeTo(::std::ostream* os) const {
Austin Schuh889ac432018-10-29 22:57:02 -07002546 *os << "is an object " << whose_property_;
Austin Schuh0cbef622015-09-06 17:34:52 -07002547 matcher_.DescribeTo(os);
2548 }
2549
2550 void DescribeNegationTo(::std::ostream* os) const {
Austin Schuh889ac432018-10-29 22:57:02 -07002551 *os << "is an object " << whose_property_;
Austin Schuh0cbef622015-09-06 17:34:52 -07002552 matcher_.DescribeNegationTo(os);
2553 }
2554
2555 template <typename T>
2556 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2557 return MatchAndExplainImpl(
2558 typename ::testing::internal::
2559 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
2560 value, listener);
2561 }
2562
2563 private:
2564 // The first argument of MatchAndExplainImpl() is needed to help
2565 // Symbian's C++ compiler choose which overload to use. Its type is
2566 // true_type iff the Property() matcher is used to match a pointer.
2567 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2568 MatchResultListener* listener) const {
Austin Schuh889ac432018-10-29 22:57:02 -07002569 *listener << whose_property_ << "is ";
Austin Schuh0cbef622015-09-06 17:34:52 -07002570 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2571 // which takes a non-const reference as argument.
2572#if defined(_PREFAST_ ) && _MSC_VER == 1800
2573 // Workaround bug in VC++ 2013's /analyze parser.
2574 // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move
2575 posix::Abort(); // To make sure it is never run.
2576 return false;
2577#else
2578 RefToConstProperty result = (obj.*property_)();
2579 return MatchPrintAndExplain(result, matcher_, listener);
2580#endif
2581 }
2582
2583 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2584 MatchResultListener* listener) const {
2585 if (p == NULL)
2586 return false;
2587
2588 *listener << "which points to an object ";
2589 // Since *p has a property method, it must be a class/struct/union
2590 // type and thus cannot be a pointer. Therefore we pass
2591 // false_type() as the first argument.
2592 return MatchAndExplainImpl(false_type(), *p, listener);
2593 }
2594
Austin Schuh889ac432018-10-29 22:57:02 -07002595 Property property_;
Austin Schuh0cbef622015-09-06 17:34:52 -07002596 const Matcher<RefToConstProperty> matcher_;
2597
Austin Schuh889ac432018-10-29 22:57:02 -07002598 // Contains either "whose given property " if the name of the property is
2599 // unknown or "whose property `name_of_property` " if the name is known.
2600 const std::string whose_property_;
2601
Austin Schuh0cbef622015-09-06 17:34:52 -07002602 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
2603};
2604
2605// Type traits specifying various features of different functors for ResultOf.
2606// The default template specifies features for functor objects.
Austin Schuh0cbef622015-09-06 17:34:52 -07002607template <typename Functor>
2608struct CallableTraits {
Austin Schuh0cbef622015-09-06 17:34:52 -07002609 typedef Functor StorageType;
2610
2611 static void CheckIsValid(Functor /* functor */) {}
Austin Schuh889ac432018-10-29 22:57:02 -07002612
2613#if GTEST_LANG_CXX11
2614 template <typename T>
2615 static auto Invoke(Functor f, T arg) -> decltype(f(arg)) { return f(arg); }
2616#else
2617 typedef typename Functor::result_type ResultType;
Austin Schuh0cbef622015-09-06 17:34:52 -07002618 template <typename T>
2619 static ResultType Invoke(Functor f, T arg) { return f(arg); }
Austin Schuh889ac432018-10-29 22:57:02 -07002620#endif
Austin Schuh0cbef622015-09-06 17:34:52 -07002621};
2622
2623// Specialization for function pointers.
2624template <typename ArgType, typename ResType>
2625struct CallableTraits<ResType(*)(ArgType)> {
2626 typedef ResType ResultType;
2627 typedef ResType(*StorageType)(ArgType);
2628
2629 static void CheckIsValid(ResType(*f)(ArgType)) {
2630 GTEST_CHECK_(f != NULL)
2631 << "NULL function pointer is passed into ResultOf().";
2632 }
2633 template <typename T>
2634 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2635 return (*f)(arg);
2636 }
2637};
2638
2639// Implements the ResultOf() matcher for matching a return value of a
2640// unary function of an object.
Austin Schuh889ac432018-10-29 22:57:02 -07002641template <typename Callable, typename InnerMatcher>
Austin Schuh0cbef622015-09-06 17:34:52 -07002642class ResultOfMatcher {
2643 public:
Austin Schuh889ac432018-10-29 22:57:02 -07002644 ResultOfMatcher(Callable callable, InnerMatcher matcher)
2645 : callable_(internal::move(callable)), matcher_(internal::move(matcher)) {
Austin Schuh0cbef622015-09-06 17:34:52 -07002646 CallableTraits<Callable>::CheckIsValid(callable_);
2647 }
2648
2649 template <typename T>
2650 operator Matcher<T>() const {
2651 return Matcher<T>(new Impl<T>(callable_, matcher_));
2652 }
2653
2654 private:
2655 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2656
2657 template <typename T>
2658 class Impl : public MatcherInterface<T> {
Austin Schuh889ac432018-10-29 22:57:02 -07002659#if GTEST_LANG_CXX11
2660 using ResultType = decltype(CallableTraits<Callable>::template Invoke<T>(
2661 std::declval<CallableStorageType>(), std::declval<T>()));
2662#else
2663 typedef typename CallableTraits<Callable>::ResultType ResultType;
2664#endif
2665
Austin Schuh0cbef622015-09-06 17:34:52 -07002666 public:
Austin Schuh889ac432018-10-29 22:57:02 -07002667 template <typename M>
2668 Impl(const CallableStorageType& callable, const M& matcher)
2669 : callable_(callable), matcher_(MatcherCast<ResultType>(matcher)) {}
Austin Schuh0cbef622015-09-06 17:34:52 -07002670
2671 virtual void DescribeTo(::std::ostream* os) const {
2672 *os << "is mapped by the given callable to a value that ";
2673 matcher_.DescribeTo(os);
2674 }
2675
2676 virtual void DescribeNegationTo(::std::ostream* os) const {
2677 *os << "is mapped by the given callable to a value that ";
2678 matcher_.DescribeNegationTo(os);
2679 }
2680
2681 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
2682 *listener << "which is mapped by the given callable to ";
Austin Schuh889ac432018-10-29 22:57:02 -07002683 // Cannot pass the return value directly to MatchPrintAndExplain, which
2684 // takes a non-const reference as argument.
2685 // Also, specifying template argument explicitly is needed because T could
2686 // be a non-const reference (e.g. Matcher<Uncopyable&>).
Austin Schuh0cbef622015-09-06 17:34:52 -07002687 ResultType result =
2688 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2689 return MatchPrintAndExplain(result, matcher_, listener);
2690 }
2691
2692 private:
2693 // Functors often define operator() as non-const method even though
Austin Schuh889ac432018-10-29 22:57:02 -07002694 // they are actually stateless. But we need to use them even when
Austin Schuh0cbef622015-09-06 17:34:52 -07002695 // 'this' is a const pointer. It's the user's responsibility not to
Austin Schuh889ac432018-10-29 22:57:02 -07002696 // use stateful callables with ResultOf(), which doesn't guarantee
Austin Schuh0cbef622015-09-06 17:34:52 -07002697 // how many times the callable will be invoked.
2698 mutable CallableStorageType callable_;
2699 const Matcher<ResultType> matcher_;
2700
2701 GTEST_DISALLOW_ASSIGN_(Impl);
2702 }; // class Impl
2703
2704 const CallableStorageType callable_;
Austin Schuh889ac432018-10-29 22:57:02 -07002705 const InnerMatcher matcher_;
Austin Schuh0cbef622015-09-06 17:34:52 -07002706
2707 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
2708};
2709
2710// Implements a matcher that checks the size of an STL-style container.
2711template <typename SizeMatcher>
2712class SizeIsMatcher {
2713 public:
2714 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2715 : size_matcher_(size_matcher) {
2716 }
2717
2718 template <typename Container>
2719 operator Matcher<Container>() const {
2720 return MakeMatcher(new Impl<Container>(size_matcher_));
2721 }
2722
2723 template <typename Container>
2724 class Impl : public MatcherInterface<Container> {
2725 public:
2726 typedef internal::StlContainerView<
2727 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2728 typedef typename ContainerView::type::size_type SizeType;
2729 explicit Impl(const SizeMatcher& size_matcher)
2730 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2731
2732 virtual void DescribeTo(::std::ostream* os) const {
2733 *os << "size ";
2734 size_matcher_.DescribeTo(os);
2735 }
2736 virtual void DescribeNegationTo(::std::ostream* os) const {
2737 *os << "size ";
2738 size_matcher_.DescribeNegationTo(os);
2739 }
2740
2741 virtual bool MatchAndExplain(Container container,
2742 MatchResultListener* listener) const {
2743 SizeType size = container.size();
2744 StringMatchResultListener size_listener;
2745 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2746 *listener
2747 << "whose size " << size << (result ? " matches" : " doesn't match");
2748 PrintIfNotEmpty(size_listener.str(), listener->stream());
2749 return result;
2750 }
2751
2752 private:
2753 const Matcher<SizeType> size_matcher_;
2754 GTEST_DISALLOW_ASSIGN_(Impl);
2755 };
2756
2757 private:
2758 const SizeMatcher size_matcher_;
2759 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2760};
2761
2762// Implements a matcher that checks the begin()..end() distance of an STL-style
2763// container.
2764template <typename DistanceMatcher>
2765class BeginEndDistanceIsMatcher {
2766 public:
2767 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2768 : distance_matcher_(distance_matcher) {}
2769
2770 template <typename Container>
2771 operator Matcher<Container>() const {
2772 return MakeMatcher(new Impl<Container>(distance_matcher_));
2773 }
2774
2775 template <typename Container>
2776 class Impl : public MatcherInterface<Container> {
2777 public:
2778 typedef internal::StlContainerView<
2779 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2780 typedef typename std::iterator_traits<
2781 typename ContainerView::type::const_iterator>::difference_type
2782 DistanceType;
2783 explicit Impl(const DistanceMatcher& distance_matcher)
2784 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2785
2786 virtual void DescribeTo(::std::ostream* os) const {
2787 *os << "distance between begin() and end() ";
2788 distance_matcher_.DescribeTo(os);
2789 }
2790 virtual void DescribeNegationTo(::std::ostream* os) const {
2791 *os << "distance between begin() and end() ";
2792 distance_matcher_.DescribeNegationTo(os);
2793 }
2794
2795 virtual bool MatchAndExplain(Container container,
2796 MatchResultListener* listener) const {
2797#if GTEST_HAS_STD_BEGIN_AND_END_
2798 using std::begin;
2799 using std::end;
2800 DistanceType distance = std::distance(begin(container), end(container));
2801#else
2802 DistanceType distance = std::distance(container.begin(), container.end());
2803#endif
2804 StringMatchResultListener distance_listener;
2805 const bool result =
2806 distance_matcher_.MatchAndExplain(distance, &distance_listener);
2807 *listener << "whose distance between begin() and end() " << distance
2808 << (result ? " matches" : " doesn't match");
2809 PrintIfNotEmpty(distance_listener.str(), listener->stream());
2810 return result;
2811 }
2812
2813 private:
2814 const Matcher<DistanceType> distance_matcher_;
2815 GTEST_DISALLOW_ASSIGN_(Impl);
2816 };
2817
2818 private:
2819 const DistanceMatcher distance_matcher_;
2820 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2821};
2822
2823// Implements an equality matcher for any STL-style container whose elements
2824// support ==. This matcher is like Eq(), but its failure explanations provide
2825// more detailed information that is useful when the container is used as a set.
2826// The failure message reports elements that are in one of the operands but not
2827// the other. The failure messages do not report duplicate or out-of-order
2828// elements in the containers (which don't properly matter to sets, but can
2829// occur if the containers are vectors or lists, for example).
2830//
2831// Uses the container's const_iterator, value_type, operator ==,
2832// begin(), and end().
2833template <typename Container>
2834class ContainerEqMatcher {
2835 public:
2836 typedef internal::StlContainerView<Container> View;
2837 typedef typename View::type StlContainer;
2838 typedef typename View::const_reference StlContainerReference;
2839
2840 // We make a copy of expected in case the elements in it are modified
2841 // after this matcher is created.
2842 explicit ContainerEqMatcher(const Container& expected)
2843 : expected_(View::Copy(expected)) {
2844 // Makes sure the user doesn't instantiate this class template
2845 // with a const or reference type.
2846 (void)testing::StaticAssertTypeEq<Container,
2847 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
2848 }
2849
2850 void DescribeTo(::std::ostream* os) const {
2851 *os << "equals ";
2852 UniversalPrint(expected_, os);
2853 }
2854 void DescribeNegationTo(::std::ostream* os) const {
2855 *os << "does not equal ";
2856 UniversalPrint(expected_, os);
2857 }
2858
2859 template <typename LhsContainer>
2860 bool MatchAndExplain(const LhsContainer& lhs,
2861 MatchResultListener* listener) const {
2862 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
2863 // that causes LhsContainer to be a const type sometimes.
2864 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
2865 LhsView;
2866 typedef typename LhsView::type LhsStlContainer;
2867 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2868 if (lhs_stl_container == expected_)
2869 return true;
2870
2871 ::std::ostream* const os = listener->stream();
2872 if (os != NULL) {
2873 // Something is different. Check for extra values first.
2874 bool printed_header = false;
2875 for (typename LhsStlContainer::const_iterator it =
2876 lhs_stl_container.begin();
2877 it != lhs_stl_container.end(); ++it) {
2878 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
2879 expected_.end()) {
2880 if (printed_header) {
2881 *os << ", ";
2882 } else {
2883 *os << "which has these unexpected elements: ";
2884 printed_header = true;
2885 }
2886 UniversalPrint(*it, os);
2887 }
2888 }
2889
2890 // Now check for missing values.
2891 bool printed_header2 = false;
2892 for (typename StlContainer::const_iterator it = expected_.begin();
2893 it != expected_.end(); ++it) {
2894 if (internal::ArrayAwareFind(
2895 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2896 lhs_stl_container.end()) {
2897 if (printed_header2) {
2898 *os << ", ";
2899 } else {
2900 *os << (printed_header ? ",\nand" : "which")
2901 << " doesn't have these expected elements: ";
2902 printed_header2 = true;
2903 }
2904 UniversalPrint(*it, os);
2905 }
2906 }
2907 }
2908
2909 return false;
2910 }
2911
2912 private:
2913 const StlContainer expected_;
2914
2915 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
2916};
2917
2918// A comparator functor that uses the < operator to compare two values.
2919struct LessComparator {
2920 template <typename T, typename U>
2921 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2922};
2923
2924// Implements WhenSortedBy(comparator, container_matcher).
2925template <typename Comparator, typename ContainerMatcher>
2926class WhenSortedByMatcher {
2927 public:
2928 WhenSortedByMatcher(const Comparator& comparator,
2929 const ContainerMatcher& matcher)
2930 : comparator_(comparator), matcher_(matcher) {}
2931
2932 template <typename LhsContainer>
2933 operator Matcher<LhsContainer>() const {
2934 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2935 }
2936
2937 template <typename LhsContainer>
2938 class Impl : public MatcherInterface<LhsContainer> {
2939 public:
2940 typedef internal::StlContainerView<
2941 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2942 typedef typename LhsView::type LhsStlContainer;
2943 typedef typename LhsView::const_reference LhsStlContainerReference;
2944 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2945 // so that we can match associative containers.
2946 typedef typename RemoveConstFromKey<
2947 typename LhsStlContainer::value_type>::type LhsValue;
2948
2949 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2950 : comparator_(comparator), matcher_(matcher) {}
2951
2952 virtual void DescribeTo(::std::ostream* os) const {
2953 *os << "(when sorted) ";
2954 matcher_.DescribeTo(os);
2955 }
2956
2957 virtual void DescribeNegationTo(::std::ostream* os) const {
2958 *os << "(when sorted) ";
2959 matcher_.DescribeNegationTo(os);
2960 }
2961
2962 virtual bool MatchAndExplain(LhsContainer lhs,
2963 MatchResultListener* listener) const {
2964 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2965 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2966 lhs_stl_container.end());
2967 ::std::sort(
2968 sorted_container.begin(), sorted_container.end(), comparator_);
2969
2970 if (!listener->IsInterested()) {
2971 // If the listener is not interested, we do not need to
2972 // construct the inner explanation.
2973 return matcher_.Matches(sorted_container);
2974 }
2975
2976 *listener << "which is ";
2977 UniversalPrint(sorted_container, listener->stream());
2978 *listener << " when sorted";
2979
2980 StringMatchResultListener inner_listener;
2981 const bool match = matcher_.MatchAndExplain(sorted_container,
2982 &inner_listener);
2983 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2984 return match;
2985 }
2986
2987 private:
2988 const Comparator comparator_;
2989 const Matcher<const ::std::vector<LhsValue>&> matcher_;
2990
2991 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2992 };
2993
2994 private:
2995 const Comparator comparator_;
2996 const ContainerMatcher matcher_;
2997
2998 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2999};
3000
3001// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
3002// must be able to be safely cast to Matcher<tuple<const T1&, const
3003// T2&> >, where T1 and T2 are the types of elements in the LHS
3004// container and the RHS container respectively.
3005template <typename TupleMatcher, typename RhsContainer>
3006class PointwiseMatcher {
Austin Schuh889ac432018-10-29 22:57:02 -07003007 GTEST_COMPILE_ASSERT_(
3008 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value,
3009 use_UnorderedPointwise_with_hash_tables);
3010
Austin Schuh0cbef622015-09-06 17:34:52 -07003011 public:
3012 typedef internal::StlContainerView<RhsContainer> RhsView;
3013 typedef typename RhsView::type RhsStlContainer;
3014 typedef typename RhsStlContainer::value_type RhsValue;
3015
3016 // Like ContainerEq, we make a copy of rhs in case the elements in
3017 // it are modified after this matcher is created.
3018 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
3019 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
3020 // Makes sure the user doesn't instantiate this class template
3021 // with a const or reference type.
3022 (void)testing::StaticAssertTypeEq<RhsContainer,
3023 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
3024 }
3025
3026 template <typename LhsContainer>
3027 operator Matcher<LhsContainer>() const {
Austin Schuh889ac432018-10-29 22:57:02 -07003028 GTEST_COMPILE_ASSERT_(
3029 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value,
3030 use_UnorderedPointwise_with_hash_tables);
3031
Austin Schuh0cbef622015-09-06 17:34:52 -07003032 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
3033 }
3034
3035 template <typename LhsContainer>
3036 class Impl : public MatcherInterface<LhsContainer> {
3037 public:
3038 typedef internal::StlContainerView<
3039 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
3040 typedef typename LhsView::type LhsStlContainer;
3041 typedef typename LhsView::const_reference LhsStlContainerReference;
3042 typedef typename LhsStlContainer::value_type LhsValue;
3043 // We pass the LHS value and the RHS value to the inner matcher by
3044 // reference, as they may be expensive to copy. We must use tuple
3045 // instead of pair here, as a pair cannot hold references (C++ 98,
3046 // 20.2.2 [lib.pairs]).
3047 typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
3048
3049 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
3050 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
3051 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
3052 rhs_(rhs) {}
3053
3054 virtual void DescribeTo(::std::ostream* os) const {
3055 *os << "contains " << rhs_.size()
3056 << " values, where each value and its corresponding value in ";
3057 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
3058 *os << " ";
3059 mono_tuple_matcher_.DescribeTo(os);
3060 }
3061 virtual void DescribeNegationTo(::std::ostream* os) const {
3062 *os << "doesn't contain exactly " << rhs_.size()
3063 << " values, or contains a value x at some index i"
3064 << " where x and the i-th value of ";
3065 UniversalPrint(rhs_, os);
3066 *os << " ";
3067 mono_tuple_matcher_.DescribeNegationTo(os);
3068 }
3069
3070 virtual bool MatchAndExplain(LhsContainer lhs,
3071 MatchResultListener* listener) const {
3072 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
3073 const size_t actual_size = lhs_stl_container.size();
3074 if (actual_size != rhs_.size()) {
3075 *listener << "which contains " << actual_size << " values";
3076 return false;
3077 }
3078
3079 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
3080 typename RhsStlContainer::const_iterator right = rhs_.begin();
3081 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
Austin Schuh0cbef622015-09-06 17:34:52 -07003082 if (listener->IsInterested()) {
3083 StringMatchResultListener inner_listener;
Austin Schuh889ac432018-10-29 22:57:02 -07003084 // Create InnerMatcherArg as a temporarily object to avoid it outlives
3085 // *left and *right. Dereference or the conversion to `const T&` may
3086 // return temp objects, e.g for vector<bool>.
Austin Schuh0cbef622015-09-06 17:34:52 -07003087 if (!mono_tuple_matcher_.MatchAndExplain(
Austin Schuh889ac432018-10-29 22:57:02 -07003088 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
3089 ImplicitCast_<const RhsValue&>(*right)),
3090 &inner_listener)) {
Austin Schuh0cbef622015-09-06 17:34:52 -07003091 *listener << "where the value pair (";
3092 UniversalPrint(*left, listener->stream());
3093 *listener << ", ";
3094 UniversalPrint(*right, listener->stream());
3095 *listener << ") at index #" << i << " don't match";
3096 PrintIfNotEmpty(inner_listener.str(), listener->stream());
3097 return false;
3098 }
3099 } else {
Austin Schuh889ac432018-10-29 22:57:02 -07003100 if (!mono_tuple_matcher_.Matches(
3101 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
3102 ImplicitCast_<const RhsValue&>(*right))))
Austin Schuh0cbef622015-09-06 17:34:52 -07003103 return false;
3104 }
3105 }
3106
3107 return true;
3108 }
3109
3110 private:
3111 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
3112 const RhsStlContainer rhs_;
3113
3114 GTEST_DISALLOW_ASSIGN_(Impl);
3115 };
3116
3117 private:
3118 const TupleMatcher tuple_matcher_;
3119 const RhsStlContainer rhs_;
3120
3121 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
3122};
3123
3124// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
3125template <typename Container>
3126class QuantifierMatcherImpl : public MatcherInterface<Container> {
3127 public:
3128 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3129 typedef StlContainerView<RawContainer> View;
3130 typedef typename View::type StlContainer;
3131 typedef typename View::const_reference StlContainerReference;
3132 typedef typename StlContainer::value_type Element;
3133
3134 template <typename InnerMatcher>
3135 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
3136 : inner_matcher_(
3137 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
3138
3139 // Checks whether:
3140 // * All elements in the container match, if all_elements_should_match.
3141 // * Any element in the container matches, if !all_elements_should_match.
3142 bool MatchAndExplainImpl(bool all_elements_should_match,
3143 Container container,
3144 MatchResultListener* listener) const {
3145 StlContainerReference stl_container = View::ConstReference(container);
3146 size_t i = 0;
3147 for (typename StlContainer::const_iterator it = stl_container.begin();
3148 it != stl_container.end(); ++it, ++i) {
3149 StringMatchResultListener inner_listener;
3150 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
3151
3152 if (matches != all_elements_should_match) {
3153 *listener << "whose element #" << i
3154 << (matches ? " matches" : " doesn't match");
3155 PrintIfNotEmpty(inner_listener.str(), listener->stream());
3156 return !all_elements_should_match;
3157 }
3158 }
3159 return all_elements_should_match;
3160 }
3161
3162 protected:
3163 const Matcher<const Element&> inner_matcher_;
3164
3165 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
3166};
3167
3168// Implements Contains(element_matcher) for the given argument type Container.
3169// Symmetric to EachMatcherImpl.
3170template <typename Container>
3171class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
3172 public:
3173 template <typename InnerMatcher>
3174 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
3175 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3176
3177 // Describes what this matcher does.
3178 virtual void DescribeTo(::std::ostream* os) const {
3179 *os << "contains at least one element that ";
3180 this->inner_matcher_.DescribeTo(os);
3181 }
3182
3183 virtual void DescribeNegationTo(::std::ostream* os) const {
3184 *os << "doesn't contain any element that ";
3185 this->inner_matcher_.DescribeTo(os);
3186 }
3187
3188 virtual bool MatchAndExplain(Container container,
3189 MatchResultListener* listener) const {
3190 return this->MatchAndExplainImpl(false, container, listener);
3191 }
3192
3193 private:
3194 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
3195};
3196
3197// Implements Each(element_matcher) for the given argument type Container.
3198// Symmetric to ContainsMatcherImpl.
3199template <typename Container>
3200class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
3201 public:
3202 template <typename InnerMatcher>
3203 explicit EachMatcherImpl(InnerMatcher inner_matcher)
3204 : QuantifierMatcherImpl<Container>(inner_matcher) {}
3205
3206 // Describes what this matcher does.
3207 virtual void DescribeTo(::std::ostream* os) const {
3208 *os << "only contains elements that ";
3209 this->inner_matcher_.DescribeTo(os);
3210 }
3211
3212 virtual void DescribeNegationTo(::std::ostream* os) const {
3213 *os << "contains some element that ";
3214 this->inner_matcher_.DescribeNegationTo(os);
3215 }
3216
3217 virtual bool MatchAndExplain(Container container,
3218 MatchResultListener* listener) const {
3219 return this->MatchAndExplainImpl(true, container, listener);
3220 }
3221
3222 private:
3223 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
3224};
3225
3226// Implements polymorphic Contains(element_matcher).
3227template <typename M>
3228class ContainsMatcher {
3229 public:
3230 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
3231
3232 template <typename Container>
3233 operator Matcher<Container>() const {
3234 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
3235 }
3236
3237 private:
3238 const M inner_matcher_;
3239
3240 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
3241};
3242
3243// Implements polymorphic Each(element_matcher).
3244template <typename M>
3245class EachMatcher {
3246 public:
3247 explicit EachMatcher(M m) : inner_matcher_(m) {}
3248
3249 template <typename Container>
3250 operator Matcher<Container>() const {
3251 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
3252 }
3253
3254 private:
3255 const M inner_matcher_;
3256
3257 GTEST_DISALLOW_ASSIGN_(EachMatcher);
3258};
3259
Austin Schuh889ac432018-10-29 22:57:02 -07003260struct Rank1 {};
3261struct Rank0 : Rank1 {};
3262
3263namespace pair_getters {
3264#if GTEST_LANG_CXX11
3265using std::get;
3266template <typename T>
3267auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT
3268 return get<0>(x);
3269}
3270template <typename T>
3271auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT
3272 return x.first;
3273}
3274
3275template <typename T>
3276auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT
3277 return get<1>(x);
3278}
3279template <typename T>
3280auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT
3281 return x.second;
3282}
3283#else
3284template <typename T>
3285typename T::first_type& First(T& x, Rank0) { // NOLINT
3286 return x.first;
3287}
3288template <typename T>
3289const typename T::first_type& First(const T& x, Rank0) {
3290 return x.first;
3291}
3292
3293template <typename T>
3294typename T::second_type& Second(T& x, Rank0) { // NOLINT
3295 return x.second;
3296}
3297template <typename T>
3298const typename T::second_type& Second(const T& x, Rank0) {
3299 return x.second;
3300}
3301#endif // GTEST_LANG_CXX11
3302} // namespace pair_getters
3303
Austin Schuh0cbef622015-09-06 17:34:52 -07003304// Implements Key(inner_matcher) for the given argument pair type.
3305// Key(inner_matcher) matches an std::pair whose 'first' field matches
3306// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3307// std::map that contains at least one element whose key is >= 5.
3308template <typename PairType>
3309class KeyMatcherImpl : public MatcherInterface<PairType> {
3310 public:
3311 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
3312 typedef typename RawPairType::first_type KeyType;
3313
3314 template <typename InnerMatcher>
3315 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
3316 : inner_matcher_(
3317 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
3318 }
3319
3320 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
3321 virtual bool MatchAndExplain(PairType key_value,
3322 MatchResultListener* listener) const {
3323 StringMatchResultListener inner_listener;
Austin Schuh889ac432018-10-29 22:57:02 -07003324 const bool match = inner_matcher_.MatchAndExplain(
3325 pair_getters::First(key_value, Rank0()), &inner_listener);
3326 const std::string explanation = inner_listener.str();
Austin Schuh0cbef622015-09-06 17:34:52 -07003327 if (explanation != "") {
3328 *listener << "whose first field is a value " << explanation;
3329 }
3330 return match;
3331 }
3332
3333 // Describes what this matcher does.
3334 virtual void DescribeTo(::std::ostream* os) const {
3335 *os << "has a key that ";
3336 inner_matcher_.DescribeTo(os);
3337 }
3338
3339 // Describes what the negation of this matcher does.
3340 virtual void DescribeNegationTo(::std::ostream* os) const {
3341 *os << "doesn't have a key that ";
3342 inner_matcher_.DescribeTo(os);
3343 }
3344
3345 private:
3346 const Matcher<const KeyType&> inner_matcher_;
3347
3348 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
3349};
3350
3351// Implements polymorphic Key(matcher_for_key).
3352template <typename M>
3353class KeyMatcher {
3354 public:
3355 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
3356
3357 template <typename PairType>
3358 operator Matcher<PairType>() const {
3359 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
3360 }
3361
3362 private:
3363 const M matcher_for_key_;
3364
3365 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
3366};
3367
3368// Implements Pair(first_matcher, second_matcher) for the given argument pair
3369// type with its two matchers. See Pair() function below.
3370template <typename PairType>
3371class PairMatcherImpl : public MatcherInterface<PairType> {
3372 public:
3373 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
3374 typedef typename RawPairType::first_type FirstType;
3375 typedef typename RawPairType::second_type SecondType;
3376
3377 template <typename FirstMatcher, typename SecondMatcher>
3378 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
3379 : first_matcher_(
3380 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
3381 second_matcher_(
3382 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
3383 }
3384
3385 // Describes what this matcher does.
3386 virtual void DescribeTo(::std::ostream* os) const {
3387 *os << "has a first field that ";
3388 first_matcher_.DescribeTo(os);
3389 *os << ", and has a second field that ";
3390 second_matcher_.DescribeTo(os);
3391 }
3392
3393 // Describes what the negation of this matcher does.
3394 virtual void DescribeNegationTo(::std::ostream* os) const {
3395 *os << "has a first field that ";
3396 first_matcher_.DescribeNegationTo(os);
3397 *os << ", or has a second field that ";
3398 second_matcher_.DescribeNegationTo(os);
3399 }
3400
3401 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3402 // matches second_matcher.
3403 virtual bool MatchAndExplain(PairType a_pair,
3404 MatchResultListener* listener) const {
3405 if (!listener->IsInterested()) {
3406 // If the listener is not interested, we don't need to construct the
3407 // explanation.
Austin Schuh889ac432018-10-29 22:57:02 -07003408 return first_matcher_.Matches(pair_getters::First(a_pair, Rank0())) &&
3409 second_matcher_.Matches(pair_getters::Second(a_pair, Rank0()));
Austin Schuh0cbef622015-09-06 17:34:52 -07003410 }
3411 StringMatchResultListener first_inner_listener;
Austin Schuh889ac432018-10-29 22:57:02 -07003412 if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank0()),
Austin Schuh0cbef622015-09-06 17:34:52 -07003413 &first_inner_listener)) {
3414 *listener << "whose first field does not match";
3415 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
3416 return false;
3417 }
3418 StringMatchResultListener second_inner_listener;
Austin Schuh889ac432018-10-29 22:57:02 -07003419 if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank0()),
Austin Schuh0cbef622015-09-06 17:34:52 -07003420 &second_inner_listener)) {
3421 *listener << "whose second field does not match";
3422 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
3423 return false;
3424 }
3425 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3426 listener);
3427 return true;
3428 }
3429
3430 private:
Austin Schuh889ac432018-10-29 22:57:02 -07003431 void ExplainSuccess(const std::string& first_explanation,
3432 const std::string& second_explanation,
Austin Schuh0cbef622015-09-06 17:34:52 -07003433 MatchResultListener* listener) const {
3434 *listener << "whose both fields match";
3435 if (first_explanation != "") {
3436 *listener << ", where the first field is a value " << first_explanation;
3437 }
3438 if (second_explanation != "") {
3439 *listener << ", ";
3440 if (first_explanation != "") {
3441 *listener << "and ";
3442 } else {
3443 *listener << "where ";
3444 }
3445 *listener << "the second field is a value " << second_explanation;
3446 }
3447 }
3448
3449 const Matcher<const FirstType&> first_matcher_;
3450 const Matcher<const SecondType&> second_matcher_;
3451
3452 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
3453};
3454
3455// Implements polymorphic Pair(first_matcher, second_matcher).
3456template <typename FirstMatcher, typename SecondMatcher>
3457class PairMatcher {
3458 public:
3459 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3460 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3461
3462 template <typename PairType>
3463 operator Matcher<PairType> () const {
3464 return MakeMatcher(
3465 new PairMatcherImpl<PairType>(
3466 first_matcher_, second_matcher_));
3467 }
3468
3469 private:
3470 const FirstMatcher first_matcher_;
3471 const SecondMatcher second_matcher_;
3472
3473 GTEST_DISALLOW_ASSIGN_(PairMatcher);
3474};
3475
3476// Implements ElementsAre() and ElementsAreArray().
3477template <typename Container>
3478class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3479 public:
3480 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3481 typedef internal::StlContainerView<RawContainer> View;
3482 typedef typename View::type StlContainer;
3483 typedef typename View::const_reference StlContainerReference;
3484 typedef typename StlContainer::value_type Element;
3485
3486 // Constructs the matcher from a sequence of element values or
3487 // element matchers.
3488 template <typename InputIter>
3489 ElementsAreMatcherImpl(InputIter first, InputIter last) {
3490 while (first != last) {
3491 matchers_.push_back(MatcherCast<const Element&>(*first++));
3492 }
3493 }
3494
3495 // Describes what this matcher does.
3496 virtual void DescribeTo(::std::ostream* os) const {
3497 if (count() == 0) {
3498 *os << "is empty";
3499 } else if (count() == 1) {
3500 *os << "has 1 element that ";
3501 matchers_[0].DescribeTo(os);
3502 } else {
3503 *os << "has " << Elements(count()) << " where\n";
3504 for (size_t i = 0; i != count(); ++i) {
3505 *os << "element #" << i << " ";
3506 matchers_[i].DescribeTo(os);
3507 if (i + 1 < count()) {
3508 *os << ",\n";
3509 }
3510 }
3511 }
3512 }
3513
3514 // Describes what the negation of this matcher does.
3515 virtual void DescribeNegationTo(::std::ostream* os) const {
3516 if (count() == 0) {
3517 *os << "isn't empty";
3518 return;
3519 }
3520
3521 *os << "doesn't have " << Elements(count()) << ", or\n";
3522 for (size_t i = 0; i != count(); ++i) {
3523 *os << "element #" << i << " ";
3524 matchers_[i].DescribeNegationTo(os);
3525 if (i + 1 < count()) {
3526 *os << ", or\n";
3527 }
3528 }
3529 }
3530
3531 virtual bool MatchAndExplain(Container container,
3532 MatchResultListener* listener) const {
3533 // To work with stream-like "containers", we must only walk
3534 // through the elements in one pass.
3535
3536 const bool listener_interested = listener->IsInterested();
3537
3538 // explanations[i] is the explanation of the element at index i.
Austin Schuh889ac432018-10-29 22:57:02 -07003539 ::std::vector<std::string> explanations(count());
Austin Schuh0cbef622015-09-06 17:34:52 -07003540 StlContainerReference stl_container = View::ConstReference(container);
3541 typename StlContainer::const_iterator it = stl_container.begin();
3542 size_t exam_pos = 0;
3543 bool mismatch_found = false; // Have we found a mismatched element yet?
3544
3545 // Go through the elements and matchers in pairs, until we reach
3546 // the end of either the elements or the matchers, or until we find a
3547 // mismatch.
3548 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3549 bool match; // Does the current element match the current matcher?
3550 if (listener_interested) {
3551 StringMatchResultListener s;
3552 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3553 explanations[exam_pos] = s.str();
3554 } else {
3555 match = matchers_[exam_pos].Matches(*it);
3556 }
3557
3558 if (!match) {
3559 mismatch_found = true;
3560 break;
3561 }
3562 }
3563 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3564
3565 // Find how many elements the actual container has. We avoid
3566 // calling size() s.t. this code works for stream-like "containers"
3567 // that don't define size().
3568 size_t actual_count = exam_pos;
3569 for (; it != stl_container.end(); ++it) {
3570 ++actual_count;
3571 }
3572
3573 if (actual_count != count()) {
3574 // The element count doesn't match. If the container is empty,
3575 // there's no need to explain anything as Google Mock already
3576 // prints the empty container. Otherwise we just need to show
3577 // how many elements there actually are.
3578 if (listener_interested && (actual_count != 0)) {
3579 *listener << "which has " << Elements(actual_count);
3580 }
3581 return false;
3582 }
3583
3584 if (mismatch_found) {
3585 // The element count matches, but the exam_pos-th element doesn't match.
3586 if (listener_interested) {
3587 *listener << "whose element #" << exam_pos << " doesn't match";
3588 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
3589 }
3590 return false;
3591 }
3592
3593 // Every element matches its expectation. We need to explain why
3594 // (the obvious ones can be skipped).
3595 if (listener_interested) {
3596 bool reason_printed = false;
3597 for (size_t i = 0; i != count(); ++i) {
Austin Schuh889ac432018-10-29 22:57:02 -07003598 const std::string& s = explanations[i];
Austin Schuh0cbef622015-09-06 17:34:52 -07003599 if (!s.empty()) {
3600 if (reason_printed) {
3601 *listener << ",\nand ";
3602 }
3603 *listener << "whose element #" << i << " matches, " << s;
3604 reason_printed = true;
3605 }
3606 }
3607 }
3608 return true;
3609 }
3610
3611 private:
3612 static Message Elements(size_t count) {
3613 return Message() << count << (count == 1 ? " element" : " elements");
3614 }
3615
3616 size_t count() const { return matchers_.size(); }
3617
3618 ::std::vector<Matcher<const Element&> > matchers_;
3619
3620 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
3621};
3622
3623// Connectivity matrix of (elements X matchers), in element-major order.
3624// Initially, there are no edges.
3625// Use NextGraph() to iterate over all possible edge configurations.
3626// Use Randomize() to generate a random edge configuration.
3627class GTEST_API_ MatchMatrix {
3628 public:
3629 MatchMatrix(size_t num_elements, size_t num_matchers)
3630 : num_elements_(num_elements),
3631 num_matchers_(num_matchers),
3632 matched_(num_elements_* num_matchers_, 0) {
3633 }
3634
3635 size_t LhsSize() const { return num_elements_; }
3636 size_t RhsSize() const { return num_matchers_; }
3637 bool HasEdge(size_t ilhs, size_t irhs) const {
3638 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3639 }
3640 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3641 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3642 }
3643
3644 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3645 // adds 1 to that number; returns false if incrementing the graph left it
3646 // empty.
3647 bool NextGraph();
3648
3649 void Randomize();
3650
Austin Schuh889ac432018-10-29 22:57:02 -07003651 std::string DebugString() const;
Austin Schuh0cbef622015-09-06 17:34:52 -07003652
3653 private:
3654 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3655 return ilhs * num_matchers_ + irhs;
3656 }
3657
3658 size_t num_elements_;
3659 size_t num_matchers_;
3660
3661 // Each element is a char interpreted as bool. They are stored as a
3662 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3663 // a (ilhs, irhs) matrix coordinate into an offset.
3664 ::std::vector<char> matched_;
3665};
3666
3667typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3668typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3669
3670// Returns a maximum bipartite matching for the specified graph 'g'.
3671// The matching is represented as a vector of {element, matcher} pairs.
3672GTEST_API_ ElementMatcherPairs
3673FindMaxBipartiteMatching(const MatchMatrix& g);
3674
Austin Schuh889ac432018-10-29 22:57:02 -07003675struct UnorderedMatcherRequire {
3676 enum Flags {
3677 Superset = 1 << 0,
3678 Subset = 1 << 1,
3679 ExactMatch = Superset | Subset,
3680 };
3681};
Austin Schuh0cbef622015-09-06 17:34:52 -07003682
3683// Untyped base class for implementing UnorderedElementsAre. By
3684// putting logic that's not specific to the element type here, we
3685// reduce binary bloat and increase compilation speed.
3686class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3687 protected:
Austin Schuh889ac432018-10-29 22:57:02 -07003688 explicit UnorderedElementsAreMatcherImplBase(
3689 UnorderedMatcherRequire::Flags matcher_flags)
3690 : match_flags_(matcher_flags) {}
3691
Austin Schuh0cbef622015-09-06 17:34:52 -07003692 // A vector of matcher describers, one for each element matcher.
3693 // Does not own the describers (and thus can be used only when the
3694 // element matchers are alive).
3695 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3696
3697 // Describes this UnorderedElementsAre matcher.
3698 void DescribeToImpl(::std::ostream* os) const;
3699
3700 // Describes the negation of this UnorderedElementsAre matcher.
3701 void DescribeNegationToImpl(::std::ostream* os) const;
3702
Austin Schuh889ac432018-10-29 22:57:02 -07003703 bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,
3704 const MatchMatrix& matrix,
3705 MatchResultListener* listener) const;
3706
3707 bool FindPairing(const MatchMatrix& matrix,
3708 MatchResultListener* listener) const;
Austin Schuh0cbef622015-09-06 17:34:52 -07003709
3710 MatcherDescriberVec& matcher_describers() {
3711 return matcher_describers_;
3712 }
3713
3714 static Message Elements(size_t n) {
3715 return Message() << n << " element" << (n == 1 ? "" : "s");
3716 }
3717
Austin Schuh889ac432018-10-29 22:57:02 -07003718 UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }
3719
Austin Schuh0cbef622015-09-06 17:34:52 -07003720 private:
Austin Schuh889ac432018-10-29 22:57:02 -07003721 UnorderedMatcherRequire::Flags match_flags_;
Austin Schuh0cbef622015-09-06 17:34:52 -07003722 MatcherDescriberVec matcher_describers_;
3723
3724 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3725};
3726
Austin Schuh889ac432018-10-29 22:57:02 -07003727// Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
3728// IsSupersetOf.
Austin Schuh0cbef622015-09-06 17:34:52 -07003729template <typename Container>
3730class UnorderedElementsAreMatcherImpl
3731 : public MatcherInterface<Container>,
3732 public UnorderedElementsAreMatcherImplBase {
3733 public:
3734 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3735 typedef internal::StlContainerView<RawContainer> View;
3736 typedef typename View::type StlContainer;
3737 typedef typename View::const_reference StlContainerReference;
3738 typedef typename StlContainer::const_iterator StlContainerConstIterator;
3739 typedef typename StlContainer::value_type Element;
3740
Austin Schuh0cbef622015-09-06 17:34:52 -07003741 template <typename InputIter>
Austin Schuh889ac432018-10-29 22:57:02 -07003742 UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,
3743 InputIter first, InputIter last)
3744 : UnorderedElementsAreMatcherImplBase(matcher_flags) {
Austin Schuh0cbef622015-09-06 17:34:52 -07003745 for (; first != last; ++first) {
3746 matchers_.push_back(MatcherCast<const Element&>(*first));
3747 matcher_describers().push_back(matchers_.back().GetDescriber());
3748 }
3749 }
3750
3751 // Describes what this matcher does.
3752 virtual void DescribeTo(::std::ostream* os) const {
3753 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3754 }
3755
3756 // Describes what the negation of this matcher does.
3757 virtual void DescribeNegationTo(::std::ostream* os) const {
3758 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3759 }
3760
3761 virtual bool MatchAndExplain(Container container,
3762 MatchResultListener* listener) const {
3763 StlContainerReference stl_container = View::ConstReference(container);
Austin Schuh889ac432018-10-29 22:57:02 -07003764 ::std::vector<std::string> element_printouts;
3765 MatchMatrix matrix =
3766 AnalyzeElements(stl_container.begin(), stl_container.end(),
3767 &element_printouts, listener);
Austin Schuh0cbef622015-09-06 17:34:52 -07003768
Austin Schuh889ac432018-10-29 22:57:02 -07003769 if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
Austin Schuh0cbef622015-09-06 17:34:52 -07003770 return true;
3771 }
Austin Schuh889ac432018-10-29 22:57:02 -07003772
3773 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
3774 if (matrix.LhsSize() != matrix.RhsSize()) {
3775 // The element count doesn't match. If the container is empty,
3776 // there's no need to explain anything as Google Mock already
3777 // prints the empty container. Otherwise we just need to show
3778 // how many elements there actually are.
3779 if (matrix.LhsSize() != 0 && listener->IsInterested()) {
3780 *listener << "which has " << Elements(matrix.LhsSize());
3781 }
3782 return false;
Austin Schuh0cbef622015-09-06 17:34:52 -07003783 }
Austin Schuh0cbef622015-09-06 17:34:52 -07003784 }
3785
Austin Schuh889ac432018-10-29 22:57:02 -07003786 return VerifyMatchMatrix(element_printouts, matrix, listener) &&
Austin Schuh0cbef622015-09-06 17:34:52 -07003787 FindPairing(matrix, listener);
3788 }
3789
3790 private:
Austin Schuh0cbef622015-09-06 17:34:52 -07003791 template <typename ElementIter>
3792 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
Austin Schuh889ac432018-10-29 22:57:02 -07003793 ::std::vector<std::string>* element_printouts,
Austin Schuh0cbef622015-09-06 17:34:52 -07003794 MatchResultListener* listener) const {
3795 element_printouts->clear();
3796 ::std::vector<char> did_match;
3797 size_t num_elements = 0;
3798 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3799 if (listener->IsInterested()) {
3800 element_printouts->push_back(PrintToString(*elem_first));
3801 }
3802 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3803 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3804 }
3805 }
3806
3807 MatchMatrix matrix(num_elements, matchers_.size());
3808 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3809 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3810 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3811 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3812 }
3813 }
3814 return matrix;
3815 }
3816
Austin Schuh889ac432018-10-29 22:57:02 -07003817 ::std::vector<Matcher<const Element&> > matchers_;
Austin Schuh0cbef622015-09-06 17:34:52 -07003818
3819 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3820};
3821
3822// Functor for use in TransformTuple.
3823// Performs MatcherCast<Target> on an input argument of any type.
3824template <typename Target>
3825struct CastAndAppendTransform {
3826 template <typename Arg>
3827 Matcher<Target> operator()(const Arg& a) const {
3828 return MatcherCast<Target>(a);
3829 }
3830};
3831
3832// Implements UnorderedElementsAre.
3833template <typename MatcherTuple>
3834class UnorderedElementsAreMatcher {
3835 public:
3836 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3837 : matchers_(args) {}
3838
3839 template <typename Container>
3840 operator Matcher<Container>() const {
3841 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3842 typedef typename internal::StlContainerView<RawContainer>::type View;
3843 typedef typename View::value_type Element;
3844 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3845 MatcherVec matchers;
3846 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
3847 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3848 ::std::back_inserter(matchers));
3849 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
Austin Schuh889ac432018-10-29 22:57:02 -07003850 UnorderedMatcherRequire::ExactMatch, matchers.begin(), matchers.end()));
Austin Schuh0cbef622015-09-06 17:34:52 -07003851 }
3852
3853 private:
3854 const MatcherTuple matchers_;
3855 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3856};
3857
3858// Implements ElementsAre.
3859template <typename MatcherTuple>
3860class ElementsAreMatcher {
3861 public:
3862 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3863
3864 template <typename Container>
3865 operator Matcher<Container>() const {
Austin Schuh889ac432018-10-29 22:57:02 -07003866 GTEST_COMPILE_ASSERT_(
3867 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value ||
3868 ::testing::tuple_size<MatcherTuple>::value < 2,
3869 use_UnorderedElementsAre_with_hash_tables);
3870
Austin Schuh0cbef622015-09-06 17:34:52 -07003871 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3872 typedef typename internal::StlContainerView<RawContainer>::type View;
3873 typedef typename View::value_type Element;
3874 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3875 MatcherVec matchers;
3876 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
3877 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3878 ::std::back_inserter(matchers));
3879 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3880 matchers.begin(), matchers.end()));
3881 }
3882
3883 private:
3884 const MatcherTuple matchers_;
3885 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3886};
3887
Austin Schuh889ac432018-10-29 22:57:02 -07003888// Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
Austin Schuh0cbef622015-09-06 17:34:52 -07003889template <typename T>
3890class UnorderedElementsAreArrayMatcher {
3891 public:
Austin Schuh0cbef622015-09-06 17:34:52 -07003892 template <typename Iter>
Austin Schuh889ac432018-10-29 22:57:02 -07003893 UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,
3894 Iter first, Iter last)
3895 : match_flags_(match_flags), matchers_(first, last) {}
Austin Schuh0cbef622015-09-06 17:34:52 -07003896
3897 template <typename Container>
3898 operator Matcher<Container>() const {
Austin Schuh889ac432018-10-29 22:57:02 -07003899 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3900 match_flags_, matchers_.begin(), matchers_.end()));
Austin Schuh0cbef622015-09-06 17:34:52 -07003901 }
3902
3903 private:
Austin Schuh889ac432018-10-29 22:57:02 -07003904 UnorderedMatcherRequire::Flags match_flags_;
Austin Schuh0cbef622015-09-06 17:34:52 -07003905 ::std::vector<T> matchers_;
3906
3907 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
3908};
3909
3910// Implements ElementsAreArray().
3911template <typename T>
3912class ElementsAreArrayMatcher {
3913 public:
3914 template <typename Iter>
3915 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
3916
3917 template <typename Container>
3918 operator Matcher<Container>() const {
Austin Schuh889ac432018-10-29 22:57:02 -07003919 GTEST_COMPILE_ASSERT_(
3920 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value,
3921 use_UnorderedElementsAreArray_with_hash_tables);
3922
Austin Schuh0cbef622015-09-06 17:34:52 -07003923 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3924 matchers_.begin(), matchers_.end()));
3925 }
3926
3927 private:
3928 const ::std::vector<T> matchers_;
3929
3930 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
3931};
3932
3933// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3934// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3935// second) is a polymorphic matcher that matches a value x iff tm
3936// matches tuple (x, second). Useful for implementing
3937// UnorderedPointwise() in terms of UnorderedElementsAreArray().
3938//
3939// BoundSecondMatcher is copyable and assignable, as we need to put
3940// instances of this class in a vector when implementing
3941// UnorderedPointwise().
3942template <typename Tuple2Matcher, typename Second>
3943class BoundSecondMatcher {
3944 public:
3945 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3946 : tuple2_matcher_(tm), second_value_(second) {}
3947
3948 template <typename T>
3949 operator Matcher<T>() const {
3950 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3951 }
3952
3953 // We have to define this for UnorderedPointwise() to compile in
3954 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3955 // which requires the elements to be assignable in C++98. The
3956 // compiler cannot generate the operator= for us, as Tuple2Matcher
3957 // and Second may not be assignable.
3958 //
3959 // However, this should never be called, so the implementation just
3960 // need to assert.
3961 void operator=(const BoundSecondMatcher& /*rhs*/) {
3962 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3963 }
3964
3965 private:
3966 template <typename T>
3967 class Impl : public MatcherInterface<T> {
3968 public:
3969 typedef ::testing::tuple<T, Second> ArgTuple;
3970
3971 Impl(const Tuple2Matcher& tm, const Second& second)
3972 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3973 second_value_(second) {}
3974
3975 virtual void DescribeTo(::std::ostream* os) const {
3976 *os << "and ";
3977 UniversalPrint(second_value_, os);
3978 *os << " ";
3979 mono_tuple2_matcher_.DescribeTo(os);
3980 }
3981
3982 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3983 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3984 listener);
3985 }
3986
3987 private:
3988 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3989 const Second second_value_;
3990
3991 GTEST_DISALLOW_ASSIGN_(Impl);
3992 };
3993
3994 const Tuple2Matcher tuple2_matcher_;
3995 const Second second_value_;
3996};
3997
3998// Given a 2-tuple matcher tm and a value second,
3999// MatcherBindSecond(tm, second) returns a matcher that matches a
4000// value x iff tm matches tuple (x, second). Useful for implementing
4001// UnorderedPointwise() in terms of UnorderedElementsAreArray().
4002template <typename Tuple2Matcher, typename Second>
4003BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
4004 const Tuple2Matcher& tm, const Second& second) {
4005 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
4006}
4007
4008// Returns the description for a matcher defined using the MATCHER*()
4009// macro where the user-supplied description string is "", if
4010// 'negation' is false; otherwise returns the description of the
4011// negation of the matcher. 'param_values' contains a list of strings
4012// that are the print-out of the matcher's parameters.
Austin Schuh889ac432018-10-29 22:57:02 -07004013GTEST_API_ std::string FormatMatcherDescription(bool negation,
4014 const char* matcher_name,
4015 const Strings& param_values);
Austin Schuh0cbef622015-09-06 17:34:52 -07004016
Austin Schuh889ac432018-10-29 22:57:02 -07004017// Implements a matcher that checks the value of a optional<> type variable.
4018template <typename ValueMatcher>
4019class OptionalMatcher {
4020 public:
4021 explicit OptionalMatcher(const ValueMatcher& value_matcher)
4022 : value_matcher_(value_matcher) {}
4023
4024 template <typename Optional>
4025 operator Matcher<Optional>() const {
4026 return MakeMatcher(new Impl<Optional>(value_matcher_));
4027 }
4028
4029 template <typename Optional>
4030 class Impl : public MatcherInterface<Optional> {
4031 public:
4032 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView;
4033 typedef typename OptionalView::value_type ValueType;
4034 explicit Impl(const ValueMatcher& value_matcher)
4035 : value_matcher_(MatcherCast<ValueType>(value_matcher)) {}
4036
4037 virtual void DescribeTo(::std::ostream* os) const {
4038 *os << "value ";
4039 value_matcher_.DescribeTo(os);
4040 }
4041
4042 virtual void DescribeNegationTo(::std::ostream* os) const {
4043 *os << "value ";
4044 value_matcher_.DescribeNegationTo(os);
4045 }
4046
4047 virtual bool MatchAndExplain(Optional optional,
4048 MatchResultListener* listener) const {
4049 if (!optional) {
4050 *listener << "which is not engaged";
4051 return false;
4052 }
4053 const ValueType& value = *optional;
4054 StringMatchResultListener value_listener;
4055 const bool match = value_matcher_.MatchAndExplain(value, &value_listener);
4056 *listener << "whose value " << PrintToString(value)
4057 << (match ? " matches" : " doesn't match");
4058 PrintIfNotEmpty(value_listener.str(), listener->stream());
4059 return match;
4060 }
4061
4062 private:
4063 const Matcher<ValueType> value_matcher_;
4064 GTEST_DISALLOW_ASSIGN_(Impl);
4065 };
4066
4067 private:
4068 const ValueMatcher value_matcher_;
4069 GTEST_DISALLOW_ASSIGN_(OptionalMatcher);
4070};
4071
4072namespace variant_matcher {
4073// Overloads to allow VariantMatcher to do proper ADL lookup.
4074template <typename T>
4075void holds_alternative() {}
4076template <typename T>
4077void get() {}
4078
4079// Implements a matcher that checks the value of a variant<> type variable.
4080template <typename T>
4081class VariantMatcher {
4082 public:
4083 explicit VariantMatcher(::testing::Matcher<const T&> matcher)
4084 : matcher_(internal::move(matcher)) {}
4085
4086 template <typename Variant>
4087 bool MatchAndExplain(const Variant& value,
4088 ::testing::MatchResultListener* listener) const {
4089 if (!listener->IsInterested()) {
4090 return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));
4091 }
4092
4093 if (!holds_alternative<T>(value)) {
4094 *listener << "whose value is not of type '" << GetTypeName() << "'";
4095 return false;
4096 }
4097
4098 const T& elem = get<T>(value);
4099 StringMatchResultListener elem_listener;
4100 const bool match = matcher_.MatchAndExplain(elem, &elem_listener);
4101 *listener << "whose value " << PrintToString(elem)
4102 << (match ? " matches" : " doesn't match");
4103 PrintIfNotEmpty(elem_listener.str(), listener->stream());
4104 return match;
4105 }
4106
4107 void DescribeTo(std::ostream* os) const {
4108 *os << "is a variant<> with value of type '" << GetTypeName()
4109 << "' and the value ";
4110 matcher_.DescribeTo(os);
4111 }
4112
4113 void DescribeNegationTo(std::ostream* os) const {
4114 *os << "is a variant<> with value of type other than '" << GetTypeName()
4115 << "' or the value ";
4116 matcher_.DescribeNegationTo(os);
4117 }
4118
4119 private:
4120 static std::string GetTypeName() {
4121#if GTEST_HAS_RTTI
4122 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
4123 return internal::GetTypeName<T>());
4124#endif
4125 return "the element type";
4126 }
4127
4128 const ::testing::Matcher<const T&> matcher_;
4129};
4130
4131} // namespace variant_matcher
4132
4133namespace any_cast_matcher {
4134
4135// Overloads to allow AnyCastMatcher to do proper ADL lookup.
4136template <typename T>
4137void any_cast() {}
4138
4139// Implements a matcher that any_casts the value.
4140template <typename T>
4141class AnyCastMatcher {
4142 public:
4143 explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher)
4144 : matcher_(matcher) {}
4145
4146 template <typename AnyType>
4147 bool MatchAndExplain(const AnyType& value,
4148 ::testing::MatchResultListener* listener) const {
4149 if (!listener->IsInterested()) {
4150 const T* ptr = any_cast<T>(&value);
4151 return ptr != NULL && matcher_.Matches(*ptr);
4152 }
4153
4154 const T* elem = any_cast<T>(&value);
4155 if (elem == NULL) {
4156 *listener << "whose value is not of type '" << GetTypeName() << "'";
4157 return false;
4158 }
4159
4160 StringMatchResultListener elem_listener;
4161 const bool match = matcher_.MatchAndExplain(*elem, &elem_listener);
4162 *listener << "whose value " << PrintToString(*elem)
4163 << (match ? " matches" : " doesn't match");
4164 PrintIfNotEmpty(elem_listener.str(), listener->stream());
4165 return match;
4166 }
4167
4168 void DescribeTo(std::ostream* os) const {
4169 *os << "is an 'any' type with value of type '" << GetTypeName()
4170 << "' and the value ";
4171 matcher_.DescribeTo(os);
4172 }
4173
4174 void DescribeNegationTo(std::ostream* os) const {
4175 *os << "is an 'any' type with value of type other than '" << GetTypeName()
4176 << "' or the value ";
4177 matcher_.DescribeNegationTo(os);
4178 }
4179
4180 private:
4181 static std::string GetTypeName() {
4182#if GTEST_HAS_RTTI
4183 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
4184 return internal::GetTypeName<T>());
4185#endif
4186 return "the element type";
4187 }
4188
4189 const ::testing::Matcher<const T&> matcher_;
4190};
4191
4192} // namespace any_cast_matcher
Austin Schuh0cbef622015-09-06 17:34:52 -07004193} // namespace internal
4194
Austin Schuh889ac432018-10-29 22:57:02 -07004195// ElementsAreArray(iterator_first, iterator_last)
Austin Schuh0cbef622015-09-06 17:34:52 -07004196// ElementsAreArray(pointer, count)
4197// ElementsAreArray(array)
4198// ElementsAreArray(container)
4199// ElementsAreArray({ e1, e2, ..., en })
4200//
4201// The ElementsAreArray() functions are like ElementsAre(...), except
4202// that they are given a homogeneous sequence rather than taking each
4203// element as a function argument. The sequence can be specified as an
4204// array, a pointer and count, a vector, an initializer list, or an
4205// STL iterator range. In each of these cases, the underlying sequence
4206// can be either a sequence of values or a sequence of matchers.
4207//
4208// All forms of ElementsAreArray() make a copy of the input matcher sequence.
4209
4210template <typename Iter>
4211inline internal::ElementsAreArrayMatcher<
4212 typename ::std::iterator_traits<Iter>::value_type>
4213ElementsAreArray(Iter first, Iter last) {
4214 typedef typename ::std::iterator_traits<Iter>::value_type T;
4215 return internal::ElementsAreArrayMatcher<T>(first, last);
4216}
4217
4218template <typename T>
4219inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
4220 const T* pointer, size_t count) {
4221 return ElementsAreArray(pointer, pointer + count);
4222}
4223
4224template <typename T, size_t N>
4225inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
4226 const T (&array)[N]) {
4227 return ElementsAreArray(array, N);
4228}
4229
4230template <typename Container>
4231inline internal::ElementsAreArrayMatcher<typename Container::value_type>
4232ElementsAreArray(const Container& container) {
4233 return ElementsAreArray(container.begin(), container.end());
4234}
4235
4236#if GTEST_HAS_STD_INITIALIZER_LIST_
4237template <typename T>
4238inline internal::ElementsAreArrayMatcher<T>
4239ElementsAreArray(::std::initializer_list<T> xs) {
4240 return ElementsAreArray(xs.begin(), xs.end());
4241}
4242#endif
4243
Austin Schuh889ac432018-10-29 22:57:02 -07004244// UnorderedElementsAreArray(iterator_first, iterator_last)
Austin Schuh0cbef622015-09-06 17:34:52 -07004245// UnorderedElementsAreArray(pointer, count)
4246// UnorderedElementsAreArray(array)
4247// UnorderedElementsAreArray(container)
4248// UnorderedElementsAreArray({ e1, e2, ..., en })
4249//
Austin Schuh889ac432018-10-29 22:57:02 -07004250// UnorderedElementsAreArray() verifies that a bijective mapping onto a
4251// collection of matchers exists.
4252//
4253// The matchers can be specified as an array, a pointer and count, a container,
4254// an initializer list, or an STL iterator range. In each of these cases, the
4255// underlying matchers can be either values or matchers.
4256
Austin Schuh0cbef622015-09-06 17:34:52 -07004257template <typename Iter>
4258inline internal::UnorderedElementsAreArrayMatcher<
4259 typename ::std::iterator_traits<Iter>::value_type>
4260UnorderedElementsAreArray(Iter first, Iter last) {
4261 typedef typename ::std::iterator_traits<Iter>::value_type T;
Austin Schuh889ac432018-10-29 22:57:02 -07004262 return internal::UnorderedElementsAreArrayMatcher<T>(
4263 internal::UnorderedMatcherRequire::ExactMatch, first, last);
Austin Schuh0cbef622015-09-06 17:34:52 -07004264}
4265
4266template <typename T>
4267inline internal::UnorderedElementsAreArrayMatcher<T>
4268UnorderedElementsAreArray(const T* pointer, size_t count) {
4269 return UnorderedElementsAreArray(pointer, pointer + count);
4270}
4271
4272template <typename T, size_t N>
4273inline internal::UnorderedElementsAreArrayMatcher<T>
4274UnorderedElementsAreArray(const T (&array)[N]) {
4275 return UnorderedElementsAreArray(array, N);
4276}
4277
4278template <typename Container>
4279inline internal::UnorderedElementsAreArrayMatcher<
4280 typename Container::value_type>
4281UnorderedElementsAreArray(const Container& container) {
4282 return UnorderedElementsAreArray(container.begin(), container.end());
4283}
4284
4285#if GTEST_HAS_STD_INITIALIZER_LIST_
4286template <typename T>
4287inline internal::UnorderedElementsAreArrayMatcher<T>
4288UnorderedElementsAreArray(::std::initializer_list<T> xs) {
4289 return UnorderedElementsAreArray(xs.begin(), xs.end());
4290}
4291#endif
4292
4293// _ is a matcher that matches anything of any type.
4294//
4295// This definition is fine as:
4296//
4297// 1. The C++ standard permits using the name _ in a namespace that
4298// is not the global namespace or ::std.
4299// 2. The AnythingMatcher class has no data member or constructor,
4300// so it's OK to create global variables of this type.
4301// 3. c-style has approved of using _ in this case.
4302const internal::AnythingMatcher _ = {};
4303// Creates a matcher that matches any value of the given type T.
4304template <typename T>
Austin Schuh889ac432018-10-29 22:57:02 -07004305inline Matcher<T> A() {
4306 return Matcher<T>(new internal::AnyMatcherImpl<T>());
4307}
Austin Schuh0cbef622015-09-06 17:34:52 -07004308
4309// Creates a matcher that matches any value of the given type T.
4310template <typename T>
4311inline Matcher<T> An() { return A<T>(); }
4312
4313// Creates a polymorphic matcher that matches anything equal to x.
4314// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
4315// wouldn't compile.
4316template <typename T>
4317inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
4318
4319// Constructs a Matcher<T> from a 'value' of type T. The constructed
4320// matcher matches any value that's equal to 'value'.
4321template <typename T>
4322Matcher<T>::Matcher(T value) { *this = Eq(value); }
4323
Austin Schuh889ac432018-10-29 22:57:02 -07004324template <typename T, typename M>
4325Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(
4326 const M& value,
4327 internal::BooleanConstant<false> /* convertible_to_matcher */,
4328 internal::BooleanConstant<false> /* convertible_to_T */) {
4329 return Eq(value);
4330}
4331
Austin Schuh0cbef622015-09-06 17:34:52 -07004332// Creates a monomorphic matcher that matches anything with type Lhs
4333// and equal to rhs. A user may need to use this instead of Eq(...)
4334// in order to resolve an overloading ambiguity.
4335//
4336// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
4337// or Matcher<T>(x), but more readable than the latter.
4338//
4339// We could define similar monomorphic matchers for other comparison
4340// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
4341// it yet as those are used much less than Eq() in practice. A user
4342// can always write Matcher<T>(Lt(5)) to be explicit about the type,
4343// for example.
4344template <typename Lhs, typename Rhs>
4345inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
4346
4347// Creates a polymorphic matcher that matches anything >= x.
4348template <typename Rhs>
4349inline internal::GeMatcher<Rhs> Ge(Rhs x) {
4350 return internal::GeMatcher<Rhs>(x);
4351}
4352
4353// Creates a polymorphic matcher that matches anything > x.
4354template <typename Rhs>
4355inline internal::GtMatcher<Rhs> Gt(Rhs x) {
4356 return internal::GtMatcher<Rhs>(x);
4357}
4358
4359// Creates a polymorphic matcher that matches anything <= x.
4360template <typename Rhs>
4361inline internal::LeMatcher<Rhs> Le(Rhs x) {
4362 return internal::LeMatcher<Rhs>(x);
4363}
4364
4365// Creates a polymorphic matcher that matches anything < x.
4366template <typename Rhs>
4367inline internal::LtMatcher<Rhs> Lt(Rhs x) {
4368 return internal::LtMatcher<Rhs>(x);
4369}
4370
4371// Creates a polymorphic matcher that matches anything != x.
4372template <typename Rhs>
4373inline internal::NeMatcher<Rhs> Ne(Rhs x) {
4374 return internal::NeMatcher<Rhs>(x);
4375}
4376
4377// Creates a polymorphic matcher that matches any NULL pointer.
4378inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
4379 return MakePolymorphicMatcher(internal::IsNullMatcher());
4380}
4381
4382// Creates a polymorphic matcher that matches any non-NULL pointer.
4383// This is convenient as Not(NULL) doesn't compile (the compiler
4384// thinks that that expression is comparing a pointer with an integer).
4385inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
4386 return MakePolymorphicMatcher(internal::NotNullMatcher());
4387}
4388
4389// Creates a polymorphic matcher that matches any argument that
4390// references variable x.
4391template <typename T>
4392inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
4393 return internal::RefMatcher<T&>(x);
4394}
4395
4396// Creates a matcher that matches any double argument approximately
4397// equal to rhs, where two NANs are considered unequal.
4398inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
4399 return internal::FloatingEqMatcher<double>(rhs, false);
4400}
4401
4402// Creates a matcher that matches any double argument approximately
4403// equal to rhs, including NaN values when rhs is NaN.
4404inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
4405 return internal::FloatingEqMatcher<double>(rhs, true);
4406}
4407
4408// Creates a matcher that matches any double argument approximately equal to
4409// rhs, up to the specified max absolute error bound, where two NANs are
4410// considered unequal. The max absolute error bound must be non-negative.
4411inline internal::FloatingEqMatcher<double> DoubleNear(
4412 double rhs, double max_abs_error) {
4413 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
4414}
4415
4416// Creates a matcher that matches any double argument approximately equal to
4417// rhs, up to the specified max absolute error bound, including NaN values when
4418// rhs is NaN. The max absolute error bound must be non-negative.
4419inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
4420 double rhs, double max_abs_error) {
4421 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
4422}
4423
4424// Creates a matcher that matches any float argument approximately
4425// equal to rhs, where two NANs are considered unequal.
4426inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
4427 return internal::FloatingEqMatcher<float>(rhs, false);
4428}
4429
4430// Creates a matcher that matches any float argument approximately
4431// equal to rhs, including NaN values when rhs is NaN.
4432inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
4433 return internal::FloatingEqMatcher<float>(rhs, true);
4434}
4435
4436// Creates a matcher that matches any float argument approximately equal to
4437// rhs, up to the specified max absolute error bound, where two NANs are
4438// considered unequal. The max absolute error bound must be non-negative.
4439inline internal::FloatingEqMatcher<float> FloatNear(
4440 float rhs, float max_abs_error) {
4441 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
4442}
4443
4444// Creates a matcher that matches any float argument approximately equal to
4445// rhs, up to the specified max absolute error bound, including NaN values when
4446// rhs is NaN. The max absolute error bound must be non-negative.
4447inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
4448 float rhs, float max_abs_error) {
4449 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
4450}
4451
4452// Creates a matcher that matches a pointer (raw or smart) that points
4453// to a value that matches inner_matcher.
4454template <typename InnerMatcher>
4455inline internal::PointeeMatcher<InnerMatcher> Pointee(
4456 const InnerMatcher& inner_matcher) {
4457 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
4458}
4459
Austin Schuh889ac432018-10-29 22:57:02 -07004460#if GTEST_HAS_RTTI
Austin Schuh0cbef622015-09-06 17:34:52 -07004461// Creates a matcher that matches a pointer or reference that matches
4462// inner_matcher when dynamic_cast<To> is applied.
4463// The result of dynamic_cast<To> is forwarded to the inner matcher.
4464// If To is a pointer and the cast fails, the inner matcher will receive NULL.
4465// If To is a reference and the cast fails, this matcher returns false
4466// immediately.
4467template <typename To>
4468inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
4469WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
4470 return MakePolymorphicMatcher(
4471 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
4472}
Austin Schuh889ac432018-10-29 22:57:02 -07004473#endif // GTEST_HAS_RTTI
Austin Schuh0cbef622015-09-06 17:34:52 -07004474
4475// Creates a matcher that matches an object whose given field matches
4476// 'matcher'. For example,
4477// Field(&Foo::number, Ge(5))
4478// matches a Foo object x iff x.number >= 5.
4479template <typename Class, typename FieldType, typename FieldMatcher>
4480inline PolymorphicMatcher<
4481 internal::FieldMatcher<Class, FieldType> > Field(
4482 FieldType Class::*field, const FieldMatcher& matcher) {
4483 return MakePolymorphicMatcher(
4484 internal::FieldMatcher<Class, FieldType>(
4485 field, MatcherCast<const FieldType&>(matcher)));
4486 // The call to MatcherCast() is required for supporting inner
4487 // matchers of compatible types. For example, it allows
4488 // Field(&Foo::bar, m)
4489 // to compile where bar is an int32 and m is a matcher for int64.
4490}
4491
Austin Schuh889ac432018-10-29 22:57:02 -07004492// Same as Field() but also takes the name of the field to provide better error
4493// messages.
4494template <typename Class, typename FieldType, typename FieldMatcher>
4495inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType> > Field(
4496 const std::string& field_name, FieldType Class::*field,
4497 const FieldMatcher& matcher) {
4498 return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(
4499 field_name, field, MatcherCast<const FieldType&>(matcher)));
4500}
4501
Austin Schuh0cbef622015-09-06 17:34:52 -07004502// Creates a matcher that matches an object whose given property
4503// matches 'matcher'. For example,
4504// Property(&Foo::str, StartsWith("hi"))
4505// matches a Foo object x iff x.str() starts with "hi".
4506template <typename Class, typename PropertyType, typename PropertyMatcher>
Austin Schuh889ac432018-10-29 22:57:02 -07004507inline PolymorphicMatcher<internal::PropertyMatcher<
4508 Class, PropertyType, PropertyType (Class::*)() const> >
4509Property(PropertyType (Class::*property)() const,
4510 const PropertyMatcher& matcher) {
Austin Schuh0cbef622015-09-06 17:34:52 -07004511 return MakePolymorphicMatcher(
Austin Schuh889ac432018-10-29 22:57:02 -07004512 internal::PropertyMatcher<Class, PropertyType,
4513 PropertyType (Class::*)() const>(
Austin Schuh0cbef622015-09-06 17:34:52 -07004514 property,
4515 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4516 // The call to MatcherCast() is required for supporting inner
4517 // matchers of compatible types. For example, it allows
4518 // Property(&Foo::bar, m)
4519 // to compile where bar() returns an int32 and m is a matcher for int64.
4520}
4521
Austin Schuh889ac432018-10-29 22:57:02 -07004522// Same as Property() above, but also takes the name of the property to provide
4523// better error messages.
4524template <typename Class, typename PropertyType, typename PropertyMatcher>
4525inline PolymorphicMatcher<internal::PropertyMatcher<
4526 Class, PropertyType, PropertyType (Class::*)() const> >
4527Property(const std::string& property_name,
4528 PropertyType (Class::*property)() const,
4529 const PropertyMatcher& matcher) {
4530 return MakePolymorphicMatcher(
4531 internal::PropertyMatcher<Class, PropertyType,
4532 PropertyType (Class::*)() const>(
4533 property_name, property,
4534 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4535}
4536
4537#if GTEST_LANG_CXX11
4538// The same as above but for reference-qualified member functions.
4539template <typename Class, typename PropertyType, typename PropertyMatcher>
4540inline PolymorphicMatcher<internal::PropertyMatcher<
4541 Class, PropertyType, PropertyType (Class::*)() const &> >
4542Property(PropertyType (Class::*property)() const &,
4543 const PropertyMatcher& matcher) {
4544 return MakePolymorphicMatcher(
4545 internal::PropertyMatcher<Class, PropertyType,
4546 PropertyType (Class::*)() const &>(
4547 property,
4548 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4549}
4550
4551// Three-argument form for reference-qualified member functions.
4552template <typename Class, typename PropertyType, typename PropertyMatcher>
4553inline PolymorphicMatcher<internal::PropertyMatcher<
4554 Class, PropertyType, PropertyType (Class::*)() const &> >
4555Property(const std::string& property_name,
4556 PropertyType (Class::*property)() const &,
4557 const PropertyMatcher& matcher) {
4558 return MakePolymorphicMatcher(
4559 internal::PropertyMatcher<Class, PropertyType,
4560 PropertyType (Class::*)() const &>(
4561 property_name, property,
4562 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
4563}
4564#endif
4565
Austin Schuh0cbef622015-09-06 17:34:52 -07004566// Creates a matcher that matches an object iff the result of applying
4567// a callable to x matches 'matcher'.
4568// For example,
4569// ResultOf(f, StartsWith("hi"))
4570// matches a Foo object x iff f(x) starts with "hi".
Austin Schuh889ac432018-10-29 22:57:02 -07004571// `callable` parameter can be a function, function pointer, or a functor. It is
4572// required to keep no state affecting the results of the calls on it and make
4573// no assumptions about how many calls will be made. Any state it keeps must be
4574// protected from the concurrent access.
4575template <typename Callable, typename InnerMatcher>
4576internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(
4577 Callable callable, InnerMatcher matcher) {
4578 return internal::ResultOfMatcher<Callable, InnerMatcher>(
4579 internal::move(callable), internal::move(matcher));
Austin Schuh0cbef622015-09-06 17:34:52 -07004580}
4581
4582// String matchers.
4583
4584// Matches a string equal to str.
Austin Schuh889ac432018-10-29 22:57:02 -07004585inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
4586 const std::string& str) {
4587 return MakePolymorphicMatcher(
4588 internal::StrEqualityMatcher<std::string>(str, true, true));
Austin Schuh0cbef622015-09-06 17:34:52 -07004589}
4590
4591// Matches a string not equal to str.
Austin Schuh889ac432018-10-29 22:57:02 -07004592inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
4593 const std::string& str) {
4594 return MakePolymorphicMatcher(
4595 internal::StrEqualityMatcher<std::string>(str, false, true));
Austin Schuh0cbef622015-09-06 17:34:52 -07004596}
4597
4598// Matches a string equal to str, ignoring case.
Austin Schuh889ac432018-10-29 22:57:02 -07004599inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
4600 const std::string& str) {
4601 return MakePolymorphicMatcher(
4602 internal::StrEqualityMatcher<std::string>(str, true, false));
Austin Schuh0cbef622015-09-06 17:34:52 -07004603}
4604
4605// Matches a string not equal to str, ignoring case.
Austin Schuh889ac432018-10-29 22:57:02 -07004606inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
4607 const std::string& str) {
4608 return MakePolymorphicMatcher(
4609 internal::StrEqualityMatcher<std::string>(str, false, false));
Austin Schuh0cbef622015-09-06 17:34:52 -07004610}
4611
4612// Creates a matcher that matches any string, std::string, or C string
4613// that contains the given substring.
Austin Schuh889ac432018-10-29 22:57:02 -07004614inline PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
4615 const std::string& substring) {
4616 return MakePolymorphicMatcher(
4617 internal::HasSubstrMatcher<std::string>(substring));
Austin Schuh0cbef622015-09-06 17:34:52 -07004618}
4619
4620// Matches a string that starts with 'prefix' (case-sensitive).
Austin Schuh889ac432018-10-29 22:57:02 -07004621inline PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
4622 const std::string& prefix) {
4623 return MakePolymorphicMatcher(
4624 internal::StartsWithMatcher<std::string>(prefix));
Austin Schuh0cbef622015-09-06 17:34:52 -07004625}
4626
4627// Matches a string that ends with 'suffix' (case-sensitive).
Austin Schuh889ac432018-10-29 22:57:02 -07004628inline PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
4629 const std::string& suffix) {
4630 return MakePolymorphicMatcher(internal::EndsWithMatcher<std::string>(suffix));
Austin Schuh0cbef622015-09-06 17:34:52 -07004631}
4632
4633// Matches a string that fully matches regular expression 'regex'.
4634// The matcher takes ownership of 'regex'.
4635inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4636 const internal::RE* regex) {
4637 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
4638}
4639inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
Austin Schuh889ac432018-10-29 22:57:02 -07004640 const std::string& regex) {
Austin Schuh0cbef622015-09-06 17:34:52 -07004641 return MatchesRegex(new internal::RE(regex));
4642}
4643
4644// Matches a string that contains regular expression 'regex'.
4645// The matcher takes ownership of 'regex'.
4646inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4647 const internal::RE* regex) {
4648 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4649}
4650inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
Austin Schuh889ac432018-10-29 22:57:02 -07004651 const std::string& regex) {
Austin Schuh0cbef622015-09-06 17:34:52 -07004652 return ContainsRegex(new internal::RE(regex));
4653}
4654
4655#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4656// Wide string matchers.
4657
4658// Matches a string equal to str.
Austin Schuh889ac432018-10-29 22:57:02 -07004659inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrEq(
4660 const std::wstring& str) {
4661 return MakePolymorphicMatcher(
4662 internal::StrEqualityMatcher<std::wstring>(str, true, true));
Austin Schuh0cbef622015-09-06 17:34:52 -07004663}
4664
4665// Matches a string not equal to str.
Austin Schuh889ac432018-10-29 22:57:02 -07004666inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrNe(
4667 const std::wstring& str) {
4668 return MakePolymorphicMatcher(
4669 internal::StrEqualityMatcher<std::wstring>(str, false, true));
Austin Schuh0cbef622015-09-06 17:34:52 -07004670}
4671
4672// Matches a string equal to str, ignoring case.
Austin Schuh889ac432018-10-29 22:57:02 -07004673inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
4674StrCaseEq(const std::wstring& str) {
4675 return MakePolymorphicMatcher(
4676 internal::StrEqualityMatcher<std::wstring>(str, true, false));
Austin Schuh0cbef622015-09-06 17:34:52 -07004677}
4678
4679// Matches a string not equal to str, ignoring case.
Austin Schuh889ac432018-10-29 22:57:02 -07004680inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
4681StrCaseNe(const std::wstring& str) {
4682 return MakePolymorphicMatcher(
4683 internal::StrEqualityMatcher<std::wstring>(str, false, false));
Austin Schuh0cbef622015-09-06 17:34:52 -07004684}
4685
Austin Schuh889ac432018-10-29 22:57:02 -07004686// Creates a matcher that matches any ::wstring, std::wstring, or C wide string
Austin Schuh0cbef622015-09-06 17:34:52 -07004687// that contains the given substring.
Austin Schuh889ac432018-10-29 22:57:02 -07004688inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring> > HasSubstr(
4689 const std::wstring& substring) {
4690 return MakePolymorphicMatcher(
4691 internal::HasSubstrMatcher<std::wstring>(substring));
Austin Schuh0cbef622015-09-06 17:34:52 -07004692}
4693
4694// Matches a string that starts with 'prefix' (case-sensitive).
Austin Schuh889ac432018-10-29 22:57:02 -07004695inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring> >
4696StartsWith(const std::wstring& prefix) {
4697 return MakePolymorphicMatcher(
4698 internal::StartsWithMatcher<std::wstring>(prefix));
Austin Schuh0cbef622015-09-06 17:34:52 -07004699}
4700
4701// Matches a string that ends with 'suffix' (case-sensitive).
Austin Schuh889ac432018-10-29 22:57:02 -07004702inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring> > EndsWith(
4703 const std::wstring& suffix) {
4704 return MakePolymorphicMatcher(
4705 internal::EndsWithMatcher<std::wstring>(suffix));
Austin Schuh0cbef622015-09-06 17:34:52 -07004706}
4707
4708#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4709
4710// Creates a polymorphic matcher that matches a 2-tuple where the
4711// first field == the second field.
4712inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4713
4714// Creates a polymorphic matcher that matches a 2-tuple where the
4715// first field >= the second field.
4716inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4717
4718// Creates a polymorphic matcher that matches a 2-tuple where the
4719// first field > the second field.
4720inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4721
4722// Creates a polymorphic matcher that matches a 2-tuple where the
4723// first field <= the second field.
4724inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4725
4726// Creates a polymorphic matcher that matches a 2-tuple where the
4727// first field < the second field.
4728inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4729
4730// Creates a polymorphic matcher that matches a 2-tuple where the
4731// first field != the second field.
4732inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4733
Austin Schuh889ac432018-10-29 22:57:02 -07004734// Creates a polymorphic matcher that matches a 2-tuple where
4735// FloatEq(first field) matches the second field.
4736inline internal::FloatingEq2Matcher<float> FloatEq() {
4737 return internal::FloatingEq2Matcher<float>();
4738}
4739
4740// Creates a polymorphic matcher that matches a 2-tuple where
4741// DoubleEq(first field) matches the second field.
4742inline internal::FloatingEq2Matcher<double> DoubleEq() {
4743 return internal::FloatingEq2Matcher<double>();
4744}
4745
4746// Creates a polymorphic matcher that matches a 2-tuple where
4747// FloatEq(first field) matches the second field with NaN equality.
4748inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() {
4749 return internal::FloatingEq2Matcher<float>(true);
4750}
4751
4752// Creates a polymorphic matcher that matches a 2-tuple where
4753// DoubleEq(first field) matches the second field with NaN equality.
4754inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() {
4755 return internal::FloatingEq2Matcher<double>(true);
4756}
4757
4758// Creates a polymorphic matcher that matches a 2-tuple where
4759// FloatNear(first field, max_abs_error) matches the second field.
4760inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) {
4761 return internal::FloatingEq2Matcher<float>(max_abs_error);
4762}
4763
4764// Creates a polymorphic matcher that matches a 2-tuple where
4765// DoubleNear(first field, max_abs_error) matches the second field.
4766inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) {
4767 return internal::FloatingEq2Matcher<double>(max_abs_error);
4768}
4769
4770// Creates a polymorphic matcher that matches a 2-tuple where
4771// FloatNear(first field, max_abs_error) matches the second field with NaN
4772// equality.
4773inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear(
4774 float max_abs_error) {
4775 return internal::FloatingEq2Matcher<float>(max_abs_error, true);
4776}
4777
4778// Creates a polymorphic matcher that matches a 2-tuple where
4779// DoubleNear(first field, max_abs_error) matches the second field with NaN
4780// equality.
4781inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear(
4782 double max_abs_error) {
4783 return internal::FloatingEq2Matcher<double>(max_abs_error, true);
4784}
4785
Austin Schuh0cbef622015-09-06 17:34:52 -07004786// Creates a matcher that matches any value of type T that m doesn't
4787// match.
4788template <typename InnerMatcher>
4789inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4790 return internal::NotMatcher<InnerMatcher>(m);
4791}
4792
4793// Returns a matcher that matches anything that satisfies the given
4794// predicate. The predicate can be any unary function or functor
4795// whose return type can be implicitly converted to bool.
4796template <typename Predicate>
4797inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4798Truly(Predicate pred) {
4799 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4800}
4801
4802// Returns a matcher that matches the container size. The container must
4803// support both size() and size_type which all STL-like containers provide.
4804// Note that the parameter 'size' can be a value of type size_type as well as
4805// matcher. For instance:
4806// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
4807// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
4808template <typename SizeMatcher>
4809inline internal::SizeIsMatcher<SizeMatcher>
4810SizeIs(const SizeMatcher& size_matcher) {
4811 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4812}
4813
4814// Returns a matcher that matches the distance between the container's begin()
4815// iterator and its end() iterator, i.e. the size of the container. This matcher
4816// can be used instead of SizeIs with containers such as std::forward_list which
4817// do not implement size(). The container must provide const_iterator (with
4818// valid iterator_traits), begin() and end().
4819template <typename DistanceMatcher>
4820inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4821BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4822 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4823}
4824
4825// Returns a matcher that matches an equal container.
4826// This matcher behaves like Eq(), but in the event of mismatch lists the
4827// values that are included in one container but not the other. (Duplicate
4828// values and order differences are not explained.)
4829template <typename Container>
4830inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
4831 GTEST_REMOVE_CONST_(Container)> >
4832 ContainerEq(const Container& rhs) {
4833 // This following line is for working around a bug in MSVC 8.0,
4834 // which causes Container to be a const type sometimes.
4835 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4836 return MakePolymorphicMatcher(
4837 internal::ContainerEqMatcher<RawContainer>(rhs));
4838}
4839
4840// Returns a matcher that matches a container that, when sorted using
4841// the given comparator, matches container_matcher.
4842template <typename Comparator, typename ContainerMatcher>
4843inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4844WhenSortedBy(const Comparator& comparator,
4845 const ContainerMatcher& container_matcher) {
4846 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4847 comparator, container_matcher);
4848}
4849
4850// Returns a matcher that matches a container that, when sorted using
4851// the < operator, matches container_matcher.
4852template <typename ContainerMatcher>
4853inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4854WhenSorted(const ContainerMatcher& container_matcher) {
4855 return
4856 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4857 internal::LessComparator(), container_matcher);
4858}
4859
4860// Matches an STL-style container or a native array that contains the
4861// same number of elements as in rhs, where its i-th element and rhs's
4862// i-th element (as a pair) satisfy the given pair matcher, for all i.
4863// TupleMatcher must be able to be safely cast to Matcher<tuple<const
4864// T1&, const T2&> >, where T1 and T2 are the types of elements in the
4865// LHS container and the RHS container respectively.
4866template <typename TupleMatcher, typename Container>
4867inline internal::PointwiseMatcher<TupleMatcher,
4868 GTEST_REMOVE_CONST_(Container)>
4869Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4870 // This following line is for working around a bug in MSVC 8.0,
4871 // which causes Container to be a const type sometimes (e.g. when
4872 // rhs is a const int[])..
4873 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4874 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4875 tuple_matcher, rhs);
4876}
4877
4878#if GTEST_HAS_STD_INITIALIZER_LIST_
4879
4880// Supports the Pointwise(m, {a, b, c}) syntax.
4881template <typename TupleMatcher, typename T>
4882inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4883 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4884 return Pointwise(tuple_matcher, std::vector<T>(rhs));
4885}
4886
4887#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4888
4889// UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4890// container or a native array that contains the same number of
4891// elements as in rhs, where in some permutation of the container, its
4892// i-th element and rhs's i-th element (as a pair) satisfy the given
4893// pair matcher, for all i. Tuple2Matcher must be able to be safely
4894// cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4895// the types of elements in the LHS container and the RHS container
4896// respectively.
4897//
4898// This is like Pointwise(pair_matcher, rhs), except that the element
4899// order doesn't matter.
4900template <typename Tuple2Matcher, typename RhsContainer>
4901inline internal::UnorderedElementsAreArrayMatcher<
4902 typename internal::BoundSecondMatcher<
4903 Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4904 RhsContainer)>::type::value_type> >
4905UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4906 const RhsContainer& rhs_container) {
4907 // This following line is for working around a bug in MSVC 8.0,
4908 // which causes RhsContainer to be a const type sometimes (e.g. when
4909 // rhs_container is a const int[]).
4910 typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4911
4912 // RhsView allows the same code to handle RhsContainer being a
4913 // STL-style container and it being a native C-style array.
4914 typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4915 typedef typename RhsView::type RhsStlContainer;
4916 typedef typename RhsStlContainer::value_type Second;
4917 const RhsStlContainer& rhs_stl_container =
4918 RhsView::ConstReference(rhs_container);
4919
4920 // Create a matcher for each element in rhs_container.
4921 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4922 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4923 it != rhs_stl_container.end(); ++it) {
4924 matchers.push_back(
4925 internal::MatcherBindSecond(tuple2_matcher, *it));
4926 }
4927
4928 // Delegate the work to UnorderedElementsAreArray().
4929 return UnorderedElementsAreArray(matchers);
4930}
4931
4932#if GTEST_HAS_STD_INITIALIZER_LIST_
4933
4934// Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4935template <typename Tuple2Matcher, typename T>
4936inline internal::UnorderedElementsAreArrayMatcher<
4937 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4938UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4939 std::initializer_list<T> rhs) {
4940 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4941}
4942
4943#endif // GTEST_HAS_STD_INITIALIZER_LIST_
4944
4945// Matches an STL-style container or a native array that contains at
4946// least one element matching the given value or matcher.
4947//
4948// Examples:
4949// ::std::set<int> page_ids;
4950// page_ids.insert(3);
4951// page_ids.insert(1);
4952// EXPECT_THAT(page_ids, Contains(1));
4953// EXPECT_THAT(page_ids, Contains(Gt(2)));
4954// EXPECT_THAT(page_ids, Not(Contains(4)));
4955//
4956// ::std::map<int, size_t> page_lengths;
4957// page_lengths[1] = 100;
4958// EXPECT_THAT(page_lengths,
4959// Contains(::std::pair<const int, size_t>(1, 100)));
4960//
4961// const char* user_ids[] = { "joe", "mike", "tom" };
4962// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4963template <typename M>
4964inline internal::ContainsMatcher<M> Contains(M matcher) {
4965 return internal::ContainsMatcher<M>(matcher);
4966}
4967
Austin Schuh889ac432018-10-29 22:57:02 -07004968// IsSupersetOf(iterator_first, iterator_last)
4969// IsSupersetOf(pointer, count)
4970// IsSupersetOf(array)
4971// IsSupersetOf(container)
4972// IsSupersetOf({e1, e2, ..., en})
4973//
4974// IsSupersetOf() verifies that a surjective partial mapping onto a collection
4975// of matchers exists. In other words, a container matches
4976// IsSupersetOf({e1, ..., en}) if and only if there is a permutation
4977// {y1, ..., yn} of some of the container's elements where y1 matches e1,
4978// ..., and yn matches en. Obviously, the size of the container must be >= n
4979// in order to have a match. Examples:
4980//
4981// - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and
4982// 1 matches Ne(0).
4983// - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches
4984// both Eq(1) and Lt(2). The reason is that different matchers must be used
4985// for elements in different slots of the container.
4986// - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches
4987// Eq(1) and (the second) 1 matches Lt(2).
4988// - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)
4989// Gt(1) and 3 matches (the second) Gt(1).
4990//
4991// The matchers can be specified as an array, a pointer and count, a container,
4992// an initializer list, or an STL iterator range. In each of these cases, the
4993// underlying matchers can be either values or matchers.
4994
4995template <typename Iter>
4996inline internal::UnorderedElementsAreArrayMatcher<
4997 typename ::std::iterator_traits<Iter>::value_type>
4998IsSupersetOf(Iter first, Iter last) {
4999 typedef typename ::std::iterator_traits<Iter>::value_type T;
5000 return internal::UnorderedElementsAreArrayMatcher<T>(
5001 internal::UnorderedMatcherRequire::Superset, first, last);
5002}
5003
5004template <typename T>
5005inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
5006 const T* pointer, size_t count) {
5007 return IsSupersetOf(pointer, pointer + count);
5008}
5009
5010template <typename T, size_t N>
5011inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
5012 const T (&array)[N]) {
5013 return IsSupersetOf(array, N);
5014}
5015
5016template <typename Container>
5017inline internal::UnorderedElementsAreArrayMatcher<
5018 typename Container::value_type>
5019IsSupersetOf(const Container& container) {
5020 return IsSupersetOf(container.begin(), container.end());
5021}
5022
5023#if GTEST_HAS_STD_INITIALIZER_LIST_
5024template <typename T>
5025inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
5026 ::std::initializer_list<T> xs) {
5027 return IsSupersetOf(xs.begin(), xs.end());
5028}
5029#endif
5030
5031// IsSubsetOf(iterator_first, iterator_last)
5032// IsSubsetOf(pointer, count)
5033// IsSubsetOf(array)
5034// IsSubsetOf(container)
5035// IsSubsetOf({e1, e2, ..., en})
5036//
5037// IsSubsetOf() verifies that an injective mapping onto a collection of matchers
5038// exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and
5039// only if there is a subset of matchers {m1, ..., mk} which would match the
5040// container using UnorderedElementsAre. Obviously, the size of the container
5041// must be <= n in order to have a match. Examples:
5042//
5043// - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).
5044// - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1
5045// matches Lt(0).
5046// - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both
5047// match Gt(0). The reason is that different matchers must be used for
5048// elements in different slots of the container.
5049//
5050// The matchers can be specified as an array, a pointer and count, a container,
5051// an initializer list, or an STL iterator range. In each of these cases, the
5052// underlying matchers can be either values or matchers.
5053
5054template <typename Iter>
5055inline internal::UnorderedElementsAreArrayMatcher<
5056 typename ::std::iterator_traits<Iter>::value_type>
5057IsSubsetOf(Iter first, Iter last) {
5058 typedef typename ::std::iterator_traits<Iter>::value_type T;
5059 return internal::UnorderedElementsAreArrayMatcher<T>(
5060 internal::UnorderedMatcherRequire::Subset, first, last);
5061}
5062
5063template <typename T>
5064inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
5065 const T* pointer, size_t count) {
5066 return IsSubsetOf(pointer, pointer + count);
5067}
5068
5069template <typename T, size_t N>
5070inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
5071 const T (&array)[N]) {
5072 return IsSubsetOf(array, N);
5073}
5074
5075template <typename Container>
5076inline internal::UnorderedElementsAreArrayMatcher<
5077 typename Container::value_type>
5078IsSubsetOf(const Container& container) {
5079 return IsSubsetOf(container.begin(), container.end());
5080}
5081
5082#if GTEST_HAS_STD_INITIALIZER_LIST_
5083template <typename T>
5084inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
5085 ::std::initializer_list<T> xs) {
5086 return IsSubsetOf(xs.begin(), xs.end());
5087}
5088#endif
5089
Austin Schuh0cbef622015-09-06 17:34:52 -07005090// Matches an STL-style container or a native array that contains only
5091// elements matching the given value or matcher.
5092//
5093// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
5094// the messages are different.
5095//
5096// Examples:
5097// ::std::set<int> page_ids;
5098// // Each(m) matches an empty container, regardless of what m is.
5099// EXPECT_THAT(page_ids, Each(Eq(1)));
5100// EXPECT_THAT(page_ids, Each(Eq(77)));
5101//
5102// page_ids.insert(3);
5103// EXPECT_THAT(page_ids, Each(Gt(0)));
5104// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
5105// page_ids.insert(1);
5106// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
5107//
5108// ::std::map<int, size_t> page_lengths;
5109// page_lengths[1] = 100;
5110// page_lengths[2] = 200;
5111// page_lengths[3] = 300;
5112// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
5113// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
5114//
5115// const char* user_ids[] = { "joe", "mike", "tom" };
5116// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
5117template <typename M>
5118inline internal::EachMatcher<M> Each(M matcher) {
5119 return internal::EachMatcher<M>(matcher);
5120}
5121
5122// Key(inner_matcher) matches an std::pair whose 'first' field matches
5123// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
5124// std::map that contains at least one element whose key is >= 5.
5125template <typename M>
5126inline internal::KeyMatcher<M> Key(M inner_matcher) {
5127 return internal::KeyMatcher<M>(inner_matcher);
5128}
5129
5130// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
5131// matches first_matcher and whose 'second' field matches second_matcher. For
5132// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
5133// to match a std::map<int, string> that contains exactly one element whose key
5134// is >= 5 and whose value equals "foo".
5135template <typename FirstMatcher, typename SecondMatcher>
5136inline internal::PairMatcher<FirstMatcher, SecondMatcher>
5137Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
5138 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
5139 first_matcher, second_matcher);
5140}
5141
5142// Returns a predicate that is satisfied by anything that matches the
5143// given matcher.
5144template <typename M>
5145inline internal::MatcherAsPredicate<M> Matches(M matcher) {
5146 return internal::MatcherAsPredicate<M>(matcher);
5147}
5148
5149// Returns true iff the value matches the matcher.
5150template <typename T, typename M>
5151inline bool Value(const T& value, M matcher) {
5152 return testing::Matches(matcher)(value);
5153}
5154
5155// Matches the value against the given matcher and explains the match
5156// result to listener.
5157template <typename T, typename M>
5158inline bool ExplainMatchResult(
5159 M matcher, const T& value, MatchResultListener* listener) {
5160 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
5161}
5162
Austin Schuh889ac432018-10-29 22:57:02 -07005163// Returns a string representation of the given matcher. Useful for description
5164// strings of matchers defined using MATCHER_P* macros that accept matchers as
5165// their arguments. For example:
5166//
5167// MATCHER_P(XAndYThat, matcher,
5168// "X that " + DescribeMatcher<int>(matcher, negation) +
5169// " and Y that " + DescribeMatcher<double>(matcher, negation)) {
5170// return ExplainMatchResult(matcher, arg.x(), result_listener) &&
5171// ExplainMatchResult(matcher, arg.y(), result_listener);
5172// }
5173template <typename T, typename M>
5174std::string DescribeMatcher(const M& matcher, bool negation = false) {
5175 ::std::stringstream ss;
5176 Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher);
5177 if (negation) {
5178 monomorphic_matcher.DescribeNegationTo(&ss);
5179 } else {
5180 monomorphic_matcher.DescribeTo(&ss);
5181 }
5182 return ss.str();
5183}
5184
Austin Schuh0cbef622015-09-06 17:34:52 -07005185#if GTEST_LANG_CXX11
5186// Define variadic matcher versions. They are overloaded in
5187// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
5188template <typename... Args>
Austin Schuh889ac432018-10-29 22:57:02 -07005189internal::AllOfMatcher<typename std::decay<const Args&>::type...> AllOf(
5190 const Args&... matchers) {
5191 return internal::AllOfMatcher<typename std::decay<const Args&>::type...>(
5192 matchers...);
Austin Schuh0cbef622015-09-06 17:34:52 -07005193}
5194
5195template <typename... Args>
Austin Schuh889ac432018-10-29 22:57:02 -07005196internal::AnyOfMatcher<typename std::decay<const Args&>::type...> AnyOf(
5197 const Args&... matchers) {
5198 return internal::AnyOfMatcher<typename std::decay<const Args&>::type...>(
5199 matchers...);
5200}
5201
5202template <typename... Args>
5203internal::ElementsAreMatcher<tuple<typename std::decay<const Args&>::type...>>
5204ElementsAre(const Args&... matchers) {
5205 return internal::ElementsAreMatcher<
5206 tuple<typename std::decay<const Args&>::type...>>(
5207 make_tuple(matchers...));
5208}
5209
5210template <typename... Args>
5211internal::UnorderedElementsAreMatcher<
5212 tuple<typename std::decay<const Args&>::type...>>
5213UnorderedElementsAre(const Args&... matchers) {
5214 return internal::UnorderedElementsAreMatcher<
5215 tuple<typename std::decay<const Args&>::type...>>(
5216 make_tuple(matchers...));
Austin Schuh0cbef622015-09-06 17:34:52 -07005217}
5218
5219#endif // GTEST_LANG_CXX11
5220
5221// AllArgs(m) is a synonym of m. This is useful in
5222//
5223// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
5224//
5225// which is easier to read than
5226//
5227// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
5228template <typename InnerMatcher>
5229inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
5230
Austin Schuh889ac432018-10-29 22:57:02 -07005231// Returns a matcher that matches the value of an optional<> type variable.
5232// The matcher implementation only uses '!arg' and requires that the optional<>
5233// type has a 'value_type' member type and that '*arg' is of type 'value_type'
5234// and is printable using 'PrintToString'. It is compatible with
5235// std::optional/std::experimental::optional.
5236// Note that to compare an optional type variable against nullopt you should
5237// use Eq(nullopt) and not Optional(Eq(nullopt)). The latter implies that the
5238// optional value contains an optional itself.
5239template <typename ValueMatcher>
5240inline internal::OptionalMatcher<ValueMatcher> Optional(
5241 const ValueMatcher& value_matcher) {
5242 return internal::OptionalMatcher<ValueMatcher>(value_matcher);
5243}
5244
5245// Returns a matcher that matches the value of a absl::any type variable.
5246template <typename T>
5247PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T> > AnyWith(
5248 const Matcher<const T&>& matcher) {
5249 return MakePolymorphicMatcher(
5250 internal::any_cast_matcher::AnyCastMatcher<T>(matcher));
5251}
5252
5253// Returns a matcher that matches the value of a variant<> type variable.
5254// The matcher implementation uses ADL to find the holds_alternative and get
5255// functions.
5256// It is compatible with std::variant.
5257template <typename T>
5258PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
5259 const Matcher<const T&>& matcher) {
5260 return MakePolymorphicMatcher(
5261 internal::variant_matcher::VariantMatcher<T>(matcher));
5262}
5263
Austin Schuh0cbef622015-09-06 17:34:52 -07005264// These macros allow using matchers to check values in Google Test
5265// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
5266// succeed iff the value matches the matcher. If the assertion fails,
5267// the value and the description of the matcher will be printed.
5268#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
5269 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
5270#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
5271 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
5272
5273} // namespace testing
5274
Austin Schuh889ac432018-10-29 22:57:02 -07005275GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
5276
Austin Schuh0cbef622015-09-06 17:34:52 -07005277// Include any custom callback matchers added by the local installation.
5278// We must include this header at the end to make sure it can use the
5279// declarations from this file.
5280#include "gmock/internal/custom/gmock-matchers.h"
Austin Schuh889ac432018-10-29 22:57:02 -07005281
Austin Schuh0cbef622015-09-06 17:34:52 -07005282#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_