• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/python
2# Copyright (c) 2009 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.
5
6import string
7
8HEADER = """\
9// Copyright (c) 2009 The Chromium Authors. All rights reserved.
10// Use of this source code is governed by a BSD-style license that can be
11// found in the LICENSE file.
12
13// This file automatically generated by testing/generate_gmock_mutant.py.
14// DO NOT EDIT.
15
16#ifndef TESTING_GMOCK_MUTANT_H_
17#define TESTING_GMOCK_MUTANT_H_
18
19// The intention of this file is to make possible using GMock actions in
20// all of its syntactic beauty. Classes and helper functions can be used as
21// more generic variants of Task and Callback classes (see base/task.h)
22// Mutant supports both pre-bound arguments (like Task) and call-time
23// arguments (like Callback) - hence the name. :-)
24//
25// DispatchToMethod/Function supports two sets of arguments: pre-bound (P) and
26// call-time (C). The arguments as well as the return type are templatized.
27// DispatchToMethod/Function will also try to call the selected method or
28// function even if provided pre-bound arguments does not match exactly with
29// the function signature hence the X1, X2 ... XN parameters in CreateFunctor.
30// DispatchToMethod will try to invoke method that may not belong to the
31// object's class itself but to the object's class base class.
32//
33// Additionally you can bind the object at calltime by binding a pointer to
34// pointer to the object at creation time - before including this file you
35// have to #define GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING.
36//
37// TODO(stoyan): It's yet not clear to me should we use T& and T&* instead
38// of T* and T** when we invoke CreateFunctor to match the EXPECT_CALL style.
39//
40//
41// Sample usage with gMock:
42//
43// struct Mock : public ObjectDelegate {
44//   MOCK_METHOD2(string, OnRequest(int n, const string& request));
45//   MOCK_METHOD1(void, OnQuit(int exit_code));
46//   MOCK_METHOD2(void, LogMessage(int level, const string& message));
47//
48//   string HandleFlowers(const string& reply, int n, const string& request) {
49//     string result = SStringPrintf("In request of %d %s ", n, request);
50//     for (int i = 0; i < n; ++i) result.append(reply)
51//     return result;
52//   }
53//
54//   void DoLogMessage(int level, const string& message) {
55//   }
56//
57//   void QuitMessageLoop(int seconds) {
58//     MessageLoop* loop = MessageLoop::current();
59//     loop->PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask,
60//                           1000 * seconds);
61//   }
62// };
63//
64// Mock mock;
65// // Will invoke mock.HandleFlowers("orchids", n, request)
66// // "orchids" is a pre-bound argument, and <n> and <request> are call-time
67// // arguments - they are not known until the OnRequest mock is invoked.
68// EXPECT_CALL(mock, OnRequest(Ge(5), StartsWith("flower"))
69//   .Times(1)
70//   .WillOnce(Invoke(CreateFunctor(&mock, &Mock::HandleFlowers,
71//       string("orchids"))));
72//
73//
74// // No pre-bound arguments, two call-time arguments passed
75// // directly to DoLogMessage
76// EXPECT_CALL(mock, OnLogMessage(_, _))
77//   .Times(AnyNumber())
78//   .WillAlways(Invoke(CreateFunctor, &mock, &Mock::DoLogMessage));
79//
80//
81// // In this case we have a single pre-bound argument - 3. We ignore
82// // all of the arguments of OnQuit.
83// EXCEPT_CALL(mock, OnQuit(_))
84//   .Times(1)
85//   .WillOnce(InvokeWithoutArgs(CreateFunctor(
86//       &mock, &Mock::QuitMessageLoop, 3)));
87//
88// MessageLoop loop;
89// loop.Run();
90//
91//
92//  // Here is another example of how we can set an action that invokes
93//  // method of an object that is not yet created.
94// struct Mock : public ObjectDelegate {
95//   MOCK_METHOD1(void, DemiurgeCreated(Demiurge*));
96//   MOCK_METHOD2(void, OnRequest(int count, const string&));
97//
98//   void StoreDemiurge(Demiurge* w) {
99//     demiurge_ = w;
100//   }
101//
102//   Demiurge* demiurge;
103// }
104//
105// EXPECT_CALL(mock, DemiurgeCreated(_)).Times(1)
106//    .WillOnce(Invoke(CreateFunctor(&mock, &Mock::StoreDemiurge)));
107//
108// EXPECT_CALL(mock, OnRequest(_, StrEq("Moby Dick")))
109//    .Times(AnyNumber())
110//    .WillAlways(WithArgs<0>(Invoke(
111//        CreateFunctor(&mock->demiurge_, &Demiurge::DecreaseMonsters))));
112//
113
114#include "base/linked_ptr.h"
115#include "base/tuple.h"  // for Tuple
116
117namespace testing {"""
118
119MUTANT = """\
120
121// Interface that is exposed to the consumer, that does the actual calling
122// of the method.
123template <typename R, typename Params>
124class MutantRunner {
125 public:
126  virtual R RunWithParams(const Params& params) = 0;
127  virtual ~MutantRunner() {}
128};
129
130// Mutant holds pre-bound arguments (like Task). Like Callback
131// allows call-time arguments. You bind a pointer to the object
132// at creation time.
133template <typename R, typename T, typename Method,
134          typename PreBound, typename Params>
135class Mutant : public MutantRunner<R, Params> {
136 public:
137  Mutant(T* obj, Method method, const PreBound& pb)
138      : obj_(obj), method_(method), pb_(pb) {
139  }
140
141  // MutantRunner implementation
142  virtual R RunWithParams(const Params& params) {
143    return DispatchToMethod<R>(this->obj_, this->method_, pb_, params);
144  }
145
146  T* obj_;
147  Method method_;
148  PreBound pb_;
149};
150
151template <typename R, typename Function, typename PreBound, typename Params>
152class MutantFunction : public MutantRunner<R, Params> {
153 public:
154  MutantFunction(Function function, const PreBound& pb)
155      : function_(function), pb_(pb) {
156  }
157
158  // MutantRunner implementation
159  virtual R RunWithParams(const Params& params) {
160    return DispatchToFunction<R>(function_, pb_, params);
161  }
162
163  Function function_;
164  PreBound pb_;
165};
166
167#ifdef GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING
168// MutantLateBind is like Mutant, but you bind a pointer to a pointer
169// to the object. This way you can create actions for an object
170// that is not yet created (has only storage for a pointer to it).
171template <typename R, typename T, typename Method,
172          typename PreBound, typename Params>
173class MutantLateObjectBind : public MutantRunner<R, Params> {
174 public:
175  MutantLateObjectBind(T** obj, Method method, const PreBound& pb)
176      : obj_(obj), method_(method), pb_(pb) {
177  }
178
179  // MutantRunner implementation.
180  virtual R RunWithParams(const Params& params) {
181    EXPECT_THAT(*this->obj_, testing::NotNull());
182    if (NULL == *this->obj_)
183      return R();
184    return DispatchToMethod<R>( *this->obj_, this->method_, pb_, params);
185  }
186
187  T** obj_;
188  Method method_;
189  PreBound pb_;
190};
191#endif
192
193// Simple MutantRunner<> wrapper acting as a functor.
194// Redirects operator() to MutantRunner<Params>::Run()
195template <typename R, typename Params>
196struct MutantFunctor {
197  explicit MutantFunctor(MutantRunner<R, Params>*  cb) : impl_(cb) {
198  }
199
200  ~MutantFunctor() {
201  }
202
203  inline R operator()() {
204    return impl_->RunWithParams(Tuple0());
205  }
206
207  template <typename Arg1>
208  inline R operator()(const Arg1& a) {
209    return impl_->RunWithParams(Params(a));
210  }
211
212  template <typename Arg1, typename Arg2>
213  inline R operator()(const Arg1& a, const Arg2& b) {
214    return impl_->RunWithParams(Params(a, b));
215  }
216
217  template <typename Arg1, typename Arg2, typename Arg3>
218  inline R operator()(const Arg1& a, const Arg2& b, const Arg3& c) {
219    return impl_->RunWithParams(Params(a, b, c));
220  }
221
222  template <typename Arg1, typename Arg2, typename Arg3, typename Arg4>
223  inline R operator()(const Arg1& a, const Arg2& b, const Arg3& c,
224                         const Arg4& d) {
225    return impl_->RunWithParams(Params(a, b, c, d));
226  }
227
228 private:
229  // We need copy constructor since MutantFunctor is copied few times
230  // inside GMock machinery, hence no DISALLOW_EVIL_CONTRUCTORS
231  MutantFunctor();
232  linked_ptr<MutantRunner<R, Params> > impl_;
233};
234"""
235
236FOOTER = """\
237}  // namespace testing
238
239#endif  // TESTING_GMOCK_MUTANT_H_"""
240
241# Templates for DispatchToMethod/DispatchToFunction functions.
242# template_params - typename P1, typename P2.. typename C1..
243# prebound - TupleN<P1, .. PN>
244# calltime - TupleN<C1, .. CN>
245# args - p.a, p.b.., c.a, c.b..
246DISPATCH_TO_METHOD_TEMPLATE = """\
247template <typename R, typename T, typename Method, %(template_params)s>
248inline R DispatchToMethod(T* obj, Method method,
249                          const %(prebound)s& p,
250                          const %(calltime)s& c) {
251  return (obj->*method)(%(args)s);
252}
253"""
254
255DISPATCH_TO_FUNCTION_TEMPLATE = """\
256template <typename R, typename Function, %(template_params)s>
257inline R DispatchToFunction(Function function,
258                            const %(prebound)s& p,
259                            const %(calltime)s& c) {
260  return (*function)(%(args)s);
261}
262"""
263
264# Templates for CreateFunctor functions.
265# template_params - typename P1, typename P2.. typename C1.. typename X1..
266# prebound - TupleN<P1, .. PN>
267# calltime - TupleN<A1, .. AN>
268# params - X1,.. , A1, ..
269# args - const P1& p1 ..
270# call_args - p1, p2, p3..
271CREATE_METHOD_FUNCTOR_TEMPLATE = """\
272template <typename R, typename T, typename U, %(template_params)s>
273inline MutantFunctor<R, %(calltime)s>
274CreateFunctor(T* obj, R (U::*method)(%(params)s), %(args)s) {
275  MutantRunner<R, %(calltime)s>* t =
276      new Mutant<R, T, R (U::*)(%(params)s),
277                 %(prebound)s, %(calltime)s>
278          (obj, method, MakeTuple(%(call_args)s));
279  return MutantFunctor<R, %(calltime)s>(t);
280}
281"""
282
283CREATE_FUNCTION_FUNCTOR_TEMPLATE = """\
284template <typename R, %(template_params)s>
285inline MutantFunctor<R, %(calltime)s>
286CreateFunctor(R (*function)(%(params)s), %(args)s) {
287  MutantRunner<R, %(calltime)s>* t =
288      new MutantFunction<R, R (*)(%(params)s),
289                         %(prebound)s, %(calltime)s>
290          (function, MakeTuple(%(call_args)s));
291  return MutantFunctor<R, %(calltime)s>(t);
292}
293"""
294
295def SplitLine(line, width):
296  """Splits a single line at comma, at most |width| characters long."""
297  if len(line) < width:
298    return (line, None)
299  n = 1 + line[:width].rfind(",")
300  if n == 0:  # If comma cannot be found give up and return the entire line.
301    return (line, None)
302  # Assume there is a space after the comma
303  assert line[n] == " "
304  return (line[:n], line[n + 1:])
305
306
307def Wrap(s, width, subsequent_offset=4):
308  """Wraps a single line |s| at commas so every line is at most |width|
309     characters long.
310  """
311  w = []
312  spaces = " " * subsequent_offset
313  while s:
314    (f, s) = SplitLine(s, width)
315    w.append(f)
316    if s:
317      s = spaces  + s
318  return "\n".join(w)
319
320
321def Clean(s):
322  """Cleans artifacts from generated C++ code.
323
324  Our simple string formatting/concatenation may introduce extra commas.
325  """
326  s = s.replace("<>", "")
327  s = s.replace(", >", ">")
328  s = s.replace(", )", ")")
329  s = s.replace(">>", "> >")
330  return s
331
332
333def ExpandPattern(pattern, it):
334  """Return list of expanded pattern strings.
335
336  Each string is created by replacing all '%' in |pattern| with element of |it|.
337  """
338  return [pattern.replace("%", x) for x in it]
339
340
341def Gen(pattern, n):
342  """Expands pattern replacing '%' with sequential integers.
343
344  Expanded patterns will be joined with comma separator.
345  GenAlphs("X%", 3) will return "X1, X2, X3".
346  """
347  it = string.hexdigits[1:n + 1]
348  return ", ".join(ExpandPattern(pattern, it))
349
350
351def GenAlpha(pattern, n):
352  """Expands pattern replacing '%' with sequential small ASCII letters.
353
354  Expanded patterns will be joined with comma separator.
355  GenAlphs("X%", 3) will return "Xa, Xb, Xc".
356  """
357  it = string.ascii_lowercase[0:n]
358  return ", ".join(ExpandPattern(pattern, it))
359
360
361def Merge(a):
362  return ", ".join(filter(len, a))
363
364
365def GenTuple(pattern, n):
366  return Clean("Tuple%d<%s>" % (n, Gen(pattern, n)))
367
368
369def FixCode(s):
370  lines = Clean(s).splitlines()
371  # Wrap sometimes very long 1st and 3rd line at 80th column.
372  lines[0] = Wrap(lines[0], 80, 10)
373  lines[2] = Wrap(lines[2], 80, 4)
374  return "\n".join(lines)
375
376
377def GenerateDispatch(prebound, calltime):
378  print "\n// %d - %d" % (prebound, calltime)
379  args = {
380      "template_params": Merge([Gen("typename P%", prebound),
381                                Gen("typename C%", calltime)]),
382      "prebound": GenTuple("P%", prebound),
383      "calltime": GenTuple("C%", calltime),
384      "args": Merge([GenAlpha("p.%", prebound), GenAlpha("c.%", calltime)]),
385  }
386
387  print FixCode(DISPATCH_TO_METHOD_TEMPLATE % args)
388  print FixCode(DISPATCH_TO_FUNCTION_TEMPLATE % args)
389
390
391def GenerateCreateFunctor(prebound, calltime):
392  print "// %d - %d" % (prebound, calltime)
393  args = {
394      "calltime": GenTuple("A%", calltime),
395      "prebound": GenTuple("P%", prebound),
396      "params": Merge([Gen("X%", prebound), Gen("A%", calltime)]),
397      "args": Gen("const P%& p%", prebound),
398      "call_args": Gen("p%", prebound),
399      "template_params": Merge([Gen("typename P%", prebound),
400                                Gen("typename A%", calltime),
401                                Gen("typename X%", prebound)])
402  }
403
404  mutant = FixCode(CREATE_METHOD_FUNCTOR_TEMPLATE % args)
405  print mutant
406
407  # Slightly different version for free function call.
408  print "\n", FixCode(CREATE_FUNCTION_FUNCTOR_TEMPLATE % args)
409
410  # Functor with pointer to a pointer of the object.
411  print "\n#ifdef GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING"
412  mutant2 = mutant.replace("CreateFunctor(T* obj,", "CreateFunctor(T** obj,")
413  mutant2 = mutant2.replace("new Mutant", "new MutantLateObjectBind")
414  mutant2 = mutant2.replace(" " * 17 + "Tuple", " " * 31 + "Tuple")
415  print mutant2
416  print "#endif  // GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING\n"
417
418  # OS_WIN specific. Same functors but with stdcall calling conventions.
419  # Functor for method with __stdcall calling conventions.
420  print "#if defined (OS_WIN)"
421  stdcall_method = CREATE_METHOD_FUNCTOR_TEMPLATE
422  stdcall_method = stdcall_method.replace("U::", "__stdcall U::")
423  stdcall_method = FixCode(stdcall_method % args)
424  print stdcall_method
425  # Functor for free function with __stdcall calling conventions.
426  stdcall_function = CREATE_FUNCTION_FUNCTOR_TEMPLATE
427  stdcall_function = stdcall_function.replace("R (*", "R (__stdcall *");
428  print "\n", FixCode(stdcall_function % args)
429
430  print "#ifdef GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING"
431  stdcall2 = stdcall_method;
432  stdcall2 = stdcall2.replace("CreateFunctor(T* obj,", "CreateFunctor(T** obj,")
433  stdcall2 = stdcall2.replace("new Mutant", "new MutantLateObjectBind")
434  stdcall2 = stdcall2.replace(" " * 17 + "Tuple", " " * 31 + "Tuple")
435  print stdcall2
436  print "#endif  // GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING"
437  print "#endif  // OS_WIN\n"
438
439
440def main():
441  print HEADER
442  for prebound in xrange(0, 6 + 1):
443    for args in xrange(0, 6 + 1):
444      GenerateDispatch(prebound, args)
445  print MUTANT
446  for prebound in xrange(0, 6 + 1):
447    for args in xrange(0, 6 + 1):
448      GenerateCreateFunctor(prebound, args)
449  print FOOTER
450
451if __name__ == "__main__":
452  main()
453