blob: a3beb567d3050d8666a667405c2c9fda7ff031f2 (
plain)
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
94
95
96
97
98
99
|
import inspect
import sys
import unittest
from pydevd_save_locals import save_locals
def use_save_locals(name, value):
"""
Attempt to set the local of the given name to value, using locals_to_fast.
"""
frame = inspect.currentframe().f_back
locals_dict = frame.f_locals
locals_dict[name] = value
save_locals(frame)
def check_method(fn):
"""
A harness for testing methods that attempt to modify the values of locals on the stack.
"""
x = 1
# The method 'fn' should attempt to set x = 2 in the current frame.
fn('x', 2)
return x
class TestSetLocals(unittest.TestCase):
"""
Test setting locals in one function from another function using several approaches.
"""
def test_set_locals_using_save_locals(self):
x = check_method(use_save_locals)
self.assertEqual(x, 2) # Expected to succeed
def test_frame_simple_change(self):
frame = sys._getframe()
a = 20
frame.f_locals['a'] = 50
save_locals(frame)
self.assertEquals(50, a)
def test_frame_co_freevars(self):
outer_var = 20
def func():
frame = sys._getframe()
frame.f_locals['outer_var'] = 50
save_locals(frame)
self.assertEquals(50, outer_var)
func()
def test_frame_co_cellvars(self):
def check_co_vars(a):
frame = sys._getframe()
def function2():
print(a)
assert 'a' in frame.f_code.co_cellvars
frame = sys._getframe()
frame.f_locals['a'] = 50
save_locals(frame)
self.assertEquals(50, a)
check_co_vars(1)
def test_frame_change_in_inner_frame(self):
def change(f):
self.assert_(f is not sys._getframe())
f.f_locals['a']= 50
save_locals(f)
frame = sys._getframe()
a = 20
change(frame)
self.assertEquals(50, a)
if __name__ == '__main__':
suite = unittest.TestSuite()
# suite.addTest(TestSetLocals('test_set_locals_using_dict'))
# #suite.addTest(Test('testCase10a'))
# unittest.TextTestRunner(verbosity=3).run(suite)
suite = unittest.makeSuite(TestSetLocals)
unittest.TextTestRunner(verbosity=3).run(suite)
|