blob: 6535316dbea24fbe90491557fb3f9c97681ffea1 [file] [log] [blame]
Gregory P. Smith49fa4a92018-11-08 17:55:07 -08001import dis
Antoine Pitrou99614052014-05-23 11:46:03 +02002import math
Benjamin Petersond73aca72015-04-21 12:05:19 -04003import os
Raymond Hettinger8a99b502003-06-23 13:36:57 +00004import unittest
Raymond Hettinger8a99b502003-06-23 13:36:57 +00005import sys
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00006import _ast
Benjamin Petersond73aca72015-04-21 12:05:19 -04007import tempfile
Benjamin Peterson43b06862011-05-27 09:08:01 -05008import types
Berker Peksag076dbd02015-05-06 07:01:52 +03009from test import support
Serhiy Storchakab21d1552018-03-02 11:53:51 +020010from test.support import script_helper, FakePath
Peter Schneider-Kampfdee0f02000-07-25 22:15:45 +000011
Raymond Hettinger8a99b502003-06-23 13:36:57 +000012class TestSpecifics(unittest.TestCase):
Jeremy Hylton778e2652001-11-09 19:50:08 +000013
Meador Ingefa21bf02012-01-19 01:08:41 -060014 def compile_single(self, source):
15 compile(source, "<single>", "single")
16
17 def assertInvalidSingle(self, source):
18 self.assertRaises(SyntaxError, self.compile_single, source)
19
Benjamin Petersonaeaa5922009-11-13 00:17:59 +000020 def test_no_ending_newline(self):
21 compile("hi", "<test>", "exec")
22 compile("hi\r", "<test>", "exec")
23
24 def test_empty(self):
25 compile("", "<test>", "exec")
26
27 def test_other_newlines(self):
28 compile("\r\n", "<test>", "exec")
29 compile("\r", "<test>", "exec")
30 compile("hi\r\nstuff\r\ndef f():\n pass\r", "<test>", "exec")
31 compile("this_is\rreally_old_mac\rdef f():\n pass", "<test>", "exec")
32
Raymond Hettinger8a99b502003-06-23 13:36:57 +000033 def test_debug_assignment(self):
34 # catch assignments to __debug__
35 self.assertRaises(SyntaxError, compile, '__debug__ = 1', '?', 'single')
Georg Brandl1a3284e2007-12-02 09:40:06 +000036 import builtins
37 prev = builtins.__debug__
38 setattr(builtins, '__debug__', 'sure')
Serhiy Storchaka3325a672017-12-15 12:35:48 +020039 self.assertEqual(__debug__, prev)
Georg Brandl1a3284e2007-12-02 09:40:06 +000040 setattr(builtins, '__debug__', prev)
Jeremy Hylton778e2652001-11-09 19:50:08 +000041
Raymond Hettinger8a99b502003-06-23 13:36:57 +000042 def test_argument_handling(self):
43 # detect duplicate positional and keyword arguments
44 self.assertRaises(SyntaxError, eval, 'lambda a,a:0')
45 self.assertRaises(SyntaxError, eval, 'lambda a,a=1:0')
46 self.assertRaises(SyntaxError, eval, 'lambda a=1,a=1:0')
Benjamin Petersonec19d952008-06-30 15:01:21 +000047 self.assertRaises(SyntaxError, exec, 'def f(a, a): pass')
48 self.assertRaises(SyntaxError, exec, 'def f(a = 0, a = 1): pass')
49 self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1')
Jeremy Hylton778e2652001-11-09 19:50:08 +000050
Raymond Hettinger8a99b502003-06-23 13:36:57 +000051 def test_syntax_error(self):
52 self.assertRaises(SyntaxError, compile, "1+*3", "filename", "exec")
Peter Schneider-Kampfdee0f02000-07-25 22:15:45 +000053
Guido van Rossumcd16bf62007-06-13 18:07:49 +000054 def test_none_keyword_arg(self):
55 self.assertRaises(SyntaxError, compile, "f(None=1)", "<string>", "exec")
56
Raymond Hettinger8a99b502003-06-23 13:36:57 +000057 def test_duplicate_global_local(self):
Benjamin Petersonec19d952008-06-30 15:01:21 +000058 self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1')
Peter Schneider-Kampfdee0f02000-07-25 22:15:45 +000059
Raymond Hettinger66bd2332004-08-02 08:30:07 +000060 def test_exec_with_general_mapping_for_locals(self):
61
62 class M:
63 "Test mapping interface versus possible calls from eval()."
64 def __getitem__(self, key):
65 if key == 'a':
66 return 12
67 raise KeyError
68 def __setitem__(self, key, value):
69 self.results = (key, value)
Guido van Rossum63eecc72007-02-22 23:55:25 +000070 def keys(self):
71 return list('xyz')
Raymond Hettinger66bd2332004-08-02 08:30:07 +000072
73 m = M()
74 g = globals()
Georg Brandl7cae87c2006-09-06 06:51:57 +000075 exec('z = a', g, m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000076 self.assertEqual(m.results, ('z', 12))
77 try:
Georg Brandl7cae87c2006-09-06 06:51:57 +000078 exec('z = b', g, m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000079 except NameError:
80 pass
81 else:
82 self.fail('Did not detect a KeyError')
Georg Brandl7cae87c2006-09-06 06:51:57 +000083 exec('z = dir()', g, m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000084 self.assertEqual(m.results, ('z', list('xyz')))
Georg Brandl7cae87c2006-09-06 06:51:57 +000085 exec('z = globals()', g, m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000086 self.assertEqual(m.results, ('z', g))
Georg Brandl7cae87c2006-09-06 06:51:57 +000087 exec('z = locals()', g, m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000088 self.assertEqual(m.results, ('z', m))
Benjamin Petersonec19d952008-06-30 15:01:21 +000089 self.assertRaises(TypeError, exec, 'z = b', m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000090
91 class A:
92 "Non-mapping"
93 pass
94 m = A()
Benjamin Petersonec19d952008-06-30 15:01:21 +000095 self.assertRaises(TypeError, exec, 'z = a', g, m)
Raymond Hettinger66bd2332004-08-02 08:30:07 +000096
97 # Verify that dict subclasses work as well
98 class D(dict):
99 def __getitem__(self, key):
100 if key == 'a':
101 return 12
102 return dict.__getitem__(self, key)
103 d = D()
Georg Brandl7cae87c2006-09-06 06:51:57 +0000104 exec('z = a', g, d)
Raymond Hettinger66bd2332004-08-02 08:30:07 +0000105 self.assertEqual(d['z'], 12)
106
Neal Norwitz6ab080c2005-10-24 00:08:10 +0000107 def test_extended_arg(self):
108 longexpr = 'x = x or ' + '-x' * 2500
Georg Brandl7cae87c2006-09-06 06:51:57 +0000109 g = {}
Neal Norwitz6ab080c2005-10-24 00:08:10 +0000110 code = '''
111def f(x):
112 %s
113 %s
114 %s
115 %s
116 %s
117 %s
118 %s
119 %s
120 %s
121 %s
122 # the expressions above have no effect, x == argument
123 while x:
124 x -= 1
125 # EXTENDED_ARG/JUMP_ABSOLUTE here
126 return x
127''' % ((longexpr,)*10)
Georg Brandl7cae87c2006-09-06 06:51:57 +0000128 exec(code, g)
129 self.assertEqual(g['f'](5), 0)
Neal Norwitz6ab080c2005-10-24 00:08:10 +0000130
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000131 def test_argument_order(self):
Benjamin Petersonec19d952008-06-30 15:01:21 +0000132 self.assertRaises(SyntaxError, exec, 'def f(a=1, b): pass')
Jeremy Hylton121b6eb2001-02-19 23:53:42 +0000133
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000134 def test_float_literals(self):
135 # testing bad float literals
136 self.assertRaises(SyntaxError, eval, "2e")
137 self.assertRaises(SyntaxError, eval, "2.0e+")
138 self.assertRaises(SyntaxError, eval, "1e-")
139 self.assertRaises(SyntaxError, eval, "3-4e/21")
Jeremy Hylton121b6eb2001-02-19 23:53:42 +0000140
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000141 def test_indentation(self):
142 # testing compile() of indented block w/o trailing newline"
143 s = """
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000144if 1:
145 if 2:
146 pass"""
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000147 compile(s, "<string>", "exec")
148
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000149 # This test is probably specific to CPython and may not generalize
150 # to other implementations. We are trying to ensure that when
151 # the first line of code starts after 256, correct line numbers
152 # in tracebacks are still produced.
153 def test_leading_newlines(self):
154 s256 = "".join(["\n"] * 256 + ["spam"])
155 co = compile(s256, 'fn', 'exec')
156 self.assertEqual(co.co_firstlineno, 257)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000157 self.assertEqual(co.co_lnotab, bytes())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000158
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000159 def test_literals_with_leading_zeroes(self):
160 for arg in ["077787", "0xj", "0x.", "0e", "090000000000000",
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000161 "080000000000000", "000000000000009", "000000000000008",
162 "0b42", "0BADCAFE", "0o123456789", "0b1.1", "0o4.2",
163 "0b101j2", "0o153j2", "0b100e1", "0o777e1", "0777",
164 "000777", "000000000000007"]:
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000165 self.assertRaises(SyntaxError, eval, arg)
166
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000167 self.assertEqual(eval("0xff"), 255)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000168 self.assertEqual(eval("0777."), 777)
169 self.assertEqual(eval("0777.0"), 777)
170 self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777)
171 self.assertEqual(eval("0777e1"), 7770)
172 self.assertEqual(eval("0e0"), 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000173 self.assertEqual(eval("0000e-012"), 0)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000174 self.assertEqual(eval("09.5"), 9.5)
175 self.assertEqual(eval("0777j"), 777j)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000176 self.assertEqual(eval("000"), 0)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000177 self.assertEqual(eval("00j"), 0j)
178 self.assertEqual(eval("00.0"), 0)
179 self.assertEqual(eval("0e3"), 0)
180 self.assertEqual(eval("090000000000000."), 90000000000000.)
181 self.assertEqual(eval("090000000000000.0000000000000000000000"), 90000000000000.)
182 self.assertEqual(eval("090000000000000e0"), 90000000000000.)
183 self.assertEqual(eval("090000000000000e-0"), 90000000000000.)
184 self.assertEqual(eval("090000000000000j"), 90000000000000j)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000185 self.assertEqual(eval("000000000000008."), 8.)
186 self.assertEqual(eval("000000000000009."), 9.)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000187 self.assertEqual(eval("0b101010"), 42)
188 self.assertEqual(eval("-0b000000000010"), -2)
189 self.assertEqual(eval("0o777"), 511)
190 self.assertEqual(eval("-0o0000010"), -8)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000191
192 def test_unary_minus(self):
193 # Verify treatment of unary minus on negative numbers SF bug #660455
Christian Heimesa37d4c62007-12-04 23:02:19 +0000194 if sys.maxsize == 2147483647:
Guido van Rossum6c9e1302003-11-29 23:52:13 +0000195 # 32-bit machine
196 all_one_bits = '0xffffffff'
Guido van Rossume2a383d2007-01-15 16:59:06 +0000197 self.assertEqual(eval(all_one_bits), 4294967295)
198 self.assertEqual(eval("-" + all_one_bits), -4294967295)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000199 elif sys.maxsize == 9223372036854775807:
Guido van Rossum6c9e1302003-11-29 23:52:13 +0000200 # 64-bit machine
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000201 all_one_bits = '0xffffffffffffffff'
Guido van Rossume2a383d2007-01-15 16:59:06 +0000202 self.assertEqual(eval(all_one_bits), 18446744073709551615)
203 self.assertEqual(eval("-" + all_one_bits), -18446744073709551615)
Guido van Rossum6c9e1302003-11-29 23:52:13 +0000204 else:
205 self.fail("How many bits *does* this machine have???")
Ezio Melotti42da6632011-03-15 05:18:48 +0200206 # Verify treatment of constant folding on -(sys.maxsize+1)
Serhiy Storchaka95949422013-08-27 19:40:23 +0300207 # i.e. -2147483648 on 32 bit platforms. Should return int.
Ezio Melottie9615932010-01-24 19:26:24 +0000208 self.assertIsInstance(eval("%s" % (-sys.maxsize - 1)), int)
209 self.assertIsInstance(eval("%s" % (-sys.maxsize - 2)), int)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000210
Christian Heimesa37d4c62007-12-04 23:02:19 +0000211 if sys.maxsize == 9223372036854775807:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000212 def test_32_63_bit_values(self):
213 a = +4294967296 # 1 << 32
214 b = -4294967296 # 1 << 32
215 c = +281474976710656 # 1 << 48
216 d = -281474976710656 # 1 << 48
217 e = +4611686018427387904 # 1 << 62
218 f = -4611686018427387904 # 1 << 62
219 g = +9223372036854775807 # 1 << 63 - 1
220 h = -9223372036854775807 # 1 << 63 - 1
221
Neal Norwitz221085d2007-02-25 20:55:47 +0000222 for variable in self.test_32_63_bit_values.__code__.co_consts:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000223 if variable is not None:
Ezio Melottie9615932010-01-24 19:26:24 +0000224 self.assertIsInstance(variable, int)
Raymond Hettinger8a99b502003-06-23 13:36:57 +0000225
226 def test_sequence_unpacking_error(self):
227 # Verify sequence packing/unpacking with "or". SF bug #757818
228 i,j = (1, -1) or (-1, 1)
229 self.assertEqual(i, 1)
230 self.assertEqual(j, -1)
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000231
Raymond Hettinger11a70c72004-07-17 21:46:25 +0000232 def test_none_assignment(self):
233 stmts = [
234 'None = 0',
235 'None += 0',
236 '__builtins__.None = 0',
237 'def None(): pass',
238 'class None: pass',
239 '(a, None) = 0, 0',
240 'for None in range(10): pass',
241 'def f(None): pass',
Benjamin Peterson78565b22009-06-28 19:19:51 +0000242 'import None',
243 'import x as None',
244 'from x import None',
245 'from x import y as None'
Raymond Hettinger11a70c72004-07-17 21:46:25 +0000246 ]
247 for stmt in stmts:
248 stmt += "\n"
249 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'single')
250 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
Tim Petersd507dab2001-08-30 20:51:59 +0000251
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000252 def test_import(self):
253 succeed = [
254 'import sys',
255 'import os, sys',
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000256 'import os as bar',
257 'import os.path as bar',
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000258 'from __future__ import nested_scopes, generators',
259 'from __future__ import (nested_scopes,\ngenerators)',
260 'from __future__ import (nested_scopes,\ngenerators,)',
261 'from sys import stdin, stderr, stdout',
262 'from sys import (stdin, stderr,\nstdout)',
263 'from sys import (stdin, stderr,\nstdout,)',
264 'from sys import (stdin\n, stderr, stdout)',
265 'from sys import (stdin\n, stderr, stdout,)',
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 'from sys import (stdin as si, stdout as so, stderr as se,)',
269 ]
270 fail = [
271 'import (os, sys)',
272 'import (os), (sys)',
273 'import ((os), (sys))',
274 'import (sys',
275 'import sys)',
276 'import (os,)',
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000277 'import os As bar',
278 'import os.path a bar',
279 'from sys import stdin As stdout',
280 'from sys import stdin a stdout',
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000281 'from (sys) import stdin',
282 'from __future__ import (nested_scopes',
283 'from __future__ import nested_scopes)',
284 'from __future__ import nested_scopes,\ngenerators',
285 'from sys import (stdin',
286 'from sys import stdin)',
287 'from sys import stdin, stdout,\nstderr',
288 'from sys import stdin si',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +0200289 'from sys import stdin,',
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000290 'from sys import (*)',
291 'from sys import (stdin,, stdout, stderr)',
292 'from sys import (stdin, stdout),',
293 ]
294 for stmt in succeed:
295 compile(stmt, 'tmp', 'exec')
296 for stmt in fail:
297 self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
298
Raymond Hettinger9047c8f2004-10-24 00:10:06 +0000299 def test_for_distinct_code_objects(self):
300 # SF bug 1048870
301 def f():
302 f1 = lambda x=1: x
303 f2 = lambda x=2: x
304 return f1, f2
305 f1, f2 = f()
Neal Norwitz221085d2007-02-25 20:55:47 +0000306 self.assertNotEqual(id(f1.__code__), id(f2.__code__))
Raymond Hettinger9047c8f2004-10-24 00:10:06 +0000307
Benjamin Petersone6dd2cb2010-03-17 20:56:58 +0000308 def test_lambda_doc(self):
309 l = lambda: "foo"
310 self.assertIsNone(l.__doc__)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000311
Serhiy Storchaka607cb9c2014-09-05 11:00:56 +0300312 def test_encoding(self):
313 code = b'# -*- coding: badencoding -*-\npass\n'
314 self.assertRaises(SyntaxError, compile, code, 'tmp', 'exec')
315 code = '# -*- coding: badencoding -*-\n"\xc2\xa4"\n'
316 compile(code, 'tmp', 'exec')
317 self.assertEqual(eval(code), '\xc2\xa4')
318 code = '"\xc2\xa4"\n'
319 self.assertEqual(eval(code), '\xc2\xa4')
320 code = b'"\xc2\xa4"\n'
321 self.assertEqual(eval(code), '\xa4')
322 code = b'# -*- coding: latin1 -*-\n"\xc2\xa4"\n'
323 self.assertEqual(eval(code), '\xc2\xa4')
324 code = b'# -*- coding: utf-8 -*-\n"\xc2\xa4"\n'
325 self.assertEqual(eval(code), '\xa4')
326 code = b'# -*- coding: iso8859-15 -*-\n"\xc2\xa4"\n'
327 self.assertEqual(eval(code), '\xc2\u20ac')
328 code = '"""\\\n# -*- coding: iso8859-15 -*-\n\xc2\xa4"""\n'
329 self.assertEqual(eval(code), '# -*- coding: iso8859-15 -*-\n\xc2\xa4')
330 code = b'"""\\\n# -*- coding: iso8859-15 -*-\n\xc2\xa4"""\n'
331 self.assertEqual(eval(code), '# -*- coding: iso8859-15 -*-\n\xa4')
Benjamin Peterson5d2ad252010-03-17 20:57:32 +0000332
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000333 def test_subscripts(self):
334 # SF bug 1448804
335 # Class to make testing subscript results easy
336 class str_map(object):
337 def __init__(self):
338 self.data = {}
339 def __getitem__(self, key):
340 return self.data[str(key)]
341 def __setitem__(self, key, value):
342 self.data[str(key)] = value
343 def __delitem__(self, key):
344 del self.data[str(key)]
345 def __contains__(self, key):
346 return str(key) in self.data
347 d = str_map()
348 # Index
349 d[1] = 1
350 self.assertEqual(d[1], 1)
351 d[1] += 1
352 self.assertEqual(d[1], 2)
353 del d[1]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000354 self.assertNotIn(1, d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000355 # Tuple of indices
356 d[1, 1] = 1
357 self.assertEqual(d[1, 1], 1)
358 d[1, 1] += 1
359 self.assertEqual(d[1, 1], 2)
360 del d[1, 1]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000361 self.assertNotIn((1, 1), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000362 # Simple slice
363 d[1:2] = 1
364 self.assertEqual(d[1:2], 1)
365 d[1:2] += 1
366 self.assertEqual(d[1:2], 2)
367 del d[1:2]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000368 self.assertNotIn(slice(1, 2), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000369 # Tuple of simple slices
370 d[1:2, 1:2] = 1
371 self.assertEqual(d[1:2, 1:2], 1)
372 d[1:2, 1:2] += 1
373 self.assertEqual(d[1:2, 1:2], 2)
374 del d[1:2, 1:2]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000375 self.assertNotIn((slice(1, 2), slice(1, 2)), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000376 # Extended slice
377 d[1:2:3] = 1
378 self.assertEqual(d[1:2:3], 1)
379 d[1:2:3] += 1
380 self.assertEqual(d[1:2:3], 2)
381 del d[1:2:3]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000382 self.assertNotIn(slice(1, 2, 3), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000383 # Tuple of extended slices
384 d[1:2:3, 1:2:3] = 1
385 self.assertEqual(d[1:2:3, 1:2:3], 1)
386 d[1:2:3, 1:2:3] += 1
387 self.assertEqual(d[1:2:3, 1:2:3], 2)
388 del d[1:2:3, 1:2:3]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000389 self.assertNotIn((slice(1, 2, 3), slice(1, 2, 3)), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000390 # Ellipsis
391 d[...] = 1
392 self.assertEqual(d[...], 1)
393 d[...] += 1
394 self.assertEqual(d[...], 2)
395 del d[...]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000396 self.assertNotIn(Ellipsis, d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000397 # Tuple of Ellipses
398 d[..., ...] = 1
399 self.assertEqual(d[..., ...], 1)
400 d[..., ...] += 1
401 self.assertEqual(d[..., ...], 2)
402 del d[..., ...]
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000403 self.assertNotIn((Ellipsis, Ellipsis), d)
Nick Coghlaneadee9a2006-03-13 12:31:58 +0000404
Guido van Rossum0240b922007-02-26 21:23:50 +0000405 def test_annotation_limit(self):
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200406 # more than 255 annotations, should compile ok
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000407 s = "def f(%s): pass"
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200408 s %= ', '.join('a%d:%d' % (i,i) for i in range(300))
Guido van Rossum0240b922007-02-26 21:23:50 +0000409 compile(s, '?', 'exec')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000410
411 def test_mangling(self):
412 class A:
413 def f():
414 __mangled = 1
415 __not_mangled__ = 2
416 import __mangled_mod
417 import __package__.module
418
Benjamin Peterson577473f2010-01-19 00:09:57 +0000419 self.assertIn("_A__mangled", A.f.__code__.co_varnames)
420 self.assertIn("__not_mangled__", A.f.__code__.co_varnames)
421 self.assertIn("_A__mangled_mod", A.f.__code__.co_varnames)
422 self.assertIn("__package__", A.f.__code__.co_varnames)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000423
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000424 def test_compile_ast(self):
425 fname = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400426 if fname.lower().endswith('pyc'):
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000427 fname = fname[:-1]
428 with open(fname, 'r') as f:
429 fcontents = f.read()
430 sample_code = [
431 ['<assign>', 'x = 5'],
432 ['<ifblock>', """if True:\n pass\n"""],
433 ['<forblock>', """for n in [1, 2, 3]:\n print(n)\n"""],
434 ['<deffunc>', """def foo():\n pass\nfoo()\n"""],
435 [fname, fcontents],
436 ]
437
438 for fname, code in sample_code:
439 co1 = compile(code, '%s1' % fname, 'exec')
440 ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000441 self.assertTrue(type(ast) == _ast.Module)
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000442 co2 = compile(ast, '%s3' % fname, 'exec')
443 self.assertEqual(co1, co2)
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000444 # the code object's filename comes from the second compilation step
445 self.assertEqual(co2.co_filename, '%s3' % fname)
446
447 # raise exception when node type doesn't match with compile mode
448 co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST)
449 self.assertRaises(TypeError, compile, co1, '<ast>', 'eval')
450
451 # raise exception when node type is no start node
452 self.assertRaises(TypeError, compile, _ast.If(), '<ast>', 'exec')
453
454 # raise exception when node has invalid children
455 ast = _ast.Module()
456 ast.body = [_ast.BoolOp()]
457 self.assertRaises(TypeError, compile, ast, '<ast>', 'exec')
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000458
Benjamin Petersonee853392015-05-28 14:30:26 -0500459 def test_dict_evaluation_order(self):
460 i = 0
461
462 def f():
463 nonlocal i
464 i += 1
465 return i
466
467 d = {f(): f(), f(): f()}
468 self.assertEqual(d, {1: 2, 3: 4})
469
Serhiy Storchaka9305d832016-06-18 13:53:36 +0300470 def test_compile_filename(self):
Serhiy Storchakafebc3322016-08-06 23:29:29 +0300471 for filename in 'file.py', b'file.py':
Serhiy Storchaka9305d832016-06-18 13:53:36 +0300472 code = compile('pass', filename, 'exec')
473 self.assertEqual(code.co_filename, 'file.py')
Serhiy Storchakafebc3322016-08-06 23:29:29 +0300474 for filename in bytearray(b'file.py'), memoryview(b'file.py'):
475 with self.assertWarns(DeprecationWarning):
476 code = compile('pass', filename, 'exec')
477 self.assertEqual(code.co_filename, 'file.py')
Serhiy Storchaka9305d832016-06-18 13:53:36 +0300478 self.assertRaises(TypeError, compile, 'pass', list(b'file.py'), 'exec')
479
Benjamin Peterson43b06862011-05-27 09:08:01 -0500480 @support.cpython_only
481 def test_same_filename_used(self):
482 s = """def f(): pass\ndef g(): pass"""
483 c = compile(s, "myfile", "exec")
484 for obj in c.co_consts:
485 if isinstance(obj, types.CodeType):
486 self.assertIs(obj.co_filename, c.co_filename)
487
Meador Ingefa21bf02012-01-19 01:08:41 -0600488 def test_single_statement(self):
489 self.compile_single("1 + 2")
490 self.compile_single("\n1 + 2")
491 self.compile_single("1 + 2\n")
492 self.compile_single("1 + 2\n\n")
493 self.compile_single("1 + 2\t\t\n")
494 self.compile_single("1 + 2\t\t\n ")
495 self.compile_single("1 + 2 # one plus two")
496 self.compile_single("1; 2")
497 self.compile_single("import sys; sys")
498 self.compile_single("def f():\n pass")
499 self.compile_single("while False:\n pass")
500 self.compile_single("if x:\n f(x)")
501 self.compile_single("if x:\n f(x)\nelse:\n g(x)")
502 self.compile_single("class T:\n pass")
503
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100504 @unittest.skipIf(sys.flags.use_peg, 'Pegen does not disallow multiline single stmts')
Meador Ingefa21bf02012-01-19 01:08:41 -0600505 def test_bad_single_statement(self):
506 self.assertInvalidSingle('1\n2')
507 self.assertInvalidSingle('def f(): pass')
508 self.assertInvalidSingle('a = 13\nb = 187')
509 self.assertInvalidSingle('del x\ndel y')
510 self.assertInvalidSingle('f()\ng()')
Benjamin Petersoncff92372012-01-19 17:46:13 -0500511 self.assertInvalidSingle('f()\n# blah\nblah()')
512 self.assertInvalidSingle('f()\nxy # blah\nblah()')
Benjamin Peterson77fc1f32012-01-20 11:01:06 -0500513 self.assertInvalidSingle('x = 5 # comment\nx = 6\n')
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000514
Benjamin Petersond73aca72015-04-21 12:05:19 -0400515 def test_particularly_evil_undecodable(self):
516 # Issue 24022
517 src = b'0000\x00\n00000000000\n\x00\n\x9e\n'
518 with tempfile.TemporaryDirectory() as tmpd:
519 fn = os.path.join(tmpd, "bad.py")
520 with open(fn, "wb") as fp:
521 fp.write(src)
522 res = script_helper.run_python_until_end(fn)[0]
523 self.assertIn(b"Non-UTF-8", res.err)
524
Serhiy Storchaka0d441112015-11-14 15:10:35 +0200525 def test_yet_more_evil_still_undecodable(self):
526 # Issue #25388
527 src = b"#\x00\n#\xfd\n"
528 with tempfile.TemporaryDirectory() as tmpd:
529 fn = os.path.join(tmpd, "bad.py")
530 with open(fn, "wb") as fp:
531 fp.write(src)
532 res = script_helper.run_python_until_end(fn)[0]
533 self.assertIn(b"Non-UTF-8", res.err)
534
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000535 @support.cpython_only
536 def test_compiler_recursion_limit(self):
537 # Expected limit is sys.getrecursionlimit() * the scaling factor
538 # in symtable.c (currently 3)
539 # We expect to fail *at* that limit, because we use up some of
540 # the stack depth limit in the test suite code
541 # So we check the expected limit and 75% of that
542 # XXX (ncoghlan): duplicating the scaling factor here is a little
543 # ugly. Perhaps it should be exposed somewhere...
544 fail_depth = sys.getrecursionlimit() * 3
545 success_depth = int(fail_depth * 0.75)
546
547 def check_limit(prefix, repeated):
548 expect_ok = prefix + repeated * success_depth
549 self.compile_single(expect_ok)
550 broken = prefix + repeated * fail_depth
551 details = "Compiling ({!r} + {!r} * {})".format(
552 prefix, repeated, fail_depth)
Yury Selivanovf488fb42015-07-03 01:04:23 -0400553 with self.assertRaises(RecursionError, msg=details):
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000554 self.compile_single(broken)
555
556 check_limit("a", "()")
557 check_limit("a", ".b")
558 check_limit("a", "[0]")
559 check_limit("a", "*a")
560
Martin Pantereeb896c2015-11-07 02:32:21 +0000561 def test_null_terminated(self):
562 # The source code is null-terminated internally, but bytes-like
563 # objects are accepted, which could be not terminated.
Martin Panterd61d8602015-11-08 11:09:13 +0000564 with self.assertRaisesRegex(ValueError, "cannot contain null"):
Martin Pantereeb896c2015-11-07 02:32:21 +0000565 compile("123\x00", "<dummy>", "eval")
Martin Panterd61d8602015-11-08 11:09:13 +0000566 with self.assertRaisesRegex(ValueError, "cannot contain null"):
Martin Pantereeb896c2015-11-07 02:32:21 +0000567 compile(memoryview(b"123\x00"), "<dummy>", "eval")
568 code = compile(memoryview(b"123\x00")[1:-1], "<dummy>", "eval")
569 self.assertEqual(eval(code), 23)
570 code = compile(memoryview(b"1234")[1:-1], "<dummy>", "eval")
571 self.assertEqual(eval(code), 23)
572 code = compile(memoryview(b"$23$")[1:-1], "<dummy>", "eval")
573 self.assertEqual(eval(code), 23)
574
575 # Also test when eval() and exec() do the compilation step
576 self.assertEqual(eval(memoryview(b"1234")[1:-1]), 23)
577 namespace = dict()
578 exec(memoryview(b"ax = 123")[1:-1], namespace)
579 self.assertEqual(namespace['x'], 12)
580
Victor Stinner3cdd5fb2016-01-22 12:33:12 +0100581 def check_constant(self, func, expected):
582 for const in func.__code__.co_consts:
583 if repr(const) == repr(expected):
584 break
585 else:
586 self.fail("unable to find constant %r in %r"
587 % (expected, func.__code__.co_consts))
588
589 # Merging equal constants is not a strict requirement for the Python
590 # semantics, it's a more an implementation detail.
591 @support.cpython_only
592 def test_merge_constants(self):
593 # Issue #25843: compile() must merge constants which are equal
594 # and have the same type.
595
596 def check_same_constant(const):
597 ns = {}
598 code = "f1, f2 = lambda: %r, lambda: %r" % (const, const)
599 exec(code, ns)
600 f1 = ns['f1']
601 f2 = ns['f2']
602 self.assertIs(f1.__code__, f2.__code__)
603 self.check_constant(f1, const)
604 self.assertEqual(repr(f1()), repr(const))
605
606 check_same_constant(None)
607 check_same_constant(0)
608 check_same_constant(0.0)
609 check_same_constant(b'abc')
610 check_same_constant('abc')
611
612 # Note: "lambda: ..." emits "LOAD_CONST Ellipsis",
613 # whereas "lambda: Ellipsis" emits "LOAD_GLOBAL Ellipsis"
614 f1, f2 = lambda: ..., lambda: ...
615 self.assertIs(f1.__code__, f2.__code__)
616 self.check_constant(f1, Ellipsis)
617 self.assertEqual(repr(f1()), repr(Ellipsis))
618
INADA Naokif7e4d362018-11-29 00:58:46 +0900619 # Merge constants in tuple or frozenset
620 f1, f2 = lambda: "not a name", lambda: ("not a name",)
621 f3 = lambda x: x in {("not a name",)}
622 self.assertIs(f1.__code__.co_consts[1],
623 f2.__code__.co_consts[1][0])
624 self.assertIs(next(iter(f3.__code__.co_consts[1])),
625 f2.__code__.co_consts[1])
626
Victor Stinner3cdd5fb2016-01-22 12:33:12 +0100627 # {0} is converted to a constant frozenset({0}) by the peephole
628 # optimizer
629 f1, f2 = lambda x: x in {0}, lambda x: x in {0}
630 self.assertIs(f1.__code__, f2.__code__)
631 self.check_constant(f1, frozenset({0}))
632 self.assertTrue(f1(0))
633
Gregory P. Smith49fa4a92018-11-08 17:55:07 -0800634 # This is a regression test for a CPython specific peephole optimizer
635 # implementation bug present in a few releases. It's assertion verifies
636 # that peephole optimization was actually done though that isn't an
637 # indication of the bugs presence or not (crashing is).
638 @support.cpython_only
639 def test_peephole_opt_unreachable_code_array_access_in_bounds(self):
640 """Regression test for issue35193 when run under clang msan."""
641 def unused_code_at_end():
642 return 3
643 raise RuntimeError("unreachable")
644 # The above function definition will trigger the out of bounds
645 # bug in the peephole optimizer as it scans opcodes past the
646 # RETURN_VALUE opcode. This does not always crash an interpreter.
647 # When you build with the clang memory sanitizer it reliably aborts.
648 self.assertEqual(
649 'RETURN_VALUE',
650 list(dis.get_instructions(unused_code_at_end))[-1].opname)
651
Victor Stinner3cdd5fb2016-01-22 12:33:12 +0100652 def test_dont_merge_constants(self):
653 # Issue #25843: compile() must not merge constants which are equal
654 # but have a different type.
655
656 def check_different_constants(const1, const2):
657 ns = {}
658 exec("f1, f2 = lambda: %r, lambda: %r" % (const1, const2), ns)
659 f1 = ns['f1']
660 f2 = ns['f2']
661 self.assertIsNot(f1.__code__, f2.__code__)
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200662 self.assertNotEqual(f1.__code__, f2.__code__)
Victor Stinner3cdd5fb2016-01-22 12:33:12 +0100663 self.check_constant(f1, const1)
664 self.check_constant(f2, const2)
665 self.assertEqual(repr(f1()), repr(const1))
666 self.assertEqual(repr(f2()), repr(const2))
667
668 check_different_constants(0, 0.0)
669 check_different_constants(+0.0, -0.0)
670 check_different_constants((0,), (0.0,))
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200671 check_different_constants('a', b'a')
672 check_different_constants(('a',), (b'a',))
Victor Stinner3cdd5fb2016-01-22 12:33:12 +0100673
674 # check_different_constants() cannot be used because repr(-0j) is
675 # '(-0-0j)', but when '(-0-0j)' is evaluated to 0j: we loose the sign.
676 f1, f2 = lambda: +0.0j, lambda: -0.0j
677 self.assertIsNot(f1.__code__, f2.__code__)
678 self.check_constant(f1, +0.0j)
679 self.check_constant(f2, -0.0j)
680 self.assertEqual(repr(f1()), repr(+0.0j))
681 self.assertEqual(repr(f2()), repr(-0.0j))
682
683 # {0} is converted to a constant frozenset({0}) by the peephole
684 # optimizer
685 f1, f2 = lambda x: x in {0}, lambda x: x in {0.0}
686 self.assertIsNot(f1.__code__, f2.__code__)
687 self.check_constant(f1, frozenset({0}))
688 self.check_constant(f2, frozenset({0.0}))
689 self.assertTrue(f1(0))
690 self.assertTrue(f2(0.0))
691
Brett Cannona5711202016-09-06 19:36:01 -0700692 def test_path_like_objects(self):
693 # An implicit test for PyUnicode_FSDecoder().
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200694 compile("42", FakePath("test_compile_pathlike"), "single")
Brett Cannona5711202016-09-06 19:36:01 -0700695
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +0200696 def test_stack_overflow(self):
697 # bpo-31113: Stack overflow when compile a long sequence of
698 # complex statements.
699 compile("if a: b\n" * 200000, "<dummy>", "exec")
700
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100701 # Multiple users rely on the fact that CPython does not generate
702 # bytecode for dead code blocks. See bpo-37500 for more context.
703 @support.cpython_only
704 def test_dead_blocks_do_not_generate_bytecode(self):
705 def unused_block_if():
706 if 0:
707 return 42
708
709 def unused_block_while():
710 while 0:
711 return 42
712
713 def unused_block_if_else():
714 if 1:
715 return None
716 else:
717 return 42
718
719 def unused_block_while_else():
720 while 1:
721 return None
722 else:
723 return 42
724
725 funcs = [unused_block_if, unused_block_while,
726 unused_block_if_else, unused_block_while_else]
727
728 for func in funcs:
729 opcodes = list(dis.get_instructions(func))
730 self.assertEqual(2, len(opcodes))
731 self.assertEqual('LOAD_CONST', opcodes[0].opname)
732 self.assertEqual(None, opcodes[0].argval)
733 self.assertEqual('RETURN_VALUE', opcodes[1].opname)
734
Pablo Galindo6c3e66a2019-10-30 11:53:26 +0000735 def test_false_while_loop(self):
736 def break_in_while():
737 while False:
738 break
739
740 def continue_in_while():
741 while False:
742 continue
743
744 funcs = [break_in_while, continue_in_while]
745
746 # Check that we did not raise but we also don't generate bytecode
747 for func in funcs:
748 opcodes = list(dis.get_instructions(func))
749 self.assertEqual(2, len(opcodes))
750 self.assertEqual('LOAD_CONST', opcodes[0].opname)
751 self.assertEqual(None, opcodes[0].argval)
752 self.assertEqual('RETURN_VALUE', opcodes[1].opname)
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000753
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200754class TestExpressionStackSize(unittest.TestCase):
Antoine Pitrou99614052014-05-23 11:46:03 +0200755 # These tests check that the computed stack size for a code object
756 # stays within reasonable bounds (see issue #21523 for an example
757 # dysfunction).
758 N = 100
759
760 def check_stack_size(self, code):
761 # To assert that the alleged stack size is not O(N), we
762 # check that it is smaller than log(N).
763 if isinstance(code, str):
764 code = compile(code, "<foo>", "single")
765 max_size = math.ceil(math.log(len(code.co_code)))
766 self.assertLessEqual(code.co_stacksize, max_size)
767
768 def test_and(self):
769 self.check_stack_size("x and " * self.N + "x")
770
771 def test_or(self):
772 self.check_stack_size("x or " * self.N + "x")
773
774 def test_and_or(self):
775 self.check_stack_size("x and x or " * self.N + "x")
776
777 def test_chained_comparison(self):
778 self.check_stack_size("x < " * self.N + "x")
779
780 def test_if_else(self):
781 self.check_stack_size("x if x else " * self.N + "x")
782
783 def test_binop(self):
784 self.check_stack_size("x + " * self.N + "x")
785
786 def test_func_and(self):
787 code = "def f(x):\n"
788 code += " x and x\n" * self.N
789 self.check_stack_size(code)
790
Tim Petersd507dab2001-08-30 20:51:59 +0000791
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200792class TestStackSizeStability(unittest.TestCase):
793 # Check that repeating certain snippets doesn't increase the stack size
794 # beyond what a single snippet requires.
795
796 def check_stack_size(self, snippet, async_=False):
797 def compile_snippet(i):
798 ns = {}
799 script = """def func():\n""" + i * snippet
800 if async_:
801 script = "async " + script
802 code = compile(script, "<script>", "exec")
803 exec(code, ns, ns)
804 return ns['func'].__code__
805
806 sizes = [compile_snippet(i).co_stacksize for i in range(2, 5)]
807 if len(set(sizes)) != 1:
808 import dis, io
809 out = io.StringIO()
810 dis.dis(compile_snippet(1), file=out)
811 self.fail("stack sizes diverge with # of consecutive snippets: "
812 "%s\n%s\n%s" % (sizes, snippet, out.getvalue()))
813
814 def test_if(self):
815 snippet = """
816 if x:
817 a
818 """
819 self.check_stack_size(snippet)
820
821 def test_if_else(self):
822 snippet = """
823 if x:
824 a
825 elif y:
826 b
827 else:
828 c
829 """
830 self.check_stack_size(snippet)
831
832 def test_try_except_bare(self):
833 snippet = """
834 try:
835 a
836 except:
837 b
838 """
839 self.check_stack_size(snippet)
840
841 def test_try_except_qualified(self):
842 snippet = """
843 try:
844 a
845 except ImportError:
846 b
847 except:
848 c
849 else:
850 d
851 """
852 self.check_stack_size(snippet)
853
854 def test_try_except_as(self):
855 snippet = """
856 try:
857 a
858 except ImportError as e:
859 b
860 except:
861 c
862 else:
863 d
864 """
865 self.check_stack_size(snippet)
866
867 def test_try_finally(self):
868 snippet = """
869 try:
870 a
871 finally:
872 b
873 """
874 self.check_stack_size(snippet)
875
876 def test_with(self):
877 snippet = """
878 with x as y:
879 a
880 """
881 self.check_stack_size(snippet)
882
883 def test_while_else(self):
884 snippet = """
885 while x:
886 a
887 else:
888 b
889 """
890 self.check_stack_size(snippet)
891
892 def test_for(self):
893 snippet = """
894 for x in y:
895 a
896 """
897 self.check_stack_size(snippet)
898
899 def test_for_else(self):
900 snippet = """
901 for x in y:
902 a
903 else:
904 b
905 """
906 self.check_stack_size(snippet)
907
908 def test_for_break_continue(self):
909 snippet = """
910 for x in y:
911 if z:
912 break
913 elif u:
914 continue
915 else:
916 a
917 else:
918 b
919 """
920 self.check_stack_size(snippet)
921
922 def test_for_break_continue_inside_try_finally_block(self):
923 snippet = """
924 for x in y:
925 try:
926 if z:
927 break
928 elif u:
929 continue
930 else:
931 a
932 finally:
933 f
934 else:
935 b
936 """
937 self.check_stack_size(snippet)
938
Serhiy Storchakafe2bbb12018-03-18 09:56:52 +0200939 def test_for_break_continue_inside_finally_block(self):
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200940 snippet = """
941 for x in y:
942 try:
943 t
944 finally:
945 if z:
946 break
Serhiy Storchakafe2bbb12018-03-18 09:56:52 +0200947 elif u:
948 continue
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200949 else:
950 a
951 else:
952 b
953 """
954 self.check_stack_size(snippet)
955
956 def test_for_break_continue_inside_except_block(self):
957 snippet = """
958 for x in y:
959 try:
960 t
961 except:
962 if z:
963 break
964 elif u:
965 continue
966 else:
967 a
968 else:
969 b
970 """
971 self.check_stack_size(snippet)
972
973 def test_for_break_continue_inside_with_block(self):
974 snippet = """
975 for x in y:
976 with c:
977 if z:
978 break
979 elif u:
980 continue
981 else:
982 a
983 else:
984 b
985 """
986 self.check_stack_size(snippet)
987
988 def test_return_inside_try_finally_block(self):
989 snippet = """
990 try:
991 if z:
992 return
993 else:
994 a
995 finally:
996 f
997 """
998 self.check_stack_size(snippet)
999
1000 def test_return_inside_finally_block(self):
1001 snippet = """
1002 try:
1003 t
1004 finally:
1005 if z:
1006 return
1007 else:
1008 a
1009 """
1010 self.check_stack_size(snippet)
1011
1012 def test_return_inside_except_block(self):
1013 snippet = """
1014 try:
1015 t
1016 except:
1017 if z:
1018 return
1019 else:
1020 a
1021 """
1022 self.check_stack_size(snippet)
1023
1024 def test_return_inside_with_block(self):
1025 snippet = """
1026 with c:
1027 if z:
1028 return
1029 else:
1030 a
1031 """
1032 self.check_stack_size(snippet)
1033
1034 def test_async_with(self):
1035 snippet = """
1036 async with x as y:
1037 a
1038 """
1039 self.check_stack_size(snippet, async_=True)
1040
1041 def test_async_for(self):
1042 snippet = """
1043 async for x in y:
1044 a
1045 """
1046 self.check_stack_size(snippet, async_=True)
1047
1048 def test_async_for_else(self):
1049 snippet = """
1050 async for x in y:
1051 a
1052 else:
1053 b
1054 """
1055 self.check_stack_size(snippet, async_=True)
1056
1057 def test_for_break_continue_inside_async_with_block(self):
1058 snippet = """
1059 for x in y:
1060 async with c:
1061 if z:
1062 break
1063 elif u:
1064 continue
1065 else:
1066 a
1067 else:
1068 b
1069 """
1070 self.check_stack_size(snippet, async_=True)
1071
1072 def test_return_inside_async_with_block(self):
1073 snippet = """
1074 async with c:
1075 if z:
1076 return
1077 else:
1078 a
1079 """
1080 self.check_stack_size(snippet, async_=True)
1081
1082
Raymond Hettinger8a99b502003-06-23 13:36:57 +00001083if __name__ == "__main__":
Antoine Pitrou99614052014-05-23 11:46:03 +02001084 unittest.main()