media/webrtc/trunk/testing/generate_gmock_mutant.py

Thu, 15 Jan 2015 15:55:04 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Thu, 15 Jan 2015 15:55:04 +0100
branch
TOR_BUG_9701
changeset 9
a63d609f5ebe
permissions
-rwxr-xr-x

Back out 97036ab72558 which inappropriately compared turds to third parties.

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

mercurial