Enable Surfaces on Android (try #2)
[chromium-blink-merge.git] / testing / generate_gmock_mutant.py
bloba6ee4c3cd3a967060a1b805e534c5917a34ea2a2
1 #!/usr/bin/env python
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.
6 import string
7 import sys
9 HEADER = """\
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.
15 // DO NOT EDIT.
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)
52 // return result;
53 // }
55 // void DoLogMessage(int level, const string& message) {
56 // }
58 // void QuitMessageLoop(int seconds) {
59 // base::MessageLoop* loop = base::MessageLoop::current();
60 // loop->PostDelayedTask(FROM_HERE, base::MessageLoop::QuitClosure(),
61 // 1000 * seconds);
62 // }
63 // };
65 // Mock mock;
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"))
70 // .Times(1)
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(_))
85 // .Times(1)
86 // .WillOnce(InvokeWithoutArgs(CreateFunctor(
87 // &mock, &Mock::QuitMessageLoop, 3)));
89 // MessageLoop loop;
90 // loop.Run();
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) {
100 // demiurge_ = w;
101 // }
103 // Demiurge* demiurge;
104 // }
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" // for Tuple
118 namespace testing {"""
120 MUTANT = """\
122 // Interface that is exposed to the consumer, that does the actual calling
123 // of the method.
124 template <typename R, typename Params>
125 class MutantRunner {
126 public:
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
133 // at creation time.
134 template <typename R, typename T, typename Method,
135 typename PreBound, typename Params>
136 class Mutant : public MutantRunner<R, Params> {
137 public:
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);
147 T* obj_;
148 Method method_;
149 PreBound pb_;
152 template <typename R, typename Function, typename PreBound, typename Params>
153 class MutantFunction : public MutantRunner<R, Params> {
154 public:
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);
164 Function function_;
165 PreBound pb_;
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> {
175 public:
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_)
184 return R();
185 return DispatchToMethod<R>( *this->obj_, this->method_, pb_, params);
188 T** obj_;
189 Method method_;
190 PreBound pb_;
192 #endif
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) {
201 ~MutantFunctor() {
204 inline R operator()() {
205 return impl_->RunWithParams(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,
225 const Arg4& d) {
226 return impl_->RunWithParams(Params(a, b, c, d));
229 private:
230 // We need copy constructor since MutantFunctor is copied few times
231 // inside GMock machinery, hence no DISALLOW_EVIL_CONTRUCTORS
232 MutantFunctor();
233 linked_ptr<MutantRunner<R, Params> > impl_;
237 FOOTER = """\
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, 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, 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:
299 return (line, None)
300 n = 1 + line[:width].rfind(",")
301 if n == 0: # If comma cannot be found give up and return the entire line.
302 return (line, None)
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|
310 characters long.
312 w = []
313 spaces = " " * subsequent_offset
314 while s:
315 (f, s) = SplitLine(s, width)
316 w.append(f)
317 if s:
318 s = spaces + s
319 return "\n".join(w)
322 def Clean(s):
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(", )", ")")
329 return s
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))
350 def Merge(a):
351 return ", ".join(filter(len, a))
354 def GenTuple(pattern, n):
355 return Clean("Tuple<%s>" % (Gen(pattern, n, 1)))
358 def FixCode(s):
359 lines = Clean(s).splitlines()
360 # Wrap sometimes very long 1st and 3rd line at 80th column.
361 lines[0] = Wrap(lines[0], 80, 10)
362 lines[2] = Wrap(lines[2], 80, 4)
363 return "\n".join(lines)
366 def GenerateDispatch(prebound, calltime):
367 print "\n// %d - %d" % (prebound, calltime)
368 args = {
369 "template_params": Merge([Gen("typename P%", prebound, 1),
370 Gen("typename C%", calltime, 1)]),
371 "prebound": GenTuple("P%", prebound),
372 "calltime": GenTuple("C%", calltime),
373 "args": Merge([Gen("get<%>(p)", prebound, 0),
374 Gen("get<%>(c)", calltime, 0)]),
377 print FixCode(DISPATCH_TO_METHOD_TEMPLATE % args)
378 print FixCode(DISPATCH_TO_FUNCTION_TEMPLATE % args)
381 def GenerateCreateFunctor(prebound, calltime):
382 print "// %d - %d" % (prebound, calltime)
383 args = {
384 "calltime": GenTuple("A%", calltime),
385 "prebound": GenTuple("P%", prebound),
386 "params": Merge([Gen("X%", prebound, 1), Gen("A%", calltime, 1)]),
387 "args": Gen("const P%& p%", prebound, 1),
388 "call_args": Gen("p%", prebound, 1),
389 "template_params": Merge([Gen("typename P%", prebound, 1),
390 Gen("typename A%", calltime, 1),
391 Gen("typename X%", prebound, 1)])
394 mutant = FixCode(CREATE_METHOD_FUNCTOR_TEMPLATE % args)
395 print mutant
397 # Slightly different version for free function call.
398 print "\n", FixCode(CREATE_FUNCTION_FUNCTOR_TEMPLATE % args)
400 # Functor with pointer to a pointer of the object.
401 print "\n#ifdef GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING"
402 mutant2 = mutant.replace("CreateFunctor(T* obj,", "CreateFunctor(T** obj,")
403 mutant2 = mutant2.replace("new Mutant", "new MutantLateObjectBind")
404 mutant2 = mutant2.replace(" " * 17 + "Tuple", " " * 31 + "Tuple")
405 print mutant2
406 print "#endif // GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING\n"
408 # OS_WIN specific. Same functors but with stdcall calling conventions.
409 # These are not for WIN64 (x86_64) because there is only one calling
410 # convention in WIN64.
411 # Functor for method with __stdcall calling conventions.
412 print "#if defined (OS_WIN) && !defined (ARCH_CPU_X86_64)"
413 stdcall_method = CREATE_METHOD_FUNCTOR_TEMPLATE
414 stdcall_method = stdcall_method.replace("U::", "__stdcall U::")
415 stdcall_method = FixCode(stdcall_method % args)
416 print stdcall_method
417 # Functor for free function with __stdcall calling conventions.
418 stdcall_function = CREATE_FUNCTION_FUNCTOR_TEMPLATE
419 stdcall_function = stdcall_function.replace("R (*", "R (__stdcall *")
420 print "\n", FixCode(stdcall_function % args)
422 print "#ifdef GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING"
423 stdcall2 = stdcall_method
424 stdcall2 = stdcall2.replace("CreateFunctor(T* obj,", "CreateFunctor(T** obj,")
425 stdcall2 = stdcall2.replace("new Mutant", "new MutantLateObjectBind")
426 stdcall2 = stdcall2.replace(" " * 17 + "Tuple", " " * 31 + "Tuple")
427 print stdcall2
428 print "#endif // GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING"
429 print "#endif // defined (OS_WIN) && !defined (ARCH_CPU_X86_64)\n"
432 def main():
433 print HEADER
434 for prebound in xrange(0, 6 + 1):
435 for args in xrange(0, 6 + 1):
436 GenerateDispatch(prebound, args)
437 print MUTANT
438 for prebound in xrange(0, 6 + 1):
439 for args in xrange(0, 6 + 1):
440 GenerateCreateFunctor(prebound, args)
441 print FOOTER
442 return 0
445 if __name__ == "__main__":
446 sys.exit(main())