-
Notifications
You must be signed in to change notification settings - Fork 227
/
Copy pathtest_exec.py
384 lines (288 loc) · 9.22 KB
/
test_exec.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
##
## to test how exec related to globals/locals
##
import os
from iptest import IronPythonTestCase, is_cli, run_test
tc = IronPythonTestCase('__init__')
tc.setUp()
def _contains(large, small):
for (key, value) in small.items():
tc.assertEqual(large[key], value)
def _not_contains(dict, *keylist):
for key in keylist:
tc.assertFalse(dict.has_key(key))
## exec without in something
x = 1
y = "hello"
_contains(globals(), {"x":1, "y":"hello"})
_contains(locals(), {"x":1, "y":"hello"})
exec "x, y"
_contains(globals(), {"x":1, "y":"hello"})
_contains(locals(), {"x":1, "y":"hello"})
## exec with custom globals
# -- use global x, y; assign
g1 = {'x':2, 'y':'world'}
exec "global x; x, y; x = 4" in g1
_contains(globals(), {"x":1, "y":"hello"})
_contains(locals(), {"x":1, "y":"hello"})
_contains(g1, {"x":4, "y":"world"})
exec "global x; x, y; x = x + 4" in g1
_contains(g1, {"x":8})
# -- declare global
exec "global z" in g1
_not_contains(globals(), 'z')
_not_contains(locals(), 'z')
_not_contains(g1, 'z')
# -- new global
exec "global z; z = -1" in g1
_not_contains(globals(), 'z')
_not_contains(locals(), 'z')
_contains(g1, {'z':-1})
# y is missing in g2
g2 = {'x':3}
try:
exec "x, y" in g2
except NameError: pass
else: tc.assertTrue(False, "should throw NameError exception")
exec "y = 'ironpython'" in g2
_contains(g2, {"x":3, "y":"ironpython"})
_contains(globals(), {"y":"hello"})
_contains(locals(), {"y":"hello"})
## exec with custom globals, locals
g = {'x': -1, 'y': 'python' }
l = {}
# use global
exec "if x != -1: throw" in g, l
exec "if y != 'python': throw" in g, l
_not_contains(l, 'x', 'y')
# new local
exec "x = 20; z = 2" in g, l
_contains(g, {"x":-1, "y":"python"})
_contains(l, {"x":20, "z":2})
# changes
exec "global y; y = y.upper(); z = -2" in g, l
_contains(g, {'x': -1, 'y': 'PYTHON'})
_contains(l, {'x': 20, 'z': -2})
# new global
exec "global w; w = -2" in g, l
_contains(g, {'x': -1, 'y': 'PYTHON', 'w': -2})
_contains(l, {'x': 20, 'z': -2})
# x in both g and l; use it
exec "global x; x = x - 1" in g, l
_contains(g, {'x': -2, 'y': 'PYTHON', 'w': -2})
_contains(l, {'x': 20, 'z': -2})
exec "x = x + 1" in g, l
_contains(g, {'x': -2, 'y': 'PYTHON', 'w': -2})
_contains(l, {'x': 21, 'z': -2})
## Inside Function: same as last part of previous checks
def InsideFunc():
g = {'x': -1, 'y': 'python' }
l = {}
# use global
exec "if x != -1: throw" in g, l
exec "if y != 'python': throw" in g, l
_not_contains(l, 'x', 'y')
# new local
exec "x = 20; z = 2" in g, l
_contains(g, {"x":-1, "y":"python"})
_contains(l, {"x":20, "z":2})
# changes
exec "global y; y = y.upper(); z = -2" in g, l
_contains(g, {'x': -1, 'y': 'PYTHON'})
_contains(l, {'x': 20, 'z': -2})
# new global
exec "global w; w = -2" in g, l
_contains(g, {'x': -1, 'y': 'PYTHON', 'w': -2})
_contains(l, {'x': 20, 'z': -2})
# x in both g and l; use it
exec "global x; x = x - 1" in g, l
_contains(g, {'x': -2, 'y': 'PYTHON', 'w': -2})
_contains(l, {'x': 20, 'z': -2})
exec "x = x + 1" in g, l
_contains(g, {'x': -2, 'y': 'PYTHON', 'w': -2})
_contains(l, {'x': 21, 'z': -2})
InsideFunc()
unique_global_name = 987654321
class C:
exec 'a = unique_global_name'
exec "if unique_global_name != 987654321: raise AssertionError('cannott see unique_global_name')"
tc.assertEqual(C.a, 987654321)
def f():
exec "if unique_global_name != 987654321: raise AssertionError('cannot see unique_global_name')"
def g(): exec "if unique_global_name != 987654321: raise AssertionError('cannot see unique_global_name')"
g()
f()
# exec tests
# verify passing a bad value throws...
try:
exec(3)
except TypeError: pass
else: tc.fail("Should already thrown (3)")
# verify exec(...) takes a code object
codeobj = compile ('1+1', '<compiled code>', 'exec')
exec(codeobj)
# verify exec(...) takes a file...
fn = os.path.join(tc.temporary_dir, 'testfile.tmp')
tc.write_to_file(fn, "x = [1,2,3,4,5]\nx.reverse()\ntc.assertEquals(x, [5,4,3,2,1])\n")
f = file(fn, "r")
exec(f)
tc.assertEquals(x, [5,4,3,2,1])
f.close()
# and now verify it'll take a .NET Stream as well...
if is_cli:
import System
f = System.IO.FileStream(fn, System.IO.FileMode.Open)
exec(f)
f.Close()
# verify that exec'd code has access to existing locals
qqq = 3
exec('qqq+1')
# and not to *non*-existing locals..
del qqq
try: exec('qqq+1')
except NameError: pass
else: tc.fail("should already thrown (qqq+1)")
exec('qqq+1', {'qqq':99})
# Test passing alternative local and global scopes to exec.
# Explicit global and local scope.
# Functional form of exec.
myloc = {}
myglob = {}
exec("a = 1; global b; b = 1", myglob, myloc)
tc.assertTrue("a" in myloc)
tc.assertTrue("a" not in myglob)
tc.assertTrue("b" in myglob)
tc.assertTrue("b" not in myloc)
# Statement form of exec.
myloc = {}
myglob = {}
exec "a = 1; global b; b = 1" in myglob, myloc
tc.assertTrue("a" in myloc)
tc.assertTrue("a" not in myglob)
tc.assertTrue("b" in myglob)
tc.assertTrue("b" not in myloc)
# Explicit global scope implies the same local scope.
# Functional form of exec.
myloc = {}
myglob = {}
exec("a = 1; global b; b = 1", myglob)
tc.assertTrue("a" in myglob)
tc.assertTrue("a" not in myloc)
tc.assertTrue("b" in myglob)
tc.assertTrue("b" not in myloc)
# Statement form of exec.
myloc = {}
myglob = {}
exec "a = 1; global b; b = 1" in myglob
tc.assertTrue("a" in myglob)
tc.assertTrue("a" not in myloc)
tc.assertTrue("b" in myglob)
tc.assertTrue("b" not in myloc)
# Testing interesting exec cases
x = "global_x"
def TryExecG(what, glob):
exec what in glob
def TryExecGL(what, glob, loc):
exec what in glob, loc
class Nothing:
pass
def MakeDict(value):
return { 'AreEqual' : tc.assertEqual, 'AssertError' : tc.assertRaises, 'x' : value, 'str' : str }
class Mapping:
def __init__(self, value = None):
self.values = MakeDict(value)
def __getitem__(self, item):
return self.values[item]
class MyDict(dict):
def __init__(self, value = None):
self.values = MakeDict(value)
def __getitem__(self, item):
return self.values[item]
TryExecG("tc.assertEqual(x, 'global_x')", None)
TryExecGL("tc.assertEqual(x, 'global_x')", None, None)
tc.assertRaises(TypeError, TryExecG, "print x", Nothing())
tc.assertRaises(TypeError, TryExecGL, "print x", Nothing(), None)
tc.assertRaises(TypeError, TryExecG, "print x", Mapping())
tc.assertRaises(TypeError, TryExecGL, "print x", Mapping(), None)
TryExecG("AreEqual(x, 17)", MakeDict(17))
TryExecGL("AreEqual(x, 19)", MakeDict(19), None)
#TryExecG("AreEqual(x, 23)", MyDict(23))
#TryExecGL("AreEqual(x, 29)", MyDict(29), None)
TryExecGL("AreEqual(x, 31)", None, MakeDict(31))
tc.assertRaises(TypeError, TryExecGL, "print x", None, Nothing())
TryExecGL("AreEqual(x, 37)", None, Mapping(37))
#TryExecGL("AreEqual(x, 41)", None, MyDict(41))
# Evaluating the "in" expressions in exec statement
def f(l):
l.append("called f")
return {}
l = []
exec "pass" in f(l)
tc.assertEqual(l, ["called f"])
def g(l):
l.append("called g")
return {}
l = []
exec "pass" in f(l), g(l)
tc.assertEqual(l, ["called f", "called g"])
class ExecTestCase(IronPythonTestCase):
# testing exec accepts \n eolns only
def test_eolns(self):
def f1(sep): exec 'x = 2$y=4$'.replace('$', sep)
def f2(sep): exec '''x = 3$y = 5$'''.replace('$', sep)
def f3(sep): exec "exec '''x = 3$y = 5$'''".replace('$', sep)
for x in [f1, f2, f3]:
if is_cli: #http://ironpython.codeplex.com/workitem/27991
self.assertRaises(SyntaxError, x, '\r\n')
self.assertRaises(SyntaxError, x, '\r')
else:
temp = x('\r\n')
temp = x('\r')
self.assertRaises(SyntaxError, x, '\a')
x('\n')
def test_tuple_syntax(self):
x = 6
g = { 'x' : 3 }
exec('x = 4', g)
self.assertEquals(g['x'], 4)
self.assertEquals(x, 6)
l = { 'x' : 5 }
exec('a = 5', g, l)
self.assertEquals(l['a'], 5)
self.assertEquals(g['x'], 4)
self.assertEquals(l['x'], 5)
self.assertEquals(x, 6)
exec('x = 100')
self.assertEqual(x, 100)
exec('x = 20') in g, l
self.assertEqual(g['x'], 4)
self.assertEqual(l['x'], 20)
def test1():
exec('', {}, {}, 1)
self.assertRaises(TypeError, test1)
def test2():
exec('', {}) in {}
self.assertRaises(TypeError, test2)
def test_set_builtins(self):
g = {}
exec("", g, None)
self.assertTrue('__builtins__' in g.keys())
def test_builtins_type(self):
x, y = {}, {}
exec 'abc = 42' in x, y
self.assertEqual(type(x['__builtins__']), dict)
def test_exec_locals(self):
tc = self
exec """
def body():
tc.assertEqual('anythingatall' in locals(), False)
body()
foozbab = 2
def body():
tc.assertEqual('foozbab' in locals(), False)
body()
"""
run_test(__name__)