2 $$ This is a Pump source file. Please use Pump to convert it to
3 $$ gmock-generated-variadic-actions.h.
5 $var n = 10 $$ The maximum arity we support.
6 // Copyright 2008, Google Inc.
7 // All rights reserved.
9 // Redistribution and use in source and binary forms, with or without
10 // modification, are permitted provided that the following conditions are
13 // * Redistributions of source code must retain the above copyright
14 // notice, this list of conditions and the following disclaimer.
15 // * Redistributions in binary form must reproduce the above
16 // copyright notice, this list of conditions and the following disclaimer
17 // in the documentation and/or other materials provided with the
19 // * Neither the name of Google Inc. nor the names of its
20 // contributors may be used to endorse or promote products derived from
21 // this software without specific prior written permission.
23 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 // Google Mock - a framework for writing C++ mock classes.
37 // This file implements some commonly used variadic matchers.
39 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
40 #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
45 #include <gmock/gmock-matchers.h>
46 #include <gmock/gmock-printers.h>
51 // Implements ElementsAre() and ElementsAreArray().
52 template <typename Container>
53 class ElementsAreMatcherImpl : public MatcherInterface<Container> {
55 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
56 typedef typename RawContainer::value_type Element;
58 // Constructs the matcher from a sequence of element values or
60 template <typename InputIter>
61 ElementsAreMatcherImpl(InputIter first, size_t count) {
62 matchers_.reserve(count);
64 for (size_t i = 0; i != count; ++i, ++it) {
65 matchers_.push_back(MatcherCast<const Element&>(*it));
69 // Returns true iff 'container' matches.
70 virtual bool Matches(Container container) const {
71 if (container.size() != count())
74 typename RawContainer::const_iterator container_iter = container.begin();
75 for (size_t i = 0; i != count(); ++container_iter, ++i) {
76 if (!matchers_[i].Matches(*container_iter))
83 // Describes what this matcher does.
84 virtual void DescribeTo(::std::ostream* os) const {
87 } else if (count() == 1) {
88 *os << "has 1 element that ";
89 matchers_[0].DescribeTo(os);
91 *os << "has " << Elements(count()) << " where\n";
92 for (size_t i = 0; i != count(); ++i) {
93 *os << "element " << i << " ";
94 matchers_[i].DescribeTo(os);
95 if (i + 1 < count()) {
102 // Describes what the negation of this matcher does.
103 virtual void DescribeNegationTo(::std::ostream* os) const {
105 *os << "is not empty";
109 *os << "does not have " << Elements(count()) << ", or\n";
110 for (size_t i = 0; i != count(); ++i) {
111 *os << "element " << i << " ";
112 matchers_[i].DescribeNegationTo(os);
113 if (i + 1 < count()) {
119 // Explains why 'container' matches, or doesn't match, this matcher.
120 virtual void ExplainMatchResultTo(Container container,
121 ::std::ostream* os) const {
122 if (Matches(container)) {
123 // We need to explain why *each* element matches (the obvious
124 // ones can be skipped).
126 bool reason_printed = false;
127 typename RawContainer::const_iterator container_iter = container.begin();
128 for (size_t i = 0; i != count(); ++container_iter, ++i) {
129 ::std::stringstream ss;
130 matchers_[i].ExplainMatchResultTo(*container_iter, &ss);
132 const string s = ss.str();
134 if (reason_printed) {
137 *os << "element " << i << " " << s;
138 reason_printed = true;
142 // We need to explain why the container doesn't match.
143 const size_t actual_count = container.size();
144 if (actual_count != count()) {
145 // The element count doesn't match. If the container is
146 // empty, there's no need to explain anything as Google Mock
147 // already prints the empty container. Otherwise we just need
148 // to show how many elements there actually are.
149 if (actual_count != 0) {
150 *os << "has " << Elements(actual_count);
155 // The container has the right size but at least one element
156 // doesn't match expectation. We need to find this element and
157 // explain why it doesn't match.
158 typename RawContainer::const_iterator container_iter = container.begin();
159 for (size_t i = 0; i != count(); ++container_iter, ++i) {
160 if (matchers_[i].Matches(*container_iter)) {
164 *os << "element " << i << " doesn't match";
166 ::std::stringstream ss;
167 matchers_[i].ExplainMatchResultTo(*container_iter, &ss);
168 const string s = ss.str();
170 *os << " (" << s << ")";
178 static Message Elements(size_t count) {
179 return Message() << count << (count == 1 ? " element" : " elements");
182 size_t count() const { return matchers_.size(); }
183 std::vector<Matcher<const Element&> > matchers_;
186 // Implements ElementsAre() of 0-10 arguments.
188 class ElementsAreMatcher0 {
190 ElementsAreMatcher0() {}
192 template <typename Container>
193 operator Matcher<Container>() const {
194 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
196 typedef typename RawContainer::value_type Element;
198 const Matcher<const Element&>* const matchers = NULL;
199 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
207 template <$for j, [[typename T$j]]>
208 class ElementsAreMatcher$i {
210 $if i==1 [[explicit ]]ElementsAreMatcher$i($for j, [[const T$j& e$j]])$if i > 0 [[ : ]]
211 $for j, [[e$j[[]]_(e$j)]] {}
213 template <typename Container>
214 operator Matcher<Container>() const {
215 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
217 typedef typename RawContainer::value_type Element;
219 const Matcher<const Element&> matchers[] = {
222 MatcherCast<const Element&>(e$j[[]]_),
227 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, $i));
240 // Implements ElementsAreArray().
241 template <typename T>
242 class ElementsAreArrayMatcher {
244 ElementsAreArrayMatcher(const T* first, size_t count) :
245 first_(first), count_(count) {}
247 template <typename Container>
248 operator Matcher<Container>() const {
249 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
251 typedef typename RawContainer::value_type Element;
253 return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
257 const T* const first_;
261 } // namespace internal
263 // ElementsAre(e0, e1, ..., e_n) matches an STL-style container with
264 // (n + 1) elements, where the i-th element in the container must
265 // match the i-th argument in the list. Each argument of
266 // ElementsAre() can be either a value or a matcher. We support up to
269 // NOTE: Since ElementsAre() cares about the order of the elements, it
270 // must not be used with containers whose elements's order is
271 // undefined (e.g. hash_map).
273 inline internal::ElementsAreMatcher0 ElementsAre() {
274 return internal::ElementsAreMatcher0();
280 template <$for j, [[typename T$j]]>
281 inline internal::ElementsAreMatcher$i<$for j, [[T$j]]> ElementsAre($for j, [[const T$j& e$j]]) {
282 return internal::ElementsAreMatcher$i<$for j, [[T$j]]>($for j, [[e$j]]);
287 // ElementsAreArray(array) and ElementAreArray(array, count) are like
288 // ElementsAre(), except that they take an array of values or
289 // matchers. The former form infers the size of 'array', which must
290 // be a static C-style array. In the latter form, 'array' can either
291 // be a static array or a pointer to a dynamically created array.
293 template <typename T>
294 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
295 const T* first, size_t count) {
296 return internal::ElementsAreArrayMatcher<T>(first, count);
299 template <typename T, size_t N>
300 inline internal::ElementsAreArrayMatcher<T>
301 ElementsAreArray(const T (&array)[N]) {
302 return internal::ElementsAreArrayMatcher<T>(array, N);
305 } // namespace testing
306 $$ } // This Pump meta comment fixes auto-indentation in Emacs. It will not
307 $$ // show up in the generated code.
310 // The MATCHER* family of macros can be used in a namespace scope to
311 // define custom matchers easily. The syntax:
313 // MATCHER(name, description_string) { statements; }
315 // will define a matcher with the given name that executes the
316 // statements, which must return a bool to indicate if the match
317 // succeeds. Inside the statements, you can refer to the value being
318 // matched by 'arg', and refer to its type by 'arg_type'.
320 // The description string documents what the matcher does, and is used
321 // to generate the failure message when the match fails. Since a
322 // MATCHER() is usually defined in a header file shared by multiple
323 // C++ source files, we require the description to be a C-string
324 // literal to avoid possible side effects. It can be empty, in which
325 // case we'll use the sequence of words in the matcher name as the
330 // MATCHER(IsEven, "") { return (arg % 2) == 0; }
332 // allows you to write
334 // // Expects mock_foo.Bar(n) to be called where n is even.
335 // EXPECT_CALL(mock_foo, Bar(IsEven()));
339 // // Verifies that the value of some_expression is even.
340 // EXPECT_THAT(some_expression, IsEven());
342 // If the above assertion fails, it will print something like:
344 // Value of: some_expression
348 // where the description "is even" is automatically calculated from the
349 // matcher name IsEven.
351 // Note that the type of the value being matched (arg_type) is
352 // determined by the context in which you use the matcher and is
353 // supplied to you by the compiler, so you don't need to worry about
354 // declaring it (nor can you). This allows the matcher to be
355 // polymorphic. For example, IsEven() can be used to match any type
356 // where the value of "(arg % 2) == 0" can be implicitly converted to
357 // a bool. In the "Bar(IsEven())" example above, if method Bar()
358 // takes an int, 'arg_type' will be int; if it takes an unsigned long,
359 // 'arg_type' will be unsigned long; and so on.
361 // Sometimes you'll want to parameterize the matcher. For that you
362 // can use another macro:
364 // MATCHER_P(name, param_name, description_string) { statements; }
368 // MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
370 // will allow you to write:
372 // EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
374 // which may lead to this message (assuming n is 10):
376 // Value of: Blah("a")
377 // Expected: has absolute value 10
380 // Note that both the matcher description and its parameter are
381 // printed, making the message human-friendly.
383 // In the matcher definition body, you can write 'foo_type' to
384 // reference the type of a parameter named 'foo'. For example, in the
385 // body of MATCHER_P(HasAbsoluteValue, value) above, you can write
386 // 'value_type' to refer to the type of 'value'.
388 // We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to
389 // support multi-parameter matchers.
391 // When defining a parameterized matcher, you can use Python-style
392 // interpolations in the description string to refer to the parameter
393 // values. We support the following syntax currently:
395 // %% a single '%' character
396 // %(*)s all parameters of the matcher printed as a tuple
397 // %(foo)s value of the matcher parameter named 'foo'
401 // MATCHER_P2(InClosedRange, low, hi, "is in range [%(low)s, %(hi)s]") {
402 // return low <= arg && arg <= hi;
405 // EXPECT_THAT(3, InClosedRange(4, 6));
407 // would generate a failure that contains the message:
409 // Expected: is in range [4, 6]
411 // If you specify "" as the description, the failure message will
412 // contain the sequence of words in the matcher name followed by the
413 // parameter values printed as a tuple. For example,
415 // MATCHER_P2(InClosedRange, low, hi, "") { ... }
417 // EXPECT_THAT(3, InClosedRange(4, 6));
419 // would generate a failure that contains the text:
421 // Expected: in closed range (4, 6)
423 // For the purpose of typing, you can view
425 // MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
429 // template <typename p1_type, ..., typename pk_type>
430 // FooMatcherPk<p1_type, ..., pk_type>
431 // Foo(p1_type p1, ..., pk_type pk) { ... }
433 // When you write Foo(v1, ..., vk), the compiler infers the types of
434 // the parameters v1, ..., and vk for you. If you are not happy with
435 // the result of the type inference, you can specify the types by
436 // explicitly instantiating the template, as in Foo<long, bool>(5,
437 // false). As said earlier, you don't get to (or need to) specify
438 // 'arg_type' as that's determined by the context in which the matcher
439 // is used. You can assign the result of expression Foo(p1, ..., pk)
440 // to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This
441 // can be useful when composing matchers.
443 // While you can instantiate a matcher template with reference types,
444 // passing the parameters by pointer usually makes your code more
445 // readable. If, however, you still want to pass a parameter by
446 // reference, be aware that in the failure message generated by the
447 // matcher you will see the value of the referenced object but not its
450 // You can overload matchers with different numbers of parameters:
452 // MATCHER_P(Blah, a, description_string1) { ... }
453 // MATCHER_P2(Blah, a, b, description_string2) { ... }
455 // While it's tempting to always use the MATCHER* macros when defining
456 // a new matcher, you should also consider implementing
457 // MatcherInterface or using MakePolymorphicMatcher() instead,
458 // especially if you need to use the matcher a lot. While these
459 // approaches require more work, they give you more control on the
460 // types of the value being matched and the matcher parameters, which
461 // in general leads to better compiler error messages that pay off in
462 // the long run. They also allow overloading matchers based on
463 // parameter types (as opposed to just based on the number of
468 // MATCHER*() can only be used in a namespace scope. The reason is
469 // that C++ doesn't yet allow function-local types to be used to
470 // instantiate templates. The up-coming C++0x standard will fix this.
471 // Once that's done, we'll consider supporting using MATCHER*() inside
476 // To learn more about using these macros, please search for 'MATCHER'
477 // on http://code.google.com/p/googlemock/wiki/CookBook.
482 // Constants denoting interpolations in a matcher description string.
483 const int kTupleInterpolation = -1; // "%(*)s"
484 const int kPercentInterpolation = -2; // "%%"
485 const int kInvalidInterpolation = -3; // "%" followed by invalid text
487 // Records the location and content of an interpolation.
488 struct Interpolation {
489 Interpolation(const char* start, const char* end, int param)
490 : start_pos(start), end_pos(end), param_index(param) {}
492 // Points to the start of the interpolation (the '%' character).
493 const char* start_pos;
494 // Points to the first character after the interpolation.
496 // 0-based index of the interpolated matcher parameter;
497 // kTupleInterpolation for "%(*)s"; kPercentInterpolation for "%%".
501 typedef ::std::vector<Interpolation> Interpolations;
503 // Parses a matcher description string and returns a vector of
504 // interpolations that appear in the string; generates non-fatal
505 // failures iff 'description' is an invalid matcher description.
506 // 'param_names' is a NULL-terminated array of parameter names in the
507 // order they appear in the MATCHER_P*() parameter list.
508 Interpolations ValidateMatcherDescription(
509 const char* param_names[], const char* description);
511 // Returns the actual matcher description, given the matcher name,
512 // user-supplied description template string, interpolations in the
513 // string, and the printed values of the matcher parameters.
514 string FormatMatcherDescription(
515 const char* matcher_name, const char* description,
516 const Interpolations& interp, const Strings& param_values);
518 } // namespace internal
519 } // namespace testing
525 $var macro_name = [[$if i==0 [[MATCHER]] $elif i==1 [[MATCHER_P]]
526 $else [[MATCHER_P$i]]]]
527 $var class_name = [[name##Matcher[[$if i==0 [[]] $elif i==1 [[P]]
530 $var template = [[$if i==0 [[]] $else [[
532 template <$for j, [[typename p$j##_type]]>\
534 $var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
535 $var impl_ctor_param_list = [[$for j [[p$j##_type gmock_p$j, ]]
536 const ::testing::internal::Interpolations& gmock_interp]]
537 $var impl_inits = [[ : $for j [[p$j(gmock_p$j), ]]gmock_interp_(gmock_interp)]]
538 $var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(gmock_p$j)]]]]]]
539 $var params_and_interp = [[$for j [[p$j, ]]gmock_interp_]]
540 $var params = [[$for j, [[p$j]]]]
541 $var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]]
542 $var param_types_and_names = [[$for j, [[p$j##_type p$j]]]]
543 $var param_field_decls = [[$for j
548 $var param_field_decls2 = [[$for j
554 #define $macro_name(name$for j [[, p$j]], description)\$template
557 template <typename arg_type>\
558 class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
560 [[$if i==1 [[explicit ]]]]gmock_Impl($impl_ctor_param_list)\
562 virtual bool Matches(arg_type arg) const;\
563 virtual void DescribeTo(::std::ostream* gmock_os) const {\
564 const ::testing::internal::Strings& gmock_printed_params = \
565 ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
566 ::std::tr1::tuple<$for j, [[p$j##_type]]>($for j, [[p$j]]));\
567 *gmock_os << ::testing::internal::FormatMatcherDescription(\
568 #name, description, gmock_interp_, gmock_printed_params);\
570 const ::testing::internal::Interpolations gmock_interp_;\
572 template <typename arg_type>\
573 operator ::testing::Matcher<arg_type>() const {\
574 return ::testing::Matcher<arg_type>(\
575 new gmock_Impl<arg_type>($params_and_interp));\
577 $class_name($ctor_param_list)$inits {\
578 const char* gmock_param_names[] = { $for j [[#p$j, ]]NULL };\
579 gmock_interp_ = ::testing::internal::ValidateMatcherDescription(\
580 gmock_param_names, ("" description ""));\
581 }\$param_field_decls2
582 ::testing::internal::Interpolations gmock_interp_;\
584 inline $class_name$param_types name($param_types_and_names) {\
585 return $class_name$param_types($params);\
587 template <typename arg_type>\
588 bool $class_name$param_types::\
589 gmock_Impl<arg_type>::Matches(arg_type arg) const
596 // Returns true iff element is in the STL-style container.
597 template <typename Container, typename Element>
598 inline bool Contains(const Container& container, const Element& element) {
599 return ::std::find(container.begin(), container.end(), element) !=
603 // Returns true iff element is in the C-style array.
604 template <typename ArrayElement, size_t N, typename Element>
605 inline bool Contains(const ArrayElement (&array)[N], const Element& element) {
606 return ::std::find(array, array + N, element) != array + N;
609 } // namespace internal
611 // Matches an STL-style container or a C-style array that contains the given
615 // ::std::set<int> page_ids;
616 // page_ids.insert(3);
617 // page_ids.insert(1);
618 // EXPECT_THAT(page_ids, Contains(1));
619 // EXPECT_THAT(page_ids, Contains(3.0));
620 // EXPECT_THAT(page_ids, Not(Contains(4)));
622 // ::std::map<int, size_t> page_lengths;
623 // page_lengths[1] = 100;
624 // EXPECT_THAT(map_int, Contains(::std::pair<const int, size_t>(1, 100)));
626 // const char* user_ids[] = { "joe", "mike", "tom" };
627 // EXPECT_THAT(user_ids, Contains(::std::string("tom")));
628 MATCHER_P(Contains, element, "") {
629 return internal::Contains(arg, element);
632 } // namespace testing
634 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_