blob: 4617a126abee1d96072b8809275804ead6abce18 [file] [log] [blame]
Antoine Pitrou99614052014-05-23 11:46:03 +02001import math
Benjamin Petersond73aca72015-04-21 12:05:19 -04002import os
Raymond Hettinger8a99b502003-06-23 13:36:57 +00003import unittest
Raymond Hettinger8a99b502003-06-23 13:36:57 +00004import sys
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00005import _ast
Benjamin Petersond73aca72015-04-21 12:05:19 -04006import tempfile
Benjamin Peterson43b06862011-05-27 09:08:01 -05007import types
Berker Peksag076dbd02015-05-06 07:01:52 +03008from test import support
9from test.support import script_helper
Peter Schneider-Kampfdee0f02000-07-25 22:15:45 +000010
Raymond Hettinger8a99b502003-06-23 13:36:57 +000011class TestSpecifics(unittest.TestCase):
Jeremy Hylton778e2652001-11-09 19:50:08 +000012
Meador Ingefa21bf02012-01-19 01:08:41 -060013 def compile_single(self, source):
14 compile(source, "<single>", "single")
15
16 def assertInvalidSingle(self, source):
17 self.assertRaises(SyntaxError, self.compile_single, source)
18
Benjamin Petersonaeaa5922009-11-13 00:17:59 +000019 def test_no_ending_newline(self):
20 compile("hi", "<test>", "exec")
21 compile("hi\r", "<test>", "exec")
22
23 def test_empty(self):
24 compile("", "<test>", "exec")
25
26 def test_other_newlines(self):
27 compile("\r\n", "<test>", "exec")
28 compile("\r", "<test>", "exec")
29 compile("hi\r\nstuff\r\ndef f():\n pass\r", "<test>", "exec")
30 compile("this_is\rreally_old_mac\rdef f():\n pass", "<test>", "exec")
31
Raymond Hettinger8a99b502003-06-23 13:36:57 +000032 def test_debug_assignment(self):
33 # catch assignments to __debug__
34 self.assertRaises(SyntaxError, compile, '__debug__ = 1', '?', 'single')
Georg Brandl1a3284e2007-12-02 09:40:06 +000035 import builtins
36 prev = builtins.__debug__
37 setattr(builtins, '__debug__', 'sure')
Serhiy Storchaka3325a672017-12-15 12:35:48 +020038 self.assertEqual(__debug__, prev)
Georg Brandl1a3284e2007-12-02 09:40:06 +000039 setattr(builtins, '__debug__', prev)
Jeremy Hylton778e2652001-11-09 19:50:08 +000040
Raymond Hettinger8a99b502003-06-23 13:36:57 +000041 def test_argument_handling(self):
42 # detect duplicate positional and keyword arguments
43 self.assertRaises(SyntaxError, eval, 'lambda a,a:0')
44 self.assertRaises(SyntaxError, eval, 'lambda a,a=1:0')
45 self.assertRaises(SyntaxError, eval, 'lambda a=1,a=1:0')
Benjamin Petersonec19d952008-06-30 15:01:21 +000046 self.assertRaises(SyntaxError, exec, 'def f(a, a): pass')
47 self.assertRaises(SyntaxError, exec, 'def f(a = 0, a = 1): pass')
48 self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1')
Jeremy Hylton778e2652001-11-09 19:50:08 +000049
Raymond Hettinger8a99b502003-06-23 13:36:57 +000050 def test_syntax_error(self):
51 self.assertRaises(SyntaxError, compile, "1+*3", "filename", "exec")
Peter Schneider-Kampfdee0f02000-07-25 22:15:45 +000052
Guido van Rossumcd16bf62007-06-13 18:07:49 +000053 def test_none_keyword_arg(self):
54 self.assertRaises(SyntaxError, compile, "f(None=1)", "<string>", "exec")
55
Raymond Hettinger8a99b502003-06-23 13:36:57 +000056 def test_duplicate_global_local(self):
Benjamin Petersonec19d952008-06-30 15:01:21 +000057 self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1')
Peter Schneider-Kampfdee0f02000-07-25 22:15:45 +000058
Raymond Hettinger66bd2332004-08-02 08:30:07 +000059 def test_exec_with_general_mapping_for_locals(self):
60
61 class M:
62 "Test mapping interface versus possible calls from eval()."
63 def __getitem__(self, key):
64 if key == 'a':
65 return 12
66 raise KeyError
67 def __setitem__(self, key, value):
68 self.results = (key, value)
Guido van Rossum63eecc72007-02-22 23:55:25 +000069 def keys(self):
70 return list('xyz')
Raymond Hettinger66bd2332004-08-02 08:30:07 +000071
72 m = M()
73 g = globals()
Georg Brandl7cae87c2006-09-06 06:51:57 +000074 exec('z = a', g, m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000075 self.assertEqual(m.results, ('z', 12))
76 try:
Georg Brandl7cae87c2006-09-06 06:51:57 +000077 exec('z = b', g, m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000078 except NameError:
79 pass
80 else:
81 self.fail('Did not detect a KeyError')
Georg Brandl7cae87c2006-09-06 06:51:57 +000082 exec('z = dir()', g, m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000083 self.assertEqual(m.results, ('z', list('xyz')))
Georg Brandl7cae87c2006-09-06 06:51:57 +000084 exec('z = globals()', g, m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000085 self.assertEqual(m.results, ('z', g))
Georg Brandl7cae87c2006-09-06 06:51:57 +000086 exec('z = locals()', g, m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000087 self.assertEqual(m.results, ('z', m))
Benjamin Petersonec19d952008-06-30 15:01:21 +000088 self.assertRaises(TypeError, exec, 'z = b', m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000089
90 class A:
91 "Non-mapping"
92 pass
93 m = A()
Benjamin Petersonec19d952008-06-30 15:01:21 +000094 self.assertRaises(TypeError, exec, 'z = a', g, m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000095
96 # Verify that dict subclasses work as well
97 class D(dict):
98 def __getitem__(self, key):
99 if key == 'a':
100 return 12
101 return dict.__getitem__(self, key)
102 d = D()
Georg Brandl7cae87c2006-09-06 06:51:57 +0000103 exec('z = a', g, d)
Raymond Hettinger66bd2332004-08-02 08:30:07 +0000104 self.assertEqual(d['z'], 12)
105
Neal Norwitz6ab080c2005-10-24 00:08:10 +0000106 def test_extended_arg(self):
107 longexpr = 'x = x or ' + '-x' * 2500
Georg Brandl7cae87c2006-09-06 06:51:57 +0000108 g = {}
Neal Norwitz6ab080c2005-10-24 00:08:10 +0000109 code = '''
110def f(x):
111 %s
112 %s
113 %s
114 %s
115 %s
116 %s
117 %s
118 %s
119 %s
120 %s
121 # the expressions above have no effect, x == argument
122 while x:
123 x -= 1
124 # EXTENDED_ARG/JUMP_ABSOLUTE here
125 return x
126''' % ((longexpr,)*10)
Georg Brandl7cae87c2006-09-06 06:51:57 +0000127 exec(code, g)
128 self.assertEqual(g['f'](5), 0)
Neal Norwitz6ab080c2005-10-24 00:08:10 +0000129
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000130 def test_argument_order(self):
Benjamin Petersonec19d952008-06-30 15:01:21 +0000131 self.assertRaises(SyntaxError, exec, 'def f(a=1, b): pass')
Jeremy Hylton121b6eb2001-02-19 23:53:42 +0000132
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000133 def test_float_literals(self):
134 # testing bad float literals
135 self.assertRaises(SyntaxError, eval, "2e")
136 self.assertRaises(SyntaxError, eval, "2.0e+")
137 self.assertRaises(SyntaxError, eval, "1e-")
138 self.assertRaises(SyntaxError, eval, "3-4e/21")
Jeremy Hylton121b6eb2001-02-19 23:53:42 +0000139
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000140 def test_indentation(self):
141 # testing compile() of indented block w/o trailing newline"
142 s = """
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000143if 1:
144 if 2:
145 pass"""
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000146 compile(s, "<string>", "exec")
147
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000148 # This test is probably specific to CPython and may not generalize
149 # to other implementations. We are trying to ensure that when
150 # the first line of code starts after 256, correct line numbers
151 # in tracebacks are still produced.
152 def test_leading_newlines(self):
153 s256 = "".join(["\n"] * 256 + ["spam"])
154 co = compile(s256, 'fn', 'exec')
155 self.assertEqual(co.co_firstlineno, 257)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000156 self.assertEqual(co.co_lnotab, bytes())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000157
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000158 def test_literals_with_leading_zeroes(self):
159 for arg in ["077787", "0xj", "0x.", "0e", "090000000000000",
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000160 "080000000000000", "000000000000009", "000000000000008",
161 "0b42", "0BADCAFE", "0o123456789", "0b1.1", "0o4.2",
162 "0b101j2", "0o153j2", "0b100e1", "0o777e1", "0777",
163 "000777", "000000000000007"]:
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000164 self.assertRaises(SyntaxError, eval, arg)
165
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000166 self.assertEqual(eval("0xff"), 255)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000167 self.assertEqual(eval("0777."), 777)
168 self.assertEqual(eval("0777.0"), 777)
169 self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777)
170 self.assertEqual(eval("0777e1"), 7770)
171 self.assertEqual(eval("0e0"), 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000172 self.assertEqual(eval("0000e-012"), 0)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000173 self.assertEqual(eval("09.5"), 9.5)
174 self.assertEqual(eval("0777j"), 777j)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000175 self.assertEqual(eval("000"), 0)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000176 self.assertEqual(eval("00j"), 0j)
177 self.assertEqual(eval("00.0"), 0)
178 self.assertEqual(eval("0e3"), 0)
179 self.assertEqual(eval("090000000000000."), 90000000000000.)
180 self.assertEqual(eval("090000000000000.0000000000000000000000"), 90000000000000.)
181 self.assertEqual(eval("090000000000000e0"), 90000000000000.)
182 self.assertEqual(eval("090000000000000e-0"), 90000000000000.)
183 self.assertEqual(eval("090000000000000j"), 90000000000000j)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000184 self.assertEqual(eval("000000000000008."), 8.)
185 self.assertEqual(eval("000000000000009."), 9.)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000186 self.assertEqual(eval("0b101010"), 42)
187 self.assertEqual(eval("-0b000000000010"), -2)
188 self.assertEqual(eval("0o777"), 511)
189 self.assertEqual(eval("-0o0000010"), -8)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000190
191 def test_unary_minus(self):
192 # Verify treatment of unary minus on negative numbers SF bug #660455
Christian Heimesa37d4c62007-12-04 23:02:19 +0000193 if sys.maxsize == 2147483647:
Guido van Rossum6c9e1302003-11-29 23:52:13 +0000194 # 32-bit machine
195 all_one_bits = '0xffffffff'
Guido van Rossume2a383d2007-01-15 16:59:06 +0000196 self.assertEqual(eval(all_one_bits), 4294967295)
197 self.assertEqual(eval("-" + all_one_bits), -4294967295)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000198 elif sys.maxsize == 9223372036854775807:
Guido van Rossum6c9e1302003-11-29 23:52:13 +0000199 # 64-bit machine
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000200 all_one_bits = '0xffffffffffffffff'
Guido van Rossume2a383d2007-01-15 16:59:06 +0000201 self.assertEqual(eval(all_one_bits), 18446744073709551615)
202 self.assertEqual(eval("-" + all_one_bits), -18446744073709551615)
Guido van Rossum6c9e1302003-11-29 23:52:13 +0000203 else:
204 self.fail("How many bits *does* this machine have???")
Ezio Melotti42da6632011-03-15 05:18:48 +0200205 # Verify treatment of constant folding on -(sys.maxsize+1)
Serhiy Storchaka95949422013-08-27 19:40:23 +0300206 # i.e. -2147483648 on 32 bit platforms. Should return int.
Ezio Melottie9615932010-01-24 19:26:24 +0000207 self.assertIsInstance(eval("%s" % (-sys.maxsize - 1)), int)
208 self.assertIsInstance(eval("%s" % (-sys.maxsize - 2)), int)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000209
Christian Heimesa37d4c62007-12-04 23:02:19 +0000210 if sys.maxsize == 9223372036854775807:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000211 def test_32_63_bit_values(self):
212 a = +4294967296 # 1 << 32
213 b = -4294967296 # 1 << 32
214 c = +281474976710656 # 1 << 48
215 d = -281474976710656 # 1 << 48
216 e = +4611686018427387904 # 1 << 62
217 f = -4611686018427387904 # 1 << 62
218 g = +9223372036854775807 # 1 << 63 - 1
219 h = -9223372036854775807 # 1 << 63 - 1
220
Neal Norwitz221085d2007-02-25 20:55:47 +0000221 for variable in self.test_32_63_bit_values.__code__.co_consts:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000222 if variable is not None:
Ezio Melottie9615932010-01-24 19:26:24 +0000223 self.assertIsInstance(variable, int)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000224
225 def test_sequence_unpacking_error(self):
226 # Verify sequence packing/unpacking with "or". SF bug #757818
227 i,j = (1, -1) or (-1, 1)
228 self.assertEqual(i, 1)
229 self.assertEqual(j, -1)
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000230
Raymond Hettinger11a70c72004-07-17 21:46:25 +0000231 def test_none_assignment(self):
232 stmts = [
233 'None = 0',
234 'None += 0',
235 '__builtins__.None = 0',
236 'def None(): pass',
237 'class None: pass',
238 '(a, None) = 0, 0',
239 'for None in range(10): pass',
240 'def f(None): pass',
Benjamin Peterson78565b22009-06-28 19:19:51 +0000241 'import None',
242 'import x as None',
243 'from x import None',
244 'from x import y as None'
Raymond Hettinger11a70c72004-07-17 21:46:25 +0000245 ]
246 for stmt in stmts:
247 stmt += "\n"
248 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'single')
249 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
Tim Petersd507dab2001-08-30 20:51:59 +0000250
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000251 def test_import(self):
252 succeed = [
253 'import sys',
254 'import os, sys',
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000255 'import os as bar',
256 'import os.path as bar',
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000257 'from __future__ import nested_scopes, generators',
258 'from __future__ import (nested_scopes,\ngenerators)',
259 'from __future__ import (nested_scopes,\ngenerators,)',
260 'from sys import stdin, stderr, stdout',
261 'from sys import (stdin, stderr,\nstdout)',
262 'from sys import (stdin, stderr,\nstdout,)',
263 'from sys import (stdin\n, stderr, stdout)',
264 'from sys import (stdin\n, stderr, stdout,)',
265 'from sys import stdin as si, stdout as so, stderr as se',
266 'from sys import (stdin as si, stdout as so, stderr as se)',
267 'from sys import (stdin as si, stdout as so, stderr as se,)',
268 ]
269 fail = [
270 'import (os, sys)',
271 'import (os), (sys)',
272 'import ((os), (sys))',
273 'import (sys',
274 'import sys)',
275 'import (os,)',
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000276 'import os As bar',
277 'import os.path a bar',
278 'from sys import stdin As stdout',
279 'from sys import stdin a stdout',
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000280 'from (sys) import stdin',
281 'from __future__ import (nested_scopes',
282 'from __future__ import nested_scopes)',
283 'from __future__ import nested_scopes,\ngenerators',
284 'from sys import (stdin',
285 'from sys import stdin)',
286 'from sys import stdin, stdout,\nstderr',
287 'from sys import stdin si',
288 'from sys import stdin,'
289 'from sys import (*)',
290 'from sys import (stdin,, stdout, stderr)',
291 'from sys import (stdin, stdout),',
292 ]
293 for stmt in succeed:
294 compile(stmt, 'tmp', 'exec')
295 for stmt in fail:
296 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
297
Raymond Hettinger9047c8f2004-10-24 00:10:06 +0000298 def test_for_distinct_code_objects(self):
299 # SF bug 1048870
300 def f():
301 f1 = lambda x=1: x
302 f2 = lambda x=2: x
303 return f1, f2
304 f1, f2 = f()
Neal Norwitz221085d2007-02-25 20:55:47 +0000305 self.assertNotEqual(id(f1.__code__), id(f2.__code__))
Raymond Hettinger9047c8f2004-10-24 00:10:06 +0000306
Benjamin Petersone6dd2cb2010-03-17 20:56:58 +0000307 def test_lambda_doc(self):
308 l = lambda: "foo"
309 self.assertIsNone(l.__doc__)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000310
Serhiy Storchaka607cb9c2014-09-05 11:00:56 +0300311 def test_encoding(self):
312 code = b'# -*- coding: badencoding -*-\npass\n'
313 self.assertRaises(SyntaxError, compile, code, 'tmp', 'exec')
314 code = '# -*- coding: badencoding -*-\n"\xc2\xa4"\n'
315 compile(code, 'tmp', 'exec')
316 self.assertEqual(eval(code), '\xc2\xa4')
317 code = '"\xc2\xa4"\n'
318 self.assertEqual(eval(code), '\xc2\xa4')
319 code = b'"\xc2\xa4"\n'
320 self.assertEqual(eval(code), '\xa4')
321 code = b'# -*- coding: latin1 -*-\n"\xc2\xa4"\n'
322 self.assertEqual(eval(code), '\xc2\xa4')
323 code = b'# -*- coding: utf-8 -*-\n"\xc2\xa4"\n'
324 self.assertEqual(eval(code), '\xa4')
325 code = b'# -*- coding: iso8859-15 -*-\n"\xc2\xa4"\n'
326 self.assertEqual(eval(code), '\xc2\u20ac')
327 code = '"""\\\n# -*- coding: iso8859-15 -*-\n\xc2\xa4"""\n'
328 self.assertEqual(eval(code), '# -*- coding: iso8859-15 -*-\n\xc2\xa4')
329 code = b'"""\\\n# -*- coding: iso8859-15 -*-\n\xc2\xa4"""\n'
330 self.assertEqual(eval(code), '# -*- coding: iso8859-15 -*-\n\xa4')
Benjamin Peterson5d2ad252010-03-17 20:57:32 +0000331
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000332 def test_subscripts(self):
333 # SF bug 1448804
334 # Class to make testing subscript results easy
335 class str_map(object):
336 def __init__(self):
337 self.data = {}
338 def __getitem__(self, key):
339 return self.data[str(key)]
340 def __setitem__(self, key, value):
341 self.data[str(key)] = value
342 def __delitem__(self, key):
343 del self.data[str(key)]
344 def __contains__(self, key):
345 return str(key) in self.data
346 d = str_map()
347 # Index
348 d[1] = 1
349 self.assertEqual(d[1], 1)
350 d[1] += 1
351 self.assertEqual(d[1], 2)
352 del d[1]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000353 self.assertNotIn(1, d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000354 # Tuple of indices
355 d[1, 1] = 1
356 self.assertEqual(d[1, 1], 1)
357 d[1, 1] += 1
358 self.assertEqual(d[1, 1], 2)
359 del d[1, 1]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000360 self.assertNotIn((1, 1), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000361 # Simple slice
362 d[1:2] = 1
363 self.assertEqual(d[1:2], 1)
364 d[1:2] += 1
365 self.assertEqual(d[1:2], 2)
366 del d[1:2]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000367 self.assertNotIn(slice(1, 2), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000368 # Tuple of simple slices
369 d[1:2, 1:2] = 1
370 self.assertEqual(d[1:2, 1:2], 1)
371 d[1:2, 1:2] += 1
372 self.assertEqual(d[1:2, 1:2], 2)
373 del d[1:2, 1:2]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000374 self.assertNotIn((slice(1, 2), slice(1, 2)), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000375 # Extended slice
376 d[1:2:3] = 1
377 self.assertEqual(d[1:2:3], 1)
378 d[1:2:3] += 1
379 self.assertEqual(d[1:2:3], 2)
380 del d[1:2:3]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000381 self.assertNotIn(slice(1, 2, 3), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000382 # Tuple of extended slices
383 d[1:2:3, 1:2:3] = 1
384 self.assertEqual(d[1:2:3, 1:2:3], 1)
385 d[1:2:3, 1:2:3] += 1
386 self.assertEqual(d[1:2:3, 1:2:3], 2)
387 del d[1:2:3, 1:2:3]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000388 self.assertNotIn((slice(1, 2, 3), slice(1, 2, 3)), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000389 # Ellipsis
390 d[...] = 1
391 self.assertEqual(d[...], 1)
392 d[...] += 1
393 self.assertEqual(d[...], 2)
394 del d[...]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000395 self.assertNotIn(Ellipsis, d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000396 # Tuple of Ellipses
397 d[..., ...] = 1
398 self.assertEqual(d[..., ...], 1)
399 d[..., ...] += 1
400 self.assertEqual(d[..., ...], 2)
401 del d[..., ...]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000402 self.assertNotIn((Ellipsis, Ellipsis), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000403
Guido van Rossum0240b922007-02-26 21:23:50 +0000404 def test_annotation_limit(self):
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200405 # more than 255 annotations, should compile ok
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000406 s = "def f(%s): pass"
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200407 s %= ', '.join('a%d:%d' % (i,i) for i in range(300))
Guido van Rossum0240b922007-02-26 21:23:50 +0000408 compile(s, '?', 'exec')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000409
410 def test_mangling(self):
411 class A:
412 def f():
413 __mangled = 1
414 __not_mangled__ = 2
415 import __mangled_mod
416 import __package__.module
417
Benjamin Peterson577473f2010-01-19 00:09:57 +0000418 self.assertIn("_A__mangled", A.f.__code__.co_varnames)
419 self.assertIn("__not_mangled__", A.f.__code__.co_varnames)
420 self.assertIn("_A__mangled_mod", A.f.__code__.co_varnames)
421 self.assertIn("__package__", A.f.__code__.co_varnames)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000422
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000423 def test_compile_ast(self):
424 fname = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400425 if fname.lower().endswith('pyc'):
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000426 fname = fname[:-1]
427 with open(fname, 'r') as f:
428 fcontents = f.read()
429 sample_code = [
430 ['<assign>', 'x = 5'],
431 ['<ifblock>', """if True:\n pass\n"""],
432 ['<forblock>', """for n in [1, 2, 3]:\n print(n)\n"""],
433 ['<deffunc>', """def foo():\n pass\nfoo()\n"""],
434 [fname, fcontents],
435 ]
436
437 for fname, code in sample_code:
438 co1 = compile(code, '%s1' % fname, 'exec')
439 ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000440 self.assertTrue(type(ast) == _ast.Module)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000441 co2 = compile(ast, '%s3' % fname, 'exec')
442 self.assertEqual(co1, co2)
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000443 # the code object's filename comes from the second compilation step
444 self.assertEqual(co2.co_filename, '%s3' % fname)
445
446 # raise exception when node type doesn't match with compile mode
447 co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST)
448 self.assertRaises(TypeError, compile, co1, '<ast>', 'eval')
449
450 # raise exception when node type is no start node
451 self.assertRaises(TypeError, compile, _ast.If(), '<ast>', 'exec')
452
453 # raise exception when node has invalid children
454 ast = _ast.Module()
455 ast.body = [_ast.BoolOp()]
456 self.assertRaises(TypeError, compile, ast, '<ast>', 'exec')
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000457
Benjamin Petersonee853392015-05-28 14:30:26 -0500458 def test_dict_evaluation_order(self):
459 i = 0
460
461 def f():
462 nonlocal i
463 i += 1
464 return i
465
466 d = {f(): f(), f(): f()}
467 self.assertEqual(d, {1: 2, 3: 4})
468
Serhiy Storchaka9305d832016-06-18 13:53:36 +0300469 def test_compile_filename(self):
Serhiy Storchakafebc3322016-08-06 23:29:29 +0300470 for filename in 'file.py', b'file.py':
Serhiy Storchaka9305d832016-06-18 13:53:36 +0300471 code = compile('pass', filename, 'exec')
472 self.assertEqual(code.co_filename, 'file.py')
Serhiy Storchakafebc3322016-08-06 23:29:29 +0300473 for filename in bytearray(b'file.py'), memoryview(b'file.py'):
474 with self.assertWarns(DeprecationWarning):
475 code = compile('pass', filename, 'exec')
476 self.assertEqual(code.co_filename, 'file.py')
Serhiy Storchaka9305d832016-06-18 13:53:36 +0300477 self.assertRaises(TypeError, compile, 'pass', list(b'file.py'), 'exec')
478
Benjamin Peterson43b06862011-05-27 09:08:01 -0500479 @support.cpython_only
480 def test_same_filename_used(self):
481 s = """def f(): pass\ndef g(): pass"""
482 c = compile(s, "myfile", "exec")
483 for obj in c.co_consts:
484 if isinstance(obj, types.CodeType):
485 self.assertIs(obj.co_filename, c.co_filename)
486
Meador Ingefa21bf02012-01-19 01:08:41 -0600487 def test_single_statement(self):
488 self.compile_single("1 + 2")
489 self.compile_single("\n1 + 2")
490 self.compile_single("1 + 2\n")
491 self.compile_single("1 + 2\n\n")
492 self.compile_single("1 + 2\t\t\n")
493 self.compile_single("1 + 2\t\t\n ")
494 self.compile_single("1 + 2 # one plus two")
495 self.compile_single("1; 2")
496 self.compile_single("import sys; sys")
497 self.compile_single("def f():\n pass")
498 self.compile_single("while False:\n pass")
499 self.compile_single("if x:\n f(x)")
500 self.compile_single("if x:\n f(x)\nelse:\n g(x)")
501 self.compile_single("class T:\n pass")
502
503 def test_bad_single_statement(self):
504 self.assertInvalidSingle('1\n2')
505 self.assertInvalidSingle('def f(): pass')
506 self.assertInvalidSingle('a = 13\nb = 187')
507 self.assertInvalidSingle('del x\ndel y')
508 self.assertInvalidSingle('f()\ng()')
Benjamin Petersoncff92372012-01-19 17:46:13 -0500509 self.assertInvalidSingle('f()\n# blah\nblah()')
510 self.assertInvalidSingle('f()\nxy # blah\nblah()')
Benjamin Peterson77fc1f32012-01-20 11:01:06 -0500511 self.assertInvalidSingle('x = 5 # comment\nx = 6\n')
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000512
Benjamin Petersond73aca72015-04-21 12:05:19 -0400513 def test_particularly_evil_undecodable(self):
514 # Issue 24022
515 src = b'0000\x00\n00000000000\n\x00\n\x9e\n'
516 with tempfile.TemporaryDirectory() as tmpd:
517 fn = os.path.join(tmpd, "bad.py")
518 with open(fn, "wb") as fp:
519 fp.write(src)
520 res = script_helper.run_python_until_end(fn)[0]
521 self.assertIn(b"Non-UTF-8", res.err)
522
Serhiy Storchaka0d441112015-11-14 15:10:35 +0200523 def test_yet_more_evil_still_undecodable(self):
524 # Issue #25388
525 src = b"#\x00\n#\xfd\n"
526 with tempfile.TemporaryDirectory() as tmpd:
527 fn = os.path.join(tmpd, "bad.py")
528 with open(fn, "wb") as fp:
529 fp.write(src)
530 res = script_helper.run_python_until_end(fn)[0]
531 self.assertIn(b"Non-UTF-8", res.err)
532
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000533 @support.cpython_only
534 def test_compiler_recursion_limit(self):
535 # Expected limit is sys.getrecursionlimit() * the scaling factor
536 # in symtable.c (currently 3)
537 # We expect to fail *at* that limit, because we use up some of
538 # the stack depth limit in the test suite code
539 # So we check the expected limit and 75% of that
540 # XXX (ncoghlan): duplicating the scaling factor here is a little
541 # ugly. Perhaps it should be exposed somewhere...
542 fail_depth = sys.getrecursionlimit() * 3
543 success_depth = int(fail_depth * 0.75)
544
545 def check_limit(prefix, repeated):
546 expect_ok = prefix + repeated * success_depth
547 self.compile_single(expect_ok)
548 broken = prefix + repeated * fail_depth
549 details = "Compiling ({!r} + {!r} * {})".format(
550 prefix, repeated, fail_depth)
Yury Selivanovf488fb42015-07-03 01:04:23 -0400551 with self.assertRaises(RecursionError, msg=details):
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000552 self.compile_single(broken)
553
554 check_limit("a", "()")
555 check_limit("a", ".b")
556 check_limit("a", "[0]")
557 check_limit("a", "*a")
558
Martin Pantereeb896c2015-11-07 02:32:21 +0000559 def test_null_terminated(self):
560 # The source code is null-terminated internally, but bytes-like
561 # objects are accepted, which could be not terminated.
Martin Panterd61d8602015-11-08 11:09:13 +0000562 with self.assertRaisesRegex(ValueError, "cannot contain null"):
Martin Pantereeb896c2015-11-07 02:32:21 +0000563 compile("123\x00", "<dummy>", "eval")
Martin Panterd61d8602015-11-08 11:09:13 +0000564 with self.assertRaisesRegex(ValueError, "cannot contain null"):
Martin Pantereeb896c2015-11-07 02:32:21 +0000565 compile(memoryview(b"123\x00"), "<dummy>", "eval")
566 code = compile(memoryview(b"123\x00")[1:-1], "<dummy>", "eval")
567 self.assertEqual(eval(code), 23)
568 code = compile(memoryview(b"1234")[1:-1], "<dummy>", "eval")
569 self.assertEqual(eval(code), 23)
570 code = compile(memoryview(b"$23$")[1:-1], "<dummy>", "eval")
571 self.assertEqual(eval(code), 23)
572
573 # Also test when eval() and exec() do the compilation step
574 self.assertEqual(eval(memoryview(b"1234")[1:-1]), 23)
575 namespace = dict()
576 exec(memoryview(b"ax = 123")[1:-1], namespace)
577 self.assertEqual(namespace['x'], 12)
578
Victor Stinner3cdd5fb2016-01-22 12:33:12 +0100579 def check_constant(self, func, expected):
580 for const in func.__code__.co_consts:
581 if repr(const) == repr(expected):
582 break
583 else:
584 self.fail("unable to find constant %r in %r"
585 % (expected, func.__code__.co_consts))
586
587 # Merging equal constants is not a strict requirement for the Python
588 # semantics, it's a more an implementation detail.
589 @support.cpython_only
590 def test_merge_constants(self):
591 # Issue #25843: compile() must merge constants which are equal
592 # and have the same type.
593
594 def check_same_constant(const):
595 ns = {}
596 code = "f1, f2 = lambda: %r, lambda: %r" % (const, const)
597 exec(code, ns)
598 f1 = ns['f1']
599 f2 = ns['f2']
600 self.assertIs(f1.__code__, f2.__code__)
601 self.check_constant(f1, const)
602 self.assertEqual(repr(f1()), repr(const))
603
604 check_same_constant(None)
605 check_same_constant(0)
606 check_same_constant(0.0)
607 check_same_constant(b'abc')
608 check_same_constant('abc')
609
610 # Note: "lambda: ..." emits "LOAD_CONST Ellipsis",
611 # whereas "lambda: Ellipsis" emits "LOAD_GLOBAL Ellipsis"
612 f1, f2 = lambda: ..., lambda: ...
613 self.assertIs(f1.__code__, f2.__code__)
614 self.check_constant(f1, Ellipsis)
615 self.assertEqual(repr(f1()), repr(Ellipsis))
616
617 # {0} is converted to a constant frozenset({0}) by the peephole
618 # optimizer
619 f1, f2 = lambda x: x in {0}, lambda x: x in {0}
620 self.assertIs(f1.__code__, f2.__code__)
621 self.check_constant(f1, frozenset({0}))
622 self.assertTrue(f1(0))
623
624 def test_dont_merge_constants(self):
625 # Issue #25843: compile() must not merge constants which are equal
626 # but have a different type.
627
628 def check_different_constants(const1, const2):
629 ns = {}
630 exec("f1, f2 = lambda: %r, lambda: %r" % (const1, const2), ns)
631 f1 = ns['f1']
632 f2 = ns['f2']
633 self.assertIsNot(f1.__code__, f2.__code__)
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200634 self.assertNotEqual(f1.__code__, f2.__code__)
Victor Stinner3cdd5fb2016-01-22 12:33:12 +0100635 self.check_constant(f1, const1)
636 self.check_constant(f2, const2)
637 self.assertEqual(repr(f1()), repr(const1))
638 self.assertEqual(repr(f2()), repr(const2))
639
640 check_different_constants(0, 0.0)
641 check_different_constants(+0.0, -0.0)
642 check_different_constants((0,), (0.0,))
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200643 check_different_constants('a', b'a')
644 check_different_constants(('a',), (b'a',))
Victor Stinner3cdd5fb2016-01-22 12:33:12 +0100645
646 # check_different_constants() cannot be used because repr(-0j) is
647 # '(-0-0j)', but when '(-0-0j)' is evaluated to 0j: we loose the sign.
648 f1, f2 = lambda: +0.0j, lambda: -0.0j
649 self.assertIsNot(f1.__code__, f2.__code__)
650 self.check_constant(f1, +0.0j)
651 self.check_constant(f2, -0.0j)
652 self.assertEqual(repr(f1()), repr(+0.0j))
653 self.assertEqual(repr(f2()), repr(-0.0j))
654
655 # {0} is converted to a constant frozenset({0}) by the peephole
656 # optimizer
657 f1, f2 = lambda x: x in {0}, lambda x: x in {0.0}
658 self.assertIsNot(f1.__code__, f2.__code__)
659 self.check_constant(f1, frozenset({0}))
660 self.check_constant(f2, frozenset({0.0}))
661 self.assertTrue(f1(0))
662 self.assertTrue(f2(0.0))
663
Brett Cannona5711202016-09-06 19:36:01 -0700664 def test_path_like_objects(self):
665 # An implicit test for PyUnicode_FSDecoder().
666 class PathLike:
667 def __init__(self, path):
668 self._path = path
669 def __fspath__(self):
670 return self._path
671
672 compile("42", PathLike("test_compile_pathlike"), "single")
673
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +0200674 def test_stack_overflow(self):
675 # bpo-31113: Stack overflow when compile a long sequence of
676 # complex statements.
677 compile("if a: b\n" * 200000, "<dummy>", "exec")
678
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000679
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200680class TestExpressionStackSize(unittest.TestCase):
Antoine Pitrou99614052014-05-23 11:46:03 +0200681 # These tests check that the computed stack size for a code object
682 # stays within reasonable bounds (see issue #21523 for an example
683 # dysfunction).
684 N = 100
685
686 def check_stack_size(self, code):
687 # To assert that the alleged stack size is not O(N), we
688 # check that it is smaller than log(N).
689 if isinstance(code, str):
690 code = compile(code, "<foo>", "single")
691 max_size = math.ceil(math.log(len(code.co_code)))
692 self.assertLessEqual(code.co_stacksize, max_size)
693
694 def test_and(self):
695 self.check_stack_size("x and " * self.N + "x")
696
697 def test_or(self):
698 self.check_stack_size("x or " * self.N + "x")
699
700 def test_and_or(self):
701 self.check_stack_size("x and x or " * self.N + "x")
702
703 def test_chained_comparison(self):
704 self.check_stack_size("x < " * self.N + "x")
705
706 def test_if_else(self):
707 self.check_stack_size("x if x else " * self.N + "x")
708
709 def test_binop(self):
710 self.check_stack_size("x + " * self.N + "x")
711
712 def test_func_and(self):
713 code = "def f(x):\n"
714 code += " x and x\n" * self.N
715 self.check_stack_size(code)
716
Tim Petersd507dab2001-08-30 20:51:59 +0000717
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200718class TestStackSizeStability(unittest.TestCase):
719 # Check that repeating certain snippets doesn't increase the stack size
720 # beyond what a single snippet requires.
721
722 def check_stack_size(self, snippet, async_=False):
723 def compile_snippet(i):
724 ns = {}
725 script = """def func():\n""" + i * snippet
726 if async_:
727 script = "async " + script
728 code = compile(script, "<script>", "exec")
729 exec(code, ns, ns)
730 return ns['func'].__code__
731
732 sizes = [compile_snippet(i).co_stacksize for i in range(2, 5)]
733 if len(set(sizes)) != 1:
734 import dis, io
735 out = io.StringIO()
736 dis.dis(compile_snippet(1), file=out)
737 self.fail("stack sizes diverge with # of consecutive snippets: "
738 "%s\n%s\n%s" % (sizes, snippet, out.getvalue()))
739
740 def test_if(self):
741 snippet = """
742 if x:
743 a
744 """
745 self.check_stack_size(snippet)
746
747 def test_if_else(self):
748 snippet = """
749 if x:
750 a
751 elif y:
752 b
753 else:
754 c
755 """
756 self.check_stack_size(snippet)
757
758 def test_try_except_bare(self):
759 snippet = """
760 try:
761 a
762 except:
763 b
764 """
765 self.check_stack_size(snippet)
766
767 def test_try_except_qualified(self):
768 snippet = """
769 try:
770 a
771 except ImportError:
772 b
773 except:
774 c
775 else:
776 d
777 """
778 self.check_stack_size(snippet)
779
780 def test_try_except_as(self):
781 snippet = """
782 try:
783 a
784 except ImportError as e:
785 b
786 except:
787 c
788 else:
789 d
790 """
791 self.check_stack_size(snippet)
792
793 def test_try_finally(self):
794 snippet = """
795 try:
796 a
797 finally:
798 b
799 """
800 self.check_stack_size(snippet)
801
802 def test_with(self):
803 snippet = """
804 with x as y:
805 a
806 """
807 self.check_stack_size(snippet)
808
809 def test_while_else(self):
810 snippet = """
811 while x:
812 a
813 else:
814 b
815 """
816 self.check_stack_size(snippet)
817
818 def test_for(self):
819 snippet = """
820 for x in y:
821 a
822 """
823 self.check_stack_size(snippet)
824
825 def test_for_else(self):
826 snippet = """
827 for x in y:
828 a
829 else:
830 b
831 """
832 self.check_stack_size(snippet)
833
834 def test_for_break_continue(self):
835 snippet = """
836 for x in y:
837 if z:
838 break
839 elif u:
840 continue
841 else:
842 a
843 else:
844 b
845 """
846 self.check_stack_size(snippet)
847
848 def test_for_break_continue_inside_try_finally_block(self):
849 snippet = """
850 for x in y:
851 try:
852 if z:
853 break
854 elif u:
855 continue
856 else:
857 a
858 finally:
859 f
860 else:
861 b
862 """
863 self.check_stack_size(snippet)
864
865 def test_for_break_inside_finally_block(self):
866 snippet = """
867 for x in y:
868 try:
869 t
870 finally:
871 if z:
872 break
873 else:
874 a
875 else:
876 b
877 """
878 self.check_stack_size(snippet)
879
880 def test_for_break_continue_inside_except_block(self):
881 snippet = """
882 for x in y:
883 try:
884 t
885 except:
886 if z:
887 break
888 elif u:
889 continue
890 else:
891 a
892 else:
893 b
894 """
895 self.check_stack_size(snippet)
896
897 def test_for_break_continue_inside_with_block(self):
898 snippet = """
899 for x in y:
900 with c:
901 if z:
902 break
903 elif u:
904 continue
905 else:
906 a
907 else:
908 b
909 """
910 self.check_stack_size(snippet)
911
912 def test_return_inside_try_finally_block(self):
913 snippet = """
914 try:
915 if z:
916 return
917 else:
918 a
919 finally:
920 f
921 """
922 self.check_stack_size(snippet)
923
924 def test_return_inside_finally_block(self):
925 snippet = """
926 try:
927 t
928 finally:
929 if z:
930 return
931 else:
932 a
933 """
934 self.check_stack_size(snippet)
935
936 def test_return_inside_except_block(self):
937 snippet = """
938 try:
939 t
940 except:
941 if z:
942 return
943 else:
944 a
945 """
946 self.check_stack_size(snippet)
947
948 def test_return_inside_with_block(self):
949 snippet = """
950 with c:
951 if z:
952 return
953 else:
954 a
955 """
956 self.check_stack_size(snippet)
957
958 def test_async_with(self):
959 snippet = """
960 async with x as y:
961 a
962 """
963 self.check_stack_size(snippet, async_=True)
964
965 def test_async_for(self):
966 snippet = """
967 async for x in y:
968 a
969 """
970 self.check_stack_size(snippet, async_=True)
971
972 def test_async_for_else(self):
973 snippet = """
974 async for x in y:
975 a
976 else:
977 b
978 """
979 self.check_stack_size(snippet, async_=True)
980
981 def test_for_break_continue_inside_async_with_block(self):
982 snippet = """
983 for x in y:
984 async with c:
985 if z:
986 break
987 elif u:
988 continue
989 else:
990 a
991 else:
992 b
993 """
994 self.check_stack_size(snippet, async_=True)
995
996 def test_return_inside_async_with_block(self):
997 snippet = """
998 async with c:
999 if z:
1000 return
1001 else:
1002 a
1003 """
1004 self.check_stack_size(snippet, async_=True)
1005
1006
Raymond Hettinger8a99b502003-06-23 13:36:57 +00001007if __name__ == "__main__":
Antoine Pitrou99614052014-05-23 11:46:03 +02001008 unittest.main()