blob: ca396a974e1c669cf44c26b6d797d6b55c6ff2b9 [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("", {}, {})
Benjamin Peterson4f09e612014-08-09 19:39:50 -0700105 """, """
106def g():
107 def f():
108 if True:
109 exec("", {})
Robert Jordensaf09c772014-07-29 17:24:24 +0200110 """]
111 for c in code:
112 compile(c, "<code>", "exec")
113
Raymond Hettinger66bd2332004-08-02 08:30:07 +0000114 def test_exec_with_general_mapping_for_locals(self):
115
116 class M:
117 "Test mapping interface versus possible calls from eval()."
118 def __getitem__(self, key):
119 if key == 'a':
120 return 12
121 raise KeyError
122 def __setitem__(self, key, value):
123 self.results = (key, value)
124 def keys(self):
125 return list('xyz')
126
127 m = M()
128 g = globals()
129 exec 'z = a' in g, m
130 self.assertEqual(m.results, ('z', 12))
131 try:
132 exec 'z = b' in g, m
133 except NameError:
134 pass
135 else:
136 self.fail('Did not detect a KeyError')
137 exec 'z = dir()' in g, m
138 self.assertEqual(m.results, ('z', list('xyz')))
139 exec 'z = globals()' in g, m
140 self.assertEqual(m.results, ('z', g))
141 exec 'z = locals()' in g, m
142 self.assertEqual(m.results, ('z', m))
143 try:
144 exec 'z = b' in m
145 except TypeError:
146 pass
147 else:
148 self.fail('Did not validate globals as a real dict')
149
150 class A:
151 "Non-mapping"
152 pass
153 m = A()
154 try:
155 exec 'z = a' in g, m
156 except TypeError:
157 pass
158 else:
159 self.fail('Did not validate locals as a mapping')
160
161 # Verify that dict subclasses work as well
162 class D(dict):
163 def __getitem__(self, key):
164 if key == 'a':
165 return 12
166 return dict.__getitem__(self, key)
167 d = D()
168 exec 'z = a' in g, d
169 self.assertEqual(d['z'], 12)
170
Neal Norwitz6ab080c2005-10-24 00:08:10 +0000171 def test_extended_arg(self):
172 longexpr = 'x = x or ' + '-x' * 2500
173 code = '''
174def f(x):
175 %s
176 %s
177 %s
178 %s
179 %s
180 %s
181 %s
182 %s
183 %s
184 %s
185 # the expressions above have no effect, x == argument
186 while x:
187 x -= 1
188 # EXTENDED_ARG/JUMP_ABSOLUTE here
189 return x
190''' % ((longexpr,)*10)
191 exec code
192 self.assertEqual(f(5), 0)
193
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000194 def test_complex_args(self):
Senthil Kumarance8e33a2010-01-08 19:04:16 +0000195
Florent Xiclunaaf617192010-03-21 11:03:21 +0000196 with test_support.check_py3k_warnings(
197 ("tuple parameter unpacking has been removed", SyntaxWarning)):
198 exec textwrap.dedent('''
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000199 def comp_args((a, b)):
200 return a,b
201 self.assertEqual(comp_args((1, 2)), (1, 2))
Thomas Heller6b17abf2002-07-09 09:23:27 +0000202
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000203 def comp_args((a, b)=(3, 4)):
204 return a, b
205 self.assertEqual(comp_args((1, 2)), (1, 2))
206 self.assertEqual(comp_args(), (3, 4))
Jeremy Hylton047e2c92001-01-19 03:25:56 +0000207
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000208 def comp_args(a, (b, c)):
209 return a, b, c
210 self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3))
Jeremy Hylton121b6eb2001-02-19 23:53:42 +0000211
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000212 def comp_args(a=2, (b, c)=(3, 4)):
213 return a, b, c
214 self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3))
215 self.assertEqual(comp_args(), (2, 3, 4))
Florent Xiclunaaf617192010-03-21 11:03:21 +0000216 ''')
Jeremy Hylton121b6eb2001-02-19 23:53:42 +0000217
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000218 def test_argument_order(self):
219 try:
220 exec 'def f(a=1, (b, c)): pass'
221 self.fail("non-default args after default")
222 except SyntaxError:
223 pass
Jeremy Hylton121b6eb2001-02-19 23:53:42 +0000224
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000225 def test_float_literals(self):
226 # testing bad float literals
227 self.assertRaises(SyntaxError, eval, "2e")
228 self.assertRaises(SyntaxError, eval, "2.0e+")
229 self.assertRaises(SyntaxError, eval, "1e-")
230 self.assertRaises(SyntaxError, eval, "3-4e/21")
Jeremy Hylton121b6eb2001-02-19 23:53:42 +0000231
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000232 def test_indentation(self):
233 # testing compile() of indented block w/o trailing newline"
234 s = """
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000235if 1:
236 if 2:
237 pass"""
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000238 compile(s, "<string>", "exec")
239
Neal Norwitzed657552006-07-10 00:04:44 +0000240 # This test is probably specific to CPython and may not generalize
241 # to other implementations. We are trying to ensure that when
242 # the first line of code starts after 256, correct line numbers
243 # in tracebacks are still produced.
244 def test_leading_newlines(self):
245 s256 = "".join(["\n"] * 256 + ["spam"])
246 co = compile(s256, 'fn', 'exec')
247 self.assertEqual(co.co_firstlineno, 257)
248 self.assertEqual(co.co_lnotab, '')
249
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000250 def test_literals_with_leading_zeroes(self):
251 for arg in ["077787", "0xj", "0x.", "0e", "090000000000000",
Eric Smith9ff19b52008-03-17 17:32:20 +0000252 "080000000000000", "000000000000009", "000000000000008",
253 "0b42", "0BADCAFE", "0o123456789", "0b1.1", "0o4.2",
Amaury Forgeot d'Arc52167212008-04-24 18:07:05 +0000254 "0b101j2", "0o153j2", "0b100e1", "0o777e1", "0o8", "0o78"]:
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000255 self.assertRaises(SyntaxError, eval, arg)
256
257 self.assertEqual(eval("0777"), 511)
258 self.assertEqual(eval("0777L"), 511)
259 self.assertEqual(eval("000777"), 511)
260 self.assertEqual(eval("0xff"), 255)
261 self.assertEqual(eval("0xffL"), 255)
262 self.assertEqual(eval("0XfF"), 255)
263 self.assertEqual(eval("0777."), 777)
264 self.assertEqual(eval("0777.0"), 777)
265 self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777)
266 self.assertEqual(eval("0777e1"), 7770)
267 self.assertEqual(eval("0e0"), 0)
268 self.assertEqual(eval("0000E-012"), 0)
269 self.assertEqual(eval("09.5"), 9.5)
270 self.assertEqual(eval("0777j"), 777j)
271 self.assertEqual(eval("00j"), 0j)
272 self.assertEqual(eval("00.0"), 0)
273 self.assertEqual(eval("0e3"), 0)
274 self.assertEqual(eval("090000000000000."), 90000000000000.)
275 self.assertEqual(eval("090000000000000.0000000000000000000000"), 90000000000000.)
276 self.assertEqual(eval("090000000000000e0"), 90000000000000.)
277 self.assertEqual(eval("090000000000000e-0"), 90000000000000.)
278 self.assertEqual(eval("090000000000000j"), 90000000000000j)
279 self.assertEqual(eval("000000000000007"), 7)
280 self.assertEqual(eval("000000000000008."), 8.)
281 self.assertEqual(eval("000000000000009."), 9.)
Eric Smith9ff19b52008-03-17 17:32:20 +0000282 self.assertEqual(eval("0b101010"), 42)
283 self.assertEqual(eval("-0b000000000010"), -2)
284 self.assertEqual(eval("0o777"), 511)
285 self.assertEqual(eval("-0o0000010"), -8)
Mark Dickinson64b7e502008-07-16 09:40:03 +0000286 self.assertEqual(eval("020000000000.0"), 20000000000.0)
287 self.assertEqual(eval("037777777777e0"), 37777777777.0)
288 self.assertEqual(eval("01000000000000000000000.0"),
289 1000000000000000000000.0)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000290
291 def test_unary_minus(self):
292 # Verify treatment of unary minus on negative numbers SF bug #660455
Guido van Rossum6c9e1302003-11-29 23:52:13 +0000293 if sys.maxint == 2147483647:
294 # 32-bit machine
295 all_one_bits = '0xffffffff'
296 self.assertEqual(eval(all_one_bits), 4294967295L)
297 self.assertEqual(eval("-" + all_one_bits), -4294967295L)
298 elif sys.maxint == 9223372036854775807:
299 # 64-bit machine
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000300 all_one_bits = '0xffffffffffffffff'
Guido van Rossum6c9e1302003-11-29 23:52:13 +0000301 self.assertEqual(eval(all_one_bits), 18446744073709551615L)
302 self.assertEqual(eval("-" + all_one_bits), -18446744073709551615L)
303 else:
304 self.fail("How many bits *does* this machine have???")
Ezio Melotti24b07bc2011-03-15 18:55:01 +0200305 # Verify treatment of constant folding on -(sys.maxint+1)
Neil Schemenauer6ec6ab02006-07-09 21:19:29 +0000306 # i.e. -2147483648 on 32 bit platforms. Should return int, not long.
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000307 self.assertIsInstance(eval("%s" % (-sys.maxint - 1)), int)
308 self.assertIsInstance(eval("%s" % (-sys.maxint - 2)), long)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000309
Neal Norwitz28746ab2006-07-09 22:14:42 +0000310 if sys.maxint == 9223372036854775807:
311 def test_32_63_bit_values(self):
312 a = +4294967296 # 1 << 32
313 b = -4294967296 # 1 << 32
314 c = +281474976710656 # 1 << 48
315 d = -281474976710656 # 1 << 48
316 e = +4611686018427387904 # 1 << 62
317 f = -4611686018427387904 # 1 << 62
318 g = +9223372036854775807 # 1 << 63 - 1
319 h = -9223372036854775807 # 1 << 63 - 1
320
321 for variable in self.test_32_63_bit_values.func_code.co_consts:
322 if variable is not None:
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000323 self.assertIsInstance(variable, int)
Neal Norwitz28746ab2006-07-09 22:14:42 +0000324
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000325 def test_sequence_unpacking_error(self):
326 # Verify sequence packing/unpacking with "or". SF bug #757818
327 i,j = (1, -1) or (-1, 1)
328 self.assertEqual(i, 1)
329 self.assertEqual(j, -1)
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000330
Raymond Hettinger11a70c72004-07-17 21:46:25 +0000331 def test_none_assignment(self):
332 stmts = [
333 'None = 0',
334 'None += 0',
335 '__builtins__.None = 0',
336 'def None(): pass',
337 'class None: pass',
338 '(a, None) = 0, 0',
339 'for None in range(10): pass',
340 'def f(None): pass',
Benjamin Peterson565e1b62009-06-13 03:46:30 +0000341 'import None',
342 'import x as None',
343 'from x import None',
344 'from x import y as None'
Raymond Hettinger11a70c72004-07-17 21:46:25 +0000345 ]
346 for stmt in stmts:
347 stmt += "\n"
348 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'single')
349 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
Benjamin Peterson565e1b62009-06-13 03:46:30 +0000350 # This is ok.
351 compile("from None import x", "tmp", "exec")
Benjamin Petersond1f5a592009-06-13 13:06:21 +0000352 compile("from x import None as y", "tmp", "exec")
353 compile("import None as x", "tmp", "exec")
Tim Petersd507dab2001-08-30 20:51:59 +0000354
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000355 def test_import(self):
356 succeed = [
357 'import sys',
358 'import os, sys',
Neal Norwitzfb48afa2006-07-08 05:31:37 +0000359 'import os as bar',
360 'import os.path as bar',
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000361 'from __future__ import nested_scopes, generators',
362 'from __future__ import (nested_scopes,\ngenerators)',
363 'from __future__ import (nested_scopes,\ngenerators,)',
364 'from sys import stdin, stderr, stdout',
365 'from sys import (stdin, stderr,\nstdout)',
366 'from sys import (stdin, stderr,\nstdout,)',
367 'from sys import (stdin\n, stderr, stdout)',
368 'from sys import (stdin\n, stderr, stdout,)',
369 'from sys import stdin as si, stdout as so, stderr as se',
370 'from sys import (stdin as si, stdout as so, stderr as se)',
371 'from sys import (stdin as si, stdout as so, stderr as se,)',
372 ]
373 fail = [
374 'import (os, sys)',
375 'import (os), (sys)',
376 'import ((os), (sys))',
377 'import (sys',
378 'import sys)',
379 'import (os,)',
Neal Norwitzfb48afa2006-07-08 05:31:37 +0000380 'import os As bar',
381 'import os.path a bar',
Georg Brandl9575fb22006-07-08 12:15:27 +0000382 'from sys import stdin As stdout',
383 'from sys import stdin a stdout',
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000384 'from (sys) import stdin',
385 'from __future__ import (nested_scopes',
386 'from __future__ import nested_scopes)',
387 'from __future__ import nested_scopes,\ngenerators',
388 'from sys import (stdin',
389 'from sys import stdin)',
390 'from sys import stdin, stdout,\nstderr',
391 'from sys import stdin si',
392 'from sys import stdin,'
393 'from sys import (*)',
394 'from sys import (stdin,, stdout, stderr)',
395 'from sys import (stdin, stdout),',
396 ]
397 for stmt in succeed:
398 compile(stmt, 'tmp', 'exec')
399 for stmt in fail:
400 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
401
Raymond Hettinger9047c8f2004-10-24 00:10:06 +0000402 def test_for_distinct_code_objects(self):
403 # SF bug 1048870
404 def f():
405 f1 = lambda x=1: x
406 f2 = lambda x=2: x
407 return f1, f2
408 f1, f2 = f()
409 self.assertNotEqual(id(f1.func_code), id(f2.func_code))
410
Benjamin Peterson0dee9c12010-03-17 20:41:42 +0000411 def test_lambda_doc(self):
412 l = lambda: "foo"
413 self.assertIsNone(l.__doc__)
414
Neal Norwitze98ccf62006-03-23 05:39:47 +0000415 def test_unicode_encoding(self):
416 code = u"# -*- coding: utf-8 -*-\npass\n"
417 self.assertRaises(SyntaxError, compile, code, "tmp", "exec")
418
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000419 def test_subscripts(self):
420 # SF bug 1448804
421 # Class to make testing subscript results easy
422 class str_map(object):
423 def __init__(self):
424 self.data = {}
425 def __getitem__(self, key):
426 return self.data[str(key)]
427 def __setitem__(self, key, value):
428 self.data[str(key)] = value
429 def __delitem__(self, key):
430 del self.data[str(key)]
431 def __contains__(self, key):
432 return str(key) in self.data
433 d = str_map()
434 # Index
435 d[1] = 1
436 self.assertEqual(d[1], 1)
437 d[1] += 1
438 self.assertEqual(d[1], 2)
439 del d[1]
Ezio Melottiaa980582010-01-23 23:04:36 +0000440 self.assertNotIn(1, d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000441 # Tuple of indices
442 d[1, 1] = 1
443 self.assertEqual(d[1, 1], 1)
444 d[1, 1] += 1
445 self.assertEqual(d[1, 1], 2)
446 del d[1, 1]
Ezio Melottiaa980582010-01-23 23:04:36 +0000447 self.assertNotIn((1, 1), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000448 # Simple slice
449 d[1:2] = 1
450 self.assertEqual(d[1:2], 1)
451 d[1:2] += 1
452 self.assertEqual(d[1:2], 2)
453 del d[1:2]
Ezio Melottiaa980582010-01-23 23:04:36 +0000454 self.assertNotIn(slice(1, 2), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000455 # Tuple of simple slices
456 d[1:2, 1:2] = 1
457 self.assertEqual(d[1:2, 1:2], 1)
458 d[1:2, 1:2] += 1
459 self.assertEqual(d[1:2, 1:2], 2)
460 del d[1:2, 1:2]
Ezio Melottiaa980582010-01-23 23:04:36 +0000461 self.assertNotIn((slice(1, 2), slice(1, 2)), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000462 # Extended slice
463 d[1:2:3] = 1
464 self.assertEqual(d[1:2:3], 1)
465 d[1:2:3] += 1
466 self.assertEqual(d[1:2:3], 2)
467 del d[1:2:3]
Ezio Melottiaa980582010-01-23 23:04:36 +0000468 self.assertNotIn(slice(1, 2, 3), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000469 # Tuple of extended slices
470 d[1:2:3, 1:2:3] = 1
471 self.assertEqual(d[1:2:3, 1:2:3], 1)
472 d[1:2:3, 1:2:3] += 1
473 self.assertEqual(d[1:2:3, 1:2:3], 2)
474 del d[1:2:3, 1:2:3]
Ezio Melottiaa980582010-01-23 23:04:36 +0000475 self.assertNotIn((slice(1, 2, 3), slice(1, 2, 3)), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000476 # Ellipsis
477 d[...] = 1
478 self.assertEqual(d[...], 1)
479 d[...] += 1
480 self.assertEqual(d[...], 2)
481 del d[...]
Ezio Melottiaa980582010-01-23 23:04:36 +0000482 self.assertNotIn(Ellipsis, d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000483 # Tuple of Ellipses
484 d[..., ...] = 1
485 self.assertEqual(d[..., ...], 1)
486 d[..., ...] += 1
487 self.assertEqual(d[..., ...], 2)
488 del d[..., ...]
Ezio Melottiaa980582010-01-23 23:04:36 +0000489 self.assertNotIn((Ellipsis, Ellipsis), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000490
Jeremy Hylton37075c52007-02-27 01:01:59 +0000491 def test_mangling(self):
492 class A:
493 def f():
494 __mangled = 1
495 __not_mangled__ = 2
496 import __mangled_mod
497 import __package__.module
498
Ezio Melottiaa980582010-01-23 23:04:36 +0000499 self.assertIn("_A__mangled", A.f.func_code.co_varnames)
500 self.assertIn("__not_mangled__", A.f.func_code.co_varnames)
501 self.assertIn("_A__mangled_mod", A.f.func_code.co_varnames)
502 self.assertIn("__package__", A.f.func_code.co_varnames)
Jeremy Hylton37075c52007-02-27 01:01:59 +0000503
Georg Brandlfc8eef32008-03-28 12:11:56 +0000504 def test_compile_ast(self):
505 fname = __file__
506 if fname.lower().endswith(('pyc', 'pyo')):
507 fname = fname[:-1]
508 with open(fname, 'r') as f:
509 fcontents = f.read()
510 sample_code = [
511 ['<assign>', 'x = 5'],
512 ['<print1>', 'print 1'],
513 ['<printv>', 'print v'],
514 ['<printTrue>', 'print True'],
515 ['<printList>', 'print []'],
516 ['<ifblock>', """if True:\n pass\n"""],
517 ['<forblock>', """for n in [1, 2, 3]:\n print n\n"""],
518 ['<deffunc>', """def foo():\n pass\nfoo()\n"""],
519 [fname, fcontents],
520 ]
521
522 for fname, code in sample_code:
523 co1 = compile(code, '%s1' % fname, 'exec')
524 ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000525 self.assertTrue(type(ast) == _ast.Module)
Georg Brandlfc8eef32008-03-28 12:11:56 +0000526 co2 = compile(ast, '%s3' % fname, 'exec')
527 self.assertEqual(co1, co2)
Georg Brandlf2bfd542008-03-29 13:24:23 +0000528 # the code object's filename comes from the second compilation step
529 self.assertEqual(co2.co_filename, '%s3' % fname)
530
531 # raise exception when node type doesn't match with compile mode
532 co1 = compile('print 1', '<string>', 'exec', _ast.PyCF_ONLY_AST)
533 self.assertRaises(TypeError, compile, co1, '<ast>', 'eval')
534
535 # raise exception when node type is no start node
536 self.assertRaises(TypeError, compile, _ast.If(), '<ast>', 'exec')
537
538 # raise exception when node has invalid children
539 ast = _ast.Module()
540 ast.body = [_ast.BoolOp()]
541 self.assertRaises(TypeError, compile, ast, '<ast>', 'exec')
Georg Brandlfc8eef32008-03-28 12:11:56 +0000542
543
Antoine Pitrouab4a6912014-05-23 11:46:03 +0200544class TestStackSize(unittest.TestCase):
545 # These tests check that the computed stack size for a code object
546 # stays within reasonable bounds (see issue #21523 for an example
547 # dysfunction).
548 N = 100
549
550 def check_stack_size(self, code):
551 # To assert that the alleged stack size is not O(N), we
552 # check that it is smaller than log(N).
553 if isinstance(code, str):
554 code = compile(code, "<foo>", "single")
555 max_size = math.ceil(math.log(len(code.co_code)))
556 self.assertLessEqual(code.co_stacksize, max_size)
557
558 def test_and(self):
559 self.check_stack_size("x and " * self.N + "x")
560
561 def test_or(self):
562 self.check_stack_size("x or " * self.N + "x")
563
564 def test_and_or(self):
565 self.check_stack_size("x and x or " * self.N + "x")
566
567 def test_chained_comparison(self):
568 self.check_stack_size("x < " * self.N + "x")
569
570 def test_if_else(self):
571 self.check_stack_size("x if x else " * self.N + "x")
572
573 def test_binop(self):
574 self.check_stack_size("x + " * self.N + "x")
575
576 def test_func_and(self):
577 code = "def f(x):\n"
578 code += " x and x\n" * self.N
579 self.check_stack_size(code)
580
581
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000582def test_main():
Antoine Pitrouab4a6912014-05-23 11:46:03 +0200583 test_support.run_unittest(__name__)
Tim Petersd507dab2001-08-30 20:51:59 +0000584
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000585if __name__ == "__main__":
Antoine Pitrouab4a6912014-05-23 11:46:03 +0200586 unittest.main()