blob: 46f70e5d176fcd5ed1935d79c302e86322767bb1 [file] [log] [blame]
Guido van Rossum3bead091992-01-27 17:00:37 +00001# Python test set -- part 1, grammar.
2# This just tests whether the parser accepts them all.
3
Hai Shi0c4f0f32020-06-30 21:46:31 +08004from test.support import check_syntax_error
5from test.support.warnings_helper import check_syntax_warning
Yury Selivanov75445082015-05-11 22:57:16 -04006import inspect
Thomas Wouters89f507f2006-12-13 04:49:30 +00007import unittest
Jeremy Hylton7d3dff22001-10-10 01:45:02 +00008import sys
Serhiy Storchakad31e7732018-10-21 10:09:39 +03009import warnings
Thomas Wouters89f507f2006-12-13 04:49:30 +000010# testing import *
11from sys import *
Guido van Rossum3bead091992-01-27 17:00:37 +000012
Yury Selivanovf8cb8a12016-09-08 20:50:03 -070013# different import patterns to check that __annotations__ does not interfere
14# with import machinery
15import test.ann_module as ann_module
16import typing
17from collections import ChainMap
18from test import ann_module2
19import test
20
Brett Cannona721aba2016-09-09 14:57:09 -070021# These are shared with test_tokenize and other test modules.
22#
23# Note: since several test cases filter out floats by looking for "e" and ".",
24# don't add hexadecimal literals that contain "e" or "E".
25VALID_UNDERSCORE_LITERALS = [
26 '0_0_0',
27 '4_2',
28 '1_0000_0000',
29 '0b1001_0100',
30 '0xffff_ffff',
31 '0o5_7_7',
32 '1_00_00.5',
33 '1_00_00.5e5',
34 '1_00_00e5_1',
35 '1e1_0',
36 '.1_4',
37 '.1_4e1',
38 '0b_0',
39 '0x_f',
40 '0o_5',
41 '1_00_00j',
42 '1_00_00.5j',
43 '1_00_00e5_1j',
44 '.1_4j',
45 '(1_2.5+3_3j)',
46 '(.5_6j)',
47]
48INVALID_UNDERSCORE_LITERALS = [
49 # Trailing underscores:
50 '0_',
51 '42_',
52 '1.4j_',
53 '0x_',
54 '0b1_',
55 '0xf_',
56 '0o5_',
57 '0 if 1_Else 1',
58 # Underscores in the base selector:
59 '0_b0',
60 '0_xf',
61 '0_o5',
62 # Old-style octal, still disallowed:
63 '0_7',
64 '09_99',
65 # Multiple consecutive underscores:
66 '4_______2',
67 '0.1__4',
68 '0.1__4j',
69 '0b1001__0100',
70 '0xffff__ffff',
71 '0x___',
72 '0o5__77',
73 '1e1__0',
74 '1e1__0j',
75 # Underscore right before a dot:
76 '1_.4',
77 '1_.4j',
78 # Underscore right after a dot:
79 '1._4',
80 '1._4j',
81 '._5',
82 '._5j',
83 # Underscore right after a sign:
84 '1.0e+_1',
85 '1.0e+_1j',
86 # Underscore right before j:
87 '1.4_j',
88 '1.4e5_j',
89 # Underscore right before e:
90 '1_e1',
91 '1.4_e1',
92 '1.4_e1j',
93 # Underscore right after e:
94 '1e_1',
95 '1.4e_1',
96 '1.4e_1j',
97 # Complex cases with parens:
98 '(1+1.5_j_)',
99 '(1+1.5_j)',
100]
101
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000102
Thomas Wouters89f507f2006-12-13 04:49:30 +0000103class TokenTests(unittest.TestCase):
Guido van Rossum3bead091992-01-27 17:00:37 +0000104
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +0200105 from test.support import check_syntax_error
Serhiy Storchakacf7303e2018-07-09 15:09:35 +0300106
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500107 def test_backslash(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000108 # Backslash means line continuation:
109 x = 1 \
110 + 1
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000111 self.assertEqual(x, 2, 'backslash for line continuation')
Guido van Rossum3bead091992-01-27 17:00:37 +0000112
Thomas Wouters89f507f2006-12-13 04:49:30 +0000113 # Backslash does not means continuation in comments :\
114 x = 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000115 self.assertEqual(x, 0, 'backslash ending comment')
Guido van Rossum3bead091992-01-27 17:00:37 +0000116
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500117 def test_plain_integers(self):
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000118 self.assertEqual(type(000), type(0))
119 self.assertEqual(0xff, 255)
120 self.assertEqual(0o377, 255)
121 self.assertEqual(2147483647, 0o17777777777)
122 self.assertEqual(0b1001, 9)
Georg Brandlfceab5a2008-01-19 20:08:23 +0000123 # "0x" is not a valid literal
124 self.assertRaises(SyntaxError, eval, "0x")
Christian Heimesa37d4c62007-12-04 23:02:19 +0000125 from sys import maxsize
126 if maxsize == 2147483647:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000127 self.assertEqual(-2147483647-1, -0o20000000000)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000128 # XXX -2147483648
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000129 self.assertTrue(0o37777777777 > 0)
130 self.assertTrue(0xffffffff > 0)
131 self.assertTrue(0b1111111111111111111111111111111 > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000132 for s in ('2147483648', '0o40000000000', '0x100000000',
133 '0b10000000000000000000000000000000'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000134 try:
135 x = eval(s)
136 except OverflowError:
137 self.fail("OverflowError on huge integer literal %r" % s)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000138 elif maxsize == 9223372036854775807:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000139 self.assertEqual(-9223372036854775807-1, -0o1000000000000000000000)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000140 self.assertTrue(0o1777777777777777777777 > 0)
141 self.assertTrue(0xffffffffffffffff > 0)
142 self.assertTrue(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000143 for s in '9223372036854775808', '0o2000000000000000000000', \
144 '0x10000000000000000', \
145 '0b100000000000000000000000000000000000000000000000000000000000000':
Thomas Wouters89f507f2006-12-13 04:49:30 +0000146 try:
147 x = eval(s)
148 except OverflowError:
149 self.fail("OverflowError on huge integer literal %r" % s)
150 else:
Christian Heimesa37d4c62007-12-04 23:02:19 +0000151 self.fail('Weird maxsize value %r' % maxsize)
Guido van Rossum3bead091992-01-27 17:00:37 +0000152
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500153 def test_long_integers(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000154 x = 0
Guido van Rossume2a383d2007-01-15 16:59:06 +0000155 x = 0xffffffffffffffff
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000156 x = 0Xffffffffffffffff
157 x = 0o77777777777777777
158 x = 0O77777777777777777
Guido van Rossume2a383d2007-01-15 16:59:06 +0000159 x = 123456789012345678901234567890
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000160 x = 0b100000000000000000000000000000000000000000000000000000000000000000000
161 x = 0B111111111111111111111111111111111111111111111111111111111111111111111
Guido van Rossum3bead091992-01-27 17:00:37 +0000162
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500163 def test_floats(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000164 x = 3.14
165 x = 314.
166 x = 0.314
167 # XXX x = 000.314
168 x = .314
169 x = 3e14
170 x = 3E14
171 x = 3e-14
172 x = 3e+14
173 x = 3.e14
174 x = .3e14
175 x = 3.1e4
Guido van Rossum3bead091992-01-27 17:00:37 +0000176
Benjamin Petersonc4161622014-06-07 12:36:39 -0700177 def test_float_exponent_tokenization(self):
178 # See issue 21642.
179 self.assertEqual(1 if 1else 0, 1)
180 self.assertEqual(1 if 0else 0, 0)
181 self.assertRaises(SyntaxError, eval, "0 if 1Else 0")
182
Brett Cannona721aba2016-09-09 14:57:09 -0700183 def test_underscore_literals(self):
184 for lit in VALID_UNDERSCORE_LITERALS:
185 self.assertEqual(eval(lit), eval(lit.replace('_', '')))
186 for lit in INVALID_UNDERSCORE_LITERALS:
187 self.assertRaises(SyntaxError, eval, lit)
188 # Sanity check: no literal begins with an underscore
189 self.assertRaises(NameError, eval, "_0")
190
Serhiy Storchakacf7303e2018-07-09 15:09:35 +0300191 def test_bad_numerical_literals(self):
192 check = self.check_syntax_error
193 check("0b12", "invalid digit '2' in binary literal")
194 check("0b1_2", "invalid digit '2' in binary literal")
195 check("0b2", "invalid digit '2' in binary literal")
196 check("0b1_", "invalid binary literal")
197 check("0b", "invalid binary literal")
198 check("0o18", "invalid digit '8' in octal literal")
199 check("0o1_8", "invalid digit '8' in octal literal")
200 check("0o8", "invalid digit '8' in octal literal")
201 check("0o1_", "invalid octal literal")
202 check("0o", "invalid octal literal")
203 check("0x1_", "invalid hexadecimal literal")
204 check("0x", "invalid hexadecimal literal")
205 check("1_", "invalid decimal literal")
206 check("012",
207 "leading zeros in decimal integer literals are not permitted; "
208 "use an 0o prefix for octal integers")
209 check("1.2_", "invalid decimal literal")
210 check("1e2_", "invalid decimal literal")
211 check("1e+", "invalid decimal literal")
212
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500213 def test_string_literals(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000214 x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y)
215 x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39)
216 x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000217 x = "doesn't \"shrink\" does it"
218 y = 'doesn\'t "shrink" does it'
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000219 self.assertTrue(len(x) == 24 and x == y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000220 x = "does \"shrink\" doesn't it"
221 y = 'does "shrink" doesn\'t it'
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000222 self.assertTrue(len(x) == 24 and x == y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000223 x = """
Guido van Rossumb6775db1994-08-01 11:34:53 +0000224The "quick"
225brown fox
226jumps over
227the 'lazy' dog.
228"""
Thomas Wouters89f507f2006-12-13 04:49:30 +0000229 y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000230 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000231 y = '''
Guido van Rossumb6775db1994-08-01 11:34:53 +0000232The "quick"
233brown fox
234jumps over
235the 'lazy' dog.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000236'''
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000237 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000238 y = "\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000239The \"quick\"\n\
240brown fox\n\
241jumps over\n\
242the 'lazy' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000243"
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000244 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000245 y = '\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000246The \"quick\"\n\
247brown fox\n\
248jumps over\n\
249the \'lazy\' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000250'
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000251 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000252
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500253 def test_ellipsis(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000254 x = ...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000255 self.assertTrue(x is Ellipsis)
Georg Brandldde00282007-03-18 19:01:53 +0000256 self.assertRaises(SyntaxError, eval, ".. .")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000257
Benjamin Peterson758888d2011-05-30 11:12:38 -0500258 def test_eof_error(self):
259 samples = ("def foo(", "\ndef foo(", "def foo(\n")
260 for s in samples:
261 with self.assertRaises(SyntaxError) as cm:
262 compile(s, "<test>", "exec")
Pablo Galindod6d63712021-01-19 23:59:33 +0000263 self.assertIn("was never closed", str(cm.exception))
Benjamin Peterson758888d2011-05-30 11:12:38 -0500264
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700265var_annot_global: int # a global annotated is necessary for test_var_annot
266
267# custom namespace for testing __annotations__
268
269class CNS:
270 def __init__(self):
271 self._dct = {}
272 def __setitem__(self, item, value):
273 self._dct[item.lower()] = value
274 def __getitem__(self, item):
275 return self._dct[item]
276
277
Thomas Wouters89f507f2006-12-13 04:49:30 +0000278class GrammarTests(unittest.TestCase):
279
Hai Shi0c4f0f32020-06-30 21:46:31 +0800280 from test.support import check_syntax_error
281 from test.support.warnings_helper import check_syntax_warning
tsukasa-aua8ef4572021-03-16 22:14:41 +1100282 from test.support.warnings_helper import check_no_warnings
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200283
Thomas Wouters89f507f2006-12-13 04:49:30 +0000284 # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
285 # XXX can't test in a script -- this rule is only used when interactive
286
287 # file_input: (NEWLINE | stmt)* ENDMARKER
288 # Being tested as this very moment this very module
289
290 # expr_input: testlist NEWLINE
291 # XXX Hard to test -- used only in calls to input()
292
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500293 def test_eval_input(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000294 # testlist ENDMARKER
295 x = eval('1, 0 or 1')
296
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700297 def test_var_annot_basics(self):
298 # all these should be allowed
299 var1: int = 5
300 var2: [int, str]
301 my_lst = [42]
302 def one():
303 return 1
304 int.new_attr: int
305 [list][0]: type
306 my_lst[one()-1]: int = 5
307 self.assertEqual(my_lst, [5])
308
309 def test_var_annot_syntax_errors(self):
310 # parser pass
311 check_syntax_error(self, "def f: int")
312 check_syntax_error(self, "x: int: str")
313 check_syntax_error(self, "def f():\n"
314 " nonlocal x: int\n")
315 # AST pass
316 check_syntax_error(self, "[x, 0]: int\n")
317 check_syntax_error(self, "f(): int\n")
318 check_syntax_error(self, "(x,): int")
319 check_syntax_error(self, "def f():\n"
320 " (x, y): int = (1, 2)\n")
321 # symtable pass
322 check_syntax_error(self, "def f():\n"
323 " x: int\n"
324 " global x\n")
325 check_syntax_error(self, "def f():\n"
326 " global x\n"
327 " x: int\n")
328
329 def test_var_annot_basic_semantics(self):
330 # execution order
331 with self.assertRaises(ZeroDivisionError):
332 no_name[does_not_exist]: no_name_again = 1/0
333 with self.assertRaises(NameError):
334 no_name[does_not_exist]: 1/0 = 0
335 global var_annot_global
336
337 # function semantics
338 def f():
339 st: str = "Hello"
340 a.b: int = (1, 2)
341 return st
342 self.assertEqual(f.__annotations__, {})
343 def f_OK():
344 x: 1/0
345 f_OK()
346 def fbad():
347 x: int
348 print(x)
349 with self.assertRaises(UnboundLocalError):
350 fbad()
351 def f2bad():
352 (no_such_global): int
353 print(no_such_global)
354 try:
355 f2bad()
356 except Exception as e:
357 self.assertIs(type(e), NameError)
358
359 # class semantics
360 class C:
Guido van Rossum015d8742016-09-11 09:45:24 -0700361 __foo: int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700362 s: str = "attr"
363 z = 2
364 def __init__(self, x):
365 self.x: int = x
Pablo Galindob0544ba2021-04-21 12:41:19 +0100366 self.assertEqual(C.__annotations__, {'_C__foo': int, 's': str})
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700367 with self.assertRaises(NameError):
368 class CBad:
369 no_such_name_defined.attr: int = 0
370 with self.assertRaises(NameError):
371 class Cbad2(C):
372 x: int
373 x.y: list = []
374
375 def test_var_annot_metaclass_semantics(self):
376 class CMeta(type):
377 @classmethod
378 def __prepare__(metacls, name, bases, **kwds):
379 return {'__annotations__': CNS()}
380 class CC(metaclass=CMeta):
381 XX: 'ANNOT'
Pablo Galindob0544ba2021-04-21 12:41:19 +0100382 self.assertEqual(CC.__annotations__['xx'], 'ANNOT')
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700383
384 def test_var_annot_module_semantics(self):
larryhastings2f2b6982021-04-29 20:09:08 -0700385 self.assertEqual(test.__annotations__, {})
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700386 self.assertEqual(ann_module.__annotations__,
Pablo Galindob0544ba2021-04-21 12:41:19 +0100387 {1: 2, 'x': int, 'y': str, 'f': typing.Tuple[int, int]})
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700388 self.assertEqual(ann_module.M.__annotations__,
Pablo Galindob0544ba2021-04-21 12:41:19 +0100389 {'123': 123, 'o': type})
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700390 self.assertEqual(ann_module2.__annotations__, {})
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700391
392 def test_var_annot_in_module(self):
393 # check that functions fail the same way when executed
394 # outside of module where they were defined
395 from test.ann_module3 import f_bad_ann, g_bad_ann, D_bad_ann
396 with self.assertRaises(NameError):
397 f_bad_ann()
398 with self.assertRaises(NameError):
399 g_bad_ann()
400 with self.assertRaises(NameError):
401 D_bad_ann(5)
402
403 def test_var_annot_simple_exec(self):
404 gns = {}; lns= {}
405 exec("'docstring'\n"
406 "__annotations__[1] = 2\n"
407 "x: int = 5\n", gns, lns)
Pablo Galindob0544ba2021-04-21 12:41:19 +0100408 self.assertEqual(lns["__annotations__"], {1: 2, 'x': int})
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700409 with self.assertRaises(KeyError):
410 gns['__annotations__']
411
412 def test_var_annot_custom_maps(self):
413 # tests with custom locals() and __annotations__
414 ns = {'__annotations__': CNS()}
415 exec('X: int; Z: str = "Z"; (w): complex = 1j', ns)
Pablo Galindob0544ba2021-04-21 12:41:19 +0100416 self.assertEqual(ns['__annotations__']['x'], int)
417 self.assertEqual(ns['__annotations__']['z'], str)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700418 with self.assertRaises(KeyError):
419 ns['__annotations__']['w']
420 nonloc_ns = {}
421 class CNS2:
422 def __init__(self):
423 self._dct = {}
424 def __setitem__(self, item, value):
425 nonlocal nonloc_ns
426 self._dct[item] = value
427 nonloc_ns[item] = value
428 def __getitem__(self, item):
429 return self._dct[item]
430 exec('x: int = 1', {}, CNS2())
Pablo Galindob0544ba2021-04-21 12:41:19 +0100431 self.assertEqual(nonloc_ns['__annotations__']['x'], int)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700432
433 def test_var_annot_refleak(self):
434 # complex case: custom locals plus custom __annotations__
435 # this was causing refleak
436 cns = CNS()
437 nonloc_ns = {'__annotations__': cns}
438 class CNS2:
439 def __init__(self):
440 self._dct = {'__annotations__': cns}
441 def __setitem__(self, item, value):
442 nonlocal nonloc_ns
443 self._dct[item] = value
444 nonloc_ns[item] = value
445 def __getitem__(self, item):
446 return self._dct[item]
447 exec('X: str', {}, CNS2())
Pablo Galindob0544ba2021-04-21 12:41:19 +0100448 self.assertEqual(nonloc_ns['__annotations__']['x'], str)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700449
Ivan Levkivskyi62c35a82019-01-25 01:39:19 +0000450 def test_var_annot_rhs(self):
451 ns = {}
452 exec('x: tuple = 1, 2', ns)
453 self.assertEqual(ns['x'], (1, 2))
454 stmt = ('def f():\n'
455 ' x: int = yield')
456 exec(stmt, ns)
457 self.assertEqual(list(ns['f']()), [None])
458
Pablo Galindo8565f6b2019-06-03 08:34:20 +0100459 ns = {"a": 1, 'b': (2, 3, 4), "c":5, "Tuple": typing.Tuple}
460 exec('x: Tuple[int, ...] = a,*b,c', ns)
461 self.assertEqual(ns['x'], (1, 2, 3, 4, 5))
462
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500463 def test_funcdef(self):
Neal Norwitzc1505362006-12-28 06:47:50 +0000464 ### [decorators] 'def' NAME parameters ['->' test] ':' suite
Brandt Bucherbe501ca2020-03-03 14:25:44 -0800465 ### decorator: '@' namedexpr_test NEWLINE
Neal Norwitzc1505362006-12-28 06:47:50 +0000466 ### decorators: decorator+
467 ### parameters: '(' [typedargslist] ')'
468 ### typedargslist: ((tfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000469 ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000470 ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000471 ### tfpdef: NAME [':' test]
Neal Norwitzc1505362006-12-28 06:47:50 +0000472 ### varargslist: ((vfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000473 ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000474 ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000475 ### vfpdef: NAME
Thomas Wouters89f507f2006-12-13 04:49:30 +0000476 def f1(): pass
477 f1()
478 f1(*())
479 f1(*(), **{})
480 def f2(one_argument): pass
481 def f3(two, arguments): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000482 self.assertEqual(f2.__code__.co_varnames, ('one_argument',))
483 self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments'))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000484 def a1(one_arg,): pass
485 def a2(two, args,): pass
486 def v0(*rest): pass
487 def v1(a, *rest): pass
488 def v2(a, b, *rest): pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000489
490 f1()
491 f2(1)
492 f2(1,)
493 f3(1, 2)
494 f3(1, 2,)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000495 v0()
496 v0(1)
497 v0(1,)
498 v0(1,2)
499 v0(1,2,3,4,5,6,7,8,9,0)
500 v1(1)
501 v1(1,)
502 v1(1,2)
503 v1(1,2,3)
504 v1(1,2,3,4,5,6,7,8,9,0)
505 v2(1,2)
506 v2(1,2,3)
507 v2(1,2,3,4)
508 v2(1,2,3,4,5,6,7,8,9,0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000509
Thomas Wouters89f507f2006-12-13 04:49:30 +0000510 def d01(a=1): pass
511 d01()
512 d01(1)
513 d01(*(1,))
Yury Selivanov14acf5f2015-08-05 17:54:10 -0400514 d01(*[] or [2])
515 d01(*() or (), *{} and (), **() or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000516 d01(**{'a':2})
Benjamin Petersonde12b792015-05-16 09:44:45 -0400517 d01(**{'a':2} or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000518 def d11(a, b=1): pass
519 d11(1)
520 d11(1, 2)
521 d11(1, **{'b':2})
522 def d21(a, b, c=1): pass
523 d21(1, 2)
524 d21(1, 2, 3)
525 d21(*(1, 2, 3))
526 d21(1, *(2, 3))
527 d21(1, 2, *(3,))
528 d21(1, 2, **{'c':3})
529 def d02(a=1, b=2): pass
530 d02()
531 d02(1)
532 d02(1, 2)
533 d02(*(1, 2))
534 d02(1, *(2,))
535 d02(1, **{'b':2})
536 d02(**{'a': 1, 'b': 2})
537 def d12(a, b=1, c=2): pass
538 d12(1)
539 d12(1, 2)
540 d12(1, 2, 3)
541 def d22(a, b, c=1, d=2): pass
542 d22(1, 2)
543 d22(1, 2, 3)
544 d22(1, 2, 3, 4)
545 def d01v(a=1, *rest): pass
546 d01v()
547 d01v(1)
548 d01v(1, 2)
549 d01v(*(1, 2, 3, 4))
550 d01v(*(1,))
551 d01v(**{'a':2})
552 def d11v(a, b=1, *rest): pass
553 d11v(1)
554 d11v(1, 2)
555 d11v(1, 2, 3)
556 def d21v(a, b, c=1, *rest): pass
557 d21v(1, 2)
558 d21v(1, 2, 3)
559 d21v(1, 2, 3, 4)
560 d21v(*(1, 2, 3, 4))
561 d21v(1, 2, **{'c': 3})
562 def d02v(a=1, b=2, *rest): pass
563 d02v()
564 d02v(1)
565 d02v(1, 2)
566 d02v(1, 2, 3)
567 d02v(1, *(2, 3, 4))
568 d02v(**{'a': 1, 'b': 2})
569 def d12v(a, b=1, c=2, *rest): pass
570 d12v(1)
571 d12v(1, 2)
572 d12v(1, 2, 3)
573 d12v(1, 2, 3, 4)
574 d12v(*(1, 2, 3, 4))
575 d12v(1, 2, *(3, 4, 5))
576 d12v(1, *(2,), **{'c': 3})
577 def d22v(a, b, c=1, d=2, *rest): pass
578 d22v(1, 2)
579 d22v(1, 2, 3)
580 d22v(1, 2, 3, 4)
581 d22v(1, 2, 3, 4, 5)
582 d22v(*(1, 2, 3, 4))
583 d22v(1, 2, *(3, 4, 5))
584 d22v(1, *(2, 3), **{'d': 4})
Georg Brandld8b690f2008-05-16 17:28:50 +0000585
586 # keyword argument type tests
Serhiy Storchaka12f43342020-07-20 15:53:55 +0300587 with warnings.catch_warnings():
588 warnings.simplefilter('ignore', BytesWarning)
589 try:
590 str('x', **{b'foo':1 })
591 except TypeError:
592 pass
593 else:
594 self.fail('Bytes should not work as keyword argument names')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000595 # keyword only argument tests
596 def pos0key1(*, key): return key
597 pos0key1(key=100)
598 def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
599 pos2key2(1, 2, k1=100)
600 pos2key2(1, 2, k1=100, k2=200)
601 pos2key2(1, 2, k2=100, k1=200)
602 def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
603 pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
604 pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
605
Robert Collinsdf395992015-08-12 08:00:06 +1200606 self.assertRaises(SyntaxError, eval, "def f(*): pass")
607 self.assertRaises(SyntaxError, eval, "def f(*,): pass")
608 self.assertRaises(SyntaxError, eval, "def f(*, **kwds): pass")
609
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000610 # keyword arguments after *arglist
611 def f(*args, **kwargs):
612 return args, kwargs
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000613 self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000614 {'x':2, 'y':5}))
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400615 self.assertEqual(f(1, *(2,3), 4), ((1, 2, 3, 4), {}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000616 self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400617 self.assertEqual(f(**{'eggs':'scrambled', 'spam':'fried'}),
618 ((), {'eggs':'scrambled', 'spam':'fried'}))
619 self.assertEqual(f(spam='fried', **{'eggs':'scrambled'}),
620 ((), {'eggs':'scrambled', 'spam':'fried'}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000621
Serhiy Storchaka0cc99c82018-01-04 10:36:35 +0200622 # Check ast errors in *args and *kwargs
623 check_syntax_error(self, "f(*g(1=2))")
624 check_syntax_error(self, "f(**g(1=2))")
625
Neal Norwitzc1505362006-12-28 06:47:50 +0000626 # argument annotation tests
627 def f(x) -> list: pass
Pablo Galindob0544ba2021-04-21 12:41:19 +0100628 self.assertEqual(f.__annotations__, {'return': list})
Zachary Warece17f762015-08-01 21:55:36 -0500629 def f(x: int): pass
Pablo Galindob0544ba2021-04-21 12:41:19 +0100630 self.assertEqual(f.__annotations__, {'x': int})
Pablo Galindoa0c01bf2019-05-31 15:19:50 +0100631 def f(x: int, /): pass
Pablo Galindob0544ba2021-04-21 12:41:19 +0100632 self.assertEqual(f.__annotations__, {'x': int})
Pablo Galindoa0c01bf2019-05-31 15:19:50 +0100633 def f(x: int = 34, /): pass
Pablo Galindob0544ba2021-04-21 12:41:19 +0100634 self.assertEqual(f.__annotations__, {'x': int})
Zachary Warece17f762015-08-01 21:55:36 -0500635 def f(*x: str): pass
Pablo Galindob0544ba2021-04-21 12:41:19 +0100636 self.assertEqual(f.__annotations__, {'x': str})
Zachary Warece17f762015-08-01 21:55:36 -0500637 def f(**x: float): pass
Pablo Galindob0544ba2021-04-21 12:41:19 +0100638 self.assertEqual(f.__annotations__, {'x': float})
639 def f(x, y: 1+2): pass
640 self.assertEqual(f.__annotations__, {'y': 3})
641 def f(x, y: 1+2, /): pass
642 self.assertEqual(f.__annotations__, {'y': 3})
Zachary Warece17f762015-08-01 21:55:36 -0500643 def f(a, b: 1, c: 2, d): pass
Pablo Galindob0544ba2021-04-21 12:41:19 +0100644 self.assertEqual(f.__annotations__, {'b': 1, 'c': 2})
Pablo Galindoa0c01bf2019-05-31 15:19:50 +0100645 def f(a, b: 1, /, c: 2, d): pass
Pablo Galindob0544ba2021-04-21 12:41:19 +0100646 self.assertEqual(f.__annotations__, {'b': 1, 'c': 2})
Zachary Warece17f762015-08-01 21:55:36 -0500647 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000648 self.assertEqual(f.__annotations__,
Pablo Galindob0544ba2021-04-21 12:41:19 +0100649 {'b': 1, 'c': 2, 'e': 3, 'g': 6})
Zachary Warece17f762015-08-01 21:55:36 -0500650 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6, h: 7, i=8, j: 9 = 10,
651 **k: 11) -> 12: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000652 self.assertEqual(f.__annotations__,
Pablo Galindob0544ba2021-04-21 12:41:19 +0100653 {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
654 'k': 11, 'return': 12})
Pablo Galindoa0c01bf2019-05-31 15:19:50 +0100655 def f(a, b: 1, c: 2, d, e: 3 = 4, f: int = 5, /, *g: 6, h: 7, i=8, j: 9 = 10,
656 **k: 11) -> 12: pass
657 self.assertEqual(f.__annotations__,
Pablo Galindob0544ba2021-04-21 12:41:19 +0100658 {'b': 1, 'c': 2, 'e': 3, 'f': int, 'g': 6, 'h': 7, 'j': 9,
659 'k': 11, 'return': 12})
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500660 # Check for issue #20625 -- annotations mangling
661 class Spam:
Zachary Warece17f762015-08-01 21:55:36 -0500662 def f(self, *, __kw: 1):
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500663 pass
664 class Ham(Spam): pass
Pablo Galindob0544ba2021-04-21 12:41:19 +0100665 self.assertEqual(Spam.f.__annotations__, {'_Spam__kw': 1})
666 self.assertEqual(Ham.f.__annotations__, {'_Spam__kw': 1})
Nick Coghlan71011e22007-04-23 11:05:01 +0000667 # Check for SF Bug #1697248 - mixing decorators and a return annotation
668 def null(x): return x
669 @null
670 def f(x) -> list: pass
Pablo Galindob0544ba2021-04-21 12:41:19 +0100671 self.assertEqual(f.__annotations__, {'return': list})
Nick Coghlan71011e22007-04-23 11:05:01 +0000672
Brandt Bucherbe501ca2020-03-03 14:25:44 -0800673 # Test expressions as decorators (PEP 614):
674 @False or null
675 def f(x): pass
676 @d := null
677 def f(x): pass
678 @lambda f: null(f)
679 def f(x): pass
680 @[..., null, ...][1]
681 def f(x): pass
682 @null(null)(null)
683 def f(x): pass
684 @[null][0].__call__.__call__
685 def f(x): pass
686
Serhiy Storchaka64204de2016-06-12 17:36:24 +0300687 # test closures with a variety of opargs
Guido van Rossum0240b922007-02-26 21:23:50 +0000688 closure = 1
689 def f(): return closure
690 def f(x=1): return closure
691 def f(*, k=1): return closure
692 def f() -> int: return closure
Neal Norwitzc1505362006-12-28 06:47:50 +0000693
Robert Collinsdf395992015-08-12 08:00:06 +1200694 # Check trailing commas are permitted in funcdef argument list
695 def f(a,): pass
696 def f(*args,): pass
697 def f(**kwds,): pass
698 def f(a, *args,): pass
699 def f(a, **kwds,): pass
700 def f(*args, b,): pass
701 def f(*, b,): pass
702 def f(*args, **kwds,): pass
703 def f(a, *args, b,): pass
704 def f(a, *, b,): pass
705 def f(a, *args, **kwds,): pass
706 def f(*args, b, **kwds,): pass
707 def f(*, b, **kwds,): pass
708 def f(a, *args, b, **kwds,): pass
709 def f(a, *, b, **kwds,): pass
710
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500711 def test_lambdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000712 ### lambdef: 'lambda' [varargslist] ':' test
713 l1 = lambda : 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000714 self.assertEqual(l1(), 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000715 l2 = lambda : a[d] # XXX just testing the expression
Guido van Rossume2a383d2007-01-15 16:59:06 +0000716 l3 = lambda : [2 < x for x in [-1, 3, 0]]
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000717 self.assertEqual(l3(), [0, 1, 0])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000718 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000719 self.assertEqual(l4(), 1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000720 l5 = lambda x, y, z=2: x + y + z
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000721 self.assertEqual(l5(1, 2), 5)
722 self.assertEqual(l5(1, 2, 3), 6)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000723 check_syntax_error(self, "lambda x: x = 2")
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000724 check_syntax_error(self, "lambda (None,): None")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000725 l6 = lambda x, y, *, k=20: x+y+k
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000726 self.assertEqual(l6(1,2), 1+2+20)
727 self.assertEqual(l6(1,2,k=10), 1+2+10)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000728
Robert Collinsdf395992015-08-12 08:00:06 +1200729 # check that trailing commas are permitted
730 l10 = lambda a,: 0
731 l11 = lambda *args,: 0
732 l12 = lambda **kwds,: 0
733 l13 = lambda a, *args,: 0
734 l14 = lambda a, **kwds,: 0
735 l15 = lambda *args, b,: 0
736 l16 = lambda *, b,: 0
737 l17 = lambda *args, **kwds,: 0
738 l18 = lambda a, *args, b,: 0
739 l19 = lambda a, *, b,: 0
740 l20 = lambda a, *args, **kwds,: 0
741 l21 = lambda *args, b, **kwds,: 0
742 l22 = lambda *, b, **kwds,: 0
743 l23 = lambda a, *args, b, **kwds,: 0
744 l24 = lambda a, *, b, **kwds,: 0
745
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000746
Thomas Wouters89f507f2006-12-13 04:49:30 +0000747 ### stmt: simple_stmt | compound_stmt
748 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000749
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500750 def test_simple_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000751 ### simple_stmt: small_stmt (';' small_stmt)* [';']
752 x = 1; pass; del x
753 def foo():
Ezio Melotti13925002011-03-16 11:05:33 +0200754 # verify statements that end with semi-colons
Thomas Wouters89f507f2006-12-13 04:49:30 +0000755 x = 1; pass; del x;
756 foo()
Georg Brandl52318d62006-09-06 07:06:08 +0000757
Guido van Rossumd8faa362007-04-27 19:54:29 +0000758 ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
Thomas Wouters89f507f2006-12-13 04:49:30 +0000759 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000760
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500761 def test_expr_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000762 # (exprlist '=')* exprlist
Victor Stinner15a30952016-02-08 22:45:06 +0100763 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000764 1, 2, 3
765 x = 1
766 x = 1, 2, 3
767 x = y = z = 1, 2, 3
768 x, y, z = 1, 2, 3
769 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000770
Thomas Wouters89f507f2006-12-13 04:49:30 +0000771 check_syntax_error(self, "x + 1 = 1")
772 check_syntax_error(self, "a + 1 = b + 2")
Guido van Rossum3bead091992-01-27 17:00:37 +0000773
Nick Coghlan5b1fdc12014-06-16 19:48:02 +1000774 # Check the heuristic for print & exec covers significant cases
775 # As well as placing some limits on false positives
776 def test_former_statements_refer_to_builtins(self):
777 keywords = "print", "exec"
778 # Cases where we want the custom error
779 cases = [
780 "{} foo",
781 "{} {{1:foo}}",
782 "if 1: {} foo",
783 "if 1: {} {{1:foo}}",
784 "if 1:\n {} foo",
785 "if 1:\n {} {{1:foo}}",
786 ]
787 for keyword in keywords:
788 custom_msg = "call to '{}'".format(keyword)
789 for case in cases:
790 source = case.format(keyword)
791 with self.subTest(source=source):
792 with self.assertRaisesRegex(SyntaxError, custom_msg):
793 exec(source)
794 source = source.replace("foo", "(foo.)")
795 with self.subTest(source=source):
796 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
797 exec(source)
798
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500799 def test_del_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000800 # 'del' exprlist
801 abc = [1,2,3]
802 x, y, z = abc
803 xyz = x, y, z
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000804
Thomas Wouters89f507f2006-12-13 04:49:30 +0000805 del abc
806 del x, y, (z, xyz)
Barry Warsaw9182b452000-08-29 04:57:10 +0000807
Shantanu27c0d9b2020-05-11 14:53:58 -0700808 x, y, z = "xyz"
809 del x
810 del y,
811 del (z)
812 del ()
813
814 a, b, c, d, e, f, g = "abcdefg"
815 del a, (b, c), (d, (e, f))
816
817 a, b, c, d, e, f, g = "abcdefg"
818 del a, [b, c], (d, [e, f])
819
820 abcd = list("abcd")
821 del abcd[1:2]
822
823 compile("del a, (b[0].c, (d.e, f.g[1:2])), [h.i.j], ()", "<testcase>", "exec")
824
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500825 def test_pass_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000826 # 'pass'
827 pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000828
Thomas Wouters89f507f2006-12-13 04:49:30 +0000829 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
830 # Tested below
Barry Warsaw9182b452000-08-29 04:57:10 +0000831
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500832 def test_break_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000833 # 'break'
834 while 1: break
Barry Warsaw9182b452000-08-29 04:57:10 +0000835
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500836 def test_continue_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000837 # 'continue'
838 i = 1
839 while i: i = 0; continue
Barry Warsaw9182b452000-08-29 04:57:10 +0000840
Thomas Wouters89f507f2006-12-13 04:49:30 +0000841 msg = ""
842 while not msg:
843 msg = "ok"
844 try:
845 continue
846 msg = "continue failed to continue inside try"
847 except:
848 msg = "continue inside try called except block"
849 if msg != "ok":
850 self.fail(msg)
Barry Warsawefc92ee2000-08-21 15:46:50 +0000851
Thomas Wouters89f507f2006-12-13 04:49:30 +0000852 msg = ""
853 while not msg:
854 msg = "finally block not called"
855 try:
856 continue
857 finally:
858 msg = "ok"
859 if msg != "ok":
860 self.fail(msg)
Guido van Rossum3bead091992-01-27 17:00:37 +0000861
Thomas Wouters89f507f2006-12-13 04:49:30 +0000862 def test_break_continue_loop(self):
863 # This test warrants an explanation. It is a test specifically for SF bugs
864 # #463359 and #462937. The bug is that a 'break' statement executed or
865 # exception raised inside a try/except inside a loop, *after* a continue
866 # statement has been executed in that loop, will cause the wrong number of
867 # arguments to be popped off the stack and the instruction pointer reset to
868 # a very small number (usually 0.) Because of this, the following test
869 # *must* written as a function, and the tracking vars *must* be function
870 # arguments with default values. Otherwise, the test will loop and loop.
Guido van Rossum3bead091992-01-27 17:00:37 +0000871
Thomas Wouters89f507f2006-12-13 04:49:30 +0000872 def test_inner(extra_burning_oil = 1, count=0):
873 big_hippo = 2
874 while big_hippo:
875 count += 1
876 try:
877 if extra_burning_oil and big_hippo == 1:
878 extra_burning_oil -= 1
879 break
880 big_hippo -= 1
881 continue
882 except:
883 raise
884 if count > 2 or big_hippo != 1:
885 self.fail("continue then break in try/except in loop broken!")
886 test_inner()
Guido van Rossum3bead091992-01-27 17:00:37 +0000887
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500888 def test_return(self):
David Cuthbertfd97d1f2018-09-21 18:31:15 -0700889 # 'return' [testlist_star_expr]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000890 def g1(): return
891 def g2(): return 1
David Cuthbertfd97d1f2018-09-21 18:31:15 -0700892 def g3():
893 z = [2, 3]
894 return 1, *z
895
Thomas Wouters89f507f2006-12-13 04:49:30 +0000896 g1()
897 x = g2()
David Cuthbertfd97d1f2018-09-21 18:31:15 -0700898 y = g3()
899 self.assertEqual(y, (1, 2, 3), "unparenthesized star expr return")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000900 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000901
Serhiy Storchaka7cc42c32018-01-02 02:38:35 +0200902 def test_break_in_finally(self):
903 count = 0
904 while count < 2:
905 count += 1
906 try:
907 pass
908 finally:
909 break
910 self.assertEqual(count, 1)
911
912 count = 0
913 while count < 2:
914 count += 1
915 try:
916 continue
917 finally:
918 break
919 self.assertEqual(count, 1)
920
921 count = 0
922 while count < 2:
923 count += 1
924 try:
925 1/0
926 finally:
927 break
928 self.assertEqual(count, 1)
929
930 for count in [0, 1]:
931 self.assertEqual(count, 0)
932 try:
933 pass
934 finally:
935 break
936 self.assertEqual(count, 0)
937
938 for count in [0, 1]:
939 self.assertEqual(count, 0)
940 try:
941 continue
942 finally:
943 break
944 self.assertEqual(count, 0)
945
946 for count in [0, 1]:
947 self.assertEqual(count, 0)
948 try:
949 1/0
950 finally:
951 break
952 self.assertEqual(count, 0)
953
Serhiy Storchakafe2bbb12018-03-18 09:56:52 +0200954 def test_continue_in_finally(self):
955 count = 0
956 while count < 2:
957 count += 1
958 try:
959 pass
960 finally:
961 continue
962 break
963 self.assertEqual(count, 2)
964
965 count = 0
966 while count < 2:
967 count += 1
968 try:
969 break
970 finally:
971 continue
972 self.assertEqual(count, 2)
973
974 count = 0
975 while count < 2:
976 count += 1
977 try:
978 1/0
979 finally:
980 continue
981 break
982 self.assertEqual(count, 2)
983
984 for count in [0, 1]:
985 try:
986 pass
987 finally:
988 continue
989 break
990 self.assertEqual(count, 1)
991
992 for count in [0, 1]:
993 try:
994 break
995 finally:
996 continue
997 self.assertEqual(count, 1)
998
999 for count in [0, 1]:
1000 try:
1001 1/0
1002 finally:
1003 continue
1004 break
1005 self.assertEqual(count, 1)
1006
Serhiy Storchaka7cc42c32018-01-02 02:38:35 +02001007 def test_return_in_finally(self):
1008 def g1():
1009 try:
1010 pass
1011 finally:
1012 return 1
1013 self.assertEqual(g1(), 1)
1014
1015 def g2():
1016 try:
1017 return 2
1018 finally:
1019 return 3
1020 self.assertEqual(g2(), 3)
1021
1022 def g3():
1023 try:
1024 1/0
1025 finally:
1026 return 4
1027 self.assertEqual(g3(), 4)
1028
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001029 def test_break_in_finally_after_return(self):
1030 # See issue #37830
1031 def g1(x):
1032 for count in [0, 1]:
1033 count2 = 0
1034 while count2 < 20:
1035 count2 += 10
1036 try:
1037 return count + count2
1038 finally:
1039 if x:
1040 break
1041 return 'end', count, count2
1042 self.assertEqual(g1(False), 10)
1043 self.assertEqual(g1(True), ('end', 1, 10))
1044
1045 def g2(x):
1046 for count in [0, 1]:
1047 for count2 in [10, 20]:
1048 try:
1049 return count + count2
1050 finally:
1051 if x:
1052 break
1053 return 'end', count, count2
1054 self.assertEqual(g2(False), 10)
1055 self.assertEqual(g2(True), ('end', 1, 10))
1056
1057 def test_continue_in_finally_after_return(self):
1058 # See issue #37830
1059 def g1(x):
1060 count = 0
1061 while count < 100:
1062 count += 1
1063 try:
1064 return count
1065 finally:
1066 if x:
1067 continue
1068 return 'end', count
1069 self.assertEqual(g1(False), 1)
1070 self.assertEqual(g1(True), ('end', 100))
1071
1072 def g2(x):
1073 for count in [0, 1]:
1074 try:
1075 return count
1076 finally:
1077 if x:
1078 continue
1079 return 'end', count
1080 self.assertEqual(g2(False), 0)
1081 self.assertEqual(g2(True), ('end', 1))
1082
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001083 def test_yield(self):
Nick Coghlan1f7ce622012-01-13 21:43:40 +10001084 # Allowed as standalone statement
1085 def g(): yield 1
1086 def g(): yield from ()
1087 # Allowed as RHS of assignment
1088 def g(): x = yield 1
1089 def g(): x = yield from ()
1090 # Ordinary yield accepts implicit tuples
1091 def g(): yield 1, 1
1092 def g(): x = yield 1, 1
1093 # 'yield from' does not
1094 check_syntax_error(self, "def g(): yield from (), 1")
1095 check_syntax_error(self, "def g(): x = yield from (), 1")
1096 # Requires parentheses as subexpression
1097 def g(): 1, (yield 1)
1098 def g(): 1, (yield from ())
1099 check_syntax_error(self, "def g(): 1, yield 1")
1100 check_syntax_error(self, "def g(): 1, yield from ()")
1101 # Requires parentheses as call argument
1102 def g(): f((yield 1))
1103 def g(): f((yield 1), 1)
1104 def g(): f((yield from ()))
1105 def g(): f((yield from ()), 1)
David Cuthbertfd97d1f2018-09-21 18:31:15 -07001106 # Do not require parenthesis for tuple unpacking
1107 def g(): rest = 4, 5, 6; yield 1, 2, 3, *rest
Serhiy Storchaka4642d5f2018-10-05 21:09:56 +03001108 self.assertEqual(list(g()), [(1, 2, 3, 4, 5, 6)])
Nick Coghlan1f7ce622012-01-13 21:43:40 +10001109 check_syntax_error(self, "def g(): f(yield 1)")
1110 check_syntax_error(self, "def g(): f(yield 1, 1)")
1111 check_syntax_error(self, "def g(): f(yield from ())")
1112 check_syntax_error(self, "def g(): f(yield from (), 1)")
1113 # Not allowed at top level
1114 check_syntax_error(self, "yield")
1115 check_syntax_error(self, "yield from")
1116 # Not allowed at class scope
Thomas Wouters89f507f2006-12-13 04:49:30 +00001117 check_syntax_error(self, "class foo:yield 1")
Nick Coghlan1f7ce622012-01-13 21:43:40 +10001118 check_syntax_error(self, "class foo:yield from ()")
Pablo Galindob0544ba2021-04-21 12:41:19 +01001119 # Check annotation refleak on SyntaxError
1120 check_syntax_error(self, "def g(a:(yield)): pass")
Guido van Rossum3bead091992-01-27 17:00:37 +00001121
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +02001122 def test_yield_in_comprehensions(self):
1123 # Check yield in comprehensions
1124 def g(): [x for x in [(yield 1)]]
1125 def g(): [x for x in [(yield from ())]]
1126
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +02001127 check = self.check_syntax_error
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +02001128 check("def g(): [(yield x) for x in ()]",
1129 "'yield' inside list comprehension")
1130 check("def g(): [x for x in () if not (yield x)]",
1131 "'yield' inside list comprehension")
1132 check("def g(): [y for x in () for y in [(yield x)]]",
1133 "'yield' inside list comprehension")
1134 check("def g(): {(yield x) for x in ()}",
1135 "'yield' inside set comprehension")
1136 check("def g(): {(yield x): x for x in ()}",
1137 "'yield' inside dict comprehension")
1138 check("def g(): {x: (yield x) for x in ()}",
1139 "'yield' inside dict comprehension")
1140 check("def g(): ((yield x) for x in ())",
1141 "'yield' inside generator expression")
1142 check("def g(): [(yield from x) for x in ()]",
1143 "'yield' inside list comprehension")
1144 check("class C: [(yield x) for x in ()]",
1145 "'yield' inside list comprehension")
1146 check("[(yield x) for x in ()]",
1147 "'yield' inside list comprehension")
1148
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001149 def test_raise(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001150 # 'raise' test [',' test]
Collin Winter828f04a2007-08-31 00:04:24 +00001151 try: raise RuntimeError('just testing')
Thomas Wouters89f507f2006-12-13 04:49:30 +00001152 except RuntimeError: pass
1153 try: raise KeyboardInterrupt
1154 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +00001155
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001156 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001157 # 'import' dotted_as_names
1158 import sys
1159 import time, sys
1160 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
1161 from time import time
1162 from time import (time)
1163 # not testable inside a function, but already done at top of the module
1164 # from sys import *
1165 from sys import path, argv
1166 from sys import (path, argv)
1167 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +00001168
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001169 def test_global(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001170 # 'global' NAME (',' NAME)*
1171 global a
1172 global a, b
1173 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +00001174
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001175 def test_nonlocal(self):
Benjamin Petersona933e522008-10-24 22:16:39 +00001176 # 'nonlocal' NAME (',' NAME)*
1177 x = 0
1178 y = 0
1179 def f():
1180 nonlocal x
1181 nonlocal x, y
1182
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001183 def test_assert(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001184 # assertTruestmt: 'assert' test [',' test]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001185 assert 1
1186 assert 1, 1
1187 assert lambda x:x
1188 assert 1, lambda x:x+1
Ezio Melotti6cc5bf72011-12-02 18:22:52 +02001189
1190 try:
1191 assert True
1192 except AssertionError as e:
1193 self.fail("'assert True' should not have raised an AssertionError")
1194
1195 try:
1196 assert True, 'this should always pass'
1197 except AssertionError as e:
1198 self.fail("'assert True, msg' should not have "
1199 "raised an AssertionError")
1200
1201 # these tests fail if python is run with -O, so check __debug__
1202 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
tsukasa-aua8ef4572021-03-16 22:14:41 +11001203 def test_assert_failures(self):
Thomas Wouters80d373c2001-09-26 12:43:39 +00001204 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001205 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +00001206 except AssertionError as e:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001207 self.assertEqual(e.args[0], "msg")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001208 else:
Ezio Melotti6cc5bf72011-12-02 18:22:52 +02001209 self.fail("AssertionError not raised by assert 0")
1210
1211 try:
1212 assert False
1213 except AssertionError as e:
1214 self.assertEqual(len(e.args), 0)
1215 else:
1216 self.fail("AssertionError not raised by 'assert False'")
1217
tsukasa-aua8ef4572021-03-16 22:14:41 +11001218 def test_assert_syntax_warnings(self):
1219 # Ensure that we warn users if they provide a non-zero length tuple as
1220 # the assertion test.
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001221 self.check_syntax_warning('assert(x, "msg")',
1222 'assertion is always true')
tsukasa-aua8ef4572021-03-16 22:14:41 +11001223 self.check_syntax_warning('assert(False, "msg")',
1224 'assertion is always true')
1225 self.check_syntax_warning('assert(False,)',
1226 'assertion is always true')
1227
1228 with self.check_no_warnings(category=SyntaxWarning):
1229 compile('assert x, "msg"', '<testcase>', 'exec')
1230 compile('assert False, "msg"', '<testcase>', 'exec')
1231
1232 def test_assert_warning_promotes_to_syntax_error(self):
1233 # If SyntaxWarning is configured to be an error, it actually raises a
1234 # SyntaxError.
1235 # https://bugs.python.org/issue35029
Serhiy Storchakad31e7732018-10-21 10:09:39 +03001236 with warnings.catch_warnings():
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001237 warnings.simplefilter('error', SyntaxWarning)
tsukasa-aua8ef4572021-03-16 22:14:41 +11001238 try:
1239 compile('assert x, "msg" ', '<testcase>', 'exec')
1240 except SyntaxError:
1241 self.fail('SyntaxError incorrectly raised for \'assert x, "msg"\'')
1242 with self.assertRaises(SyntaxError):
1243 compile('assert(x, "msg")', '<testcase>', 'exec')
1244 with self.assertRaises(SyntaxError):
1245 compile('assert(False, "msg")', '<testcase>', 'exec')
1246 with self.assertRaises(SyntaxError):
1247 compile('assert(False,)', '<testcase>', 'exec')
Serhiy Storchakad31e7732018-10-21 10:09:39 +03001248
Thomas Wouters80d373c2001-09-26 12:43:39 +00001249
Thomas Wouters89f507f2006-12-13 04:49:30 +00001250 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
1251 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001252
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001253 def test_if(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001254 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
1255 if 1: pass
1256 if 1: pass
1257 else: pass
1258 if 0: pass
1259 elif 0: pass
1260 if 0: pass
1261 elif 0: pass
1262 elif 0: pass
1263 elif 0: pass
1264 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001265
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001266 def test_while(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001267 # 'while' test ':' suite ['else' ':' suite]
1268 while 0: pass
1269 while 0: pass
1270 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001271
Christian Heimes969fe572008-01-25 11:23:10 +00001272 # Issue1920: "while 0" is optimized away,
1273 # ensure that the "else" clause is still present.
1274 x = 0
1275 while 0:
1276 x = 1
1277 else:
1278 x = 2
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001279 self.assertEqual(x, 2)
Christian Heimes969fe572008-01-25 11:23:10 +00001280
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001281 def test_for(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001282 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
1283 for i in 1, 2, 3: pass
1284 for i, j, k in (): pass
1285 else: pass
1286 class Squares:
1287 def __init__(self, max):
1288 self.max = max
1289 self.sofar = []
1290 def __len__(self): return len(self.sofar)
1291 def __getitem__(self, i):
1292 if not 0 <= i < self.max: raise IndexError
1293 n = len(self.sofar)
1294 while n <= i:
1295 self.sofar.append(n*n)
1296 n = n+1
1297 return self.sofar[i]
1298 n = 0
1299 for x in Squares(10): n = n+x
1300 if n != 285:
1301 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +00001302
Thomas Wouters89f507f2006-12-13 04:49:30 +00001303 result = []
1304 for x, in [(1,), (2,), (3,)]:
1305 result.append(x)
1306 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +00001307
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001308 def test_try(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001309 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
1310 ### | 'try' ':' suite 'finally' ':' suite
Lysandros Nikolaouce21cfc2020-05-14 23:13:50 +03001311 ### except_clause: 'except' [expr ['as' NAME]]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001312 try:
1313 1/0
1314 except ZeroDivisionError:
1315 pass
1316 else:
1317 pass
1318 try: 1/0
1319 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +00001320 except TypeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +00001321 except: pass
1322 else: pass
1323 try: 1/0
1324 except (EOFError, TypeError, ZeroDivisionError): pass
1325 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +00001326 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +00001327 try: pass
1328 finally: pass
Lysandros Nikolaouce21cfc2020-05-14 23:13:50 +03001329 with self.assertRaises(SyntaxError):
1330 compile("try:\n pass\nexcept Exception as a.b:\n pass", "?", "exec")
1331 compile("try:\n pass\nexcept Exception as a[b]:\n pass", "?", "exec")
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +00001332
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001333 def test_suite(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001334 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
1335 if 1: pass
1336 if 1:
1337 pass
1338 if 1:
1339 #
1340 #
1341 #
1342 pass
1343 pass
1344 #
1345 pass
1346 #
Guido van Rossum3bead091992-01-27 17:00:37 +00001347
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001348 def test_test(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001349 ### and_test ('or' and_test)*
1350 ### and_test: not_test ('and' not_test)*
1351 ### not_test: 'not' not_test | comparison
1352 if not 1: pass
1353 if 1 and 1: pass
1354 if 1 or 1: pass
1355 if not not not 1: pass
1356 if not 1 and 1 and 1: pass
1357 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001358
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001359 def test_comparison(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001360 ### comparison: expr (comp_op expr)*
1361 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
1362 if 1: pass
1363 x = (1 == 1)
1364 if 1 == 1: pass
1365 if 1 != 1: pass
1366 if 1 < 1: pass
1367 if 1 > 1: pass
1368 if 1 <= 1: pass
1369 if 1 >= 1: pass
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001370 if x is x: pass
1371 if x is not x: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +00001372 if 1 in (): pass
1373 if 1 not in (): pass
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001374 if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in x is x is not x: pass
1375
1376 def test_comparison_is_literal(self):
1377 def check(test, msg='"is" with a literal'):
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001378 self.check_syntax_warning(test, msg)
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001379
1380 check('x is 1')
1381 check('x is "thing"')
1382 check('1 is x')
1383 check('x is y is 1')
1384 check('x is not 1', '"is not" with a literal')
1385
1386 with warnings.catch_warnings():
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001387 warnings.simplefilter('error', SyntaxWarning)
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001388 compile('x is None', '<testcase>', 'exec')
1389 compile('x is False', '<testcase>', 'exec')
1390 compile('x is True', '<testcase>', 'exec')
1391 compile('x is ...', '<testcase>', 'exec')
Guido van Rossum3bead091992-01-27 17:00:37 +00001392
Serhiy Storchaka62e44812019-02-16 08:12:19 +02001393 def test_warn_missed_comma(self):
1394 def check(test):
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001395 self.check_syntax_warning(test, msg)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02001396
1397 msg=r'is not callable; perhaps you missed a comma\?'
1398 check('[(1, 2) (3, 4)]')
1399 check('[(x, y) (3, 4)]')
1400 check('[[1, 2] (3, 4)]')
1401 check('[{1, 2} (3, 4)]')
1402 check('[{1: 2} (3, 4)]')
1403 check('[[i for i in range(5)] (3, 4)]')
1404 check('[{i for i in range(5)} (3, 4)]')
1405 check('[(i for i in range(5)) (3, 4)]')
1406 check('[{i: i for i in range(5)} (3, 4)]')
1407 check('[f"{x}" (3, 4)]')
1408 check('[f"x={x}" (3, 4)]')
1409 check('["abc" (3, 4)]')
1410 check('[b"abc" (3, 4)]')
1411 check('[123 (3, 4)]')
1412 check('[12.3 (3, 4)]')
1413 check('[12.3j (3, 4)]')
1414 check('[None (3, 4)]')
1415 check('[True (3, 4)]')
1416 check('[... (3, 4)]')
1417
1418 msg=r'is not subscriptable; perhaps you missed a comma\?'
1419 check('[{1, 2} [i, j]]')
1420 check('[{i for i in range(5)} [i, j]]')
1421 check('[(i for i in range(5)) [i, j]]')
1422 check('[(lambda x, y: x) [i, j]]')
1423 check('[123 [i, j]]')
1424 check('[12.3 [i, j]]')
1425 check('[12.3j [i, j]]')
1426 check('[None [i, j]]')
1427 check('[True [i, j]]')
1428 check('[... [i, j]]')
1429
1430 msg=r'indices must be integers or slices, not tuple; perhaps you missed a comma\?'
1431 check('[(1, 2) [i, j]]')
1432 check('[(x, y) [i, j]]')
1433 check('[[1, 2] [i, j]]')
1434 check('[[i for i in range(5)] [i, j]]')
1435 check('[f"{x}" [i, j]]')
1436 check('[f"x={x}" [i, j]]')
1437 check('["abc" [i, j]]')
1438 check('[b"abc" [i, j]]')
1439
1440 msg=r'indices must be integers or slices, not tuple;'
1441 check('[[1, 2] [3, 4]]')
1442 msg=r'indices must be integers or slices, not list;'
1443 check('[[1, 2] [[3, 4]]]')
1444 check('[[1, 2] [[i for i in range(5)]]]')
1445 msg=r'indices must be integers or slices, not set;'
1446 check('[[1, 2] [{3, 4}]]')
1447 check('[[1, 2] [{i for i in range(5)}]]')
1448 msg=r'indices must be integers or slices, not dict;'
1449 check('[[1, 2] [{3: 4}]]')
1450 check('[[1, 2] [{i: i for i in range(5)}]]')
1451 msg=r'indices must be integers or slices, not generator;'
1452 check('[[1, 2] [(i for i in range(5))]]')
1453 msg=r'indices must be integers or slices, not function;'
1454 check('[[1, 2] [(lambda x, y: x)]]')
1455 msg=r'indices must be integers or slices, not str;'
1456 check('[[1, 2] [f"{x}"]]')
1457 check('[[1, 2] [f"x={x}"]]')
1458 check('[[1, 2] ["abc"]]')
1459 msg=r'indices must be integers or slices, not'
1460 check('[[1, 2] [b"abc"]]')
1461 check('[[1, 2] [12.3]]')
1462 check('[[1, 2] [12.3j]]')
1463 check('[[1, 2] [None]]')
1464 check('[[1, 2] [...]]')
1465
1466 with warnings.catch_warnings():
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001467 warnings.simplefilter('error', SyntaxWarning)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02001468 compile('[(lambda x, y: x) (3, 4)]', '<testcase>', 'exec')
1469 compile('[[1, 2] [i]]', '<testcase>', 'exec')
1470 compile('[[1, 2] [0]]', '<testcase>', 'exec')
1471 compile('[[1, 2] [True]]', '<testcase>', 'exec')
1472 compile('[[1, 2] [1:2]]', '<testcase>', 'exec')
1473 compile('[{(1, 2): 3} [i, j]]', '<testcase>', 'exec')
1474
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001475 def test_binary_mask_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001476 x = 1 & 1
1477 x = 1 ^ 1
1478 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001479
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001480 def test_shift_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001481 x = 1 << 1
1482 x = 1 >> 1
1483 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001484
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001485 def test_additive_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001486 x = 1
1487 x = 1 + 1
1488 x = 1 - 1 - 1
1489 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001490
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001491 def test_multiplicative_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001492 x = 1 * 1
1493 x = 1 / 1
1494 x = 1 % 1
1495 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001496
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001497 def test_unary_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001498 x = +1
1499 x = -1
1500 x = ~1
1501 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
1502 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +00001503
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001504 def test_selectors(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001505 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
1506 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +00001507
Thomas Wouters89f507f2006-12-13 04:49:30 +00001508 import sys, time
1509 c = sys.path[0]
1510 x = time.time()
1511 x = sys.modules['time'].time()
1512 a = '01234'
1513 c = a[0]
1514 c = a[-1]
1515 s = a[0:5]
1516 s = a[:5]
1517 s = a[0:]
1518 s = a[:]
1519 s = a[-5:]
1520 s = a[:-1]
1521 s = a[-4:-3]
1522 # A rough test of SF bug 1333982. http://python.org/sf/1333982
1523 # The testing here is fairly incomplete.
1524 # Test cases should include: commas with 1 and 2 colons
1525 d = {}
1526 d[1] = 1
1527 d[1,] = 2
1528 d[1,2] = 3
1529 d[1,2,3] = 4
1530 L = list(d)
Serhiy Storchaka0cc99c82018-01-04 10:36:35 +02001531 L.sort(key=lambda x: (type(x).__name__, x))
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001532 self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +00001533
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001534 def test_atoms(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001535 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
1536 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +00001537
Thomas Wouters89f507f2006-12-13 04:49:30 +00001538 x = (1)
1539 x = (1 or 2 or 3)
1540 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +00001541
Thomas Wouters89f507f2006-12-13 04:49:30 +00001542 x = []
1543 x = [1]
1544 x = [1 or 2 or 3]
1545 x = [1 or 2 or 3, 2, 3]
1546 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +00001547
Thomas Wouters89f507f2006-12-13 04:49:30 +00001548 x = {}
1549 x = {'one': 1}
1550 x = {'one': 1,}
1551 x = {'one' or 'two': 1 or 2}
1552 x = {'one': 1, 'two': 2}
1553 x = {'one': 1, 'two': 2,}
1554 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +00001555
Thomas Wouters89f507f2006-12-13 04:49:30 +00001556 x = {'one'}
1557 x = {'one', 1,}
1558 x = {'one', 'two', 'three'}
1559 x = {2, 3, 4,}
1560
1561 x = x
1562 x = 'x'
1563 x = 123
1564
1565 ### exprlist: expr (',' expr)* [',']
1566 ### testlist: test (',' test)* [',']
1567 # These have been exercised enough above
1568
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001569 def test_classdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001570 # 'class' NAME ['(' [testlist] ')'] ':' suite
1571 class B: pass
1572 class B2(): pass
1573 class C1(B): pass
1574 class C2(B): pass
1575 class D(C1, C2, B): pass
1576 class C:
1577 def meth1(self): pass
1578 def meth2(self, arg): pass
1579 def meth3(self, a1, a2): pass
1580
Brandt Bucherbe501ca2020-03-03 14:25:44 -08001581 # decorator: '@' namedexpr_test NEWLINE
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001582 # decorators: decorator+
1583 # decorated: decorators (classdef | funcdef)
1584 def class_decorator(x): return x
1585 @class_decorator
1586 class G: pass
1587
Brandt Bucherbe501ca2020-03-03 14:25:44 -08001588 # Test expressions as decorators (PEP 614):
1589 @False or class_decorator
1590 class H: pass
1591 @d := class_decorator
1592 class I: pass
1593 @lambda c: class_decorator(c)
1594 class J: pass
1595 @[..., class_decorator, ...][1]
1596 class K: pass
1597 @class_decorator(class_decorator)(class_decorator)
1598 class L: pass
1599 @[class_decorator][0].__call__.__call__
1600 class M: pass
1601
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001602 def test_dictcomps(self):
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001603 # dictorsetmaker: ( (test ':' test (comp_for |
1604 # (',' test ':' test)* [','])) |
1605 # (test (comp_for | (',' test)* [','])) )
1606 nums = [1, 2, 3]
1607 self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
1608
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001609 def test_listcomps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001610 # list comprehension tests
1611 nums = [1, 2, 3, 4, 5]
1612 strs = ["Apple", "Banana", "Coconut"]
1613 spcs = [" Apple", " Banana ", "Coco nut "]
1614
1615 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
1616 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
1617 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
1618 self.assertEqual([(i, s) for i in nums for s in strs],
1619 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
1620 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
1621 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
1622 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
1623 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
1624 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
1625 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
1626 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
1627 (5, 'Banana'), (5, 'Coconut')])
1628 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
1629 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
1630
1631 def test_in_func(l):
1632 return [0 < x < 3 for x in l if x > 2]
1633
1634 self.assertEqual(test_in_func(nums), [False, False, False])
1635
1636 def test_nested_front():
1637 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
1638 [[1, 2], [3, 4], [5, 6]])
1639
1640 test_nested_front()
1641
1642 check_syntax_error(self, "[i, s for i in nums for s in strs]")
1643 check_syntax_error(self, "[x if y]")
1644
1645 suppliers = [
1646 (1, "Boeing"),
1647 (2, "Ford"),
1648 (3, "Macdonalds")
1649 ]
1650
1651 parts = [
1652 (10, "Airliner"),
1653 (20, "Engine"),
1654 (30, "Cheeseburger")
1655 ]
1656
1657 suppart = [
1658 (1, 10), (1, 20), (2, 20), (3, 30)
1659 ]
1660
1661 x = [
1662 (sname, pname)
1663 for (sno, sname) in suppliers
1664 for (pno, pname) in parts
1665 for (sp_sno, sp_pno) in suppart
1666 if sno == sp_sno and pno == sp_pno
1667 ]
1668
1669 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
1670 ('Macdonalds', 'Cheeseburger')])
1671
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001672 def test_genexps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001673 # generator expression tests
1674 g = ([x for x in range(10)] for x in range(1))
Georg Brandla18af4e2007-04-21 15:47:16 +00001675 self.assertEqual(next(g), [x for x in range(10)])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001676 try:
Georg Brandla18af4e2007-04-21 15:47:16 +00001677 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001678 self.fail('should produce StopIteration exception')
1679 except StopIteration:
1680 pass
1681
1682 a = 1
1683 try:
1684 g = (a for d in a)
Georg Brandla18af4e2007-04-21 15:47:16 +00001685 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001686 self.fail('should produce TypeError')
1687 except TypeError:
1688 pass
1689
1690 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
1691 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
1692
1693 a = [x for x in range(10)]
1694 b = (x for x in (y for y in a))
1695 self.assertEqual(sum(b), sum([x for x in range(10)]))
1696
1697 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
1698 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
1699 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
1700 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
1701 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
1702 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True)) if True), sum([x for x in range(10)]))
1703 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
1704 check_syntax_error(self, "foo(x for x in range(10), 100)")
1705 check_syntax_error(self, "foo(100, x for x in range(10))")
1706
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001707 def test_comprehension_specials(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001708 # test for outmost iterable precomputation
1709 x = 10; g = (i for i in range(x)); x = 5
1710 self.assertEqual(len(list(g)), 10)
1711
1712 # This should hold, since we're only precomputing outmost iterable.
1713 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
1714 x = 5; t = True;
1715 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
1716
1717 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
1718 # even though it's silly. Make sure it works (ifelse broke this.)
1719 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
1720 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
1721
1722 # verify unpacking single element tuples in listcomp/genexp.
1723 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
1724 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
1725
Benjamin Petersonf17ab892009-05-29 21:55:57 +00001726 def test_with_statement(self):
1727 class manager(object):
1728 def __enter__(self):
1729 return (1, 2)
1730 def __exit__(self, *args):
1731 pass
1732
1733 with manager():
1734 pass
1735 with manager() as x:
1736 pass
1737 with manager() as (x, y):
1738 pass
1739 with manager(), manager():
1740 pass
1741 with manager() as x, manager() as y:
1742 pass
1743 with manager() as x, manager():
1744 pass
1745
Pablo Galindo1ed83ad2020-06-11 17:30:46 +01001746 with (
1747 manager()
1748 ):
1749 pass
Pablo Galindo99db2a12020-05-06 22:54:34 +01001750
Pablo Galindo1ed83ad2020-06-11 17:30:46 +01001751 with (
1752 manager() as x
1753 ):
1754 pass
1755
1756 with (
1757 manager() as (x, y),
1758 manager() as z,
1759 ):
1760 pass
1761
1762 with (
1763 manager(),
1764 manager()
1765 ):
1766 pass
1767
1768 with (
1769 manager() as x,
1770 manager() as y
1771 ):
1772 pass
1773
1774 with (
1775 manager() as x,
1776 manager()
1777 ):
1778 pass
1779
1780 with (
1781 manager() as x,
1782 manager() as y,
1783 manager() as z,
1784 ):
1785 pass
1786
1787 with (
1788 manager() as x,
1789 manager() as y,
1790 manager(),
1791 ):
1792 pass
Pablo Galindo99db2a12020-05-06 22:54:34 +01001793
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001794 def test_if_else_expr(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001795 # Test ifelse expressions in various cases
1796 def _checkeval(msg, ret):
1797 "helper to check that evaluation of expressions is done correctly"
Victor Stinnerc6ec54d2016-04-12 18:33:41 +02001798 print(msg)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001799 return ret
1800
Nick Coghlan650f0d02007-04-15 12:05:43 +00001801 # the next line is not allowed anymore
1802 #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001803 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
1804 self.assertEqual([ x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False) ], [True])
1805 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
1806 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
1807 self.assertEqual((5 and 6 if 0 else 1), 1)
1808 self.assertEqual(((5 and 6) if 0 else 1), 1)
1809 self.assertEqual((5 and (6 if 1 else 1)), 6)
1810 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
1811 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
1812 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
1813 self.assertEqual((not 5 if 1 else 1), False)
1814 self.assertEqual((not 5 if 0 else 1), 1)
1815 self.assertEqual((6 + 1 if 1 else 2), 7)
1816 self.assertEqual((6 - 1 if 1 else 2), 5)
1817 self.assertEqual((6 * 2 if 1 else 4), 12)
1818 self.assertEqual((6 / 2 if 1 else 3), 3)
1819 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +00001820
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001821 def test_paren_evaluation(self):
1822 self.assertEqual(16 // (4 // 2), 8)
1823 self.assertEqual((16 // 4) // 2, 2)
1824 self.assertEqual(16 // 4 // 2, 2)
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001825 x = 2
1826 y = 3
1827 self.assertTrue(False is (x is y))
1828 self.assertFalse((False is x) is y)
1829 self.assertFalse(False is x is y)
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001830
Benjamin Petersond51374e2014-04-09 23:55:56 -04001831 def test_matrix_mul(self):
1832 # This is not intended to be a comprehensive test, rather just to be few
1833 # samples of the @ operator in test_grammar.py.
1834 class M:
1835 def __matmul__(self, o):
1836 return 4
1837 def __imatmul__(self, o):
1838 self.other = o
1839 return self
1840 m = M()
1841 self.assertEqual(m @ m, 4)
1842 m @= 42
1843 self.assertEqual(m.other, 42)
1844
Yury Selivanov75445082015-05-11 22:57:16 -04001845 def test_async_await(self):
Yury Selivanov75445082015-05-11 22:57:16 -04001846 async def test():
1847 def sum():
Yury Selivanov8fb307c2015-07-22 13:33:45 +03001848 pass
Yury Selivanov75445082015-05-11 22:57:16 -04001849 if 1:
1850 await someobj()
1851
1852 self.assertEqual(test.__name__, 'test')
1853 self.assertTrue(bool(test.__code__.co_flags & inspect.CO_COROUTINE))
1854
1855 def decorator(func):
1856 setattr(func, '_marked', True)
1857 return func
1858
1859 @decorator
1860 async def test2():
1861 return 22
1862 self.assertTrue(test2._marked)
1863 self.assertEqual(test2.__name__, 'test2')
1864 self.assertTrue(bool(test2.__code__.co_flags & inspect.CO_COROUTINE))
1865
1866 def test_async_for(self):
1867 class Done(Exception): pass
1868
1869 class AIter:
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001870 def __aiter__(self):
Yury Selivanov75445082015-05-11 22:57:16 -04001871 return self
1872 async def __anext__(self):
1873 raise StopAsyncIteration
1874
1875 async def foo():
1876 async for i in AIter():
1877 pass
1878 async for i, j in AIter():
1879 pass
1880 async for i in AIter():
1881 pass
1882 else:
1883 pass
1884 raise Done
1885
1886 with self.assertRaises(Done):
1887 foo().send(None)
1888
1889 def test_async_with(self):
1890 class Done(Exception): pass
1891
1892 class manager:
1893 async def __aenter__(self):
1894 return (1, 2)
1895 async def __aexit__(self, *exc):
1896 return False
1897
1898 async def foo():
1899 async with manager():
1900 pass
1901 async with manager() as x:
1902 pass
1903 async with manager() as (x, y):
1904 pass
1905 async with manager(), manager():
1906 pass
1907 async with manager() as x, manager() as y:
1908 pass
1909 async with manager() as x, manager():
1910 pass
1911 raise Done
1912
1913 with self.assertRaises(Done):
1914 foo().send(None)
1915
Guido van Rossum3bead091992-01-27 17:00:37 +00001916
Thomas Wouters89f507f2006-12-13 04:49:30 +00001917if __name__ == '__main__':
Zachary Ware38c707e2015-04-13 15:00:43 -05001918 unittest.main()