blob: ccd08db66703e17ee93f78875913c85dc4a54cf2 [file] [log] [blame]
Raymond Hettinger8a99b502003-06-23 13:36:57 +00001import unittest
Raymond Hettinger8a99b502003-06-23 13:36:57 +00002import sys
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00003import _ast
Benjamin Peterson43b06862011-05-27 09:08:01 -05004import types
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005from test import support
Peter Schneider-Kampfdee0f02000-07-25 22:15:45 +00006
Raymond Hettinger8a99b502003-06-23 13:36:57 +00007class TestSpecifics(unittest.TestCase):
Jeremy Hylton778e2652001-11-09 19:50:08 +00008
Meador Ingefa21bf02012-01-19 01:08:41 -06009 def compile_single(self, source):
10 compile(source, "<single>", "single")
11
12 def assertInvalidSingle(self, source):
13 self.assertRaises(SyntaxError, self.compile_single, source)
14
Benjamin Petersonaeaa5922009-11-13 00:17:59 +000015 def test_no_ending_newline(self):
16 compile("hi", "<test>", "exec")
17 compile("hi\r", "<test>", "exec")
18
19 def test_empty(self):
20 compile("", "<test>", "exec")
21
22 def test_other_newlines(self):
23 compile("\r\n", "<test>", "exec")
24 compile("\r", "<test>", "exec")
25 compile("hi\r\nstuff\r\ndef f():\n pass\r", "<test>", "exec")
26 compile("this_is\rreally_old_mac\rdef f():\n pass", "<test>", "exec")
27
Raymond Hettinger8a99b502003-06-23 13:36:57 +000028 def test_debug_assignment(self):
29 # catch assignments to __debug__
30 self.assertRaises(SyntaxError, compile, '__debug__ = 1', '?', 'single')
Georg Brandl1a3284e2007-12-02 09:40:06 +000031 import builtins
32 prev = builtins.__debug__
33 setattr(builtins, '__debug__', 'sure')
34 setattr(builtins, '__debug__', prev)
Jeremy Hylton778e2652001-11-09 19:50:08 +000035
Raymond Hettinger8a99b502003-06-23 13:36:57 +000036 def test_argument_handling(self):
37 # detect duplicate positional and keyword arguments
38 self.assertRaises(SyntaxError, eval, 'lambda a,a:0')
39 self.assertRaises(SyntaxError, eval, 'lambda a,a=1:0')
40 self.assertRaises(SyntaxError, eval, 'lambda a=1,a=1:0')
Benjamin Petersonec19d952008-06-30 15:01:21 +000041 self.assertRaises(SyntaxError, exec, 'def f(a, a): pass')
42 self.assertRaises(SyntaxError, exec, 'def f(a = 0, a = 1): pass')
43 self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1')
Jeremy Hylton778e2652001-11-09 19:50:08 +000044
Raymond Hettinger8a99b502003-06-23 13:36:57 +000045 def test_syntax_error(self):
46 self.assertRaises(SyntaxError, compile, "1+*3", "filename", "exec")
Peter Schneider-Kampfdee0f02000-07-25 22:15:45 +000047
Guido van Rossumcd16bf62007-06-13 18:07:49 +000048 def test_none_keyword_arg(self):
49 self.assertRaises(SyntaxError, compile, "f(None=1)", "<string>", "exec")
50
Raymond Hettinger8a99b502003-06-23 13:36:57 +000051 def test_duplicate_global_local(self):
Benjamin Petersonec19d952008-06-30 15:01:21 +000052 self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1')
Peter Schneider-Kampfdee0f02000-07-25 22:15:45 +000053
Raymond Hettinger66bd2332004-08-02 08:30:07 +000054 def test_exec_with_general_mapping_for_locals(self):
55
56 class M:
57 "Test mapping interface versus possible calls from eval()."
58 def __getitem__(self, key):
59 if key == 'a':
60 return 12
61 raise KeyError
62 def __setitem__(self, key, value):
63 self.results = (key, value)
Guido van Rossum63eecc72007-02-22 23:55:25 +000064 def keys(self):
65 return list('xyz')
Raymond Hettinger66bd2332004-08-02 08:30:07 +000066
67 m = M()
68 g = globals()
Georg Brandl7cae87c2006-09-06 06:51:57 +000069 exec('z = a', g, m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000070 self.assertEqual(m.results, ('z', 12))
71 try:
Georg Brandl7cae87c2006-09-06 06:51:57 +000072 exec('z = b', g, m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000073 except NameError:
74 pass
75 else:
76 self.fail('Did not detect a KeyError')
Georg Brandl7cae87c2006-09-06 06:51:57 +000077 exec('z = dir()', g, m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000078 self.assertEqual(m.results, ('z', list('xyz')))
Georg Brandl7cae87c2006-09-06 06:51:57 +000079 exec('z = globals()', g, m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000080 self.assertEqual(m.results, ('z', g))
Georg Brandl7cae87c2006-09-06 06:51:57 +000081 exec('z = locals()', g, m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000082 self.assertEqual(m.results, ('z', m))
Benjamin Petersonec19d952008-06-30 15:01:21 +000083 self.assertRaises(TypeError, exec, 'z = b', m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000084
85 class A:
86 "Non-mapping"
87 pass
88 m = A()
Benjamin Petersonec19d952008-06-30 15:01:21 +000089 self.assertRaises(TypeError, exec, 'z = a', g, m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000090
91 # Verify that dict subclasses work as well
92 class D(dict):
93 def __getitem__(self, key):
94 if key == 'a':
95 return 12
96 return dict.__getitem__(self, key)
97 d = D()
Georg Brandl7cae87c2006-09-06 06:51:57 +000098 exec('z = a', g, d)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000099 self.assertEqual(d['z'], 12)
100
Neal Norwitz6ab080c2005-10-24 00:08:10 +0000101 def test_extended_arg(self):
102 longexpr = 'x = x or ' + '-x' * 2500
Georg Brandl7cae87c2006-09-06 06:51:57 +0000103 g = {}
Neal Norwitz6ab080c2005-10-24 00:08:10 +0000104 code = '''
105def f(x):
106 %s
107 %s
108 %s
109 %s
110 %s
111 %s
112 %s
113 %s
114 %s
115 %s
116 # the expressions above have no effect, x == argument
117 while x:
118 x -= 1
119 # EXTENDED_ARG/JUMP_ABSOLUTE here
120 return x
121''' % ((longexpr,)*10)
Georg Brandl7cae87c2006-09-06 06:51:57 +0000122 exec(code, g)
123 self.assertEqual(g['f'](5), 0)
Neal Norwitz6ab080c2005-10-24 00:08:10 +0000124
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000125 def test_argument_order(self):
Benjamin Petersonec19d952008-06-30 15:01:21 +0000126 self.assertRaises(SyntaxError, exec, 'def f(a=1, b): pass')
Jeremy Hylton121b6eb2001-02-19 23:53:42 +0000127
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000128 def test_float_literals(self):
129 # testing bad float literals
130 self.assertRaises(SyntaxError, eval, "2e")
131 self.assertRaises(SyntaxError, eval, "2.0e+")
132 self.assertRaises(SyntaxError, eval, "1e-")
133 self.assertRaises(SyntaxError, eval, "3-4e/21")
Jeremy Hylton121b6eb2001-02-19 23:53:42 +0000134
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000135 def test_indentation(self):
136 # testing compile() of indented block w/o trailing newline"
137 s = """
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000138if 1:
139 if 2:
140 pass"""
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000141 compile(s, "<string>", "exec")
142
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143 # This test is probably specific to CPython and may not generalize
144 # to other implementations. We are trying to ensure that when
145 # the first line of code starts after 256, correct line numbers
146 # in tracebacks are still produced.
147 def test_leading_newlines(self):
148 s256 = "".join(["\n"] * 256 + ["spam"])
149 co = compile(s256, 'fn', 'exec')
150 self.assertEqual(co.co_firstlineno, 257)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000151 self.assertEqual(co.co_lnotab, bytes())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000152
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000153 def test_literals_with_leading_zeroes(self):
154 for arg in ["077787", "0xj", "0x.", "0e", "090000000000000",
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000155 "080000000000000", "000000000000009", "000000000000008",
156 "0b42", "0BADCAFE", "0o123456789", "0b1.1", "0o4.2",
157 "0b101j2", "0o153j2", "0b100e1", "0o777e1", "0777",
158 "000777", "000000000000007"]:
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000159 self.assertRaises(SyntaxError, eval, arg)
160
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000161 self.assertEqual(eval("0xff"), 255)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000162 self.assertEqual(eval("0777."), 777)
163 self.assertEqual(eval("0777.0"), 777)
164 self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777)
165 self.assertEqual(eval("0777e1"), 7770)
166 self.assertEqual(eval("0e0"), 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000167 self.assertEqual(eval("0000e-012"), 0)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000168 self.assertEqual(eval("09.5"), 9.5)
169 self.assertEqual(eval("0777j"), 777j)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000170 self.assertEqual(eval("000"), 0)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000171 self.assertEqual(eval("00j"), 0j)
172 self.assertEqual(eval("00.0"), 0)
173 self.assertEqual(eval("0e3"), 0)
174 self.assertEqual(eval("090000000000000."), 90000000000000.)
175 self.assertEqual(eval("090000000000000.0000000000000000000000"), 90000000000000.)
176 self.assertEqual(eval("090000000000000e0"), 90000000000000.)
177 self.assertEqual(eval("090000000000000e-0"), 90000000000000.)
178 self.assertEqual(eval("090000000000000j"), 90000000000000j)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000179 self.assertEqual(eval("000000000000008."), 8.)
180 self.assertEqual(eval("000000000000009."), 9.)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000181 self.assertEqual(eval("0b101010"), 42)
182 self.assertEqual(eval("-0b000000000010"), -2)
183 self.assertEqual(eval("0o777"), 511)
184 self.assertEqual(eval("-0o0000010"), -8)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000185
186 def test_unary_minus(self):
187 # Verify treatment of unary minus on negative numbers SF bug #660455
Christian Heimesa37d4c62007-12-04 23:02:19 +0000188 if sys.maxsize == 2147483647:
Guido van Rossum6c9e1302003-11-29 23:52:13 +0000189 # 32-bit machine
190 all_one_bits = '0xffffffff'
Guido van Rossume2a383d2007-01-15 16:59:06 +0000191 self.assertEqual(eval(all_one_bits), 4294967295)
192 self.assertEqual(eval("-" + all_one_bits), -4294967295)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000193 elif sys.maxsize == 9223372036854775807:
Guido van Rossum6c9e1302003-11-29 23:52:13 +0000194 # 64-bit machine
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000195 all_one_bits = '0xffffffffffffffff'
Guido van Rossume2a383d2007-01-15 16:59:06 +0000196 self.assertEqual(eval(all_one_bits), 18446744073709551615)
197 self.assertEqual(eval("-" + all_one_bits), -18446744073709551615)
Guido van Rossum6c9e1302003-11-29 23:52:13 +0000198 else:
199 self.fail("How many bits *does* this machine have???")
Ezio Melotti42da6632011-03-15 05:18:48 +0200200 # Verify treatment of constant folding on -(sys.maxsize+1)
Serhiy Storchaka95949422013-08-27 19:40:23 +0300201 # i.e. -2147483648 on 32 bit platforms. Should return int.
Ezio Melottie9615932010-01-24 19:26:24 +0000202 self.assertIsInstance(eval("%s" % (-sys.maxsize - 1)), int)
203 self.assertIsInstance(eval("%s" % (-sys.maxsize - 2)), int)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000204
Christian Heimesa37d4c62007-12-04 23:02:19 +0000205 if sys.maxsize == 9223372036854775807:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000206 def test_32_63_bit_values(self):
207 a = +4294967296 # 1 << 32
208 b = -4294967296 # 1 << 32
209 c = +281474976710656 # 1 << 48
210 d = -281474976710656 # 1 << 48
211 e = +4611686018427387904 # 1 << 62
212 f = -4611686018427387904 # 1 << 62
213 g = +9223372036854775807 # 1 << 63 - 1
214 h = -9223372036854775807 # 1 << 63 - 1
215
Neal Norwitz221085d2007-02-25 20:55:47 +0000216 for variable in self.test_32_63_bit_values.__code__.co_consts:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000217 if variable is not None:
Ezio Melottie9615932010-01-24 19:26:24 +0000218 self.assertIsInstance(variable, int)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000219
220 def test_sequence_unpacking_error(self):
221 # Verify sequence packing/unpacking with "or". SF bug #757818
222 i,j = (1, -1) or (-1, 1)
223 self.assertEqual(i, 1)
224 self.assertEqual(j, -1)
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000225
Raymond Hettinger11a70c72004-07-17 21:46:25 +0000226 def test_none_assignment(self):
227 stmts = [
228 'None = 0',
229 'None += 0',
230 '__builtins__.None = 0',
231 'def None(): pass',
232 'class None: pass',
233 '(a, None) = 0, 0',
234 'for None in range(10): pass',
235 'def f(None): pass',
Benjamin Peterson78565b22009-06-28 19:19:51 +0000236 'import None',
237 'import x as None',
238 'from x import None',
239 'from x import y as None'
Raymond Hettinger11a70c72004-07-17 21:46:25 +0000240 ]
241 for stmt in stmts:
242 stmt += "\n"
243 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'single')
244 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
Tim Petersd507dab2001-08-30 20:51:59 +0000245
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000246 def test_import(self):
247 succeed = [
248 'import sys',
249 'import os, sys',
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000250 'import os as bar',
251 'import os.path as bar',
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000252 'from __future__ import nested_scopes, generators',
253 'from __future__ import (nested_scopes,\ngenerators)',
254 'from __future__ import (nested_scopes,\ngenerators,)',
255 'from sys import stdin, stderr, stdout',
256 'from sys import (stdin, stderr,\nstdout)',
257 'from sys import (stdin, stderr,\nstdout,)',
258 'from sys import (stdin\n, stderr, stdout)',
259 'from sys import (stdin\n, stderr, stdout,)',
260 'from sys import stdin as si, stdout as so, stderr as se',
261 'from sys import (stdin as si, stdout as so, stderr as se)',
262 'from sys import (stdin as si, stdout as so, stderr as se,)',
263 ]
264 fail = [
265 'import (os, sys)',
266 'import (os), (sys)',
267 'import ((os), (sys))',
268 'import (sys',
269 'import sys)',
270 'import (os,)',
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000271 'import os As bar',
272 'import os.path a bar',
273 'from sys import stdin As stdout',
274 'from sys import stdin a stdout',
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000275 'from (sys) import stdin',
276 'from __future__ import (nested_scopes',
277 'from __future__ import nested_scopes)',
278 'from __future__ import nested_scopes,\ngenerators',
279 'from sys import (stdin',
280 'from sys import stdin)',
281 'from sys import stdin, stdout,\nstderr',
282 'from sys import stdin si',
283 'from sys import stdin,'
284 'from sys import (*)',
285 'from sys import (stdin,, stdout, stderr)',
286 'from sys import (stdin, stdout),',
287 ]
288 for stmt in succeed:
289 compile(stmt, 'tmp', 'exec')
290 for stmt in fail:
291 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
292
Raymond Hettinger9047c8f2004-10-24 00:10:06 +0000293 def test_for_distinct_code_objects(self):
294 # SF bug 1048870
295 def f():
296 f1 = lambda x=1: x
297 f2 = lambda x=2: x
298 return f1, f2
299 f1, f2 = f()
Neal Norwitz221085d2007-02-25 20:55:47 +0000300 self.assertNotEqual(id(f1.__code__), id(f2.__code__))
Raymond Hettinger9047c8f2004-10-24 00:10:06 +0000301
Benjamin Petersone6dd2cb2010-03-17 20:56:58 +0000302 def test_lambda_doc(self):
303 l = lambda: "foo"
304 self.assertIsNone(l.__doc__)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000305
Benjamin Peterson5d2ad252010-03-17 20:57:32 +0000306## def test_unicode_encoding(self):
307## code = "# -*- coding: utf-8 -*-\npass\n"
308## self.assertRaises(SyntaxError, compile, code, "tmp", "exec")
309
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000310 def test_subscripts(self):
311 # SF bug 1448804
312 # Class to make testing subscript results easy
313 class str_map(object):
314 def __init__(self):
315 self.data = {}
316 def __getitem__(self, key):
317 return self.data[str(key)]
318 def __setitem__(self, key, value):
319 self.data[str(key)] = value
320 def __delitem__(self, key):
321 del self.data[str(key)]
322 def __contains__(self, key):
323 return str(key) in self.data
324 d = str_map()
325 # Index
326 d[1] = 1
327 self.assertEqual(d[1], 1)
328 d[1] += 1
329 self.assertEqual(d[1], 2)
330 del d[1]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000331 self.assertNotIn(1, d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000332 # Tuple of indices
333 d[1, 1] = 1
334 self.assertEqual(d[1, 1], 1)
335 d[1, 1] += 1
336 self.assertEqual(d[1, 1], 2)
337 del d[1, 1]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000338 self.assertNotIn((1, 1), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000339 # Simple slice
340 d[1:2] = 1
341 self.assertEqual(d[1:2], 1)
342 d[1:2] += 1
343 self.assertEqual(d[1:2], 2)
344 del d[1:2]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000345 self.assertNotIn(slice(1, 2), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000346 # Tuple of simple slices
347 d[1:2, 1:2] = 1
348 self.assertEqual(d[1:2, 1:2], 1)
349 d[1:2, 1:2] += 1
350 self.assertEqual(d[1:2, 1:2], 2)
351 del d[1:2, 1:2]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000352 self.assertNotIn((slice(1, 2), slice(1, 2)), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000353 # Extended slice
354 d[1:2:3] = 1
355 self.assertEqual(d[1:2:3], 1)
356 d[1:2:3] += 1
357 self.assertEqual(d[1:2:3], 2)
358 del d[1:2:3]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000359 self.assertNotIn(slice(1, 2, 3), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000360 # Tuple of extended slices
361 d[1:2:3, 1:2:3] = 1
362 self.assertEqual(d[1:2:3, 1:2:3], 1)
363 d[1:2:3, 1:2:3] += 1
364 self.assertEqual(d[1:2:3, 1:2:3], 2)
365 del d[1:2:3, 1:2:3]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000366 self.assertNotIn((slice(1, 2, 3), slice(1, 2, 3)), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000367 # Ellipsis
368 d[...] = 1
369 self.assertEqual(d[...], 1)
370 d[...] += 1
371 self.assertEqual(d[...], 2)
372 del d[...]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000373 self.assertNotIn(Ellipsis, d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000374 # Tuple of Ellipses
375 d[..., ...] = 1
376 self.assertEqual(d[..., ...], 1)
377 d[..., ...] += 1
378 self.assertEqual(d[..., ...], 2)
379 del d[..., ...]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000380 self.assertNotIn((Ellipsis, Ellipsis), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000381
Guido van Rossum0240b922007-02-26 21:23:50 +0000382 def test_annotation_limit(self):
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000383 # 16 bits are available for # of annotations, but only 8 bits are
384 # available for the parameter count, hence 255
Guido van Rossum0240b922007-02-26 21:23:50 +0000385 # is the max. Ensure the result of too many annotations is a
386 # SyntaxError.
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000387 s = "def f(%s): pass"
388 s %= ', '.join('a%d:%d' % (i,i) for i in range(256))
Guido van Rossum0240b922007-02-26 21:23:50 +0000389 self.assertRaises(SyntaxError, compile, s, '?', 'exec')
390 # Test that the max # of annotations compiles.
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000391 s = "def f(%s): pass"
392 s %= ', '.join('a%d:%d' % (i,i) for i in range(255))
Guido van Rossum0240b922007-02-26 21:23:50 +0000393 compile(s, '?', 'exec')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000394
395 def test_mangling(self):
396 class A:
397 def f():
398 __mangled = 1
399 __not_mangled__ = 2
400 import __mangled_mod
401 import __package__.module
402
Benjamin Peterson577473f2010-01-19 00:09:57 +0000403 self.assertIn("_A__mangled", A.f.__code__.co_varnames)
404 self.assertIn("__not_mangled__", A.f.__code__.co_varnames)
405 self.assertIn("_A__mangled_mod", A.f.__code__.co_varnames)
406 self.assertIn("__package__", A.f.__code__.co_varnames)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000407
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000408 def test_compile_ast(self):
409 fname = __file__
410 if fname.lower().endswith(('pyc', 'pyo')):
411 fname = fname[:-1]
412 with open(fname, 'r') as f:
413 fcontents = f.read()
414 sample_code = [
415 ['<assign>', 'x = 5'],
416 ['<ifblock>', """if True:\n pass\n"""],
417 ['<forblock>', """for n in [1, 2, 3]:\n print(n)\n"""],
418 ['<deffunc>', """def foo():\n pass\nfoo()\n"""],
419 [fname, fcontents],
420 ]
421
422 for fname, code in sample_code:
423 co1 = compile(code, '%s1' % fname, 'exec')
424 ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000425 self.assertTrue(type(ast) == _ast.Module)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000426 co2 = compile(ast, '%s3' % fname, 'exec')
427 self.assertEqual(co1, co2)
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000428 # the code object's filename comes from the second compilation step
429 self.assertEqual(co2.co_filename, '%s3' % fname)
430
431 # raise exception when node type doesn't match with compile mode
432 co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST)
433 self.assertRaises(TypeError, compile, co1, '<ast>', 'eval')
434
435 # raise exception when node type is no start node
436 self.assertRaises(TypeError, compile, _ast.If(), '<ast>', 'exec')
437
438 # raise exception when node has invalid children
439 ast = _ast.Module()
440 ast.body = [_ast.BoolOp()]
441 self.assertRaises(TypeError, compile, ast, '<ast>', 'exec')
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000442
Benjamin Peterson43b06862011-05-27 09:08:01 -0500443 @support.cpython_only
444 def test_same_filename_used(self):
445 s = """def f(): pass\ndef g(): pass"""
446 c = compile(s, "myfile", "exec")
447 for obj in c.co_consts:
448 if isinstance(obj, types.CodeType):
449 self.assertIs(obj.co_filename, c.co_filename)
450
Meador Ingefa21bf02012-01-19 01:08:41 -0600451 def test_single_statement(self):
452 self.compile_single("1 + 2")
453 self.compile_single("\n1 + 2")
454 self.compile_single("1 + 2\n")
455 self.compile_single("1 + 2\n\n")
456 self.compile_single("1 + 2\t\t\n")
457 self.compile_single("1 + 2\t\t\n ")
458 self.compile_single("1 + 2 # one plus two")
459 self.compile_single("1; 2")
460 self.compile_single("import sys; sys")
461 self.compile_single("def f():\n pass")
462 self.compile_single("while False:\n pass")
463 self.compile_single("if x:\n f(x)")
464 self.compile_single("if x:\n f(x)\nelse:\n g(x)")
465 self.compile_single("class T:\n pass")
466
467 def test_bad_single_statement(self):
468 self.assertInvalidSingle('1\n2')
469 self.assertInvalidSingle('def f(): pass')
470 self.assertInvalidSingle('a = 13\nb = 187')
471 self.assertInvalidSingle('del x\ndel y')
472 self.assertInvalidSingle('f()\ng()')
Benjamin Petersoncff92372012-01-19 17:46:13 -0500473 self.assertInvalidSingle('f()\n# blah\nblah()')
474 self.assertInvalidSingle('f()\nxy # blah\nblah()')
Benjamin Peterson77fc1f32012-01-20 11:01:06 -0500475 self.assertInvalidSingle('x = 5 # comment\nx = 6\n')
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000476
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000477 @support.cpython_only
478 def test_compiler_recursion_limit(self):
479 # Expected limit is sys.getrecursionlimit() * the scaling factor
480 # in symtable.c (currently 3)
481 # We expect to fail *at* that limit, because we use up some of
482 # the stack depth limit in the test suite code
483 # So we check the expected limit and 75% of that
484 # XXX (ncoghlan): duplicating the scaling factor here is a little
485 # ugly. Perhaps it should be exposed somewhere...
486 fail_depth = sys.getrecursionlimit() * 3
487 success_depth = int(fail_depth * 0.75)
488
489 def check_limit(prefix, repeated):
490 expect_ok = prefix + repeated * success_depth
491 self.compile_single(expect_ok)
492 broken = prefix + repeated * fail_depth
493 details = "Compiling ({!r} + {!r} * {})".format(
494 prefix, repeated, fail_depth)
495 with self.assertRaises(RuntimeError, msg=details):
496 self.compile_single(broken)
497
498 check_limit("a", "()")
499 check_limit("a", ".b")
500 check_limit("a", "[0]")
501 check_limit("a", "*a")
502
503
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000504def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000505 support.run_unittest(TestSpecifics)
Tim Petersd507dab2001-08-30 20:51:59 +0000506
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000507if __name__ == "__main__":
508 test_main()