-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtest_deco.py
93 lines (75 loc) · 2.3 KB
/
test_deco.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import unittest
import deco
class _TestException(Exception):
pass
@deco.persistent_locals
def _globalfunc(x):
z = 2*x
return z
_a = 2
@deco.persistent_locals
def _globaldependent(x):
z = x + _a
return z
@deco.persistent_locals
def _toberemoved(x):
z = 2*x
return z
class TestPersistLocals(unittest.TestCase):
def test_outer_scope(self):
_globalfunc(2)
self.assertEqual(_globalfunc.locals['x'], 2)
self.assertEqual(_globalfunc.locals['z'], 4)
def test_global_name_removed(self):
global _toberemoved
f = _toberemoved
f(2) # should pass
del _toberemoved
f(2) # might fail if 'f' looks for a global name '_toberemoved'
def test_globals_are_flexible(self):
global _a
self.assertEqual(_globaldependent(2), 4)
_a = 3
self.assertEqual(_globaldependent(2), 5)
def test_inner_scope(self):
@deco.persistent_locals
def is_sum_lt_prod(a,b,c):
sum = a+b+c
prod = a*b*c
return sum<prod
self.assertEqual(is_sum_lt_prod.locals, {})
is_sum_lt_prod(2,3,4)
self.assertEqual(set(is_sum_lt_prod.locals.keys()),
set(['a','b','c','sum','prod']))
self.assertEqual(is_sum_lt_prod.locals['sum'], 2+3+4)
self.assertEqual(is_sum_lt_prod.locals['prod'], 2*3*4)
def test_args(self):
@deco.persistent_locals
def f(x, *args):
return x, args
x, args = f(2,3,4)
self.assertEqual(x, 2)
self.assertEqual(args, (3,4))
self.assertEqual(f.locals['x'], 2)
self.assertEqual(f.locals['args'], (3,4))
def test_exception(self):
@deco.persistent_locals
def f(x):
y = 3
raise _TestException
z = 4 # this local variable is never initialized
self.assertRaises(_TestException, f, 0)
self.assertEqual(f.locals, {'x': 0, 'y': 3})
def test_late_return(self):
def g(a):
return a
@deco.persistent_locals
def f(x):
try:
return x
finally:
g(1)
f(0)
self.assertEqual(f.locals, {'x': 0, 'g': g})
if __name__ == '__main__':
unittest.main()