blob: c15f10b8bc747fb6452dfe2a35ed6d990eceb4bf [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
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300366 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'
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300382 self.assertEqual(CC.__annotations__['xx'], repr('ANNOT'))
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700383
384 def test_var_annot_module_semantics(self):
385 with self.assertRaises(AttributeError):
386 print(test.__annotations__)
387 self.assertEqual(ann_module.__annotations__,
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300388 {1: 2, 'x': 'int', 'y': 'str', 'f': 'Tuple[int, int]'})
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700389 self.assertEqual(ann_module.M.__annotations__,
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300390 {'123': 123, 'o': 'type'})
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700391 self.assertEqual(ann_module2.__annotations__, {})
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700392
393 def test_var_annot_in_module(self):
394 # check that functions fail the same way when executed
395 # outside of module where they were defined
396 from test.ann_module3 import f_bad_ann, g_bad_ann, D_bad_ann
397 with self.assertRaises(NameError):
398 f_bad_ann()
399 with self.assertRaises(NameError):
400 g_bad_ann()
401 with self.assertRaises(NameError):
402 D_bad_ann(5)
403
404 def test_var_annot_simple_exec(self):
405 gns = {}; lns= {}
406 exec("'docstring'\n"
407 "__annotations__[1] = 2\n"
408 "x: int = 5\n", gns, lns)
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300409 self.assertEqual(lns["__annotations__"], {1: 2, 'x': 'int'})
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700410 with self.assertRaises(KeyError):
411 gns['__annotations__']
412
413 def test_var_annot_custom_maps(self):
414 # tests with custom locals() and __annotations__
415 ns = {'__annotations__': CNS()}
416 exec('X: int; Z: str = "Z"; (w): complex = 1j', ns)
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300417 self.assertEqual(ns['__annotations__']['x'], 'int')
418 self.assertEqual(ns['__annotations__']['z'], 'str')
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700419 with self.assertRaises(KeyError):
420 ns['__annotations__']['w']
421 nonloc_ns = {}
422 class CNS2:
423 def __init__(self):
424 self._dct = {}
425 def __setitem__(self, item, value):
426 nonlocal nonloc_ns
427 self._dct[item] = value
428 nonloc_ns[item] = value
429 def __getitem__(self, item):
430 return self._dct[item]
431 exec('x: int = 1', {}, CNS2())
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300432 self.assertEqual(nonloc_ns['__annotations__']['x'], 'int')
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700433
434 def test_var_annot_refleak(self):
435 # complex case: custom locals plus custom __annotations__
436 # this was causing refleak
437 cns = CNS()
438 nonloc_ns = {'__annotations__': cns}
439 class CNS2:
440 def __init__(self):
441 self._dct = {'__annotations__': cns}
442 def __setitem__(self, item, value):
443 nonlocal nonloc_ns
444 self._dct[item] = value
445 nonloc_ns[item] = value
446 def __getitem__(self, item):
447 return self._dct[item]
448 exec('X: str', {}, CNS2())
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300449 self.assertEqual(nonloc_ns['__annotations__']['x'], 'str')
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700450
Ivan Levkivskyi62c35a82019-01-25 01:39:19 +0000451 def test_var_annot_rhs(self):
452 ns = {}
453 exec('x: tuple = 1, 2', ns)
454 self.assertEqual(ns['x'], (1, 2))
455 stmt = ('def f():\n'
456 ' x: int = yield')
457 exec(stmt, ns)
458 self.assertEqual(list(ns['f']()), [None])
459
Pablo Galindo8565f6b2019-06-03 08:34:20 +0100460 ns = {"a": 1, 'b': (2, 3, 4), "c":5, "Tuple": typing.Tuple}
461 exec('x: Tuple[int, ...] = a,*b,c', ns)
462 self.assertEqual(ns['x'], (1, 2, 3, 4, 5))
463
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500464 def test_funcdef(self):
Neal Norwitzc1505362006-12-28 06:47:50 +0000465 ### [decorators] 'def' NAME parameters ['->' test] ':' suite
Brandt Bucherbe501ca2020-03-03 14:25:44 -0800466 ### decorator: '@' namedexpr_test NEWLINE
Neal Norwitzc1505362006-12-28 06:47:50 +0000467 ### decorators: decorator+
468 ### parameters: '(' [typedargslist] ')'
469 ### typedargslist: ((tfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000470 ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000471 ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000472 ### tfpdef: NAME [':' test]
Neal Norwitzc1505362006-12-28 06:47:50 +0000473 ### varargslist: ((vfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000474 ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000475 ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000476 ### vfpdef: NAME
Thomas Wouters89f507f2006-12-13 04:49:30 +0000477 def f1(): pass
478 f1()
479 f1(*())
480 f1(*(), **{})
481 def f2(one_argument): pass
482 def f3(two, arguments): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000483 self.assertEqual(f2.__code__.co_varnames, ('one_argument',))
484 self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments'))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000485 def a1(one_arg,): pass
486 def a2(two, args,): pass
487 def v0(*rest): pass
488 def v1(a, *rest): pass
489 def v2(a, b, *rest): pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000490
491 f1()
492 f2(1)
493 f2(1,)
494 f3(1, 2)
495 f3(1, 2,)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000496 v0()
497 v0(1)
498 v0(1,)
499 v0(1,2)
500 v0(1,2,3,4,5,6,7,8,9,0)
501 v1(1)
502 v1(1,)
503 v1(1,2)
504 v1(1,2,3)
505 v1(1,2,3,4,5,6,7,8,9,0)
506 v2(1,2)
507 v2(1,2,3)
508 v2(1,2,3,4)
509 v2(1,2,3,4,5,6,7,8,9,0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000510
Thomas Wouters89f507f2006-12-13 04:49:30 +0000511 def d01(a=1): pass
512 d01()
513 d01(1)
514 d01(*(1,))
Yury Selivanov14acf5f2015-08-05 17:54:10 -0400515 d01(*[] or [2])
516 d01(*() or (), *{} and (), **() or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000517 d01(**{'a':2})
Benjamin Petersonde12b792015-05-16 09:44:45 -0400518 d01(**{'a':2} or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000519 def d11(a, b=1): pass
520 d11(1)
521 d11(1, 2)
522 d11(1, **{'b':2})
523 def d21(a, b, c=1): pass
524 d21(1, 2)
525 d21(1, 2, 3)
526 d21(*(1, 2, 3))
527 d21(1, *(2, 3))
528 d21(1, 2, *(3,))
529 d21(1, 2, **{'c':3})
530 def d02(a=1, b=2): pass
531 d02()
532 d02(1)
533 d02(1, 2)
534 d02(*(1, 2))
535 d02(1, *(2,))
536 d02(1, **{'b':2})
537 d02(**{'a': 1, 'b': 2})
538 def d12(a, b=1, c=2): pass
539 d12(1)
540 d12(1, 2)
541 d12(1, 2, 3)
542 def d22(a, b, c=1, d=2): pass
543 d22(1, 2)
544 d22(1, 2, 3)
545 d22(1, 2, 3, 4)
546 def d01v(a=1, *rest): pass
547 d01v()
548 d01v(1)
549 d01v(1, 2)
550 d01v(*(1, 2, 3, 4))
551 d01v(*(1,))
552 d01v(**{'a':2})
553 def d11v(a, b=1, *rest): pass
554 d11v(1)
555 d11v(1, 2)
556 d11v(1, 2, 3)
557 def d21v(a, b, c=1, *rest): pass
558 d21v(1, 2)
559 d21v(1, 2, 3)
560 d21v(1, 2, 3, 4)
561 d21v(*(1, 2, 3, 4))
562 d21v(1, 2, **{'c': 3})
563 def d02v(a=1, b=2, *rest): pass
564 d02v()
565 d02v(1)
566 d02v(1, 2)
567 d02v(1, 2, 3)
568 d02v(1, *(2, 3, 4))
569 d02v(**{'a': 1, 'b': 2})
570 def d12v(a, b=1, c=2, *rest): pass
571 d12v(1)
572 d12v(1, 2)
573 d12v(1, 2, 3)
574 d12v(1, 2, 3, 4)
575 d12v(*(1, 2, 3, 4))
576 d12v(1, 2, *(3, 4, 5))
577 d12v(1, *(2,), **{'c': 3})
578 def d22v(a, b, c=1, d=2, *rest): pass
579 d22v(1, 2)
580 d22v(1, 2, 3)
581 d22v(1, 2, 3, 4)
582 d22v(1, 2, 3, 4, 5)
583 d22v(*(1, 2, 3, 4))
584 d22v(1, 2, *(3, 4, 5))
585 d22v(1, *(2, 3), **{'d': 4})
Georg Brandld8b690f2008-05-16 17:28:50 +0000586
587 # keyword argument type tests
Serhiy Storchaka12f43342020-07-20 15:53:55 +0300588 with warnings.catch_warnings():
589 warnings.simplefilter('ignore', BytesWarning)
590 try:
591 str('x', **{b'foo':1 })
592 except TypeError:
593 pass
594 else:
595 self.fail('Bytes should not work as keyword argument names')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000596 # keyword only argument tests
597 def pos0key1(*, key): return key
598 pos0key1(key=100)
599 def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
600 pos2key2(1, 2, k1=100)
601 pos2key2(1, 2, k1=100, k2=200)
602 pos2key2(1, 2, k2=100, k1=200)
603 def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
604 pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
605 pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
606
Robert Collinsdf395992015-08-12 08:00:06 +1200607 self.assertRaises(SyntaxError, eval, "def f(*): pass")
608 self.assertRaises(SyntaxError, eval, "def f(*,): pass")
609 self.assertRaises(SyntaxError, eval, "def f(*, **kwds): pass")
610
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000611 # keyword arguments after *arglist
612 def f(*args, **kwargs):
613 return args, kwargs
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000614 self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000615 {'x':2, 'y':5}))
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400616 self.assertEqual(f(1, *(2,3), 4), ((1, 2, 3, 4), {}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000617 self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400618 self.assertEqual(f(**{'eggs':'scrambled', 'spam':'fried'}),
619 ((), {'eggs':'scrambled', 'spam':'fried'}))
620 self.assertEqual(f(spam='fried', **{'eggs':'scrambled'}),
621 ((), {'eggs':'scrambled', 'spam':'fried'}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000622
Serhiy Storchaka0cc99c82018-01-04 10:36:35 +0200623 # Check ast errors in *args and *kwargs
624 check_syntax_error(self, "f(*g(1=2))")
625 check_syntax_error(self, "f(**g(1=2))")
626
Neal Norwitzc1505362006-12-28 06:47:50 +0000627 # argument annotation tests
628 def f(x) -> list: pass
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300629 self.assertEqual(f.__annotations__, {'return': 'list'})
Zachary Warece17f762015-08-01 21:55:36 -0500630 def f(x: int): pass
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300631 self.assertEqual(f.__annotations__, {'x': 'int'})
Pablo Galindoa0c01bf2019-05-31 15:19:50 +0100632 def f(x: int, /): pass
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300633 self.assertEqual(f.__annotations__, {'x': 'int'})
Pablo Galindoa0c01bf2019-05-31 15:19:50 +0100634 def f(x: int = 34, /): pass
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300635 self.assertEqual(f.__annotations__, {'x': 'int'})
Zachary Warece17f762015-08-01 21:55:36 -0500636 def f(*x: str): pass
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300637 self.assertEqual(f.__annotations__, {'x': 'str'})
Zachary Warece17f762015-08-01 21:55:36 -0500638 def f(**x: float): pass
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300639 self.assertEqual(f.__annotations__, {'x': 'float'})
Zachary Warece17f762015-08-01 21:55:36 -0500640 def f(a, b: 1, c: 2, d): pass
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300641 self.assertEqual(f.__annotations__, {'b': '1', 'c': '2'})
Pablo Galindoa0c01bf2019-05-31 15:19:50 +0100642 def f(a, b: 1, /, c: 2, d): pass
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300643 self.assertEqual(f.__annotations__, {'b': '1', 'c': '2'})
Zachary Warece17f762015-08-01 21:55:36 -0500644 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000645 self.assertEqual(f.__annotations__,
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300646 {'b': '1', 'c': '2', 'e': '3', 'g': '6'})
Zachary Warece17f762015-08-01 21:55:36 -0500647 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6, h: 7, i=8, j: 9 = 10,
648 **k: 11) -> 12: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000649 self.assertEqual(f.__annotations__,
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300650 {'b': '1', 'c': '2', 'e': '3', 'g': '6', 'h': '7', 'j': '9',
651 'k': '11', 'return': '12'})
Pablo Galindoa0c01bf2019-05-31 15:19:50 +0100652 def f(a, b: 1, c: 2, d, e: 3 = 4, f: int = 5, /, *g: 6, h: 7, i=8, j: 9 = 10,
653 **k: 11) -> 12: pass
654 self.assertEqual(f.__annotations__,
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300655 {'b': '1', 'c': '2', 'e': '3', 'f': 'int', 'g': '6', 'h': '7', 'j': '9',
656 'k': '11', 'return': '12'})
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500657 # Check for issue #20625 -- annotations mangling
658 class Spam:
Zachary Warece17f762015-08-01 21:55:36 -0500659 def f(self, *, __kw: 1):
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500660 pass
661 class Ham(Spam): pass
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300662 self.assertEqual(Spam.f.__annotations__, {'_Spam__kw': '1'})
663 self.assertEqual(Ham.f.__annotations__, {'_Spam__kw': '1'})
Nick Coghlan71011e22007-04-23 11:05:01 +0000664 # Check for SF Bug #1697248 - mixing decorators and a return annotation
665 def null(x): return x
666 @null
667 def f(x) -> list: pass
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300668 self.assertEqual(f.__annotations__, {'return': 'list'})
Nick Coghlan71011e22007-04-23 11:05:01 +0000669
Brandt Bucherbe501ca2020-03-03 14:25:44 -0800670 # Test expressions as decorators (PEP 614):
671 @False or null
672 def f(x): pass
673 @d := null
674 def f(x): pass
675 @lambda f: null(f)
676 def f(x): pass
677 @[..., null, ...][1]
678 def f(x): pass
679 @null(null)(null)
680 def f(x): pass
681 @[null][0].__call__.__call__
682 def f(x): pass
683
Serhiy Storchaka64204de2016-06-12 17:36:24 +0300684 # test closures with a variety of opargs
Guido van Rossum0240b922007-02-26 21:23:50 +0000685 closure = 1
686 def f(): return closure
687 def f(x=1): return closure
688 def f(*, k=1): return closure
689 def f() -> int: return closure
Neal Norwitzc1505362006-12-28 06:47:50 +0000690
Robert Collinsdf395992015-08-12 08:00:06 +1200691 # Check trailing commas are permitted in funcdef argument list
692 def f(a,): pass
693 def f(*args,): pass
694 def f(**kwds,): pass
695 def f(a, *args,): pass
696 def f(a, **kwds,): pass
697 def f(*args, b,): pass
698 def f(*, b,): pass
699 def f(*args, **kwds,): pass
700 def f(a, *args, b,): pass
701 def f(a, *, b,): pass
702 def f(a, *args, **kwds,): pass
703 def f(*args, b, **kwds,): pass
704 def f(*, b, **kwds,): pass
705 def f(a, *args, b, **kwds,): pass
706 def f(a, *, b, **kwds,): pass
707
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500708 def test_lambdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000709 ### lambdef: 'lambda' [varargslist] ':' test
710 l1 = lambda : 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000711 self.assertEqual(l1(), 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000712 l2 = lambda : a[d] # XXX just testing the expression
Guido van Rossume2a383d2007-01-15 16:59:06 +0000713 l3 = lambda : [2 < x for x in [-1, 3, 0]]
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000714 self.assertEqual(l3(), [0, 1, 0])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000715 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000716 self.assertEqual(l4(), 1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000717 l5 = lambda x, y, z=2: x + y + z
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000718 self.assertEqual(l5(1, 2), 5)
719 self.assertEqual(l5(1, 2, 3), 6)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000720 check_syntax_error(self, "lambda x: x = 2")
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000721 check_syntax_error(self, "lambda (None,): None")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000722 l6 = lambda x, y, *, k=20: x+y+k
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000723 self.assertEqual(l6(1,2), 1+2+20)
724 self.assertEqual(l6(1,2,k=10), 1+2+10)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000725
Robert Collinsdf395992015-08-12 08:00:06 +1200726 # check that trailing commas are permitted
727 l10 = lambda a,: 0
728 l11 = lambda *args,: 0
729 l12 = lambda **kwds,: 0
730 l13 = lambda a, *args,: 0
731 l14 = lambda a, **kwds,: 0
732 l15 = lambda *args, b,: 0
733 l16 = lambda *, b,: 0
734 l17 = lambda *args, **kwds,: 0
735 l18 = lambda a, *args, b,: 0
736 l19 = lambda a, *, b,: 0
737 l20 = lambda a, *args, **kwds,: 0
738 l21 = lambda *args, b, **kwds,: 0
739 l22 = lambda *, b, **kwds,: 0
740 l23 = lambda a, *args, b, **kwds,: 0
741 l24 = lambda a, *, b, **kwds,: 0
742
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000743
Thomas Wouters89f507f2006-12-13 04:49:30 +0000744 ### stmt: simple_stmt | compound_stmt
745 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000746
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500747 def test_simple_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000748 ### simple_stmt: small_stmt (';' small_stmt)* [';']
749 x = 1; pass; del x
750 def foo():
Ezio Melotti13925002011-03-16 11:05:33 +0200751 # verify statements that end with semi-colons
Thomas Wouters89f507f2006-12-13 04:49:30 +0000752 x = 1; pass; del x;
753 foo()
Georg Brandl52318d62006-09-06 07:06:08 +0000754
Guido van Rossumd8faa362007-04-27 19:54:29 +0000755 ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
Thomas Wouters89f507f2006-12-13 04:49:30 +0000756 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000757
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500758 def test_expr_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000759 # (exprlist '=')* exprlist
Victor Stinner15a30952016-02-08 22:45:06 +0100760 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000761 1, 2, 3
762 x = 1
763 x = 1, 2, 3
764 x = y = z = 1, 2, 3
765 x, y, z = 1, 2, 3
766 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000767
Thomas Wouters89f507f2006-12-13 04:49:30 +0000768 check_syntax_error(self, "x + 1 = 1")
769 check_syntax_error(self, "a + 1 = b + 2")
Guido van Rossum3bead091992-01-27 17:00:37 +0000770
Nick Coghlan5b1fdc12014-06-16 19:48:02 +1000771 # Check the heuristic for print & exec covers significant cases
772 # As well as placing some limits on false positives
773 def test_former_statements_refer_to_builtins(self):
774 keywords = "print", "exec"
775 # Cases where we want the custom error
776 cases = [
777 "{} foo",
778 "{} {{1:foo}}",
779 "if 1: {} foo",
780 "if 1: {} {{1:foo}}",
781 "if 1:\n {} foo",
782 "if 1:\n {} {{1:foo}}",
783 ]
784 for keyword in keywords:
785 custom_msg = "call to '{}'".format(keyword)
786 for case in cases:
787 source = case.format(keyword)
788 with self.subTest(source=source):
789 with self.assertRaisesRegex(SyntaxError, custom_msg):
790 exec(source)
791 source = source.replace("foo", "(foo.)")
792 with self.subTest(source=source):
793 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
794 exec(source)
795
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500796 def test_del_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000797 # 'del' exprlist
798 abc = [1,2,3]
799 x, y, z = abc
800 xyz = x, y, z
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000801
Thomas Wouters89f507f2006-12-13 04:49:30 +0000802 del abc
803 del x, y, (z, xyz)
Barry Warsaw9182b452000-08-29 04:57:10 +0000804
Shantanu27c0d9b2020-05-11 14:53:58 -0700805 x, y, z = "xyz"
806 del x
807 del y,
808 del (z)
809 del ()
810
811 a, b, c, d, e, f, g = "abcdefg"
812 del a, (b, c), (d, (e, f))
813
814 a, b, c, d, e, f, g = "abcdefg"
815 del a, [b, c], (d, [e, f])
816
817 abcd = list("abcd")
818 del abcd[1:2]
819
820 compile("del a, (b[0].c, (d.e, f.g[1:2])), [h.i.j], ()", "<testcase>", "exec")
821
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500822 def test_pass_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000823 # 'pass'
824 pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000825
Thomas Wouters89f507f2006-12-13 04:49:30 +0000826 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
827 # Tested below
Barry Warsaw9182b452000-08-29 04:57:10 +0000828
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500829 def test_break_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000830 # 'break'
831 while 1: break
Barry Warsaw9182b452000-08-29 04:57:10 +0000832
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500833 def test_continue_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000834 # 'continue'
835 i = 1
836 while i: i = 0; continue
Barry Warsaw9182b452000-08-29 04:57:10 +0000837
Thomas Wouters89f507f2006-12-13 04:49:30 +0000838 msg = ""
839 while not msg:
840 msg = "ok"
841 try:
842 continue
843 msg = "continue failed to continue inside try"
844 except:
845 msg = "continue inside try called except block"
846 if msg != "ok":
847 self.fail(msg)
Barry Warsawefc92ee2000-08-21 15:46:50 +0000848
Thomas Wouters89f507f2006-12-13 04:49:30 +0000849 msg = ""
850 while not msg:
851 msg = "finally block not called"
852 try:
853 continue
854 finally:
855 msg = "ok"
856 if msg != "ok":
857 self.fail(msg)
Guido van Rossum3bead091992-01-27 17:00:37 +0000858
Thomas Wouters89f507f2006-12-13 04:49:30 +0000859 def test_break_continue_loop(self):
860 # This test warrants an explanation. It is a test specifically for SF bugs
861 # #463359 and #462937. The bug is that a 'break' statement executed or
862 # exception raised inside a try/except inside a loop, *after* a continue
863 # statement has been executed in that loop, will cause the wrong number of
864 # arguments to be popped off the stack and the instruction pointer reset to
865 # a very small number (usually 0.) Because of this, the following test
866 # *must* written as a function, and the tracking vars *must* be function
867 # arguments with default values. Otherwise, the test will loop and loop.
Guido van Rossum3bead091992-01-27 17:00:37 +0000868
Thomas Wouters89f507f2006-12-13 04:49:30 +0000869 def test_inner(extra_burning_oil = 1, count=0):
870 big_hippo = 2
871 while big_hippo:
872 count += 1
873 try:
874 if extra_burning_oil and big_hippo == 1:
875 extra_burning_oil -= 1
876 break
877 big_hippo -= 1
878 continue
879 except:
880 raise
881 if count > 2 or big_hippo != 1:
882 self.fail("continue then break in try/except in loop broken!")
883 test_inner()
Guido van Rossum3bead091992-01-27 17:00:37 +0000884
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500885 def test_return(self):
David Cuthbertfd97d1f2018-09-21 18:31:15 -0700886 # 'return' [testlist_star_expr]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000887 def g1(): return
888 def g2(): return 1
David Cuthbertfd97d1f2018-09-21 18:31:15 -0700889 def g3():
890 z = [2, 3]
891 return 1, *z
892
Thomas Wouters89f507f2006-12-13 04:49:30 +0000893 g1()
894 x = g2()
David Cuthbertfd97d1f2018-09-21 18:31:15 -0700895 y = g3()
896 self.assertEqual(y, (1, 2, 3), "unparenthesized star expr return")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000897 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000898
Serhiy Storchaka7cc42c32018-01-02 02:38:35 +0200899 def test_break_in_finally(self):
900 count = 0
901 while count < 2:
902 count += 1
903 try:
904 pass
905 finally:
906 break
907 self.assertEqual(count, 1)
908
909 count = 0
910 while count < 2:
911 count += 1
912 try:
913 continue
914 finally:
915 break
916 self.assertEqual(count, 1)
917
918 count = 0
919 while count < 2:
920 count += 1
921 try:
922 1/0
923 finally:
924 break
925 self.assertEqual(count, 1)
926
927 for count in [0, 1]:
928 self.assertEqual(count, 0)
929 try:
930 pass
931 finally:
932 break
933 self.assertEqual(count, 0)
934
935 for count in [0, 1]:
936 self.assertEqual(count, 0)
937 try:
938 continue
939 finally:
940 break
941 self.assertEqual(count, 0)
942
943 for count in [0, 1]:
944 self.assertEqual(count, 0)
945 try:
946 1/0
947 finally:
948 break
949 self.assertEqual(count, 0)
950
Serhiy Storchakafe2bbb12018-03-18 09:56:52 +0200951 def test_continue_in_finally(self):
952 count = 0
953 while count < 2:
954 count += 1
955 try:
956 pass
957 finally:
958 continue
959 break
960 self.assertEqual(count, 2)
961
962 count = 0
963 while count < 2:
964 count += 1
965 try:
966 break
967 finally:
968 continue
969 self.assertEqual(count, 2)
970
971 count = 0
972 while count < 2:
973 count += 1
974 try:
975 1/0
976 finally:
977 continue
978 break
979 self.assertEqual(count, 2)
980
981 for count in [0, 1]:
982 try:
983 pass
984 finally:
985 continue
986 break
987 self.assertEqual(count, 1)
988
989 for count in [0, 1]:
990 try:
991 break
992 finally:
993 continue
994 self.assertEqual(count, 1)
995
996 for count in [0, 1]:
997 try:
998 1/0
999 finally:
1000 continue
1001 break
1002 self.assertEqual(count, 1)
1003
Serhiy Storchaka7cc42c32018-01-02 02:38:35 +02001004 def test_return_in_finally(self):
1005 def g1():
1006 try:
1007 pass
1008 finally:
1009 return 1
1010 self.assertEqual(g1(), 1)
1011
1012 def g2():
1013 try:
1014 return 2
1015 finally:
1016 return 3
1017 self.assertEqual(g2(), 3)
1018
1019 def g3():
1020 try:
1021 1/0
1022 finally:
1023 return 4
1024 self.assertEqual(g3(), 4)
1025
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001026 def test_break_in_finally_after_return(self):
1027 # See issue #37830
1028 def g1(x):
1029 for count in [0, 1]:
1030 count2 = 0
1031 while count2 < 20:
1032 count2 += 10
1033 try:
1034 return count + count2
1035 finally:
1036 if x:
1037 break
1038 return 'end', count, count2
1039 self.assertEqual(g1(False), 10)
1040 self.assertEqual(g1(True), ('end', 1, 10))
1041
1042 def g2(x):
1043 for count in [0, 1]:
1044 for count2 in [10, 20]:
1045 try:
1046 return count + count2
1047 finally:
1048 if x:
1049 break
1050 return 'end', count, count2
1051 self.assertEqual(g2(False), 10)
1052 self.assertEqual(g2(True), ('end', 1, 10))
1053
1054 def test_continue_in_finally_after_return(self):
1055 # See issue #37830
1056 def g1(x):
1057 count = 0
1058 while count < 100:
1059 count += 1
1060 try:
1061 return count
1062 finally:
1063 if x:
1064 continue
1065 return 'end', count
1066 self.assertEqual(g1(False), 1)
1067 self.assertEqual(g1(True), ('end', 100))
1068
1069 def g2(x):
1070 for count in [0, 1]:
1071 try:
1072 return count
1073 finally:
1074 if x:
1075 continue
1076 return 'end', count
1077 self.assertEqual(g2(False), 0)
1078 self.assertEqual(g2(True), ('end', 1))
1079
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001080 def test_yield(self):
Nick Coghlan1f7ce622012-01-13 21:43:40 +10001081 # Allowed as standalone statement
1082 def g(): yield 1
1083 def g(): yield from ()
1084 # Allowed as RHS of assignment
1085 def g(): x = yield 1
1086 def g(): x = yield from ()
1087 # Ordinary yield accepts implicit tuples
1088 def g(): yield 1, 1
1089 def g(): x = yield 1, 1
1090 # 'yield from' does not
1091 check_syntax_error(self, "def g(): yield from (), 1")
1092 check_syntax_error(self, "def g(): x = yield from (), 1")
1093 # Requires parentheses as subexpression
1094 def g(): 1, (yield 1)
1095 def g(): 1, (yield from ())
1096 check_syntax_error(self, "def g(): 1, yield 1")
1097 check_syntax_error(self, "def g(): 1, yield from ()")
1098 # Requires parentheses as call argument
1099 def g(): f((yield 1))
1100 def g(): f((yield 1), 1)
1101 def g(): f((yield from ()))
1102 def g(): f((yield from ()), 1)
David Cuthbertfd97d1f2018-09-21 18:31:15 -07001103 # Do not require parenthesis for tuple unpacking
1104 def g(): rest = 4, 5, 6; yield 1, 2, 3, *rest
Serhiy Storchaka4642d5f2018-10-05 21:09:56 +03001105 self.assertEqual(list(g()), [(1, 2, 3, 4, 5, 6)])
Nick Coghlan1f7ce622012-01-13 21:43:40 +10001106 check_syntax_error(self, "def g(): f(yield 1)")
1107 check_syntax_error(self, "def g(): f(yield 1, 1)")
1108 check_syntax_error(self, "def g(): f(yield from ())")
1109 check_syntax_error(self, "def g(): f(yield from (), 1)")
1110 # Not allowed at top level
1111 check_syntax_error(self, "yield")
1112 check_syntax_error(self, "yield from")
1113 # Not allowed at class scope
Thomas Wouters89f507f2006-12-13 04:49:30 +00001114 check_syntax_error(self, "class foo:yield 1")
Nick Coghlan1f7ce622012-01-13 21:43:40 +10001115 check_syntax_error(self, "class foo:yield from ()")
Guido van Rossum3bead091992-01-27 17:00:37 +00001116
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +02001117 def test_yield_in_comprehensions(self):
1118 # Check yield in comprehensions
1119 def g(): [x for x in [(yield 1)]]
1120 def g(): [x for x in [(yield from ())]]
1121
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +02001122 check = self.check_syntax_error
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +02001123 check("def g(): [(yield x) for x in ()]",
1124 "'yield' inside list comprehension")
1125 check("def g(): [x for x in () if not (yield x)]",
1126 "'yield' inside list comprehension")
1127 check("def g(): [y for x in () for y in [(yield x)]]",
1128 "'yield' inside list comprehension")
1129 check("def g(): {(yield x) for x in ()}",
1130 "'yield' inside set comprehension")
1131 check("def g(): {(yield x): x for x in ()}",
1132 "'yield' inside dict comprehension")
1133 check("def g(): {x: (yield x) for x in ()}",
1134 "'yield' inside dict comprehension")
1135 check("def g(): ((yield x) for x in ())",
1136 "'yield' inside generator expression")
1137 check("def g(): [(yield from x) for x in ()]",
1138 "'yield' inside list comprehension")
1139 check("class C: [(yield x) for x in ()]",
1140 "'yield' inside list comprehension")
1141 check("[(yield x) for x in ()]",
1142 "'yield' inside list comprehension")
1143
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001144 def test_raise(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001145 # 'raise' test [',' test]
Collin Winter828f04a2007-08-31 00:04:24 +00001146 try: raise RuntimeError('just testing')
Thomas Wouters89f507f2006-12-13 04:49:30 +00001147 except RuntimeError: pass
1148 try: raise KeyboardInterrupt
1149 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +00001150
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001151 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001152 # 'import' dotted_as_names
1153 import sys
1154 import time, sys
1155 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
1156 from time import time
1157 from time import (time)
1158 # not testable inside a function, but already done at top of the module
1159 # from sys import *
1160 from sys import path, argv
1161 from sys import (path, argv)
1162 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +00001163
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001164 def test_global(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001165 # 'global' NAME (',' NAME)*
1166 global a
1167 global a, b
1168 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +00001169
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001170 def test_nonlocal(self):
Benjamin Petersona933e522008-10-24 22:16:39 +00001171 # 'nonlocal' NAME (',' NAME)*
1172 x = 0
1173 y = 0
1174 def f():
1175 nonlocal x
1176 nonlocal x, y
1177
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001178 def test_assert(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001179 # assertTruestmt: 'assert' test [',' test]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001180 assert 1
1181 assert 1, 1
1182 assert lambda x:x
1183 assert 1, lambda x:x+1
Ezio Melotti6cc5bf72011-12-02 18:22:52 +02001184
1185 try:
1186 assert True
1187 except AssertionError as e:
1188 self.fail("'assert True' should not have raised an AssertionError")
1189
1190 try:
1191 assert True, 'this should always pass'
1192 except AssertionError as e:
1193 self.fail("'assert True, msg' should not have "
1194 "raised an AssertionError")
1195
1196 # these tests fail if python is run with -O, so check __debug__
1197 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
tsukasa-aua8ef4572021-03-16 22:14:41 +11001198 def test_assert_failures(self):
Thomas Wouters80d373c2001-09-26 12:43:39 +00001199 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001200 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +00001201 except AssertionError as e:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001202 self.assertEqual(e.args[0], "msg")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001203 else:
Ezio Melotti6cc5bf72011-12-02 18:22:52 +02001204 self.fail("AssertionError not raised by assert 0")
1205
1206 try:
1207 assert False
1208 except AssertionError as e:
1209 self.assertEqual(len(e.args), 0)
1210 else:
1211 self.fail("AssertionError not raised by 'assert False'")
1212
tsukasa-aua8ef4572021-03-16 22:14:41 +11001213 def test_assert_syntax_warnings(self):
1214 # Ensure that we warn users if they provide a non-zero length tuple as
1215 # the assertion test.
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001216 self.check_syntax_warning('assert(x, "msg")',
1217 'assertion is always true')
tsukasa-aua8ef4572021-03-16 22:14:41 +11001218 self.check_syntax_warning('assert(False, "msg")',
1219 'assertion is always true')
1220 self.check_syntax_warning('assert(False,)',
1221 'assertion is always true')
1222
1223 with self.check_no_warnings(category=SyntaxWarning):
1224 compile('assert x, "msg"', '<testcase>', 'exec')
1225 compile('assert False, "msg"', '<testcase>', 'exec')
1226
1227 def test_assert_warning_promotes_to_syntax_error(self):
1228 # If SyntaxWarning is configured to be an error, it actually raises a
1229 # SyntaxError.
1230 # https://bugs.python.org/issue35029
Serhiy Storchakad31e7732018-10-21 10:09:39 +03001231 with warnings.catch_warnings():
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001232 warnings.simplefilter('error', SyntaxWarning)
tsukasa-aua8ef4572021-03-16 22:14:41 +11001233 try:
1234 compile('assert x, "msg" ', '<testcase>', 'exec')
1235 except SyntaxError:
1236 self.fail('SyntaxError incorrectly raised for \'assert x, "msg"\'')
1237 with self.assertRaises(SyntaxError):
1238 compile('assert(x, "msg")', '<testcase>', 'exec')
1239 with self.assertRaises(SyntaxError):
1240 compile('assert(False, "msg")', '<testcase>', 'exec')
1241 with self.assertRaises(SyntaxError):
1242 compile('assert(False,)', '<testcase>', 'exec')
Serhiy Storchakad31e7732018-10-21 10:09:39 +03001243
Thomas Wouters80d373c2001-09-26 12:43:39 +00001244
Thomas Wouters89f507f2006-12-13 04:49:30 +00001245 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
1246 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001247
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001248 def test_if(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001249 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
1250 if 1: pass
1251 if 1: pass
1252 else: pass
1253 if 0: pass
1254 elif 0: pass
1255 if 0: pass
1256 elif 0: pass
1257 elif 0: pass
1258 elif 0: pass
1259 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001260
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001261 def test_while(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001262 # 'while' test ':' suite ['else' ':' suite]
1263 while 0: pass
1264 while 0: pass
1265 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001266
Christian Heimes969fe572008-01-25 11:23:10 +00001267 # Issue1920: "while 0" is optimized away,
1268 # ensure that the "else" clause is still present.
1269 x = 0
1270 while 0:
1271 x = 1
1272 else:
1273 x = 2
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001274 self.assertEqual(x, 2)
Christian Heimes969fe572008-01-25 11:23:10 +00001275
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001276 def test_for(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001277 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
1278 for i in 1, 2, 3: pass
1279 for i, j, k in (): pass
1280 else: pass
1281 class Squares:
1282 def __init__(self, max):
1283 self.max = max
1284 self.sofar = []
1285 def __len__(self): return len(self.sofar)
1286 def __getitem__(self, i):
1287 if not 0 <= i < self.max: raise IndexError
1288 n = len(self.sofar)
1289 while n <= i:
1290 self.sofar.append(n*n)
1291 n = n+1
1292 return self.sofar[i]
1293 n = 0
1294 for x in Squares(10): n = n+x
1295 if n != 285:
1296 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +00001297
Thomas Wouters89f507f2006-12-13 04:49:30 +00001298 result = []
1299 for x, in [(1,), (2,), (3,)]:
1300 result.append(x)
1301 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +00001302
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001303 def test_try(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001304 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
1305 ### | 'try' ':' suite 'finally' ':' suite
Lysandros Nikolaouce21cfc2020-05-14 23:13:50 +03001306 ### except_clause: 'except' [expr ['as' NAME]]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001307 try:
1308 1/0
1309 except ZeroDivisionError:
1310 pass
1311 else:
1312 pass
1313 try: 1/0
1314 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +00001315 except TypeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +00001316 except: pass
1317 else: pass
1318 try: 1/0
1319 except (EOFError, TypeError, ZeroDivisionError): pass
1320 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +00001321 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +00001322 try: pass
1323 finally: pass
Lysandros Nikolaouce21cfc2020-05-14 23:13:50 +03001324 with self.assertRaises(SyntaxError):
1325 compile("try:\n pass\nexcept Exception as a.b:\n pass", "?", "exec")
1326 compile("try:\n pass\nexcept Exception as a[b]:\n pass", "?", "exec")
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +00001327
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001328 def test_suite(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001329 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
1330 if 1: pass
1331 if 1:
1332 pass
1333 if 1:
1334 #
1335 #
1336 #
1337 pass
1338 pass
1339 #
1340 pass
1341 #
Guido van Rossum3bead091992-01-27 17:00:37 +00001342
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001343 def test_test(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001344 ### and_test ('or' and_test)*
1345 ### and_test: not_test ('and' not_test)*
1346 ### not_test: 'not' not_test | comparison
1347 if not 1: pass
1348 if 1 and 1: pass
1349 if 1 or 1: pass
1350 if not not not 1: pass
1351 if not 1 and 1 and 1: pass
1352 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001353
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001354 def test_comparison(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001355 ### comparison: expr (comp_op expr)*
1356 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
1357 if 1: pass
1358 x = (1 == 1)
1359 if 1 == 1: pass
1360 if 1 != 1: pass
1361 if 1 < 1: pass
1362 if 1 > 1: pass
1363 if 1 <= 1: pass
1364 if 1 >= 1: pass
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001365 if x is x: pass
1366 if x is not x: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +00001367 if 1 in (): pass
1368 if 1 not in (): pass
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001369 if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in x is x is not x: pass
1370
1371 def test_comparison_is_literal(self):
1372 def check(test, msg='"is" with a literal'):
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001373 self.check_syntax_warning(test, msg)
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001374
1375 check('x is 1')
1376 check('x is "thing"')
1377 check('1 is x')
1378 check('x is y is 1')
1379 check('x is not 1', '"is not" with a literal')
1380
1381 with warnings.catch_warnings():
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001382 warnings.simplefilter('error', SyntaxWarning)
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001383 compile('x is None', '<testcase>', 'exec')
1384 compile('x is False', '<testcase>', 'exec')
1385 compile('x is True', '<testcase>', 'exec')
1386 compile('x is ...', '<testcase>', 'exec')
Guido van Rossum3bead091992-01-27 17:00:37 +00001387
Serhiy Storchaka62e44812019-02-16 08:12:19 +02001388 def test_warn_missed_comma(self):
1389 def check(test):
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001390 self.check_syntax_warning(test, msg)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02001391
1392 msg=r'is not callable; perhaps you missed a comma\?'
1393 check('[(1, 2) (3, 4)]')
1394 check('[(x, y) (3, 4)]')
1395 check('[[1, 2] (3, 4)]')
1396 check('[{1, 2} (3, 4)]')
1397 check('[{1: 2} (3, 4)]')
1398 check('[[i for i in range(5)] (3, 4)]')
1399 check('[{i for i in range(5)} (3, 4)]')
1400 check('[(i for i in range(5)) (3, 4)]')
1401 check('[{i: i for i in range(5)} (3, 4)]')
1402 check('[f"{x}" (3, 4)]')
1403 check('[f"x={x}" (3, 4)]')
1404 check('["abc" (3, 4)]')
1405 check('[b"abc" (3, 4)]')
1406 check('[123 (3, 4)]')
1407 check('[12.3 (3, 4)]')
1408 check('[12.3j (3, 4)]')
1409 check('[None (3, 4)]')
1410 check('[True (3, 4)]')
1411 check('[... (3, 4)]')
1412
1413 msg=r'is not subscriptable; perhaps you missed a comma\?'
1414 check('[{1, 2} [i, j]]')
1415 check('[{i for i in range(5)} [i, j]]')
1416 check('[(i for i in range(5)) [i, j]]')
1417 check('[(lambda x, y: x) [i, j]]')
1418 check('[123 [i, j]]')
1419 check('[12.3 [i, j]]')
1420 check('[12.3j [i, j]]')
1421 check('[None [i, j]]')
1422 check('[True [i, j]]')
1423 check('[... [i, j]]')
1424
1425 msg=r'indices must be integers or slices, not tuple; perhaps you missed a comma\?'
1426 check('[(1, 2) [i, j]]')
1427 check('[(x, y) [i, j]]')
1428 check('[[1, 2] [i, j]]')
1429 check('[[i for i in range(5)] [i, j]]')
1430 check('[f"{x}" [i, j]]')
1431 check('[f"x={x}" [i, j]]')
1432 check('["abc" [i, j]]')
1433 check('[b"abc" [i, j]]')
1434
1435 msg=r'indices must be integers or slices, not tuple;'
1436 check('[[1, 2] [3, 4]]')
1437 msg=r'indices must be integers or slices, not list;'
1438 check('[[1, 2] [[3, 4]]]')
1439 check('[[1, 2] [[i for i in range(5)]]]')
1440 msg=r'indices must be integers or slices, not set;'
1441 check('[[1, 2] [{3, 4}]]')
1442 check('[[1, 2] [{i for i in range(5)}]]')
1443 msg=r'indices must be integers or slices, not dict;'
1444 check('[[1, 2] [{3: 4}]]')
1445 check('[[1, 2] [{i: i for i in range(5)}]]')
1446 msg=r'indices must be integers or slices, not generator;'
1447 check('[[1, 2] [(i for i in range(5))]]')
1448 msg=r'indices must be integers or slices, not function;'
1449 check('[[1, 2] [(lambda x, y: x)]]')
1450 msg=r'indices must be integers or slices, not str;'
1451 check('[[1, 2] [f"{x}"]]')
1452 check('[[1, 2] [f"x={x}"]]')
1453 check('[[1, 2] ["abc"]]')
1454 msg=r'indices must be integers or slices, not'
1455 check('[[1, 2] [b"abc"]]')
1456 check('[[1, 2] [12.3]]')
1457 check('[[1, 2] [12.3j]]')
1458 check('[[1, 2] [None]]')
1459 check('[[1, 2] [...]]')
1460
1461 with warnings.catch_warnings():
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001462 warnings.simplefilter('error', SyntaxWarning)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02001463 compile('[(lambda x, y: x) (3, 4)]', '<testcase>', 'exec')
1464 compile('[[1, 2] [i]]', '<testcase>', 'exec')
1465 compile('[[1, 2] [0]]', '<testcase>', 'exec')
1466 compile('[[1, 2] [True]]', '<testcase>', 'exec')
1467 compile('[[1, 2] [1:2]]', '<testcase>', 'exec')
1468 compile('[{(1, 2): 3} [i, j]]', '<testcase>', 'exec')
1469
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001470 def test_binary_mask_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001471 x = 1 & 1
1472 x = 1 ^ 1
1473 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001474
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001475 def test_shift_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001476 x = 1 << 1
1477 x = 1 >> 1
1478 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001479
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001480 def test_additive_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001481 x = 1
1482 x = 1 + 1
1483 x = 1 - 1 - 1
1484 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001485
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001486 def test_multiplicative_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001487 x = 1 * 1
1488 x = 1 / 1
1489 x = 1 % 1
1490 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001491
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001492 def test_unary_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001493 x = +1
1494 x = -1
1495 x = ~1
1496 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
1497 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +00001498
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001499 def test_selectors(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001500 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
1501 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +00001502
Thomas Wouters89f507f2006-12-13 04:49:30 +00001503 import sys, time
1504 c = sys.path[0]
1505 x = time.time()
1506 x = sys.modules['time'].time()
1507 a = '01234'
1508 c = a[0]
1509 c = a[-1]
1510 s = a[0:5]
1511 s = a[:5]
1512 s = a[0:]
1513 s = a[:]
1514 s = a[-5:]
1515 s = a[:-1]
1516 s = a[-4:-3]
1517 # A rough test of SF bug 1333982. http://python.org/sf/1333982
1518 # The testing here is fairly incomplete.
1519 # Test cases should include: commas with 1 and 2 colons
1520 d = {}
1521 d[1] = 1
1522 d[1,] = 2
1523 d[1,2] = 3
1524 d[1,2,3] = 4
1525 L = list(d)
Serhiy Storchaka0cc99c82018-01-04 10:36:35 +02001526 L.sort(key=lambda x: (type(x).__name__, x))
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001527 self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +00001528
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001529 def test_atoms(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001530 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
1531 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +00001532
Thomas Wouters89f507f2006-12-13 04:49:30 +00001533 x = (1)
1534 x = (1 or 2 or 3)
1535 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +00001536
Thomas Wouters89f507f2006-12-13 04:49:30 +00001537 x = []
1538 x = [1]
1539 x = [1 or 2 or 3]
1540 x = [1 or 2 or 3, 2, 3]
1541 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +00001542
Thomas Wouters89f507f2006-12-13 04:49:30 +00001543 x = {}
1544 x = {'one': 1}
1545 x = {'one': 1,}
1546 x = {'one' or 'two': 1 or 2}
1547 x = {'one': 1, 'two': 2}
1548 x = {'one': 1, 'two': 2,}
1549 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +00001550
Thomas Wouters89f507f2006-12-13 04:49:30 +00001551 x = {'one'}
1552 x = {'one', 1,}
1553 x = {'one', 'two', 'three'}
1554 x = {2, 3, 4,}
1555
1556 x = x
1557 x = 'x'
1558 x = 123
1559
1560 ### exprlist: expr (',' expr)* [',']
1561 ### testlist: test (',' test)* [',']
1562 # These have been exercised enough above
1563
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001564 def test_classdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001565 # 'class' NAME ['(' [testlist] ')'] ':' suite
1566 class B: pass
1567 class B2(): pass
1568 class C1(B): pass
1569 class C2(B): pass
1570 class D(C1, C2, B): pass
1571 class C:
1572 def meth1(self): pass
1573 def meth2(self, arg): pass
1574 def meth3(self, a1, a2): pass
1575
Brandt Bucherbe501ca2020-03-03 14:25:44 -08001576 # decorator: '@' namedexpr_test NEWLINE
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001577 # decorators: decorator+
1578 # decorated: decorators (classdef | funcdef)
1579 def class_decorator(x): return x
1580 @class_decorator
1581 class G: pass
1582
Brandt Bucherbe501ca2020-03-03 14:25:44 -08001583 # Test expressions as decorators (PEP 614):
1584 @False or class_decorator
1585 class H: pass
1586 @d := class_decorator
1587 class I: pass
1588 @lambda c: class_decorator(c)
1589 class J: pass
1590 @[..., class_decorator, ...][1]
1591 class K: pass
1592 @class_decorator(class_decorator)(class_decorator)
1593 class L: pass
1594 @[class_decorator][0].__call__.__call__
1595 class M: pass
1596
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001597 def test_dictcomps(self):
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001598 # dictorsetmaker: ( (test ':' test (comp_for |
1599 # (',' test ':' test)* [','])) |
1600 # (test (comp_for | (',' test)* [','])) )
1601 nums = [1, 2, 3]
1602 self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
1603
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001604 def test_listcomps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001605 # list comprehension tests
1606 nums = [1, 2, 3, 4, 5]
1607 strs = ["Apple", "Banana", "Coconut"]
1608 spcs = [" Apple", " Banana ", "Coco nut "]
1609
1610 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
1611 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
1612 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
1613 self.assertEqual([(i, s) for i in nums for s in strs],
1614 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
1615 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
1616 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
1617 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
1618 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
1619 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
1620 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
1621 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
1622 (5, 'Banana'), (5, 'Coconut')])
1623 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
1624 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
1625
1626 def test_in_func(l):
1627 return [0 < x < 3 for x in l if x > 2]
1628
1629 self.assertEqual(test_in_func(nums), [False, False, False])
1630
1631 def test_nested_front():
1632 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
1633 [[1, 2], [3, 4], [5, 6]])
1634
1635 test_nested_front()
1636
1637 check_syntax_error(self, "[i, s for i in nums for s in strs]")
1638 check_syntax_error(self, "[x if y]")
1639
1640 suppliers = [
1641 (1, "Boeing"),
1642 (2, "Ford"),
1643 (3, "Macdonalds")
1644 ]
1645
1646 parts = [
1647 (10, "Airliner"),
1648 (20, "Engine"),
1649 (30, "Cheeseburger")
1650 ]
1651
1652 suppart = [
1653 (1, 10), (1, 20), (2, 20), (3, 30)
1654 ]
1655
1656 x = [
1657 (sname, pname)
1658 for (sno, sname) in suppliers
1659 for (pno, pname) in parts
1660 for (sp_sno, sp_pno) in suppart
1661 if sno == sp_sno and pno == sp_pno
1662 ]
1663
1664 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
1665 ('Macdonalds', 'Cheeseburger')])
1666
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001667 def test_genexps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001668 # generator expression tests
1669 g = ([x for x in range(10)] for x in range(1))
Georg Brandla18af4e2007-04-21 15:47:16 +00001670 self.assertEqual(next(g), [x for x in range(10)])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001671 try:
Georg Brandla18af4e2007-04-21 15:47:16 +00001672 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001673 self.fail('should produce StopIteration exception')
1674 except StopIteration:
1675 pass
1676
1677 a = 1
1678 try:
1679 g = (a for d in a)
Georg Brandla18af4e2007-04-21 15:47:16 +00001680 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001681 self.fail('should produce TypeError')
1682 except TypeError:
1683 pass
1684
1685 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
1686 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
1687
1688 a = [x for x in range(10)]
1689 b = (x for x in (y for y in a))
1690 self.assertEqual(sum(b), sum([x for x in range(10)]))
1691
1692 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
1693 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
1694 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
1695 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
1696 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
1697 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)]))
1698 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
1699 check_syntax_error(self, "foo(x for x in range(10), 100)")
1700 check_syntax_error(self, "foo(100, x for x in range(10))")
1701
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001702 def test_comprehension_specials(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001703 # test for outmost iterable precomputation
1704 x = 10; g = (i for i in range(x)); x = 5
1705 self.assertEqual(len(list(g)), 10)
1706
1707 # This should hold, since we're only precomputing outmost iterable.
1708 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
1709 x = 5; t = True;
1710 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
1711
1712 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
1713 # even though it's silly. Make sure it works (ifelse broke this.)
1714 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
1715 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
1716
1717 # verify unpacking single element tuples in listcomp/genexp.
1718 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
1719 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
1720
Benjamin Petersonf17ab892009-05-29 21:55:57 +00001721 def test_with_statement(self):
1722 class manager(object):
1723 def __enter__(self):
1724 return (1, 2)
1725 def __exit__(self, *args):
1726 pass
1727
1728 with manager():
1729 pass
1730 with manager() as x:
1731 pass
1732 with manager() as (x, y):
1733 pass
1734 with manager(), manager():
1735 pass
1736 with manager() as x, manager() as y:
1737 pass
1738 with manager() as x, manager():
1739 pass
1740
Pablo Galindo1ed83ad2020-06-11 17:30:46 +01001741 with (
1742 manager()
1743 ):
1744 pass
Pablo Galindo99db2a12020-05-06 22:54:34 +01001745
Pablo Galindo1ed83ad2020-06-11 17:30:46 +01001746 with (
1747 manager() as x
1748 ):
1749 pass
1750
1751 with (
1752 manager() as (x, y),
1753 manager() as z,
1754 ):
1755 pass
1756
1757 with (
1758 manager(),
1759 manager()
1760 ):
1761 pass
1762
1763 with (
1764 manager() as x,
1765 manager() as y
1766 ):
1767 pass
1768
1769 with (
1770 manager() as x,
1771 manager()
1772 ):
1773 pass
1774
1775 with (
1776 manager() as x,
1777 manager() as y,
1778 manager() as z,
1779 ):
1780 pass
1781
1782 with (
1783 manager() as x,
1784 manager() as y,
1785 manager(),
1786 ):
1787 pass
Pablo Galindo99db2a12020-05-06 22:54:34 +01001788
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001789 def test_if_else_expr(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001790 # Test ifelse expressions in various cases
1791 def _checkeval(msg, ret):
1792 "helper to check that evaluation of expressions is done correctly"
Victor Stinnerc6ec54d2016-04-12 18:33:41 +02001793 print(msg)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001794 return ret
1795
Nick Coghlan650f0d02007-04-15 12:05:43 +00001796 # the next line is not allowed anymore
1797 #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001798 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
1799 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])
1800 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
1801 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
1802 self.assertEqual((5 and 6 if 0 else 1), 1)
1803 self.assertEqual(((5 and 6) if 0 else 1), 1)
1804 self.assertEqual((5 and (6 if 1 else 1)), 6)
1805 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
1806 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
1807 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
1808 self.assertEqual((not 5 if 1 else 1), False)
1809 self.assertEqual((not 5 if 0 else 1), 1)
1810 self.assertEqual((6 + 1 if 1 else 2), 7)
1811 self.assertEqual((6 - 1 if 1 else 2), 5)
1812 self.assertEqual((6 * 2 if 1 else 4), 12)
1813 self.assertEqual((6 / 2 if 1 else 3), 3)
1814 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +00001815
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001816 def test_paren_evaluation(self):
1817 self.assertEqual(16 // (4 // 2), 8)
1818 self.assertEqual((16 // 4) // 2, 2)
1819 self.assertEqual(16 // 4 // 2, 2)
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001820 x = 2
1821 y = 3
1822 self.assertTrue(False is (x is y))
1823 self.assertFalse((False is x) is y)
1824 self.assertFalse(False is x is y)
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001825
Benjamin Petersond51374e2014-04-09 23:55:56 -04001826 def test_matrix_mul(self):
1827 # This is not intended to be a comprehensive test, rather just to be few
1828 # samples of the @ operator in test_grammar.py.
1829 class M:
1830 def __matmul__(self, o):
1831 return 4
1832 def __imatmul__(self, o):
1833 self.other = o
1834 return self
1835 m = M()
1836 self.assertEqual(m @ m, 4)
1837 m @= 42
1838 self.assertEqual(m.other, 42)
1839
Yury Selivanov75445082015-05-11 22:57:16 -04001840 def test_async_await(self):
Yury Selivanov75445082015-05-11 22:57:16 -04001841 async def test():
1842 def sum():
Yury Selivanov8fb307c2015-07-22 13:33:45 +03001843 pass
Yury Selivanov75445082015-05-11 22:57:16 -04001844 if 1:
1845 await someobj()
1846
1847 self.assertEqual(test.__name__, 'test')
1848 self.assertTrue(bool(test.__code__.co_flags & inspect.CO_COROUTINE))
1849
1850 def decorator(func):
1851 setattr(func, '_marked', True)
1852 return func
1853
1854 @decorator
1855 async def test2():
1856 return 22
1857 self.assertTrue(test2._marked)
1858 self.assertEqual(test2.__name__, 'test2')
1859 self.assertTrue(bool(test2.__code__.co_flags & inspect.CO_COROUTINE))
1860
1861 def test_async_for(self):
1862 class Done(Exception): pass
1863
1864 class AIter:
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001865 def __aiter__(self):
Yury Selivanov75445082015-05-11 22:57:16 -04001866 return self
1867 async def __anext__(self):
1868 raise StopAsyncIteration
1869
1870 async def foo():
1871 async for i in AIter():
1872 pass
1873 async for i, j in AIter():
1874 pass
1875 async for i in AIter():
1876 pass
1877 else:
1878 pass
1879 raise Done
1880
1881 with self.assertRaises(Done):
1882 foo().send(None)
1883
1884 def test_async_with(self):
1885 class Done(Exception): pass
1886
1887 class manager:
1888 async def __aenter__(self):
1889 return (1, 2)
1890 async def __aexit__(self, *exc):
1891 return False
1892
1893 async def foo():
1894 async with manager():
1895 pass
1896 async with manager() as x:
1897 pass
1898 async with manager() as (x, y):
1899 pass
1900 async with manager(), manager():
1901 pass
1902 async with manager() as x, manager() as y:
1903 pass
1904 async with manager() as x, manager():
1905 pass
1906 raise Done
1907
1908 with self.assertRaises(Done):
1909 foo().send(None)
1910
Guido van Rossum3bead091992-01-27 17:00:37 +00001911
Thomas Wouters89f507f2006-12-13 04:49:30 +00001912if __name__ == '__main__':
Zachary Ware38c707e2015-04-13 15:00:43 -05001913 unittest.main()