blob: 5f91d0d6387cde7e1489501248492ab4d97eabe3 [file] [log] [blame]
Antoine Pitrouab4a6912014-05-23 11:46:03 +02001import math
Raymond Hettinger8a99b502003-06-23 13:36:57 +00002import unittest
Raymond Hettinger8a99b502003-06-23 13:36:57 +00003import sys
Georg Brandlfc8eef32008-03-28 12:11:56 +00004import _ast
Raymond Hettinger8a99b502003-06-23 13:36:57 +00005from test import test_support
Florent Xiclunaaf617192010-03-21 11:03:21 +00006import textwrap
Peter Schneider-Kampfdee0f02000-07-25 22:15:45 +00007
Raymond Hettinger8a99b502003-06-23 13:36:57 +00008class TestSpecifics(unittest.TestCase):
Jeremy Hylton778e2652001-11-09 19:50:08 +00009
Benjamin Petersone36199b2009-11-12 23:39:44 +000010 def test_no_ending_newline(self):
11 compile("hi", "<test>", "exec")
12 compile("hi\r", "<test>", "exec")
13
14 def test_empty(self):
15 compile("", "<test>", "exec")
16
17 def test_other_newlines(self):
18 compile("\r\n", "<test>", "exec")
19 compile("\r", "<test>", "exec")
20 compile("hi\r\nstuff\r\ndef f():\n pass\r", "<test>", "exec")
21 compile("this_is\rreally_old_mac\rdef f():\n pass", "<test>", "exec")
22
Raymond Hettinger8a99b502003-06-23 13:36:57 +000023 def test_debug_assignment(self):
24 # catch assignments to __debug__
25 self.assertRaises(SyntaxError, compile, '__debug__ = 1', '?', 'single')
26 import __builtin__
27 prev = __builtin__.__debug__
28 setattr(__builtin__, '__debug__', 'sure')
29 setattr(__builtin__, '__debug__', prev)
Jeremy Hylton778e2652001-11-09 19:50:08 +000030
Raymond Hettinger8a99b502003-06-23 13:36:57 +000031 def test_argument_handling(self):
32 # detect duplicate positional and keyword arguments
33 self.assertRaises(SyntaxError, eval, 'lambda a,a:0')
34 self.assertRaises(SyntaxError, eval, 'lambda a,a=1:0')
35 self.assertRaises(SyntaxError, eval, 'lambda a=1,a=1:0')
36 try:
37 exec 'def f(a, a): pass'
38 self.fail("duplicate arguments")
39 except SyntaxError:
40 pass
41 try:
42 exec 'def f(a = 0, a = 1): pass'
43 self.fail("duplicate keyword arguments")
44 except SyntaxError:
45 pass
46 try:
47 exec 'def f(a): global a; a = 1'
48 self.fail("variable is global and local")
49 except SyntaxError:
50 pass
Jeremy Hylton778e2652001-11-09 19:50:08 +000051
Raymond Hettinger8a99b502003-06-23 13:36:57 +000052 def test_syntax_error(self):
53 self.assertRaises(SyntaxError, compile, "1+*3", "filename", "exec")
Peter Schneider-Kampfdee0f02000-07-25 22:15:45 +000054
Georg Brandle06cf452007-06-07 13:23:24 +000055 def test_none_keyword_arg(self):
56 self.assertRaises(SyntaxError, compile, "f(None=1)", "<string>", "exec")
57
Raymond Hettinger8a99b502003-06-23 13:36:57 +000058 def test_duplicate_global_local(self):
59 try:
60 exec 'def f(a): global a; a = 1'
61 self.fail("variable is global and local")
62 except SyntaxError:
63 pass
Peter Schneider-Kampfdee0f02000-07-25 22:15:45 +000064
Mark Dickinson16587972012-11-25 13:25:57 +000065 def test_exec_functional_style(self):
66 # Exec'ing a tuple of length 2 works.
67 g = {'b': 2}
68 exec("a = b + 1", g)
69 self.assertEqual(g['a'], 3)
70
71 # As does exec'ing a tuple of length 3.
72 l = {'b': 3}
73 g = {'b': 5, 'c': 7}
74 exec("a = b + c", g, l)
75 self.assertNotIn('a', g)
76 self.assertEqual(l['a'], 10)
77
78 # Tuples not of length 2 or 3 are invalid.
79 with self.assertRaises(TypeError):
80 exec("a = b + 1",)
81
82 with self.assertRaises(TypeError):
83 exec("a = b + 1", {}, {}, {})
84
85 # Can't mix and match the two calling forms.
86 g = {'a': 3, 'b': 4}
87 l = {}
88 with self.assertRaises(TypeError):
89 exec("a = b + 1", g) in g
90 with self.assertRaises(TypeError):
91 exec("a = b + 1", g, l) in g, l
92
Robert Jordensaf09c772014-07-29 17:24:24 +020093 def test_nested_qualified_exec(self):
94 # Can use qualified exec in nested functions.
95 code = ["""
96def g():
97 def f():
98 if True:
99 exec "" in {}, {}
100 """, """
101def g():
102 def f():
103 if True:
104 exec("", {}, {})
105 """]
106 for c in code:
107 compile(c, "<code>", "exec")
108
Raymond Hettinger66bd2332004-08-02 08:30:07 +0000109 def test_exec_with_general_mapping_for_locals(self):
110
111 class M:
112 "Test mapping interface versus possible calls from eval()."
113 def __getitem__(self, key):
114 if key == 'a':
115 return 12
116 raise KeyError
117 def __setitem__(self, key, value):
118 self.results = (key, value)
119 def keys(self):
120 return list('xyz')
121
122 m = M()
123 g = globals()
124 exec 'z = a' in g, m
125 self.assertEqual(m.results, ('z', 12))
126 try:
127 exec 'z = b' in g, m
128 except NameError:
129 pass
130 else:
131 self.fail('Did not detect a KeyError')
132 exec 'z = dir()' in g, m
133 self.assertEqual(m.results, ('z', list('xyz')))
134 exec 'z = globals()' in g, m
135 self.assertEqual(m.results, ('z', g))
136 exec 'z = locals()' in g, m
137 self.assertEqual(m.results, ('z', m))
138 try:
139 exec 'z = b' in m
140 except TypeError:
141 pass
142 else:
143 self.fail('Did not validate globals as a real dict')
144
145 class A:
146 "Non-mapping"
147 pass
148 m = A()
149 try:
150 exec 'z = a' in g, m
151 except TypeError:
152 pass
153 else:
154 self.fail('Did not validate locals as a mapping')
155
156 # Verify that dict subclasses work as well
157 class D(dict):
158 def __getitem__(self, key):
159 if key == 'a':
160 return 12
161 return dict.__getitem__(self, key)
162 d = D()
163 exec 'z = a' in g, d
164 self.assertEqual(d['z'], 12)
165
Neal Norwitz6ab080c2005-10-24 00:08:10 +0000166 def test_extended_arg(self):
167 longexpr = 'x = x or ' + '-x' * 2500
168 code = '''
169def f(x):
170 %s
171 %s
172 %s
173 %s
174 %s
175 %s
176 %s
177 %s
178 %s
179 %s
180 # the expressions above have no effect, x == argument
181 while x:
182 x -= 1
183 # EXTENDED_ARG/JUMP_ABSOLUTE here
184 return x
185''' % ((longexpr,)*10)
186 exec code
187 self.assertEqual(f(5), 0)
188
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000189 def test_complex_args(self):
Senthil Kumarance8e33a2010-01-08 19:04:16 +0000190
Florent Xiclunaaf617192010-03-21 11:03:21 +0000191 with test_support.check_py3k_warnings(
192 ("tuple parameter unpacking has been removed", SyntaxWarning)):
193 exec textwrap.dedent('''
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000194 def comp_args((a, b)):
195 return a,b
196 self.assertEqual(comp_args((1, 2)), (1, 2))
Thomas Heller6b17abf2002-07-09 09:23:27 +0000197
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000198 def comp_args((a, b)=(3, 4)):
199 return a, b
200 self.assertEqual(comp_args((1, 2)), (1, 2))
201 self.assertEqual(comp_args(), (3, 4))
Jeremy Hylton047e2c92001-01-19 03:25:56 +0000202
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000203 def comp_args(a, (b, c)):
204 return a, b, c
205 self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3))
Jeremy Hylton121b6eb2001-02-19 23:53:42 +0000206
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000207 def comp_args(a=2, (b, c)=(3, 4)):
208 return a, b, c
209 self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3))
210 self.assertEqual(comp_args(), (2, 3, 4))
Florent Xiclunaaf617192010-03-21 11:03:21 +0000211 ''')
Jeremy Hylton121b6eb2001-02-19 23:53:42 +0000212
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000213 def test_argument_order(self):
214 try:
215 exec 'def f(a=1, (b, c)): pass'
216 self.fail("non-default args after default")
217 except SyntaxError:
218 pass
Jeremy Hylton121b6eb2001-02-19 23:53:42 +0000219
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000220 def test_float_literals(self):
221 # testing bad float literals
222 self.assertRaises(SyntaxError, eval, "2e")
223 self.assertRaises(SyntaxError, eval, "2.0e+")
224 self.assertRaises(SyntaxError, eval, "1e-")
225 self.assertRaises(SyntaxError, eval, "3-4e/21")
Jeremy Hylton121b6eb2001-02-19 23:53:42 +0000226
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000227 def test_indentation(self):
228 # testing compile() of indented block w/o trailing newline"
229 s = """
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000230if 1:
231 if 2:
232 pass"""
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000233 compile(s, "<string>", "exec")
234
Neal Norwitzed657552006-07-10 00:04:44 +0000235 # This test is probably specific to CPython and may not generalize
236 # to other implementations. We are trying to ensure that when
237 # the first line of code starts after 256, correct line numbers
238 # in tracebacks are still produced.
239 def test_leading_newlines(self):
240 s256 = "".join(["\n"] * 256 + ["spam"])
241 co = compile(s256, 'fn', 'exec')
242 self.assertEqual(co.co_firstlineno, 257)
243 self.assertEqual(co.co_lnotab, '')
244
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000245 def test_literals_with_leading_zeroes(self):
246 for arg in ["077787", "0xj", "0x.", "0e", "090000000000000",
Eric Smith9ff19b52008-03-17 17:32:20 +0000247 "080000000000000", "000000000000009", "000000000000008",
248 "0b42", "0BADCAFE", "0o123456789", "0b1.1", "0o4.2",
Amaury Forgeot d'Arc52167212008-04-24 18:07:05 +0000249 "0b101j2", "0o153j2", "0b100e1", "0o777e1", "0o8", "0o78"]:
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000250 self.assertRaises(SyntaxError, eval, arg)
251
252 self.assertEqual(eval("0777"), 511)
253 self.assertEqual(eval("0777L"), 511)
254 self.assertEqual(eval("000777"), 511)
255 self.assertEqual(eval("0xff"), 255)
256 self.assertEqual(eval("0xffL"), 255)
257 self.assertEqual(eval("0XfF"), 255)
258 self.assertEqual(eval("0777."), 777)
259 self.assertEqual(eval("0777.0"), 777)
260 self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777)
261 self.assertEqual(eval("0777e1"), 7770)
262 self.assertEqual(eval("0e0"), 0)
263 self.assertEqual(eval("0000E-012"), 0)
264 self.assertEqual(eval("09.5"), 9.5)
265 self.assertEqual(eval("0777j"), 777j)
266 self.assertEqual(eval("00j"), 0j)
267 self.assertEqual(eval("00.0"), 0)
268 self.assertEqual(eval("0e3"), 0)
269 self.assertEqual(eval("090000000000000."), 90000000000000.)
270 self.assertEqual(eval("090000000000000.0000000000000000000000"), 90000000000000.)
271 self.assertEqual(eval("090000000000000e0"), 90000000000000.)
272 self.assertEqual(eval("090000000000000e-0"), 90000000000000.)
273 self.assertEqual(eval("090000000000000j"), 90000000000000j)
274 self.assertEqual(eval("000000000000007"), 7)
275 self.assertEqual(eval("000000000000008."), 8.)
276 self.assertEqual(eval("000000000000009."), 9.)
Eric Smith9ff19b52008-03-17 17:32:20 +0000277 self.assertEqual(eval("0b101010"), 42)
278 self.assertEqual(eval("-0b000000000010"), -2)
279 self.assertEqual(eval("0o777"), 511)
280 self.assertEqual(eval("-0o0000010"), -8)
Mark Dickinson64b7e502008-07-16 09:40:03 +0000281 self.assertEqual(eval("020000000000.0"), 20000000000.0)
282 self.assertEqual(eval("037777777777e0"), 37777777777.0)
283 self.assertEqual(eval("01000000000000000000000.0"),
284 1000000000000000000000.0)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000285
286 def test_unary_minus(self):
287 # Verify treatment of unary minus on negative numbers SF bug #660455
Guido van Rossum6c9e1302003-11-29 23:52:13 +0000288 if sys.maxint == 2147483647:
289 # 32-bit machine
290 all_one_bits = '0xffffffff'
291 self.assertEqual(eval(all_one_bits), 4294967295L)
292 self.assertEqual(eval("-" + all_one_bits), -4294967295L)
293 elif sys.maxint == 9223372036854775807:
294 # 64-bit machine
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000295 all_one_bits = '0xffffffffffffffff'
Guido van Rossum6c9e1302003-11-29 23:52:13 +0000296 self.assertEqual(eval(all_one_bits), 18446744073709551615L)
297 self.assertEqual(eval("-" + all_one_bits), -18446744073709551615L)
298 else:
299 self.fail("How many bits *does* this machine have???")
Ezio Melotti24b07bc2011-03-15 18:55:01 +0200300 # Verify treatment of constant folding on -(sys.maxint+1)
Neil Schemenauer6ec6ab02006-07-09 21:19:29 +0000301 # i.e. -2147483648 on 32 bit platforms. Should return int, not long.
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000302 self.assertIsInstance(eval("%s" % (-sys.maxint - 1)), int)
303 self.assertIsInstance(eval("%s" % (-sys.maxint - 2)), long)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000304
Neal Norwitz28746ab2006-07-09 22:14:42 +0000305 if sys.maxint == 9223372036854775807:
306 def test_32_63_bit_values(self):
307 a = +4294967296 # 1 << 32
308 b = -4294967296 # 1 << 32
309 c = +281474976710656 # 1 << 48
310 d = -281474976710656 # 1 << 48
311 e = +4611686018427387904 # 1 << 62
312 f = -4611686018427387904 # 1 << 62
313 g = +9223372036854775807 # 1 << 63 - 1
314 h = -9223372036854775807 # 1 << 63 - 1
315
316 for variable in self.test_32_63_bit_values.func_code.co_consts:
317 if variable is not None:
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000318 self.assertIsInstance(variable, int)
Neal Norwitz28746ab2006-07-09 22:14:42 +0000319
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000320 def test_sequence_unpacking_error(self):
321 # Verify sequence packing/unpacking with "or". SF bug #757818
322 i,j = (1, -1) or (-1, 1)
323 self.assertEqual(i, 1)
324 self.assertEqual(j, -1)
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000325
Raymond Hettinger11a70c72004-07-17 21:46:25 +0000326 def test_none_assignment(self):
327 stmts = [
328 'None = 0',
329 'None += 0',
330 '__builtins__.None = 0',
331 'def None(): pass',
332 'class None: pass',
333 '(a, None) = 0, 0',
334 'for None in range(10): pass',
335 'def f(None): pass',
Benjamin Peterson565e1b62009-06-13 03:46:30 +0000336 'import None',
337 'import x as None',
338 'from x import None',
339 'from x import y as None'
Raymond Hettinger11a70c72004-07-17 21:46:25 +0000340 ]
341 for stmt in stmts:
342 stmt += "\n"
343 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'single')
344 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
Benjamin Peterson565e1b62009-06-13 03:46:30 +0000345 # This is ok.
346 compile("from None import x", "tmp", "exec")
Benjamin Petersond1f5a592009-06-13 13:06:21 +0000347 compile("from x import None as y", "tmp", "exec")
348 compile("import None as x", "tmp", "exec")
Tim Petersd507dab2001-08-30 20:51:59 +0000349
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000350 def test_import(self):
351 succeed = [
352 'import sys',
353 'import os, sys',
Neal Norwitzfb48afa2006-07-08 05:31:37 +0000354 'import os as bar',
355 'import os.path as bar',
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000356 'from __future__ import nested_scopes, generators',
357 'from __future__ import (nested_scopes,\ngenerators)',
358 'from __future__ import (nested_scopes,\ngenerators,)',
359 'from sys import stdin, stderr, stdout',
360 'from sys import (stdin, stderr,\nstdout)',
361 'from sys import (stdin, stderr,\nstdout,)',
362 'from sys import (stdin\n, stderr, stdout)',
363 'from sys import (stdin\n, stderr, stdout,)',
364 'from sys import stdin as si, stdout as so, stderr as se',
365 'from sys import (stdin as si, stdout as so, stderr as se)',
366 'from sys import (stdin as si, stdout as so, stderr as se,)',
367 ]
368 fail = [
369 'import (os, sys)',
370 'import (os), (sys)',
371 'import ((os), (sys))',
372 'import (sys',
373 'import sys)',
374 'import (os,)',
Neal Norwitzfb48afa2006-07-08 05:31:37 +0000375 'import os As bar',
376 'import os.path a bar',
Georg Brandl9575fb22006-07-08 12:15:27 +0000377 'from sys import stdin As stdout',
378 'from sys import stdin a stdout',
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000379 'from (sys) import stdin',
380 'from __future__ import (nested_scopes',
381 'from __future__ import nested_scopes)',
382 'from __future__ import nested_scopes,\ngenerators',
383 'from sys import (stdin',
384 'from sys import stdin)',
385 'from sys import stdin, stdout,\nstderr',
386 'from sys import stdin si',
387 'from sys import stdin,'
388 'from sys import (*)',
389 'from sys import (stdin,, stdout, stderr)',
390 'from sys import (stdin, stdout),',
391 ]
392 for stmt in succeed:
393 compile(stmt, 'tmp', 'exec')
394 for stmt in fail:
395 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
396
Raymond Hettinger9047c8f2004-10-24 00:10:06 +0000397 def test_for_distinct_code_objects(self):
398 # SF bug 1048870
399 def f():
400 f1 = lambda x=1: x
401 f2 = lambda x=2: x
402 return f1, f2
403 f1, f2 = f()
404 self.assertNotEqual(id(f1.func_code), id(f2.func_code))
405
Benjamin Peterson0dee9c12010-03-17 20:41:42 +0000406 def test_lambda_doc(self):
407 l = lambda: "foo"
408 self.assertIsNone(l.__doc__)
409
Neal Norwitze98ccf62006-03-23 05:39:47 +0000410 def test_unicode_encoding(self):
411 code = u"# -*- coding: utf-8 -*-\npass\n"
412 self.assertRaises(SyntaxError, compile, code, "tmp", "exec")
413
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000414 def test_subscripts(self):
415 # SF bug 1448804
416 # Class to make testing subscript results easy
417 class str_map(object):
418 def __init__(self):
419 self.data = {}
420 def __getitem__(self, key):
421 return self.data[str(key)]
422 def __setitem__(self, key, value):
423 self.data[str(key)] = value
424 def __delitem__(self, key):
425 del self.data[str(key)]
426 def __contains__(self, key):
427 return str(key) in self.data
428 d = str_map()
429 # Index
430 d[1] = 1
431 self.assertEqual(d[1], 1)
432 d[1] += 1
433 self.assertEqual(d[1], 2)
434 del d[1]
Ezio Melottiaa980582010-01-23 23:04:36 +0000435 self.assertNotIn(1, d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000436 # Tuple of indices
437 d[1, 1] = 1
438 self.assertEqual(d[1, 1], 1)
439 d[1, 1] += 1
440 self.assertEqual(d[1, 1], 2)
441 del d[1, 1]
Ezio Melottiaa980582010-01-23 23:04:36 +0000442 self.assertNotIn((1, 1), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000443 # Simple slice
444 d[1:2] = 1
445 self.assertEqual(d[1:2], 1)
446 d[1:2] += 1
447 self.assertEqual(d[1:2], 2)
448 del d[1:2]
Ezio Melottiaa980582010-01-23 23:04:36 +0000449 self.assertNotIn(slice(1, 2), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000450 # Tuple of simple slices
451 d[1:2, 1:2] = 1
452 self.assertEqual(d[1:2, 1:2], 1)
453 d[1:2, 1:2] += 1
454 self.assertEqual(d[1:2, 1:2], 2)
455 del d[1:2, 1:2]
Ezio Melottiaa980582010-01-23 23:04:36 +0000456 self.assertNotIn((slice(1, 2), slice(1, 2)), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000457 # Extended slice
458 d[1:2:3] = 1
459 self.assertEqual(d[1:2:3], 1)
460 d[1:2:3] += 1
461 self.assertEqual(d[1:2:3], 2)
462 del d[1:2:3]
Ezio Melottiaa980582010-01-23 23:04:36 +0000463 self.assertNotIn(slice(1, 2, 3), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000464 # Tuple of extended slices
465 d[1:2:3, 1:2:3] = 1
466 self.assertEqual(d[1:2:3, 1:2:3], 1)
467 d[1:2:3, 1:2:3] += 1
468 self.assertEqual(d[1:2:3, 1:2:3], 2)
469 del d[1:2:3, 1:2:3]
Ezio Melottiaa980582010-01-23 23:04:36 +0000470 self.assertNotIn((slice(1, 2, 3), slice(1, 2, 3)), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000471 # Ellipsis
472 d[...] = 1
473 self.assertEqual(d[...], 1)
474 d[...] += 1
475 self.assertEqual(d[...], 2)
476 del d[...]
Ezio Melottiaa980582010-01-23 23:04:36 +0000477 self.assertNotIn(Ellipsis, d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000478 # Tuple of Ellipses
479 d[..., ...] = 1
480 self.assertEqual(d[..., ...], 1)
481 d[..., ...] += 1
482 self.assertEqual(d[..., ...], 2)
483 del d[..., ...]
Ezio Melottiaa980582010-01-23 23:04:36 +0000484 self.assertNotIn((Ellipsis, Ellipsis), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000485
Jeremy Hylton37075c52007-02-27 01:01:59 +0000486 def test_mangling(self):
487 class A:
488 def f():
489 __mangled = 1
490 __not_mangled__ = 2
491 import __mangled_mod
492 import __package__.module
493
Ezio Melottiaa980582010-01-23 23:04:36 +0000494 self.assertIn("_A__mangled", A.f.func_code.co_varnames)
495 self.assertIn("__not_mangled__", A.f.func_code.co_varnames)
496 self.assertIn("_A__mangled_mod", A.f.func_code.co_varnames)
497 self.assertIn("__package__", A.f.func_code.co_varnames)
Jeremy Hylton37075c52007-02-27 01:01:59 +0000498
Georg Brandlfc8eef32008-03-28 12:11:56 +0000499 def test_compile_ast(self):
500 fname = __file__
501 if fname.lower().endswith(('pyc', 'pyo')):
502 fname = fname[:-1]
503 with open(fname, 'r') as f:
504 fcontents = f.read()
505 sample_code = [
506 ['<assign>', 'x = 5'],
507 ['<print1>', 'print 1'],
508 ['<printv>', 'print v'],
509 ['<printTrue>', 'print True'],
510 ['<printList>', 'print []'],
511 ['<ifblock>', """if True:\n pass\n"""],
512 ['<forblock>', """for n in [1, 2, 3]:\n print n\n"""],
513 ['<deffunc>', """def foo():\n pass\nfoo()\n"""],
514 [fname, fcontents],
515 ]
516
517 for fname, code in sample_code:
518 co1 = compile(code, '%s1' % fname, 'exec')
519 ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000520 self.assertTrue(type(ast) == _ast.Module)
Georg Brandlfc8eef32008-03-28 12:11:56 +0000521 co2 = compile(ast, '%s3' % fname, 'exec')
522 self.assertEqual(co1, co2)
Georg Brandlf2bfd542008-03-29 13:24:23 +0000523 # the code object's filename comes from the second compilation step
524 self.assertEqual(co2.co_filename, '%s3' % fname)
525
526 # raise exception when node type doesn't match with compile mode
527 co1 = compile('print 1', '<string>', 'exec', _ast.PyCF_ONLY_AST)
528 self.assertRaises(TypeError, compile, co1, '<ast>', 'eval')
529
530 # raise exception when node type is no start node
531 self.assertRaises(TypeError, compile, _ast.If(), '<ast>', 'exec')
532
533 # raise exception when node has invalid children
534 ast = _ast.Module()
535 ast.body = [_ast.BoolOp()]
536 self.assertRaises(TypeError, compile, ast, '<ast>', 'exec')
Georg Brandlfc8eef32008-03-28 12:11:56 +0000537
538
Antoine Pitrouab4a6912014-05-23 11:46:03 +0200539class TestStackSize(unittest.TestCase):
540 # These tests check that the computed stack size for a code object
541 # stays within reasonable bounds (see issue #21523 for an example
542 # dysfunction).
543 N = 100
544
545 def check_stack_size(self, code):
546 # To assert that the alleged stack size is not O(N), we
547 # check that it is smaller than log(N).
548 if isinstance(code, str):
549 code = compile(code, "<foo>", "single")
550 max_size = math.ceil(math.log(len(code.co_code)))
551 self.assertLessEqual(code.co_stacksize, max_size)
552
553 def test_and(self):
554 self.check_stack_size("x and " * self.N + "x")
555
556 def test_or(self):
557 self.check_stack_size("x or " * self.N + "x")
558
559 def test_and_or(self):
560 self.check_stack_size("x and x or " * self.N + "x")
561
562 def test_chained_comparison(self):
563 self.check_stack_size("x < " * self.N + "x")
564
565 def test_if_else(self):
566 self.check_stack_size("x if x else " * self.N + "x")
567
568 def test_binop(self):
569 self.check_stack_size("x + " * self.N + "x")
570
571 def test_func_and(self):
572 code = "def f(x):\n"
573 code += " x and x\n" * self.N
574 self.check_stack_size(code)
575
576
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000577def test_main():
Antoine Pitrouab4a6912014-05-23 11:46:03 +0200578 test_support.run_unittest(__name__)
Tim Petersd507dab2001-08-30 20:51:59 +0000579
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000580if __name__ == "__main__":
Antoine Pitrouab4a6912014-05-23 11:46:03 +0200581 unittest.main()