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