2 $$ This is a Pump source file. Please use Pump to convert
3 $$ it to gmock-generated-matchers.h.
5 $var n = 10 $$ The maximum arity we support.
6 $$ }} This line fixes auto-indentation of the following code in Emacs.
7 // Copyright 2008, Google Inc.
8 // All rights reserved.
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions are
14 // * Redistributions of source code must retain the above copyright
15 // notice, this list of conditions and the following disclaimer.
16 // * Redistributions in binary form must reproduce the above
17 // copyright notice, this list of conditions and the following disclaimer
18 // in the documentation and/or other materials provided with the
20 // * Neither the name of Google Inc. nor the names of its
21 // contributors may be used to endorse or promote products derived from
22 // this software without specific prior written permission.
24 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
27 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
28 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
30 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 // Google Mock - a framework for writing C++ mock classes.
38 // This file implements some commonly used variadic matchers.
40 // GOOGLETEST_CM0002 DO NOT DELETE
42 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
43 #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
49 #include "gmock/gmock-matchers.h"
56 // The type of the i-th (0-based) field of Tuple.
57 #define GMOCK_FIELD_TYPE_(Tuple, i) \
58 typename ::testing::tuple_element<i, Tuple>::type
60 // TupleFields<Tuple, k0, ..., kn> is for selecting fields from a
61 // tuple of type Tuple. It has two members:
63 // type: a tuple type whose i-th field is the ki-th field of Tuple.
64 // GetSelectedFields(t): returns fields k0, ..., and kn of t as a tuple.
66 // For example, in class TupleFields<tuple<bool, char, int>, 2, 0>, we have:
68 // type is tuple<int, bool>, and
69 // GetSelectedFields(make_tuple(true, 'a', 42)) is (42, true).
71 template <class Tuple$for i [[, int k$i = -1]]>
74 // This generic version is used when there are $n selectors.
75 template <class Tuple$for i [[, int k$i]]>
78 typedef ::testing::tuple<$for i, [[GMOCK_FIELD_TYPE_(Tuple, k$i)]]> type;
79 static type GetSelectedFields(const Tuple& t) {
80 return type($for i, [[get<k$i>(t)]]);
84 // The following specialization is used for 0 ~ $(n-1) selectors.
91 template <class Tuple$for j [[, int k$j]]>
92 class TupleFields<Tuple, $for k, [[$if k < i [[k$k]] $else [[-1]]]]> {
94 typedef ::testing::tuple<$for j, [[GMOCK_FIELD_TYPE_(Tuple, k$j)]]> type;
95 static type GetSelectedFields(const Tuple& $if i==0 [[/* t */]] $else [[t]]) {
96 return type($for j, [[get<k$j>(t)]]);
102 #undef GMOCK_FIELD_TYPE_
104 // Implements the Args() matcher.
106 $var ks = [[$for i, [[k$i]]]]
107 template <class ArgsTuple$for i [[, int k$i = -1]]>
108 class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> {
110 // ArgsTuple may have top-level const or reference modifiers.
111 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(ArgsTuple) RawArgsTuple;
112 typedef typename internal::TupleFields<RawArgsTuple, $ks>::type SelectedArgs;
113 typedef Matcher<const SelectedArgs&> MonomorphicInnerMatcher;
115 template <typename InnerMatcher>
116 explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher)
117 : inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {}
119 virtual bool MatchAndExplain(ArgsTuple args,
120 MatchResultListener* listener) const {
121 const SelectedArgs& selected_args = GetSelectedArgs(args);
122 if (!listener->IsInterested())
123 return inner_matcher_.Matches(selected_args);
125 PrintIndices(listener->stream());
126 *listener << "are " << PrintToString(selected_args);
128 StringMatchResultListener inner_listener;
129 const bool match = inner_matcher_.MatchAndExplain(selected_args,
131 PrintIfNotEmpty(inner_listener.str(), listener->stream());
135 virtual void DescribeTo(::std::ostream* os) const {
136 *os << "are a tuple ";
138 inner_matcher_.DescribeTo(os);
141 virtual void DescribeNegationTo(::std::ostream* os) const {
142 *os << "are a tuple ";
144 inner_matcher_.DescribeNegationTo(os);
148 static SelectedArgs GetSelectedArgs(ArgsTuple args) {
149 return TupleFields<RawArgsTuple, $ks>::GetSelectedFields(args);
152 // Prints the indices of the selected fields.
153 static void PrintIndices(::std::ostream* os) {
154 *os << "whose fields (";
155 const int indices[$n] = { $ks };
156 for (int i = 0; i < $n; i++) {
163 *os << "#" << indices[i];
168 const MonomorphicInnerMatcher inner_matcher_;
170 GTEST_DISALLOW_ASSIGN_(ArgsMatcherImpl);
173 template <class InnerMatcher$for i [[, int k$i = -1]]>
176 explicit ArgsMatcher(const InnerMatcher& inner_matcher)
177 : inner_matcher_(inner_matcher) {}
179 template <typename ArgsTuple>
180 operator Matcher<ArgsTuple>() const {
181 return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, $ks>(inner_matcher_));
185 const InnerMatcher inner_matcher_;
187 GTEST_DISALLOW_ASSIGN_(ArgsMatcher);
190 // A set of metafunctions for computing the result type of AllOf.
191 // AllOf(m1, ..., mN) returns
192 // AllOfResultN<decltype(m1), ..., decltype(mN)>::type.
194 // Although AllOf isn't defined for one argument, AllOfResult1 is defined
195 // to simplify the implementation.
196 template <typename M1>
197 struct AllOfResult1 {
210 template <typename M1$for j [[, typename M$j]]>
211 struct AllOfResult$i {
212 typedef BothOfMatcher<
213 typename AllOfResult$m<$for k, [[M$k]]>::type,
214 typename AllOfResult$(i-m)<$for t, [[M$t]]>::type
220 // A set of metafunctions for computing the result type of AnyOf.
221 // AnyOf(m1, ..., mN) returns
222 // AnyOfResultN<decltype(m1), ..., decltype(mN)>::type.
224 // Although AnyOf isn't defined for one argument, AnyOfResult1 is defined
225 // to simplify the implementation.
226 template <typename M1>
227 struct AnyOfResult1 {
240 template <typename M1$for j [[, typename M$j]]>
241 struct AnyOfResult$i {
242 typedef EitherOfMatcher<
243 typename AnyOfResult$m<$for k, [[M$k]]>::type,
244 typename AnyOfResult$(i-m)<$for t, [[M$t]]>::type
250 } // namespace internal
252 // Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected
253 // fields of it matches a_matcher. C++ doesn't support default
254 // arguments for function templates, so we have to overload it.
259 template <$for j [[int k$j, ]]typename InnerMatcher>
260 inline internal::ArgsMatcher<InnerMatcher$for j [[, k$j]]>
261 Args(const InnerMatcher& matcher) {
262 return internal::ArgsMatcher<InnerMatcher$for j [[, k$j]]>(matcher);
267 // ElementsAre(e_1, e_2, ... e_n) matches an STL-style container with
268 // n elements, where the i-th element in the container must
269 // match the i-th argument in the list. Each argument of
270 // ElementsAre() can be either a value or a matcher. We support up to
273 // The use of DecayArray in the implementation allows ElementsAre()
274 // to accept string literals, whose type is const char[N], but we
275 // want to treat them as const char*.
277 // NOTE: Since ElementsAre() cares about the order of the elements, it
278 // must not be used with containers whose elements's order is
279 // undefined (e.g. hash_map).
288 template <$for j, [[typename T$j]]>
291 inline internal::ElementsAreMatcher<
295 typename internal::DecayArray<T$j[[]]>::type]]> >
296 ElementsAre($for j, [[const T$j& e$j]]) {
297 typedef ::testing::tuple<
300 typename internal::DecayArray<T$j[[]]>::type]]> Args;
301 return internal::ElementsAreMatcher<Args>(Args($for j, [[e$j]]));
306 // UnorderedElementsAre(e_1, e_2, ..., e_n) is an ElementsAre extension
307 // that matches n elements in any order. We support up to n=$n arguments.
309 // If you have >$n elements, consider UnorderedElementsAreArray() or
310 // UnorderedPointwise() instead.
319 template <$for j, [[typename T$j]]>
322 inline internal::UnorderedElementsAreMatcher<
326 typename internal::DecayArray<T$j[[]]>::type]]> >
327 UnorderedElementsAre($for j, [[const T$j& e$j]]) {
328 typedef ::testing::tuple<
331 typename internal::DecayArray<T$j[[]]>::type]]> Args;
332 return internal::UnorderedElementsAreMatcher<Args>(Args($for j, [[e$j]]));
337 // AllOf(m1, m2, ..., mk) matches any value that matches all of the given
338 // sub-matchers. AllOf is called fully qualified to prevent ADL from firing.
347 template <$for j, [[typename M$j]]>
348 inline typename internal::AllOfResult$i<$for j, [[M$j]]>::type
349 AllOf($for j, [[M$j m$j]]) {
350 return typename internal::AllOfResult$i<$for j, [[M$j]]>::type(
351 $if m == 1 [[m1]] $else [[::testing::AllOf($for k, [[m$k]])]],
352 $if m+1 == i [[m$i]] $else [[::testing::AllOf($for t, [[m$t]])]]);
357 // AnyOf(m1, m2, ..., mk) matches any value that matches any of the given
358 // sub-matchers. AnyOf is called fully qualified to prevent ADL from firing.
367 template <$for j, [[typename M$j]]>
368 inline typename internal::AnyOfResult$i<$for j, [[M$j]]>::type
369 AnyOf($for j, [[M$j m$j]]) {
370 return typename internal::AnyOfResult$i<$for j, [[M$j]]>::type(
371 $if m == 1 [[m1]] $else [[::testing::AnyOf($for k, [[m$k]])]],
372 $if m+1 == i [[m$i]] $else [[::testing::AnyOf($for t, [[m$t]])]]);
377 } // namespace testing
378 $$ } // This Pump meta comment fixes auto-indentation in Emacs. It will not
379 $$ // show up in the generated code.
382 // The MATCHER* family of macros can be used in a namespace scope to
383 // define custom matchers easily.
390 // MATCHER(name, description_string) { statements; }
392 // defines a matcher with the given name that executes the statements,
393 // which must return a bool to indicate if the match succeeds. Inside
394 // the statements, you can refer to the value being matched by 'arg',
395 // and refer to its type by 'arg_type'.
397 // The description string documents what the matcher does, and is used
398 // to generate the failure message when the match fails. Since a
399 // MATCHER() is usually defined in a header file shared by multiple
400 // C++ source files, we require the description to be a C-string
401 // literal to avoid possible side effects. It can be empty, in which
402 // case we'll use the sequence of words in the matcher name as the
407 // MATCHER(IsEven, "") { return (arg % 2) == 0; }
409 // allows you to write
411 // // Expects mock_foo.Bar(n) to be called where n is even.
412 // EXPECT_CALL(mock_foo, Bar(IsEven()));
416 // // Verifies that the value of some_expression is even.
417 // EXPECT_THAT(some_expression, IsEven());
419 // If the above assertion fails, it will print something like:
421 // Value of: some_expression
425 // where the description "is even" is automatically calculated from the
426 // matcher name IsEven.
431 // Note that the type of the value being matched (arg_type) is
432 // determined by the context in which you use the matcher and is
433 // supplied to you by the compiler, so you don't need to worry about
434 // declaring it (nor can you). This allows the matcher to be
435 // polymorphic. For example, IsEven() can be used to match any type
436 // where the value of "(arg % 2) == 0" can be implicitly converted to
437 // a bool. In the "Bar(IsEven())" example above, if method Bar()
438 // takes an int, 'arg_type' will be int; if it takes an unsigned long,
439 // 'arg_type' will be unsigned long; and so on.
441 // Parameterizing Matchers
442 // =======================
444 // Sometimes you'll want to parameterize the matcher. For that you
445 // can use another macro:
447 // MATCHER_P(name, param_name, description_string) { statements; }
451 // MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
453 // will allow you to write:
455 // EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
457 // which may lead to this message (assuming n is 10):
459 // Value of: Blah("a")
460 // Expected: has absolute value 10
463 // Note that both the matcher description and its parameter are
464 // printed, making the message human-friendly.
466 // In the matcher definition body, you can write 'foo_type' to
467 // reference the type of a parameter named 'foo'. For example, in the
468 // body of MATCHER_P(HasAbsoluteValue, value) above, you can write
469 // 'value_type' to refer to the type of 'value'.
471 // We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to
472 // support multi-parameter matchers.
474 // Describing Parameterized Matchers
475 // =================================
477 // The last argument to MATCHER*() is a string-typed expression. The
478 // expression can reference all of the matcher's parameters and a
479 // special bool-typed variable named 'negation'. When 'negation' is
480 // false, the expression should evaluate to the matcher's description;
481 // otherwise it should evaluate to the description of the negation of
482 // the matcher. For example,
484 // using testing::PrintToString;
486 // MATCHER_P2(InClosedRange, low, hi,
487 // std::string(negation ? "is not" : "is") + " in range [" +
488 // PrintToString(low) + ", " + PrintToString(hi) + "]") {
489 // return low <= arg && arg <= hi;
492 // EXPECT_THAT(3, InClosedRange(4, 6));
493 // EXPECT_THAT(3, Not(InClosedRange(2, 4)));
495 // would generate two failures that contain the text:
497 // Expected: is in range [4, 6]
499 // Expected: is not in range [2, 4]
501 // If you specify "" as the description, the failure message will
502 // contain the sequence of words in the matcher name followed by the
503 // parameter values printed as a tuple. For example,
505 // MATCHER_P2(InClosedRange, low, hi, "") { ... }
507 // EXPECT_THAT(3, InClosedRange(4, 6));
508 // EXPECT_THAT(3, Not(InClosedRange(2, 4)));
510 // would generate two failures that contain the text:
512 // Expected: in closed range (4, 6)
514 // Expected: not (in closed range (2, 4))
516 // Types of Matcher Parameters
517 // ===========================
519 // For the purpose of typing, you can view
521 // MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
525 // template <typename p1_type, ..., typename pk_type>
526 // FooMatcherPk<p1_type, ..., pk_type>
527 // Foo(p1_type p1, ..., pk_type pk) { ... }
529 // When you write Foo(v1, ..., vk), the compiler infers the types of
530 // the parameters v1, ..., and vk for you. If you are not happy with
531 // the result of the type inference, you can specify the types by
532 // explicitly instantiating the template, as in Foo<long, bool>(5,
533 // false). As said earlier, you don't get to (or need to) specify
534 // 'arg_type' as that's determined by the context in which the matcher
535 // is used. You can assign the result of expression Foo(p1, ..., pk)
536 // to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This
537 // can be useful when composing matchers.
539 // While you can instantiate a matcher template with reference types,
540 // passing the parameters by pointer usually makes your code more
541 // readable. If, however, you still want to pass a parameter by
542 // reference, be aware that in the failure message generated by the
543 // matcher you will see the value of the referenced object but not its
546 // Explaining Match Results
547 // ========================
549 // Sometimes the matcher description alone isn't enough to explain why
550 // the match has failed or succeeded. For example, when expecting a
551 // long string, it can be very helpful to also print the diff between
552 // the expected string and the actual one. To achieve that, you can
553 // optionally stream additional information to a special variable
554 // named result_listener, whose type is a pointer to class
555 // MatchResultListener:
557 // MATCHER_P(EqualsLongString, str, "") {
558 // if (arg == str) return true;
560 // *result_listener << "the difference: "
561 /// << DiffStrings(str, arg);
565 // Overloading Matchers
566 // ====================
568 // You can overload matchers with different numbers of parameters:
570 // MATCHER_P(Blah, a, description_string1) { ... }
571 // MATCHER_P2(Blah, a, b, description_string2) { ... }
576 // When defining a new matcher, you should also consider implementing
577 // MatcherInterface or using MakePolymorphicMatcher(). These
578 // approaches require more work than the MATCHER* macros, but also
579 // give you more control on the types of the value being matched and
580 // the matcher parameters, which may leads to better compiler error
581 // messages when the matcher is used wrong. They also allow
582 // overloading matchers based on parameter types (as opposed to just
583 // based on the number of parameters).
585 // MATCHER*() can only be used in a namespace scope. The reason is
586 // that C++ doesn't yet allow function-local types to be used to
587 // instantiate templates. The up-coming C++0x standard will fix this.
588 // Once that's done, we'll consider supporting using MATCHER*() inside
594 // To learn more about using these macros, please search for 'MATCHER'
596 // https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md
602 $var macro_name = [[$if i==0 [[MATCHER]] $elif i==1 [[MATCHER_P]]
603 $else [[MATCHER_P$i]]]]
604 $var class_name = [[name##Matcher[[$if i==0 [[]] $elif i==1 [[P]]
607 $var template = [[$if i==0 [[]] $else [[
609 template <$for j, [[typename p$j##_type]]>\
611 $var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
612 $var impl_ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
613 $var impl_inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::testing::internal::move(gmock_p$j))]]]]]]
614 $var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::testing::internal::move(gmock_p$j))]]]]]]
615 $var params = [[$for j, [[p$j]]]]
616 $var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]]
617 $var param_types_and_names = [[$for j, [[p$j##_type p$j]]]]
618 $var param_field_decls = [[$for j
621 p$j##_type const p$j;\
623 $var param_field_decls2 = [[$for j
626 p$j##_type const p$j;\
629 #define $macro_name(name$for j [[, p$j]], description)\$template
632 template <typename arg_type>\
633 class gmock_Impl : public ::testing::MatcherInterface<\
634 GTEST_REFERENCE_TO_CONST_(arg_type)> {\
636 [[$if i==1 [[explicit ]]]]gmock_Impl($impl_ctor_param_list)\
638 virtual bool MatchAndExplain(\
639 GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
640 ::testing::MatchResultListener* result_listener) const;\
641 virtual void DescribeTo(::std::ostream* gmock_os) const {\
642 *gmock_os << FormatDescription(false);\
644 virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
645 *gmock_os << FormatDescription(true);\
648 ::std::string FormatDescription(bool negation) const {\
649 ::std::string gmock_description = (description);\
650 if (!gmock_description.empty())\
651 return gmock_description;\
652 return ::testing::internal::FormatMatcherDescription(\
654 ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
655 ::testing::tuple<$for j, [[p$j##_type]]>($for j, [[p$j]])));\
658 template <typename arg_type>\
659 operator ::testing::Matcher<arg_type>() const {\
660 return ::testing::Matcher<arg_type>(\
661 new gmock_Impl<arg_type>($params));\
663 [[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {\
664 }\$param_field_decls2
667 inline $class_name$param_types name($param_types_and_names) {\
668 return $class_name$param_types($params);\
670 template <typename arg_type>\
671 bool $class_name$param_types::gmock_Impl<arg_type>::MatchAndExplain(\
672 GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
673 ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
678 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_