2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
10 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
11 // Use of this source code is governed by a BSD-style license that can be
12 // found in the LICENSE file.
14 // This file automatically generated by testing/generate_gmock_mutant.py.
17 #ifndef TESTING_GMOCK_MUTANT_H_
18 #define TESTING_GMOCK_MUTANT_H_
20 // The intention of this file is to make possible using GMock actions in
21 // all of its syntactic beauty. Classes and helper functions can be used as
22 // more generic variants of Task and Callback classes (see base/task.h)
23 // Mutant supports both pre-bound arguments (like Task) and call-time
24 // arguments (like Callback) - hence the name. :-)
26 // DispatchToMethod/Function supports two sets of arguments: pre-bound (P) and
27 // call-time (C). The arguments as well as the return type are templatized.
28 // DispatchToMethod/Function will also try to call the selected method or
29 // function even if provided pre-bound arguments does not match exactly with
30 // the function signature hence the X1, X2 ... XN parameters in CreateFunctor.
31 // DispatchToMethod will try to invoke method that may not belong to the
32 // object's class itself but to the object's class base class.
34 // Additionally you can bind the object at calltime by binding a pointer to
35 // pointer to the object at creation time - before including this file you
36 // have to #define GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING.
38 // TODO(stoyan): It's yet not clear to me should we use T& and T&* instead
39 // of T* and T** when we invoke CreateFunctor to match the EXPECT_CALL style.
42 // Sample usage with gMock:
44 // struct Mock : public ObjectDelegate {
45 // MOCK_METHOD2(string, OnRequest(int n, const string& request));
46 // MOCK_METHOD1(void, OnQuit(int exit_code));
47 // MOCK_METHOD2(void, LogMessage(int level, const string& message));
49 // string HandleFlowers(const string& reply, int n, const string& request) {
50 // string result = SStringPrintf("In request of %d %s ", n, request);
51 // for (int i = 0; i < n; ++i) result.append(reply)
55 // void DoLogMessage(int level, const string& message) {
58 // void QuitMessageLoop(int seconds) {
59 // base::MessageLoop* loop = base::MessageLoop::current();
60 // loop->PostDelayedTask(FROM_HERE, base::MessageLoop::QuitClosure(),
66 // // Will invoke mock.HandleFlowers("orchids", n, request)
67 // // "orchids" is a pre-bound argument, and <n> and <request> are call-time
68 // // arguments - they are not known until the OnRequest mock is invoked.
69 // EXPECT_CALL(mock, OnRequest(Ge(5), StartsWith("flower"))
71 // .WillOnce(Invoke(CreateFunctor(&mock, &Mock::HandleFlowers,
72 // string("orchids"))));
75 // // No pre-bound arguments, two call-time arguments passed
76 // // directly to DoLogMessage
77 // EXPECT_CALL(mock, OnLogMessage(_, _))
78 // .Times(AnyNumber())
79 // .WillAlways(Invoke(CreateFunctor, &mock, &Mock::DoLogMessage));
82 // // In this case we have a single pre-bound argument - 3. We ignore
83 // // all of the arguments of OnQuit.
84 // EXCEPT_CALL(mock, OnQuit(_))
86 // .WillOnce(InvokeWithoutArgs(CreateFunctor(
87 // &mock, &Mock::QuitMessageLoop, 3)));
93 // // Here is another example of how we can set an action that invokes
94 // // method of an object that is not yet created.
95 // struct Mock : public ObjectDelegate {
96 // MOCK_METHOD1(void, DemiurgeCreated(Demiurge*));
97 // MOCK_METHOD2(void, OnRequest(int count, const string&));
99 // void StoreDemiurge(Demiurge* w) {
103 // Demiurge* demiurge;
106 // EXPECT_CALL(mock, DemiurgeCreated(_)).Times(1)
107 // .WillOnce(Invoke(CreateFunctor(&mock, &Mock::StoreDemiurge)));
109 // EXPECT_CALL(mock, OnRequest(_, StrEq("Moby Dick")))
110 // .Times(AnyNumber())
111 // .WillAlways(WithArgs<0>(Invoke(
112 // CreateFunctor(&mock->demiurge_, &Demiurge::DecreaseMonsters))));
115 #include "base/memory/linked_ptr.h"
116 #include "base/tuple.h"
118 namespace testing {"""
122 // Interface that is exposed to the consumer, that does the actual calling
124 template <typename R, typename Params>
127 virtual R RunWithParams(const Params& params) = 0;
128 virtual ~MutantRunner() {}
131 // Mutant holds pre-bound arguments (like Task). Like Callback
132 // allows call-time arguments. You bind a pointer to the object
134 template <typename R, typename T, typename Method,
135 typename PreBound, typename Params>
136 class Mutant : public MutantRunner<R, Params> {
138 Mutant(T* obj, Method method, const PreBound& pb)
139 : obj_(obj), method_(method), pb_(pb) {
142 // MutantRunner implementation
143 virtual R RunWithParams(const Params& params) {
144 return DispatchToMethod<R>(this->obj_, this->method_, pb_, params);
152 template <typename R, typename Function, typename PreBound, typename Params>
153 class MutantFunction : public MutantRunner<R, Params> {
155 MutantFunction(Function function, const PreBound& pb)
156 : function_(function), pb_(pb) {
159 // MutantRunner implementation
160 virtual R RunWithParams(const Params& params) {
161 return DispatchToFunction<R>(function_, pb_, params);
168 #ifdef GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING
169 // MutantLateBind is like Mutant, but you bind a pointer to a pointer
170 // to the object. This way you can create actions for an object
171 // that is not yet created (has only storage for a pointer to it).
172 template <typename R, typename T, typename Method,
173 typename PreBound, typename Params>
174 class MutantLateObjectBind : public MutantRunner<R, Params> {
176 MutantLateObjectBind(T** obj, Method method, const PreBound& pb)
177 : obj_(obj), method_(method), pb_(pb) {
180 // MutantRunner implementation.
181 virtual R RunWithParams(const Params& params) {
182 EXPECT_THAT(*this->obj_, testing::NotNull());
183 if (NULL == *this->obj_)
185 return DispatchToMethod<R>( *this->obj_, this->method_, pb_, params);
194 // Simple MutantRunner<> wrapper acting as a functor.
195 // Redirects operator() to MutantRunner<Params>::Run()
196 template <typename R, typename Params>
197 struct MutantFunctor {
198 explicit MutantFunctor(MutantRunner<R, Params>* cb) : impl_(cb) {
204 inline R operator()() {
205 return impl_->RunWithParams(base::Tuple<>());
208 template <typename Arg1>
209 inline R operator()(const Arg1& a) {
210 return impl_->RunWithParams(Params(a));
213 template <typename Arg1, typename Arg2>
214 inline R operator()(const Arg1& a, const Arg2& b) {
215 return impl_->RunWithParams(Params(a, b));
218 template <typename Arg1, typename Arg2, typename Arg3>
219 inline R operator()(const Arg1& a, const Arg2& b, const Arg3& c) {
220 return impl_->RunWithParams(Params(a, b, c));
223 template <typename Arg1, typename Arg2, typename Arg3, typename Arg4>
224 inline R operator()(const Arg1& a, const Arg2& b, const Arg3& c,
226 return impl_->RunWithParams(Params(a, b, c, d));
230 // We need copy constructor since MutantFunctor is copied few times
231 // inside GMock machinery, hence no DISALLOW_EVIL_CONTRUCTORS
233 linked_ptr<MutantRunner<R, Params> > impl_;
238 } // namespace testing
240 #endif // TESTING_GMOCK_MUTANT_H_"""
242 # Templates for DispatchToMethod/DispatchToFunction functions.
243 # template_params - typename P1, typename P2.. typename C1..
244 # prebound - Tuple<P1, .. PN>
245 # calltime - Tuple<C1, .. CN>
246 # args - p.a, p.b.., c.a, c.b..
247 DISPATCH_TO_METHOD_TEMPLATE
= """\
248 template <typename R, typename T, typename Method, %(template_params)s>
249 inline R DispatchToMethod(T* obj, Method method,
250 const %(prebound)s& p,
251 const %(calltime)s& c) {
252 return (obj->*method)(%(args)s);
256 DISPATCH_TO_FUNCTION_TEMPLATE
= """\
257 template <typename R, typename Function, %(template_params)s>
258 inline R DispatchToFunction(Function function,
259 const %(prebound)s& p,
260 const %(calltime)s& c) {
261 return (*function)(%(args)s);
265 # Templates for CreateFunctor functions.
266 # template_params - typename P1, typename P2.. typename C1.. typename X1..
267 # prebound - Tuple<P1, .. PN>
268 # calltime - Tuple<A1, .. AN>
269 # params - X1,.. , A1, ..
270 # args - const P1& p1 ..
271 # call_args - p1, p2, p3..
272 CREATE_METHOD_FUNCTOR_TEMPLATE
= """\
273 template <typename R, typename T, typename U, %(template_params)s>
274 inline MutantFunctor<R, %(calltime)s>
275 CreateFunctor(T* obj, R (U::*method)(%(params)s), %(args)s) {
276 MutantRunner<R, %(calltime)s>* t =
277 new Mutant<R, T, R (U::*)(%(params)s),
278 %(prebound)s, %(calltime)s>
279 (obj, method, base::MakeTuple(%(call_args)s));
280 return MutantFunctor<R, %(calltime)s>(t);
284 CREATE_FUNCTION_FUNCTOR_TEMPLATE
= """\
285 template <typename R, %(template_params)s>
286 inline MutantFunctor<R, %(calltime)s>
287 CreateFunctor(R (*function)(%(params)s), %(args)s) {
288 MutantRunner<R, %(calltime)s>* t =
289 new MutantFunction<R, R (*)(%(params)s),
290 %(prebound)s, %(calltime)s>
291 (function, base::MakeTuple(%(call_args)s));
292 return MutantFunctor<R, %(calltime)s>(t);
296 def SplitLine(line
, width
):
297 """Splits a single line at comma, at most |width| characters long."""
298 if len(line
) <= width
:
300 n
= 1 + line
[:width
].rfind(",")
301 if n
== 0: # If comma cannot be found give up and return the entire line.
303 # Assume there is a space after the comma
304 assert line
[n
] == " "
305 return (line
[:n
], line
[n
+ 1:])
308 def Wrap(s
, width
, subsequent_offset
):
309 """Wraps a single line |s| at commas so every line is at most |width|
313 spaces
= " " * subsequent_offset
315 (f
, s
) = SplitLine(s
, width
)
323 """Cleans artifacts from generated C++ code.
325 Our simple string formatting/concatenation may introduce extra commas.
327 s
= s
.replace(", >", ">")
328 s
= s
.replace(", )", ")")
332 def ExpandPattern(pattern
, it
):
333 """Return list of expanded pattern strings.
335 Each string is created by replacing all '%' in |pattern| with element of |it|.
337 return [pattern
.replace("%", x
) for x
in it
]
340 def Gen(pattern
, n
, start
):
341 """Expands pattern replacing '%' with sequential integers starting with start.
343 Expanded patterns will be joined with comma separator.
344 Gen("X%", 3, 1) will return "X1, X2, X3".
346 it
= string
.hexdigits
[start
:n
+ start
]
347 return ", ".join(ExpandPattern(pattern
, it
))
351 return ", ".join(filter(len, a
))
354 def GenTuple(pattern
, n
):
355 return Clean("base::Tuple<%s>" % (Gen(pattern
, n
, 1)))
359 lines
= Clean(s
).splitlines()
360 # Wrap sometimes very long 1st line to be inside the "template <"
361 lines
[0] = Wrap(lines
[0], 80, 10)
363 # Wrap all subsequent lines to 6 spaces arbitrarily. This is a 2-space line
364 # indent, plus a 4 space continuation indent.
365 for line
in xrange(1, len(lines
)):
366 lines
[line
] = Wrap(lines
[line
], 80, 6)
367 return "\n".join(lines
)
370 def GenerateDispatch(prebound
, calltime
):
371 print "\n// %d - %d" % (prebound
, calltime
)
373 "template_params": Merge([Gen("typename P%", prebound
, 1),
374 Gen("typename C%", calltime
, 1)]),
375 "prebound": GenTuple("P%", prebound
),
376 "calltime": GenTuple("C%", calltime
),
377 "args": Merge([Gen("base::get<%>(p)", prebound
, 0),
378 Gen("base::get<%>(c)", calltime
, 0)]),
381 print FixCode(DISPATCH_TO_METHOD_TEMPLATE
% args
)
382 print FixCode(DISPATCH_TO_FUNCTION_TEMPLATE
% args
)
385 def GenerateCreateFunctor(prebound
, calltime
):
386 print "// %d - %d" % (prebound
, calltime
)
388 "calltime": GenTuple("A%", calltime
),
389 "prebound": GenTuple("P%", prebound
),
390 "params": Merge([Gen("X%", prebound
, 1), Gen("A%", calltime
, 1)]),
391 "args": Gen("const P%& p%", prebound
, 1),
392 "call_args": Gen("p%", prebound
, 1),
393 "template_params": Merge([Gen("typename P%", prebound
, 1),
394 Gen("typename A%", calltime
, 1),
395 Gen("typename X%", prebound
, 1)])
398 mutant
= FixCode(CREATE_METHOD_FUNCTOR_TEMPLATE
% args
)
401 # Slightly different version for free function call.
402 print "\n", FixCode(CREATE_FUNCTION_FUNCTOR_TEMPLATE
% args
)
404 # Functor with pointer to a pointer of the object.
405 print "\n#ifdef GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING"
406 mutant2
= mutant
.replace("CreateFunctor(T* obj,", "CreateFunctor(T** obj,")
407 mutant2
= mutant2
.replace("new Mutant", "new MutantLateObjectBind")
408 mutant2
= mutant2
.replace(" " * 17 + "Tuple", " " * 31 + "Tuple")
410 print "#endif // GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING\n"
412 # OS_WIN specific. Same functors but with stdcall calling conventions.
413 # These are not for WIN64 (x86_64) because there is only one calling
414 # convention in WIN64.
415 # Functor for method with __stdcall calling conventions.
416 print "#if defined (OS_WIN) && !defined (ARCH_CPU_X86_64)"
417 stdcall_method
= CREATE_METHOD_FUNCTOR_TEMPLATE
418 stdcall_method
= stdcall_method
.replace("U::", "__stdcall U::")
419 stdcall_method
= FixCode(stdcall_method
% args
)
421 # Functor for free function with __stdcall calling conventions.
422 stdcall_function
= CREATE_FUNCTION_FUNCTOR_TEMPLATE
423 stdcall_function
= stdcall_function
.replace("R (*", "R (__stdcall *")
424 print "\n", FixCode(stdcall_function
% args
)
426 print "#ifdef GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING"
427 stdcall2
= stdcall_method
428 stdcall2
= stdcall2
.replace("CreateFunctor(T* obj,", "CreateFunctor(T** obj,")
429 stdcall2
= stdcall2
.replace("new Mutant", "new MutantLateObjectBind")
430 stdcall2
= stdcall2
.replace(" " * 17 + "Tuple", " " * 31 + "Tuple")
432 print "#endif // GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING"
433 print "#endif // defined (OS_WIN) && !defined (ARCH_CPU_X86_64)\n"
438 for prebound
in xrange(0, 6 + 1):
439 for args
in xrange(0, 6 + 1):
440 GenerateDispatch(prebound
, args
)
442 for prebound
in xrange(0, 6 + 1):
443 for args
in xrange(0, 6 + 1):
444 GenerateCreateFunctor(prebound
, args
)
449 if __name__
== "__main__":