|
| 1 | +# Copyright 2023 The go-python Authors. All rights reserved. |
| 2 | +# Use of this source code is governed by a BSD-style |
| 3 | +# license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +# Copied from Python-3.4.9\Lib\test\test_decorators.py |
| 6 | + |
| 7 | +import libtest as self |
| 8 | + |
| 9 | +def funcattrs(**kwds): |
| 10 | + def decorate(func): |
| 11 | + # FIXME func.__dict__.update(kwds) |
| 12 | + for k, v in kwds.items(): |
| 13 | + func.__dict__[k] = v |
| 14 | + return func |
| 15 | + return decorate |
| 16 | + |
| 17 | +class MiscDecorators (object): |
| 18 | + @staticmethod |
| 19 | + def author(name): |
| 20 | + def decorate(func): |
| 21 | + func.__dict__['author'] = name |
| 22 | + return func |
| 23 | + return decorate |
| 24 | + |
| 25 | +# ----------------------------------------------- |
| 26 | + |
| 27 | +class DbcheckError (Exception): |
| 28 | + def __init__(self, exprstr, func, args, kwds): |
| 29 | + # A real version of this would set attributes here |
| 30 | + Exception.__init__(self, "dbcheck %r failed (func=%s args=%s kwds=%s)" % |
| 31 | + (exprstr, func, args, kwds)) |
| 32 | + |
| 33 | + |
| 34 | +def dbcheck(exprstr, globals=None, locals=None): |
| 35 | + "Decorator to implement debugging assertions" |
| 36 | + def decorate(func): |
| 37 | + expr = compile(exprstr, "dbcheck-%s" % func.__name__, "eval") |
| 38 | + def check(*args, **kwds): |
| 39 | + if not eval(expr, globals, locals): |
| 40 | + raise DbcheckError(exprstr, func, args, kwds) |
| 41 | + return func(*args, **kwds) |
| 42 | + return check |
| 43 | + return decorate |
| 44 | + |
| 45 | +# ----------------------------------------------- |
| 46 | + |
| 47 | +def countcalls(counts): |
| 48 | + "Decorator to count calls to a function" |
| 49 | + def decorate(func): |
| 50 | + func_name = func.__name__ |
| 51 | + counts[func_name] = 0 |
| 52 | + def call(*args, **kwds): |
| 53 | + counts[func_name] += 1 |
| 54 | + return func(*args, **kwds) |
| 55 | + call.__name__ = func_name |
| 56 | + return call |
| 57 | + return decorate |
| 58 | + |
| 59 | +# ----------------------------------------------- |
| 60 | + |
| 61 | +# FIXME: dict can only have string keys |
| 62 | +# def memoize(func): |
| 63 | +# saved = {} |
| 64 | +# def call(*args): |
| 65 | +# try: |
| 66 | +# return saved[args] |
| 67 | +# except KeyError: |
| 68 | +# res = func(*args) |
| 69 | +# saved[args] = res |
| 70 | +# return res |
| 71 | +# except TypeError: |
| 72 | +# # Unhashable argument |
| 73 | +# return func(*args) |
| 74 | +# call.__name__ = func.__name__ |
| 75 | +# return call |
| 76 | +def memoize(func): |
| 77 | + saved = {} |
| 78 | + def call(*args): |
| 79 | + try: |
| 80 | + if isinstance(args[0], list): |
| 81 | + raise TypeError |
| 82 | + return saved[str(args)] |
| 83 | + except KeyError: |
| 84 | + res = func(*args) |
| 85 | + saved[str(args)] = res |
| 86 | + return res |
| 87 | + except TypeError: |
| 88 | + # Unhashable argument |
| 89 | + return func(*args) |
| 90 | + call.__name__ = func.__name__ |
| 91 | + return call |
| 92 | + |
| 93 | +# ----------------------------------------------- |
| 94 | + |
| 95 | +doc="test_single" |
| 96 | +# FIXME staticmethod |
| 97 | +# class C(object): |
| 98 | +# @staticmethod |
| 99 | +# def foo(): return 42 |
| 100 | +# self.assertEqual(C.foo(), 42) |
| 101 | +# self.assertEqual(C().foo(), 42) |
| 102 | + |
| 103 | +doc="test_staticmethod_function" |
| 104 | +@staticmethod |
| 105 | +def notamethod(x): |
| 106 | + return x |
| 107 | +self.assertRaises(TypeError, notamethod, 1) |
| 108 | + |
| 109 | +doc="test_dotted" |
| 110 | +# FIXME class decorator |
| 111 | +# decorators = MiscDecorators() |
| 112 | +# @decorators.author('Cleese') |
| 113 | +# def foo(): return 42 |
| 114 | +# self.assertEqual(foo(), 42) |
| 115 | +# self.assertEqual(foo.author, 'Cleese') |
| 116 | + |
| 117 | +doc="test_argforms" |
| 118 | +def noteargs(*args, **kwds): |
| 119 | + def decorate(func): |
| 120 | + setattr(func, 'dbval', (args, kwds)) |
| 121 | + return func |
| 122 | + return decorate |
| 123 | + |
| 124 | +args = ( 'Now', 'is', 'the', 'time' ) |
| 125 | +kwds = dict(one=1, two=2) |
| 126 | +@noteargs(*args, **kwds) |
| 127 | +def f1(): return 42 |
| 128 | +self.assertEqual(f1(), 42) |
| 129 | +self.assertEqual(f1.dbval, (args, kwds)) |
| 130 | + |
| 131 | +@noteargs('terry', 'gilliam', eric='idle', john='cleese') |
| 132 | +def f2(): return 84 |
| 133 | +self.assertEqual(f2(), 84) |
| 134 | +self.assertEqual(f2.dbval, (('terry', 'gilliam'), |
| 135 | + dict(eric='idle', john='cleese'))) |
| 136 | + |
| 137 | +@noteargs(1, 2,) |
| 138 | +def f3(): pass |
| 139 | +self.assertEqual(f3.dbval, ((1, 2), {})) |
| 140 | + |
| 141 | +doc="test_dbcheck" |
| 142 | +# FIXME TypeError: "catching 'BaseException' that does not inherit from BaseException is not allowed" |
| 143 | +# @dbcheck('args[1] is not None') |
| 144 | +# def f(a, b): |
| 145 | +# return a + b |
| 146 | +# self.assertEqual(f(1, 2), 3) |
| 147 | +# self.assertRaises(DbcheckError, f, 1, None) |
| 148 | + |
| 149 | +doc="test_memoize" |
| 150 | +counts = {} |
| 151 | + |
| 152 | +@memoize |
| 153 | +@countcalls(counts) |
| 154 | +def double(x): |
| 155 | + return x * 2 |
| 156 | +self.assertEqual(double.__name__, 'double') |
| 157 | + |
| 158 | +self.assertEqual(counts, dict(double=0)) |
| 159 | + |
| 160 | +# Only the first call with a given argument bumps the call count: |
| 161 | +# |
| 162 | +# Only the first call with a given argument bumps the call count: |
| 163 | +# |
| 164 | +self.assertEqual(double(2), 4) |
| 165 | +self.assertEqual(counts['double'], 1) |
| 166 | +self.assertEqual(double(2), 4) |
| 167 | +self.assertEqual(counts['double'], 1) |
| 168 | +self.assertEqual(double(3), 6) |
| 169 | +self.assertEqual(counts['double'], 2) |
| 170 | + |
| 171 | +# Unhashable arguments do not get memoized: |
| 172 | +# |
| 173 | +self.assertEqual(double([10]), [10, 10]) |
| 174 | +self.assertEqual(counts['double'], 3) |
| 175 | +self.assertEqual(double([10]), [10, 10]) |
| 176 | +self.assertEqual(counts['double'], 4) |
| 177 | + |
| 178 | +doc="test_errors" |
| 179 | +# Test syntax restrictions - these are all compile-time errors: |
| 180 | +# |
| 181 | +for expr in [ "1+2", "x[3]", "(1, 2)" ]: |
| 182 | + # Sanity check: is expr is a valid expression by itself? |
| 183 | + compile(expr, "testexpr", "exec") |
| 184 | + |
| 185 | + codestr = "@%s\ndef f(): pass" % expr |
| 186 | + self.assertRaises(SyntaxError, compile, codestr, "test", "exec") |
| 187 | + |
| 188 | +# You can't put multiple decorators on a single line: |
| 189 | +# |
| 190 | +self.assertRaises(SyntaxError, compile, |
| 191 | + "@f1 @f2\ndef f(): pass", "test", "exec") |
| 192 | + |
| 193 | +# Test runtime errors |
| 194 | + |
| 195 | +def unimp(func): |
| 196 | + raise NotImplementedError |
| 197 | +context = dict(nullval=None, unimp=unimp) |
| 198 | + |
| 199 | +for expr, exc in [ ("undef", NameError), |
| 200 | + ("nullval", TypeError), |
| 201 | + ("nullval.attr", NameError), # FIXME ("nullval.attr", AttributeError), |
| 202 | + ("unimp", NotImplementedError)]: |
| 203 | + codestr = "@%s\ndef f(): pass\nassert f() is None" % expr |
| 204 | + code = compile(codestr, "test", "exec") |
| 205 | + self.assertRaises(exc, eval, code, context) |
| 206 | + |
| 207 | +doc="test_double" |
| 208 | +class C(object): |
| 209 | + @funcattrs(abc=1, xyz="haha") |
| 210 | + @funcattrs(booh=42) |
| 211 | + def foo(self): return 42 |
| 212 | +self.assertEqual(C().foo(), 42) |
| 213 | +self.assertEqual(C.foo.abc, 1) |
| 214 | +self.assertEqual(C.foo.xyz, "haha") |
| 215 | +self.assertEqual(C.foo.booh, 42) |
| 216 | + |
| 217 | + |
| 218 | +doc="test_order" |
| 219 | +# Test that decorators are applied in the proper order to the function |
| 220 | +# they are decorating. |
| 221 | +def callnum(num): |
| 222 | + """Decorator factory that returns a decorator that replaces the |
| 223 | + passed-in function with one that returns the value of 'num'""" |
| 224 | + def deco(func): |
| 225 | + return lambda: num |
| 226 | + return deco |
| 227 | +@callnum(2) |
| 228 | +@callnum(1) |
| 229 | +def foo(): return 42 |
| 230 | +self.assertEqual(foo(), 2, |
| 231 | + "Application order of decorators is incorrect") |
| 232 | + |
| 233 | + |
| 234 | +doc="test_eval_order" |
| 235 | +# Evaluating a decorated function involves four steps for each |
| 236 | +# decorator-maker (the function that returns a decorator): |
| 237 | +# |
| 238 | +# 1: Evaluate the decorator-maker name |
| 239 | +# 2: Evaluate the decorator-maker arguments (if any) |
| 240 | +# 3: Call the decorator-maker to make a decorator |
| 241 | +# 4: Call the decorator |
| 242 | +# |
| 243 | +# When there are multiple decorators, these steps should be |
| 244 | +# performed in the above order for each decorator, but we should |
| 245 | +# iterate through the decorators in the reverse of the order they |
| 246 | +# appear in the source. |
| 247 | +# FIXME class decorator |
| 248 | +# actions = [] |
| 249 | +# |
| 250 | +# def make_decorator(tag): |
| 251 | +# actions.append('makedec' + tag) |
| 252 | +# def decorate(func): |
| 253 | +# actions.append('calldec' + tag) |
| 254 | +# return func |
| 255 | +# return decorate |
| 256 | +# |
| 257 | +# class NameLookupTracer (object): |
| 258 | +# def __init__(self, index): |
| 259 | +# self.index = index |
| 260 | +# |
| 261 | +# def __getattr__(self, fname): |
| 262 | +# if fname == 'make_decorator': |
| 263 | +# opname, res = ('evalname', make_decorator) |
| 264 | +# elif fname == 'arg': |
| 265 | +# opname, res = ('evalargs', str(self.index)) |
| 266 | +# else: |
| 267 | +# assert False, "Unknown attrname %s" % fname |
| 268 | +# actions.append('%s%d' % (opname, self.index)) |
| 269 | +# return res |
| 270 | +# |
| 271 | +# c1, c2, c3 = map(NameLookupTracer, [ 1, 2, 3 ]) |
| 272 | +# |
| 273 | +# expected_actions = [ 'evalname1', 'evalargs1', 'makedec1', |
| 274 | +# 'evalname2', 'evalargs2', 'makedec2', |
| 275 | +# 'evalname3', 'evalargs3', 'makedec3', |
| 276 | +# 'calldec3', 'calldec2', 'calldec1' ] |
| 277 | +# |
| 278 | +# actions = [] |
| 279 | +# @c1.make_decorator(c1.arg) |
| 280 | +# @c2.make_decorator(c2.arg) |
| 281 | +# @c3.make_decorator(c3.arg) |
| 282 | +# def foo(): return 42 |
| 283 | +# self.assertEqual(foo(), 42) |
| 284 | +# |
| 285 | +# self.assertEqual(actions, expected_actions) |
| 286 | +# |
| 287 | +# # Test the equivalence claim in chapter 7 of the reference manual. |
| 288 | +# # |
| 289 | +# actions = [] |
| 290 | +# def bar(): return 42 |
| 291 | +# bar = c1.make_decorator(c1.arg)(c2.make_decorator(c2.arg)(c3.make_decorator(c3.arg)(bar))) |
| 292 | +# self.assertEqual(bar(), 42) |
| 293 | +# self.assertEqual(actions, expected_actions) |
| 294 | + |
| 295 | +doc="test_simple" |
| 296 | +def plain(x): |
| 297 | + x.extra = 'Hello' |
| 298 | + return x |
| 299 | +@plain |
| 300 | +class C(object): pass |
| 301 | +self.assertEqual(C.extra, 'Hello') |
| 302 | + |
| 303 | +doc="test_double" |
| 304 | +def ten(x): |
| 305 | + x.extra = 10 |
| 306 | + return x |
| 307 | +def add_five(x): |
| 308 | + x.extra += 5 |
| 309 | + return x |
| 310 | + |
| 311 | +@add_five |
| 312 | +@ten |
| 313 | +class C(object): pass |
| 314 | +self.assertEqual(C.extra, 15) |
| 315 | + |
| 316 | +doc="test_order" |
| 317 | +def applied_first(x): |
| 318 | + x.extra = 'first' |
| 319 | + return x |
| 320 | +def applied_second(x): |
| 321 | + x.extra = 'second' |
| 322 | + return x |
| 323 | +@applied_second |
| 324 | +@applied_first |
| 325 | +class C(object): pass |
| 326 | +self.assertEqual(C.extra, 'second') |
| 327 | +doc="finished" |
0 commit comments