blob: 6d7d5544ed9c3fd309719b37324d14e58ee0cd88 [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
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02004from test.support import check_syntax_error, check_syntax_warning
Yury Selivanov75445082015-05-11 22:57:16 -04005import inspect
Thomas Wouters89f507f2006-12-13 04:49:30 +00006import unittest
Jeremy Hylton7d3dff22001-10-10 01:45:02 +00007import sys
Serhiy Storchakad31e7732018-10-21 10:09:39 +03008import warnings
Thomas Wouters89f507f2006-12-13 04:49:30 +00009# testing import *
10from sys import *
Guido van Rossum3bead091992-01-27 17:00:37 +000011
Yury Selivanovf8cb8a12016-09-08 20:50:03 -070012# different import patterns to check that __annotations__ does not interfere
13# with import machinery
14import test.ann_module as ann_module
15import typing
16from collections import ChainMap
17from test import ann_module2
18import test
19
Brett Cannona721aba2016-09-09 14:57:09 -070020# These are shared with test_tokenize and other test modules.
21#
22# Note: since several test cases filter out floats by looking for "e" and ".",
23# don't add hexadecimal literals that contain "e" or "E".
24VALID_UNDERSCORE_LITERALS = [
25 '0_0_0',
26 '4_2',
27 '1_0000_0000',
28 '0b1001_0100',
29 '0xffff_ffff',
30 '0o5_7_7',
31 '1_00_00.5',
32 '1_00_00.5e5',
33 '1_00_00e5_1',
34 '1e1_0',
35 '.1_4',
36 '.1_4e1',
37 '0b_0',
38 '0x_f',
39 '0o_5',
40 '1_00_00j',
41 '1_00_00.5j',
42 '1_00_00e5_1j',
43 '.1_4j',
44 '(1_2.5+3_3j)',
45 '(.5_6j)',
46]
47INVALID_UNDERSCORE_LITERALS = [
48 # Trailing underscores:
49 '0_',
50 '42_',
51 '1.4j_',
52 '0x_',
53 '0b1_',
54 '0xf_',
55 '0o5_',
56 '0 if 1_Else 1',
57 # Underscores in the base selector:
58 '0_b0',
59 '0_xf',
60 '0_o5',
61 # Old-style octal, still disallowed:
62 '0_7',
63 '09_99',
64 # Multiple consecutive underscores:
65 '4_______2',
66 '0.1__4',
67 '0.1__4j',
68 '0b1001__0100',
69 '0xffff__ffff',
70 '0x___',
71 '0o5__77',
72 '1e1__0',
73 '1e1__0j',
74 # Underscore right before a dot:
75 '1_.4',
76 '1_.4j',
77 # Underscore right after a dot:
78 '1._4',
79 '1._4j',
80 '._5',
81 '._5j',
82 # Underscore right after a sign:
83 '1.0e+_1',
84 '1.0e+_1j',
85 # Underscore right before j:
86 '1.4_j',
87 '1.4e5_j',
88 # Underscore right before e:
89 '1_e1',
90 '1.4_e1',
91 '1.4_e1j',
92 # Underscore right after e:
93 '1e_1',
94 '1.4e_1',
95 '1.4e_1j',
96 # Complex cases with parens:
97 '(1+1.5_j_)',
98 '(1+1.5_j)',
99]
100
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000101
Thomas Wouters89f507f2006-12-13 04:49:30 +0000102class TokenTests(unittest.TestCase):
Guido van Rossum3bead091992-01-27 17:00:37 +0000103
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +0200104 from test.support import check_syntax_error
Serhiy Storchakacf7303e2018-07-09 15:09:35 +0300105
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500106 def test_backslash(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000107 # Backslash means line continuation:
108 x = 1 \
109 + 1
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000110 self.assertEqual(x, 2, 'backslash for line continuation')
Guido van Rossum3bead091992-01-27 17:00:37 +0000111
Thomas Wouters89f507f2006-12-13 04:49:30 +0000112 # Backslash does not means continuation in comments :\
113 x = 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000114 self.assertEqual(x, 0, 'backslash ending comment')
Guido van Rossum3bead091992-01-27 17:00:37 +0000115
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500116 def test_plain_integers(self):
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000117 self.assertEqual(type(000), type(0))
118 self.assertEqual(0xff, 255)
119 self.assertEqual(0o377, 255)
120 self.assertEqual(2147483647, 0o17777777777)
121 self.assertEqual(0b1001, 9)
Georg Brandlfceab5a2008-01-19 20:08:23 +0000122 # "0x" is not a valid literal
123 self.assertRaises(SyntaxError, eval, "0x")
Christian Heimesa37d4c62007-12-04 23:02:19 +0000124 from sys import maxsize
125 if maxsize == 2147483647:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000126 self.assertEqual(-2147483647-1, -0o20000000000)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000127 # XXX -2147483648
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000128 self.assertTrue(0o37777777777 > 0)
129 self.assertTrue(0xffffffff > 0)
130 self.assertTrue(0b1111111111111111111111111111111 > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000131 for s in ('2147483648', '0o40000000000', '0x100000000',
132 '0b10000000000000000000000000000000'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000133 try:
134 x = eval(s)
135 except OverflowError:
136 self.fail("OverflowError on huge integer literal %r" % s)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000137 elif maxsize == 9223372036854775807:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000138 self.assertEqual(-9223372036854775807-1, -0o1000000000000000000000)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000139 self.assertTrue(0o1777777777777777777777 > 0)
140 self.assertTrue(0xffffffffffffffff > 0)
141 self.assertTrue(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000142 for s in '9223372036854775808', '0o2000000000000000000000', \
143 '0x10000000000000000', \
144 '0b100000000000000000000000000000000000000000000000000000000000000':
Thomas Wouters89f507f2006-12-13 04:49:30 +0000145 try:
146 x = eval(s)
147 except OverflowError:
148 self.fail("OverflowError on huge integer literal %r" % s)
149 else:
Christian Heimesa37d4c62007-12-04 23:02:19 +0000150 self.fail('Weird maxsize value %r' % maxsize)
Guido van Rossum3bead091992-01-27 17:00:37 +0000151
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500152 def test_long_integers(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000153 x = 0
Guido van Rossume2a383d2007-01-15 16:59:06 +0000154 x = 0xffffffffffffffff
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000155 x = 0Xffffffffffffffff
156 x = 0o77777777777777777
157 x = 0O77777777777777777
Guido van Rossume2a383d2007-01-15 16:59:06 +0000158 x = 123456789012345678901234567890
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000159 x = 0b100000000000000000000000000000000000000000000000000000000000000000000
160 x = 0B111111111111111111111111111111111111111111111111111111111111111111111
Guido van Rossum3bead091992-01-27 17:00:37 +0000161
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500162 def test_floats(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000163 x = 3.14
164 x = 314.
165 x = 0.314
166 # XXX x = 000.314
167 x = .314
168 x = 3e14
169 x = 3E14
170 x = 3e-14
171 x = 3e+14
172 x = 3.e14
173 x = .3e14
174 x = 3.1e4
Guido van Rossum3bead091992-01-27 17:00:37 +0000175
Benjamin Petersonc4161622014-06-07 12:36:39 -0700176 def test_float_exponent_tokenization(self):
177 # See issue 21642.
178 self.assertEqual(1 if 1else 0, 1)
179 self.assertEqual(1 if 0else 0, 0)
180 self.assertRaises(SyntaxError, eval, "0 if 1Else 0")
181
Brett Cannona721aba2016-09-09 14:57:09 -0700182 def test_underscore_literals(self):
183 for lit in VALID_UNDERSCORE_LITERALS:
184 self.assertEqual(eval(lit), eval(lit.replace('_', '')))
185 for lit in INVALID_UNDERSCORE_LITERALS:
186 self.assertRaises(SyntaxError, eval, lit)
187 # Sanity check: no literal begins with an underscore
188 self.assertRaises(NameError, eval, "_0")
189
Serhiy Storchakacf7303e2018-07-09 15:09:35 +0300190 def test_bad_numerical_literals(self):
191 check = self.check_syntax_error
192 check("0b12", "invalid digit '2' in binary literal")
193 check("0b1_2", "invalid digit '2' in binary literal")
194 check("0b2", "invalid digit '2' in binary literal")
195 check("0b1_", "invalid binary literal")
196 check("0b", "invalid binary literal")
197 check("0o18", "invalid digit '8' in octal literal")
198 check("0o1_8", "invalid digit '8' in octal literal")
199 check("0o8", "invalid digit '8' in octal literal")
200 check("0o1_", "invalid octal literal")
201 check("0o", "invalid octal literal")
202 check("0x1_", "invalid hexadecimal literal")
203 check("0x", "invalid hexadecimal literal")
204 check("1_", "invalid decimal literal")
205 check("012",
206 "leading zeros in decimal integer literals are not permitted; "
207 "use an 0o prefix for octal integers")
208 check("1.2_", "invalid decimal literal")
209 check("1e2_", "invalid decimal literal")
210 check("1e+", "invalid decimal literal")
211
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500212 def test_string_literals(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000213 x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y)
214 x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39)
215 x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000216 x = "doesn't \"shrink\" does it"
217 y = 'doesn\'t "shrink" does it'
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000218 self.assertTrue(len(x) == 24 and x == y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000219 x = "does \"shrink\" doesn't it"
220 y = 'does "shrink" doesn\'t it'
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000221 self.assertTrue(len(x) == 24 and x == y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000222 x = """
Guido van Rossumb6775db1994-08-01 11:34:53 +0000223The "quick"
224brown fox
225jumps over
226the 'lazy' dog.
227"""
Thomas Wouters89f507f2006-12-13 04:49:30 +0000228 y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000229 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000230 y = '''
Guido van Rossumb6775db1994-08-01 11:34:53 +0000231The "quick"
232brown fox
233jumps over
234the 'lazy' dog.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000235'''
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000236 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000237 y = "\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000238The \"quick\"\n\
239brown fox\n\
240jumps over\n\
241the 'lazy' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000242"
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000243 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000244 y = '\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000245The \"quick\"\n\
246brown fox\n\
247jumps over\n\
248the \'lazy\' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000249'
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000250 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000251
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500252 def test_ellipsis(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000253 x = ...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000254 self.assertTrue(x is Ellipsis)
Georg Brandldde00282007-03-18 19:01:53 +0000255 self.assertRaises(SyntaxError, eval, ".. .")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000256
Benjamin Peterson758888d2011-05-30 11:12:38 -0500257 def test_eof_error(self):
258 samples = ("def foo(", "\ndef foo(", "def foo(\n")
259 for s in samples:
260 with self.assertRaises(SyntaxError) as cm:
261 compile(s, "<test>", "exec")
262 self.assertIn("unexpected EOF", str(cm.exception))
263
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700264var_annot_global: int # a global annotated is necessary for test_var_annot
265
266# custom namespace for testing __annotations__
267
268class CNS:
269 def __init__(self):
270 self._dct = {}
271 def __setitem__(self, item, value):
272 self._dct[item.lower()] = value
273 def __getitem__(self, item):
274 return self._dct[item]
275
276
Thomas Wouters89f507f2006-12-13 04:49:30 +0000277class GrammarTests(unittest.TestCase):
278
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +0200279 from test.support import check_syntax_error, check_syntax_warning
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200280
Thomas Wouters89f507f2006-12-13 04:49:30 +0000281 # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
282 # XXX can't test in a script -- this rule is only used when interactive
283
284 # file_input: (NEWLINE | stmt)* ENDMARKER
285 # Being tested as this very moment this very module
286
287 # expr_input: testlist NEWLINE
288 # XXX Hard to test -- used only in calls to input()
289
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500290 def test_eval_input(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000291 # testlist ENDMARKER
292 x = eval('1, 0 or 1')
293
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700294 def test_var_annot_basics(self):
295 # all these should be allowed
296 var1: int = 5
297 var2: [int, str]
298 my_lst = [42]
299 def one():
300 return 1
301 int.new_attr: int
302 [list][0]: type
303 my_lst[one()-1]: int = 5
304 self.assertEqual(my_lst, [5])
305
306 def test_var_annot_syntax_errors(self):
307 # parser pass
308 check_syntax_error(self, "def f: int")
309 check_syntax_error(self, "x: int: str")
310 check_syntax_error(self, "def f():\n"
311 " nonlocal x: int\n")
312 # AST pass
313 check_syntax_error(self, "[x, 0]: int\n")
314 check_syntax_error(self, "f(): int\n")
315 check_syntax_error(self, "(x,): int")
316 check_syntax_error(self, "def f():\n"
317 " (x, y): int = (1, 2)\n")
318 # symtable pass
319 check_syntax_error(self, "def f():\n"
320 " x: int\n"
321 " global x\n")
322 check_syntax_error(self, "def f():\n"
323 " global x\n"
324 " x: int\n")
325
326 def test_var_annot_basic_semantics(self):
327 # execution order
328 with self.assertRaises(ZeroDivisionError):
329 no_name[does_not_exist]: no_name_again = 1/0
330 with self.assertRaises(NameError):
331 no_name[does_not_exist]: 1/0 = 0
332 global var_annot_global
333
334 # function semantics
335 def f():
336 st: str = "Hello"
337 a.b: int = (1, 2)
338 return st
339 self.assertEqual(f.__annotations__, {})
340 def f_OK():
341 x: 1/0
342 f_OK()
343 def fbad():
344 x: int
345 print(x)
346 with self.assertRaises(UnboundLocalError):
347 fbad()
348 def f2bad():
349 (no_such_global): int
350 print(no_such_global)
351 try:
352 f2bad()
353 except Exception as e:
354 self.assertIs(type(e), NameError)
355
356 # class semantics
357 class C:
Guido van Rossum015d8742016-09-11 09:45:24 -0700358 __foo: int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700359 s: str = "attr"
360 z = 2
361 def __init__(self, x):
362 self.x: int = x
Guido van Rossum015d8742016-09-11 09:45:24 -0700363 self.assertEqual(C.__annotations__, {'_C__foo': int, 's': str})
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700364 with self.assertRaises(NameError):
365 class CBad:
366 no_such_name_defined.attr: int = 0
367 with self.assertRaises(NameError):
368 class Cbad2(C):
369 x: int
370 x.y: list = []
371
372 def test_var_annot_metaclass_semantics(self):
373 class CMeta(type):
374 @classmethod
375 def __prepare__(metacls, name, bases, **kwds):
376 return {'__annotations__': CNS()}
377 class CC(metaclass=CMeta):
378 XX: 'ANNOT'
379 self.assertEqual(CC.__annotations__['xx'], 'ANNOT')
380
381 def test_var_annot_module_semantics(self):
382 with self.assertRaises(AttributeError):
383 print(test.__annotations__)
384 self.assertEqual(ann_module.__annotations__,
385 {1: 2, 'x': int, 'y': str, 'f': typing.Tuple[int, int]})
386 self.assertEqual(ann_module.M.__annotations__,
387 {'123': 123, 'o': type})
388 self.assertEqual(ann_module2.__annotations__, {})
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700389
390 def test_var_annot_in_module(self):
391 # check that functions fail the same way when executed
392 # outside of module where they were defined
393 from test.ann_module3 import f_bad_ann, g_bad_ann, D_bad_ann
394 with self.assertRaises(NameError):
395 f_bad_ann()
396 with self.assertRaises(NameError):
397 g_bad_ann()
398 with self.assertRaises(NameError):
399 D_bad_ann(5)
400
401 def test_var_annot_simple_exec(self):
402 gns = {}; lns= {}
403 exec("'docstring'\n"
404 "__annotations__[1] = 2\n"
405 "x: int = 5\n", gns, lns)
406 self.assertEqual(lns["__annotations__"], {1: 2, 'x': int})
407 with self.assertRaises(KeyError):
408 gns['__annotations__']
409
410 def test_var_annot_custom_maps(self):
411 # tests with custom locals() and __annotations__
412 ns = {'__annotations__': CNS()}
413 exec('X: int; Z: str = "Z"; (w): complex = 1j', ns)
414 self.assertEqual(ns['__annotations__']['x'], int)
415 self.assertEqual(ns['__annotations__']['z'], str)
416 with self.assertRaises(KeyError):
417 ns['__annotations__']['w']
418 nonloc_ns = {}
419 class CNS2:
420 def __init__(self):
421 self._dct = {}
422 def __setitem__(self, item, value):
423 nonlocal nonloc_ns
424 self._dct[item] = value
425 nonloc_ns[item] = value
426 def __getitem__(self, item):
427 return self._dct[item]
428 exec('x: int = 1', {}, CNS2())
429 self.assertEqual(nonloc_ns['__annotations__']['x'], int)
430
431 def test_var_annot_refleak(self):
432 # complex case: custom locals plus custom __annotations__
433 # this was causing refleak
434 cns = CNS()
435 nonloc_ns = {'__annotations__': cns}
436 class CNS2:
437 def __init__(self):
438 self._dct = {'__annotations__': cns}
439 def __setitem__(self, item, value):
440 nonlocal nonloc_ns
441 self._dct[item] = value
442 nonloc_ns[item] = value
443 def __getitem__(self, item):
444 return self._dct[item]
445 exec('X: str', {}, CNS2())
446 self.assertEqual(nonloc_ns['__annotations__']['x'], str)
447
Ivan Levkivskyi62c35a82019-01-25 01:39:19 +0000448 def test_var_annot_rhs(self):
449 ns = {}
450 exec('x: tuple = 1, 2', ns)
451 self.assertEqual(ns['x'], (1, 2))
452 stmt = ('def f():\n'
453 ' x: int = yield')
454 exec(stmt, ns)
455 self.assertEqual(list(ns['f']()), [None])
456
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500457 def test_funcdef(self):
Neal Norwitzc1505362006-12-28 06:47:50 +0000458 ### [decorators] 'def' NAME parameters ['->' test] ':' suite
459 ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
460 ### decorators: decorator+
461 ### parameters: '(' [typedargslist] ')'
462 ### typedargslist: ((tfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000463 ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000464 ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000465 ### tfpdef: NAME [':' test]
Neal Norwitzc1505362006-12-28 06:47:50 +0000466 ### varargslist: ((vfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000467 ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000468 ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000469 ### vfpdef: NAME
Thomas Wouters89f507f2006-12-13 04:49:30 +0000470 def f1(): pass
471 f1()
472 f1(*())
473 f1(*(), **{})
474 def f2(one_argument): pass
475 def f3(two, arguments): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000476 self.assertEqual(f2.__code__.co_varnames, ('one_argument',))
477 self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments'))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000478 def a1(one_arg,): pass
479 def a2(two, args,): pass
480 def v0(*rest): pass
481 def v1(a, *rest): pass
482 def v2(a, b, *rest): pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000483
484 f1()
485 f2(1)
486 f2(1,)
487 f3(1, 2)
488 f3(1, 2,)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000489 v0()
490 v0(1)
491 v0(1,)
492 v0(1,2)
493 v0(1,2,3,4,5,6,7,8,9,0)
494 v1(1)
495 v1(1,)
496 v1(1,2)
497 v1(1,2,3)
498 v1(1,2,3,4,5,6,7,8,9,0)
499 v2(1,2)
500 v2(1,2,3)
501 v2(1,2,3,4)
502 v2(1,2,3,4,5,6,7,8,9,0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000503
Thomas Wouters89f507f2006-12-13 04:49:30 +0000504 def d01(a=1): pass
505 d01()
506 d01(1)
507 d01(*(1,))
Yury Selivanov14acf5f2015-08-05 17:54:10 -0400508 d01(*[] or [2])
509 d01(*() or (), *{} and (), **() or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000510 d01(**{'a':2})
Benjamin Petersonde12b792015-05-16 09:44:45 -0400511 d01(**{'a':2} or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000512 def d11(a, b=1): pass
513 d11(1)
514 d11(1, 2)
515 d11(1, **{'b':2})
516 def d21(a, b, c=1): pass
517 d21(1, 2)
518 d21(1, 2, 3)
519 d21(*(1, 2, 3))
520 d21(1, *(2, 3))
521 d21(1, 2, *(3,))
522 d21(1, 2, **{'c':3})
523 def d02(a=1, b=2): pass
524 d02()
525 d02(1)
526 d02(1, 2)
527 d02(*(1, 2))
528 d02(1, *(2,))
529 d02(1, **{'b':2})
530 d02(**{'a': 1, 'b': 2})
531 def d12(a, b=1, c=2): pass
532 d12(1)
533 d12(1, 2)
534 d12(1, 2, 3)
535 def d22(a, b, c=1, d=2): pass
536 d22(1, 2)
537 d22(1, 2, 3)
538 d22(1, 2, 3, 4)
539 def d01v(a=1, *rest): pass
540 d01v()
541 d01v(1)
542 d01v(1, 2)
543 d01v(*(1, 2, 3, 4))
544 d01v(*(1,))
545 d01v(**{'a':2})
546 def d11v(a, b=1, *rest): pass
547 d11v(1)
548 d11v(1, 2)
549 d11v(1, 2, 3)
550 def d21v(a, b, c=1, *rest): pass
551 d21v(1, 2)
552 d21v(1, 2, 3)
553 d21v(1, 2, 3, 4)
554 d21v(*(1, 2, 3, 4))
555 d21v(1, 2, **{'c': 3})
556 def d02v(a=1, b=2, *rest): pass
557 d02v()
558 d02v(1)
559 d02v(1, 2)
560 d02v(1, 2, 3)
561 d02v(1, *(2, 3, 4))
562 d02v(**{'a': 1, 'b': 2})
563 def d12v(a, b=1, c=2, *rest): pass
564 d12v(1)
565 d12v(1, 2)
566 d12v(1, 2, 3)
567 d12v(1, 2, 3, 4)
568 d12v(*(1, 2, 3, 4))
569 d12v(1, 2, *(3, 4, 5))
570 d12v(1, *(2,), **{'c': 3})
571 def d22v(a, b, c=1, d=2, *rest): pass
572 d22v(1, 2)
573 d22v(1, 2, 3)
574 d22v(1, 2, 3, 4)
575 d22v(1, 2, 3, 4, 5)
576 d22v(*(1, 2, 3, 4))
577 d22v(1, 2, *(3, 4, 5))
578 d22v(1, *(2, 3), **{'d': 4})
Georg Brandld8b690f2008-05-16 17:28:50 +0000579
580 # keyword argument type tests
581 try:
582 str('x', **{b'foo':1 })
583 except TypeError:
584 pass
585 else:
586 self.fail('Bytes should not work as keyword argument names')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000587 # keyword only argument tests
588 def pos0key1(*, key): return key
589 pos0key1(key=100)
590 def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
591 pos2key2(1, 2, k1=100)
592 pos2key2(1, 2, k1=100, k2=200)
593 pos2key2(1, 2, k2=100, k1=200)
594 def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
595 pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
596 pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
597
Robert Collinsdf395992015-08-12 08:00:06 +1200598 self.assertRaises(SyntaxError, eval, "def f(*): pass")
599 self.assertRaises(SyntaxError, eval, "def f(*,): pass")
600 self.assertRaises(SyntaxError, eval, "def f(*, **kwds): pass")
601
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000602 # keyword arguments after *arglist
603 def f(*args, **kwargs):
604 return args, kwargs
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000605 self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000606 {'x':2, 'y':5}))
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400607 self.assertEqual(f(1, *(2,3), 4), ((1, 2, 3, 4), {}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000608 self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400609 self.assertEqual(f(**{'eggs':'scrambled', 'spam':'fried'}),
610 ((), {'eggs':'scrambled', 'spam':'fried'}))
611 self.assertEqual(f(spam='fried', **{'eggs':'scrambled'}),
612 ((), {'eggs':'scrambled', 'spam':'fried'}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000613
Serhiy Storchaka0cc99c82018-01-04 10:36:35 +0200614 # Check ast errors in *args and *kwargs
615 check_syntax_error(self, "f(*g(1=2))")
616 check_syntax_error(self, "f(**g(1=2))")
617
Neal Norwitzc1505362006-12-28 06:47:50 +0000618 # argument annotation tests
619 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000620 self.assertEqual(f.__annotations__, {'return': list})
Zachary Warece17f762015-08-01 21:55:36 -0500621 def f(x: int): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000622 self.assertEqual(f.__annotations__, {'x': int})
Zachary Warece17f762015-08-01 21:55:36 -0500623 def f(*x: str): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000624 self.assertEqual(f.__annotations__, {'x': str})
Zachary Warece17f762015-08-01 21:55:36 -0500625 def f(**x: float): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000626 self.assertEqual(f.__annotations__, {'x': float})
Zachary Warece17f762015-08-01 21:55:36 -0500627 def f(x, y: 1+2): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000628 self.assertEqual(f.__annotations__, {'y': 3})
Zachary Warece17f762015-08-01 21:55:36 -0500629 def f(a, b: 1, c: 2, d): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000630 self.assertEqual(f.__annotations__, {'b': 1, 'c': 2})
Zachary Warece17f762015-08-01 21:55:36 -0500631 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000632 self.assertEqual(f.__annotations__,
Zachary Warece17f762015-08-01 21:55:36 -0500633 {'b': 1, 'c': 2, 'e': 3, 'g': 6})
634 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6, h: 7, i=8, j: 9 = 10,
635 **k: 11) -> 12: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000636 self.assertEqual(f.__annotations__,
Zachary Warece17f762015-08-01 21:55:36 -0500637 {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
638 'k': 11, 'return': 12})
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500639 # Check for issue #20625 -- annotations mangling
640 class Spam:
Zachary Warece17f762015-08-01 21:55:36 -0500641 def f(self, *, __kw: 1):
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500642 pass
643 class Ham(Spam): pass
Benjamin Petersonbcfcfc52014-03-09 20:59:24 -0500644 self.assertEqual(Spam.f.__annotations__, {'_Spam__kw': 1})
645 self.assertEqual(Ham.f.__annotations__, {'_Spam__kw': 1})
Nick Coghlan71011e22007-04-23 11:05:01 +0000646 # Check for SF Bug #1697248 - mixing decorators and a return annotation
647 def null(x): return x
648 @null
649 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000650 self.assertEqual(f.__annotations__, {'return': list})
Nick Coghlan71011e22007-04-23 11:05:01 +0000651
Serhiy Storchaka64204de2016-06-12 17:36:24 +0300652 # test closures with a variety of opargs
Guido van Rossum0240b922007-02-26 21:23:50 +0000653 closure = 1
654 def f(): return closure
655 def f(x=1): return closure
656 def f(*, k=1): return closure
657 def f() -> int: return closure
Neal Norwitzc1505362006-12-28 06:47:50 +0000658
Robert Collinsdf395992015-08-12 08:00:06 +1200659 # Check trailing commas are permitted in funcdef argument list
660 def f(a,): pass
661 def f(*args,): pass
662 def f(**kwds,): pass
663 def f(a, *args,): pass
664 def f(a, **kwds,): pass
665 def f(*args, b,): pass
666 def f(*, b,): pass
667 def f(*args, **kwds,): pass
668 def f(a, *args, b,): pass
669 def f(a, *, b,): pass
670 def f(a, *args, **kwds,): pass
671 def f(*args, b, **kwds,): pass
672 def f(*, b, **kwds,): pass
673 def f(a, *args, b, **kwds,): pass
674 def f(a, *, b, **kwds,): pass
675
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500676 def test_lambdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000677 ### lambdef: 'lambda' [varargslist] ':' test
678 l1 = lambda : 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000679 self.assertEqual(l1(), 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000680 l2 = lambda : a[d] # XXX just testing the expression
Guido van Rossume2a383d2007-01-15 16:59:06 +0000681 l3 = lambda : [2 < x for x in [-1, 3, 0]]
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000682 self.assertEqual(l3(), [0, 1, 0])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000683 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000684 self.assertEqual(l4(), 1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000685 l5 = lambda x, y, z=2: x + y + z
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000686 self.assertEqual(l5(1, 2), 5)
687 self.assertEqual(l5(1, 2, 3), 6)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000688 check_syntax_error(self, "lambda x: x = 2")
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000689 check_syntax_error(self, "lambda (None,): None")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000690 l6 = lambda x, y, *, k=20: x+y+k
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000691 self.assertEqual(l6(1,2), 1+2+20)
692 self.assertEqual(l6(1,2,k=10), 1+2+10)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000693
Robert Collinsdf395992015-08-12 08:00:06 +1200694 # check that trailing commas are permitted
695 l10 = lambda a,: 0
696 l11 = lambda *args,: 0
697 l12 = lambda **kwds,: 0
698 l13 = lambda a, *args,: 0
699 l14 = lambda a, **kwds,: 0
700 l15 = lambda *args, b,: 0
701 l16 = lambda *, b,: 0
702 l17 = lambda *args, **kwds,: 0
703 l18 = lambda a, *args, b,: 0
704 l19 = lambda a, *, b,: 0
705 l20 = lambda a, *args, **kwds,: 0
706 l21 = lambda *args, b, **kwds,: 0
707 l22 = lambda *, b, **kwds,: 0
708 l23 = lambda a, *args, b, **kwds,: 0
709 l24 = lambda a, *, b, **kwds,: 0
710
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000711
Thomas Wouters89f507f2006-12-13 04:49:30 +0000712 ### stmt: simple_stmt | compound_stmt
713 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000714
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500715 def test_simple_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000716 ### simple_stmt: small_stmt (';' small_stmt)* [';']
717 x = 1; pass; del x
718 def foo():
Ezio Melotti13925002011-03-16 11:05:33 +0200719 # verify statements that end with semi-colons
Thomas Wouters89f507f2006-12-13 04:49:30 +0000720 x = 1; pass; del x;
721 foo()
Georg Brandl52318d62006-09-06 07:06:08 +0000722
Guido van Rossumd8faa362007-04-27 19:54:29 +0000723 ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
Thomas Wouters89f507f2006-12-13 04:49:30 +0000724 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000725
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500726 def test_expr_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000727 # (exprlist '=')* exprlist
Victor Stinner15a30952016-02-08 22:45:06 +0100728 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000729 1, 2, 3
730 x = 1
731 x = 1, 2, 3
732 x = y = z = 1, 2, 3
733 x, y, z = 1, 2, 3
734 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000735
Thomas Wouters89f507f2006-12-13 04:49:30 +0000736 check_syntax_error(self, "x + 1 = 1")
737 check_syntax_error(self, "a + 1 = b + 2")
Guido van Rossum3bead091992-01-27 17:00:37 +0000738
Nick Coghlan5b1fdc12014-06-16 19:48:02 +1000739 # Check the heuristic for print & exec covers significant cases
740 # As well as placing some limits on false positives
741 def test_former_statements_refer_to_builtins(self):
742 keywords = "print", "exec"
743 # Cases where we want the custom error
744 cases = [
745 "{} foo",
746 "{} {{1:foo}}",
747 "if 1: {} foo",
748 "if 1: {} {{1:foo}}",
749 "if 1:\n {} foo",
750 "if 1:\n {} {{1:foo}}",
751 ]
752 for keyword in keywords:
753 custom_msg = "call to '{}'".format(keyword)
754 for case in cases:
755 source = case.format(keyword)
756 with self.subTest(source=source):
757 with self.assertRaisesRegex(SyntaxError, custom_msg):
758 exec(source)
759 source = source.replace("foo", "(foo.)")
760 with self.subTest(source=source):
761 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
762 exec(source)
763
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500764 def test_del_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000765 # 'del' exprlist
766 abc = [1,2,3]
767 x, y, z = abc
768 xyz = x, y, z
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000769
Thomas Wouters89f507f2006-12-13 04:49:30 +0000770 del abc
771 del x, y, (z, xyz)
Barry Warsaw9182b452000-08-29 04:57:10 +0000772
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500773 def test_pass_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000774 # 'pass'
775 pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000776
Thomas Wouters89f507f2006-12-13 04:49:30 +0000777 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
778 # Tested below
Barry Warsaw9182b452000-08-29 04:57:10 +0000779
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500780 def test_break_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000781 # 'break'
782 while 1: break
Barry Warsaw9182b452000-08-29 04:57:10 +0000783
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500784 def test_continue_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000785 # 'continue'
786 i = 1
787 while i: i = 0; continue
Barry Warsaw9182b452000-08-29 04:57:10 +0000788
Thomas Wouters89f507f2006-12-13 04:49:30 +0000789 msg = ""
790 while not msg:
791 msg = "ok"
792 try:
793 continue
794 msg = "continue failed to continue inside try"
795 except:
796 msg = "continue inside try called except block"
797 if msg != "ok":
798 self.fail(msg)
Barry Warsawefc92ee2000-08-21 15:46:50 +0000799
Thomas Wouters89f507f2006-12-13 04:49:30 +0000800 msg = ""
801 while not msg:
802 msg = "finally block not called"
803 try:
804 continue
805 finally:
806 msg = "ok"
807 if msg != "ok":
808 self.fail(msg)
Guido van Rossum3bead091992-01-27 17:00:37 +0000809
Thomas Wouters89f507f2006-12-13 04:49:30 +0000810 def test_break_continue_loop(self):
811 # This test warrants an explanation. It is a test specifically for SF bugs
812 # #463359 and #462937. The bug is that a 'break' statement executed or
813 # exception raised inside a try/except inside a loop, *after* a continue
814 # statement has been executed in that loop, will cause the wrong number of
815 # arguments to be popped off the stack and the instruction pointer reset to
816 # a very small number (usually 0.) Because of this, the following test
817 # *must* written as a function, and the tracking vars *must* be function
818 # arguments with default values. Otherwise, the test will loop and loop.
Guido van Rossum3bead091992-01-27 17:00:37 +0000819
Thomas Wouters89f507f2006-12-13 04:49:30 +0000820 def test_inner(extra_burning_oil = 1, count=0):
821 big_hippo = 2
822 while big_hippo:
823 count += 1
824 try:
825 if extra_burning_oil and big_hippo == 1:
826 extra_burning_oil -= 1
827 break
828 big_hippo -= 1
829 continue
830 except:
831 raise
832 if count > 2 or big_hippo != 1:
833 self.fail("continue then break in try/except in loop broken!")
834 test_inner()
Guido van Rossum3bead091992-01-27 17:00:37 +0000835
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500836 def test_return(self):
David Cuthbertfd97d1f2018-09-21 18:31:15 -0700837 # 'return' [testlist_star_expr]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000838 def g1(): return
839 def g2(): return 1
David Cuthbertfd97d1f2018-09-21 18:31:15 -0700840 def g3():
841 z = [2, 3]
842 return 1, *z
843
Thomas Wouters89f507f2006-12-13 04:49:30 +0000844 g1()
845 x = g2()
David Cuthbertfd97d1f2018-09-21 18:31:15 -0700846 y = g3()
847 self.assertEqual(y, (1, 2, 3), "unparenthesized star expr return")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000848 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000849
Serhiy Storchaka7cc42c32018-01-02 02:38:35 +0200850 def test_break_in_finally(self):
851 count = 0
852 while count < 2:
853 count += 1
854 try:
855 pass
856 finally:
857 break
858 self.assertEqual(count, 1)
859
860 count = 0
861 while count < 2:
862 count += 1
863 try:
864 continue
865 finally:
866 break
867 self.assertEqual(count, 1)
868
869 count = 0
870 while count < 2:
871 count += 1
872 try:
873 1/0
874 finally:
875 break
876 self.assertEqual(count, 1)
877
878 for count in [0, 1]:
879 self.assertEqual(count, 0)
880 try:
881 pass
882 finally:
883 break
884 self.assertEqual(count, 0)
885
886 for count in [0, 1]:
887 self.assertEqual(count, 0)
888 try:
889 continue
890 finally:
891 break
892 self.assertEqual(count, 0)
893
894 for count in [0, 1]:
895 self.assertEqual(count, 0)
896 try:
897 1/0
898 finally:
899 break
900 self.assertEqual(count, 0)
901
Serhiy Storchakafe2bbb12018-03-18 09:56:52 +0200902 def test_continue_in_finally(self):
903 count = 0
904 while count < 2:
905 count += 1
906 try:
907 pass
908 finally:
909 continue
910 break
911 self.assertEqual(count, 2)
912
913 count = 0
914 while count < 2:
915 count += 1
916 try:
917 break
918 finally:
919 continue
920 self.assertEqual(count, 2)
921
922 count = 0
923 while count < 2:
924 count += 1
925 try:
926 1/0
927 finally:
928 continue
929 break
930 self.assertEqual(count, 2)
931
932 for count in [0, 1]:
933 try:
934 pass
935 finally:
936 continue
937 break
938 self.assertEqual(count, 1)
939
940 for count in [0, 1]:
941 try:
942 break
943 finally:
944 continue
945 self.assertEqual(count, 1)
946
947 for count in [0, 1]:
948 try:
949 1/0
950 finally:
951 continue
952 break
953 self.assertEqual(count, 1)
954
Serhiy Storchaka7cc42c32018-01-02 02:38:35 +0200955 def test_return_in_finally(self):
956 def g1():
957 try:
958 pass
959 finally:
960 return 1
961 self.assertEqual(g1(), 1)
962
963 def g2():
964 try:
965 return 2
966 finally:
967 return 3
968 self.assertEqual(g2(), 3)
969
970 def g3():
971 try:
972 1/0
973 finally:
974 return 4
975 self.assertEqual(g3(), 4)
976
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500977 def test_yield(self):
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000978 # Allowed as standalone statement
979 def g(): yield 1
980 def g(): yield from ()
981 # Allowed as RHS of assignment
982 def g(): x = yield 1
983 def g(): x = yield from ()
984 # Ordinary yield accepts implicit tuples
985 def g(): yield 1, 1
986 def g(): x = yield 1, 1
987 # 'yield from' does not
988 check_syntax_error(self, "def g(): yield from (), 1")
989 check_syntax_error(self, "def g(): x = yield from (), 1")
990 # Requires parentheses as subexpression
991 def g(): 1, (yield 1)
992 def g(): 1, (yield from ())
993 check_syntax_error(self, "def g(): 1, yield 1")
994 check_syntax_error(self, "def g(): 1, yield from ()")
995 # Requires parentheses as call argument
996 def g(): f((yield 1))
997 def g(): f((yield 1), 1)
998 def g(): f((yield from ()))
999 def g(): f((yield from ()), 1)
David Cuthbertfd97d1f2018-09-21 18:31:15 -07001000 # Do not require parenthesis for tuple unpacking
1001 def g(): rest = 4, 5, 6; yield 1, 2, 3, *rest
Serhiy Storchaka4642d5f2018-10-05 21:09:56 +03001002 self.assertEqual(list(g()), [(1, 2, 3, 4, 5, 6)])
Nick Coghlan1f7ce622012-01-13 21:43:40 +10001003 check_syntax_error(self, "def g(): f(yield 1)")
1004 check_syntax_error(self, "def g(): f(yield 1, 1)")
1005 check_syntax_error(self, "def g(): f(yield from ())")
1006 check_syntax_error(self, "def g(): f(yield from (), 1)")
1007 # Not allowed at top level
1008 check_syntax_error(self, "yield")
1009 check_syntax_error(self, "yield from")
1010 # Not allowed at class scope
Thomas Wouters89f507f2006-12-13 04:49:30 +00001011 check_syntax_error(self, "class foo:yield 1")
Nick Coghlan1f7ce622012-01-13 21:43:40 +10001012 check_syntax_error(self, "class foo:yield from ()")
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001013 # Check annotation refleak on SyntaxError
1014 check_syntax_error(self, "def g(a:(yield)): pass")
Guido van Rossum3bead091992-01-27 17:00:37 +00001015
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +02001016 def test_yield_in_comprehensions(self):
1017 # Check yield in comprehensions
1018 def g(): [x for x in [(yield 1)]]
1019 def g(): [x for x in [(yield from ())]]
1020
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +02001021 check = self.check_syntax_error
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +02001022 check("def g(): [(yield x) for x in ()]",
1023 "'yield' inside list comprehension")
1024 check("def g(): [x for x in () if not (yield x)]",
1025 "'yield' inside list comprehension")
1026 check("def g(): [y for x in () for y in [(yield x)]]",
1027 "'yield' inside list comprehension")
1028 check("def g(): {(yield x) for x in ()}",
1029 "'yield' inside set comprehension")
1030 check("def g(): {(yield x): x for x in ()}",
1031 "'yield' inside dict comprehension")
1032 check("def g(): {x: (yield x) for x in ()}",
1033 "'yield' inside dict comprehension")
1034 check("def g(): ((yield x) for x in ())",
1035 "'yield' inside generator expression")
1036 check("def g(): [(yield from x) for x in ()]",
1037 "'yield' inside list comprehension")
1038 check("class C: [(yield x) for x in ()]",
1039 "'yield' inside list comprehension")
1040 check("[(yield x) for x in ()]",
1041 "'yield' inside list comprehension")
1042
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001043 def test_raise(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001044 # 'raise' test [',' test]
Collin Winter828f04a2007-08-31 00:04:24 +00001045 try: raise RuntimeError('just testing')
Thomas Wouters89f507f2006-12-13 04:49:30 +00001046 except RuntimeError: pass
1047 try: raise KeyboardInterrupt
1048 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +00001049
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001050 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001051 # 'import' dotted_as_names
1052 import sys
1053 import time, sys
1054 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
1055 from time import time
1056 from time import (time)
1057 # not testable inside a function, but already done at top of the module
1058 # from sys import *
1059 from sys import path, argv
1060 from sys import (path, argv)
1061 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +00001062
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001063 def test_global(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001064 # 'global' NAME (',' NAME)*
1065 global a
1066 global a, b
1067 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +00001068
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001069 def test_nonlocal(self):
Benjamin Petersona933e522008-10-24 22:16:39 +00001070 # 'nonlocal' NAME (',' NAME)*
1071 x = 0
1072 y = 0
1073 def f():
1074 nonlocal x
1075 nonlocal x, y
1076
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001077 def test_assert(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001078 # assertTruestmt: 'assert' test [',' test]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001079 assert 1
1080 assert 1, 1
1081 assert lambda x:x
1082 assert 1, lambda x:x+1
Ezio Melotti6cc5bf72011-12-02 18:22:52 +02001083
1084 try:
1085 assert True
1086 except AssertionError as e:
1087 self.fail("'assert True' should not have raised an AssertionError")
1088
1089 try:
1090 assert True, 'this should always pass'
1091 except AssertionError as e:
1092 self.fail("'assert True, msg' should not have "
1093 "raised an AssertionError")
1094
1095 # these tests fail if python is run with -O, so check __debug__
1096 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
1097 def testAssert2(self):
Thomas Wouters80d373c2001-09-26 12:43:39 +00001098 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001099 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +00001100 except AssertionError as e:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001101 self.assertEqual(e.args[0], "msg")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001102 else:
Ezio Melotti6cc5bf72011-12-02 18:22:52 +02001103 self.fail("AssertionError not raised by assert 0")
1104
1105 try:
1106 assert False
1107 except AssertionError as e:
1108 self.assertEqual(len(e.args), 0)
1109 else:
1110 self.fail("AssertionError not raised by 'assert False'")
1111
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001112 self.check_syntax_warning('assert(x, "msg")',
1113 'assertion is always true')
Serhiy Storchakad31e7732018-10-21 10:09:39 +03001114 with warnings.catch_warnings():
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001115 warnings.simplefilter('error', SyntaxWarning)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03001116 compile('assert x, "msg"', '<testcase>', 'exec')
1117
Thomas Wouters80d373c2001-09-26 12:43:39 +00001118
Thomas Wouters89f507f2006-12-13 04:49:30 +00001119 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
1120 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001121
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001122 def test_if(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001123 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
1124 if 1: pass
1125 if 1: pass
1126 else: pass
1127 if 0: pass
1128 elif 0: pass
1129 if 0: pass
1130 elif 0: pass
1131 elif 0: pass
1132 elif 0: pass
1133 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001134
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001135 def test_while(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001136 # 'while' test ':' suite ['else' ':' suite]
1137 while 0: pass
1138 while 0: pass
1139 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001140
Christian Heimes969fe572008-01-25 11:23:10 +00001141 # Issue1920: "while 0" is optimized away,
1142 # ensure that the "else" clause is still present.
1143 x = 0
1144 while 0:
1145 x = 1
1146 else:
1147 x = 2
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001148 self.assertEqual(x, 2)
Christian Heimes969fe572008-01-25 11:23:10 +00001149
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001150 def test_for(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001151 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
1152 for i in 1, 2, 3: pass
1153 for i, j, k in (): pass
1154 else: pass
1155 class Squares:
1156 def __init__(self, max):
1157 self.max = max
1158 self.sofar = []
1159 def __len__(self): return len(self.sofar)
1160 def __getitem__(self, i):
1161 if not 0 <= i < self.max: raise IndexError
1162 n = len(self.sofar)
1163 while n <= i:
1164 self.sofar.append(n*n)
1165 n = n+1
1166 return self.sofar[i]
1167 n = 0
1168 for x in Squares(10): n = n+x
1169 if n != 285:
1170 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +00001171
Thomas Wouters89f507f2006-12-13 04:49:30 +00001172 result = []
1173 for x, in [(1,), (2,), (3,)]:
1174 result.append(x)
1175 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +00001176
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001177 def test_try(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001178 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
1179 ### | 'try' ':' suite 'finally' ':' suite
Guido van Rossumb940e112007-01-10 16:19:56 +00001180 ### except_clause: 'except' [expr ['as' expr]]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001181 try:
1182 1/0
1183 except ZeroDivisionError:
1184 pass
1185 else:
1186 pass
1187 try: 1/0
1188 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +00001189 except TypeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +00001190 except: pass
1191 else: pass
1192 try: 1/0
1193 except (EOFError, TypeError, ZeroDivisionError): pass
1194 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +00001195 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +00001196 try: pass
1197 finally: pass
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +00001198
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001199 def test_suite(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001200 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
1201 if 1: pass
1202 if 1:
1203 pass
1204 if 1:
1205 #
1206 #
1207 #
1208 pass
1209 pass
1210 #
1211 pass
1212 #
Guido van Rossum3bead091992-01-27 17:00:37 +00001213
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001214 def test_test(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001215 ### and_test ('or' and_test)*
1216 ### and_test: not_test ('and' not_test)*
1217 ### not_test: 'not' not_test | comparison
1218 if not 1: pass
1219 if 1 and 1: pass
1220 if 1 or 1: pass
1221 if not not not 1: pass
1222 if not 1 and 1 and 1: pass
1223 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001224
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001225 def test_comparison(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001226 ### comparison: expr (comp_op expr)*
1227 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
1228 if 1: pass
1229 x = (1 == 1)
1230 if 1 == 1: pass
1231 if 1 != 1: pass
1232 if 1 < 1: pass
1233 if 1 > 1: pass
1234 if 1 <= 1: pass
1235 if 1 >= 1: pass
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001236 if x is x: pass
1237 if x is not x: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +00001238 if 1 in (): pass
1239 if 1 not in (): pass
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001240 if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in x is x is not x: pass
1241
1242 def test_comparison_is_literal(self):
1243 def check(test, msg='"is" with a literal'):
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001244 self.check_syntax_warning(test, msg)
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001245
1246 check('x is 1')
1247 check('x is "thing"')
1248 check('1 is x')
1249 check('x is y is 1')
1250 check('x is not 1', '"is not" with a literal')
1251
1252 with warnings.catch_warnings():
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001253 warnings.simplefilter('error', SyntaxWarning)
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001254 compile('x is None', '<testcase>', 'exec')
1255 compile('x is False', '<testcase>', 'exec')
1256 compile('x is True', '<testcase>', 'exec')
1257 compile('x is ...', '<testcase>', 'exec')
Guido van Rossum3bead091992-01-27 17:00:37 +00001258
Serhiy Storchaka62e44812019-02-16 08:12:19 +02001259 def test_warn_missed_comma(self):
1260 def check(test):
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001261 self.check_syntax_warning(test, msg)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02001262
1263 msg=r'is not callable; perhaps you missed a comma\?'
1264 check('[(1, 2) (3, 4)]')
1265 check('[(x, y) (3, 4)]')
1266 check('[[1, 2] (3, 4)]')
1267 check('[{1, 2} (3, 4)]')
1268 check('[{1: 2} (3, 4)]')
1269 check('[[i for i in range(5)] (3, 4)]')
1270 check('[{i for i in range(5)} (3, 4)]')
1271 check('[(i for i in range(5)) (3, 4)]')
1272 check('[{i: i for i in range(5)} (3, 4)]')
1273 check('[f"{x}" (3, 4)]')
1274 check('[f"x={x}" (3, 4)]')
1275 check('["abc" (3, 4)]')
1276 check('[b"abc" (3, 4)]')
1277 check('[123 (3, 4)]')
1278 check('[12.3 (3, 4)]')
1279 check('[12.3j (3, 4)]')
1280 check('[None (3, 4)]')
1281 check('[True (3, 4)]')
1282 check('[... (3, 4)]')
1283
1284 msg=r'is not subscriptable; perhaps you missed a comma\?'
1285 check('[{1, 2} [i, j]]')
1286 check('[{i for i in range(5)} [i, j]]')
1287 check('[(i for i in range(5)) [i, j]]')
1288 check('[(lambda x, y: x) [i, j]]')
1289 check('[123 [i, j]]')
1290 check('[12.3 [i, j]]')
1291 check('[12.3j [i, j]]')
1292 check('[None [i, j]]')
1293 check('[True [i, j]]')
1294 check('[... [i, j]]')
1295
1296 msg=r'indices must be integers or slices, not tuple; perhaps you missed a comma\?'
1297 check('[(1, 2) [i, j]]')
1298 check('[(x, y) [i, j]]')
1299 check('[[1, 2] [i, j]]')
1300 check('[[i for i in range(5)] [i, j]]')
1301 check('[f"{x}" [i, j]]')
1302 check('[f"x={x}" [i, j]]')
1303 check('["abc" [i, j]]')
1304 check('[b"abc" [i, j]]')
1305
1306 msg=r'indices must be integers or slices, not tuple;'
1307 check('[[1, 2] [3, 4]]')
1308 msg=r'indices must be integers or slices, not list;'
1309 check('[[1, 2] [[3, 4]]]')
1310 check('[[1, 2] [[i for i in range(5)]]]')
1311 msg=r'indices must be integers or slices, not set;'
1312 check('[[1, 2] [{3, 4}]]')
1313 check('[[1, 2] [{i for i in range(5)}]]')
1314 msg=r'indices must be integers or slices, not dict;'
1315 check('[[1, 2] [{3: 4}]]')
1316 check('[[1, 2] [{i: i for i in range(5)}]]')
1317 msg=r'indices must be integers or slices, not generator;'
1318 check('[[1, 2] [(i for i in range(5))]]')
1319 msg=r'indices must be integers or slices, not function;'
1320 check('[[1, 2] [(lambda x, y: x)]]')
1321 msg=r'indices must be integers or slices, not str;'
1322 check('[[1, 2] [f"{x}"]]')
1323 check('[[1, 2] [f"x={x}"]]')
1324 check('[[1, 2] ["abc"]]')
1325 msg=r'indices must be integers or slices, not'
1326 check('[[1, 2] [b"abc"]]')
1327 check('[[1, 2] [12.3]]')
1328 check('[[1, 2] [12.3j]]')
1329 check('[[1, 2] [None]]')
1330 check('[[1, 2] [...]]')
1331
1332 with warnings.catch_warnings():
Serhiy Storchakae7a4bb52019-02-19 08:30:15 +02001333 warnings.simplefilter('error', SyntaxWarning)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02001334 compile('[(lambda x, y: x) (3, 4)]', '<testcase>', 'exec')
1335 compile('[[1, 2] [i]]', '<testcase>', 'exec')
1336 compile('[[1, 2] [0]]', '<testcase>', 'exec')
1337 compile('[[1, 2] [True]]', '<testcase>', 'exec')
1338 compile('[[1, 2] [1:2]]', '<testcase>', 'exec')
1339 compile('[{(1, 2): 3} [i, j]]', '<testcase>', 'exec')
1340
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001341 def test_binary_mask_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001342 x = 1 & 1
1343 x = 1 ^ 1
1344 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001345
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001346 def test_shift_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001347 x = 1 << 1
1348 x = 1 >> 1
1349 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001350
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001351 def test_additive_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001352 x = 1
1353 x = 1 + 1
1354 x = 1 - 1 - 1
1355 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001356
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001357 def test_multiplicative_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001358 x = 1 * 1
1359 x = 1 / 1
1360 x = 1 % 1
1361 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001362
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001363 def test_unary_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001364 x = +1
1365 x = -1
1366 x = ~1
1367 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
1368 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +00001369
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001370 def test_selectors(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001371 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
1372 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +00001373
Thomas Wouters89f507f2006-12-13 04:49:30 +00001374 import sys, time
1375 c = sys.path[0]
1376 x = time.time()
1377 x = sys.modules['time'].time()
1378 a = '01234'
1379 c = a[0]
1380 c = a[-1]
1381 s = a[0:5]
1382 s = a[:5]
1383 s = a[0:]
1384 s = a[:]
1385 s = a[-5:]
1386 s = a[:-1]
1387 s = a[-4:-3]
1388 # A rough test of SF bug 1333982. http://python.org/sf/1333982
1389 # The testing here is fairly incomplete.
1390 # Test cases should include: commas with 1 and 2 colons
1391 d = {}
1392 d[1] = 1
1393 d[1,] = 2
1394 d[1,2] = 3
1395 d[1,2,3] = 4
1396 L = list(d)
Serhiy Storchaka0cc99c82018-01-04 10:36:35 +02001397 L.sort(key=lambda x: (type(x).__name__, x))
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001398 self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +00001399
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001400 def test_atoms(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001401 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
1402 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +00001403
Thomas Wouters89f507f2006-12-13 04:49:30 +00001404 x = (1)
1405 x = (1 or 2 or 3)
1406 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +00001407
Thomas Wouters89f507f2006-12-13 04:49:30 +00001408 x = []
1409 x = [1]
1410 x = [1 or 2 or 3]
1411 x = [1 or 2 or 3, 2, 3]
1412 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +00001413
Thomas Wouters89f507f2006-12-13 04:49:30 +00001414 x = {}
1415 x = {'one': 1}
1416 x = {'one': 1,}
1417 x = {'one' or 'two': 1 or 2}
1418 x = {'one': 1, 'two': 2}
1419 x = {'one': 1, 'two': 2,}
1420 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +00001421
Thomas Wouters89f507f2006-12-13 04:49:30 +00001422 x = {'one'}
1423 x = {'one', 1,}
1424 x = {'one', 'two', 'three'}
1425 x = {2, 3, 4,}
1426
1427 x = x
1428 x = 'x'
1429 x = 123
1430
1431 ### exprlist: expr (',' expr)* [',']
1432 ### testlist: test (',' test)* [',']
1433 # These have been exercised enough above
1434
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001435 def test_classdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001436 # 'class' NAME ['(' [testlist] ')'] ':' suite
1437 class B: pass
1438 class B2(): pass
1439 class C1(B): pass
1440 class C2(B): pass
1441 class D(C1, C2, B): pass
1442 class C:
1443 def meth1(self): pass
1444 def meth2(self, arg): pass
1445 def meth3(self, a1, a2): pass
1446
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001447 # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
1448 # decorators: decorator+
1449 # decorated: decorators (classdef | funcdef)
1450 def class_decorator(x): return x
1451 @class_decorator
1452 class G: pass
1453
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001454 def test_dictcomps(self):
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001455 # dictorsetmaker: ( (test ':' test (comp_for |
1456 # (',' test ':' test)* [','])) |
1457 # (test (comp_for | (',' test)* [','])) )
1458 nums = [1, 2, 3]
1459 self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
1460
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001461 def test_listcomps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001462 # list comprehension tests
1463 nums = [1, 2, 3, 4, 5]
1464 strs = ["Apple", "Banana", "Coconut"]
1465 spcs = [" Apple", " Banana ", "Coco nut "]
1466
1467 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
1468 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
1469 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
1470 self.assertEqual([(i, s) for i in nums for s in strs],
1471 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
1472 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
1473 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
1474 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
1475 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
1476 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
1477 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
1478 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
1479 (5, 'Banana'), (5, 'Coconut')])
1480 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
1481 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
1482
1483 def test_in_func(l):
1484 return [0 < x < 3 for x in l if x > 2]
1485
1486 self.assertEqual(test_in_func(nums), [False, False, False])
1487
1488 def test_nested_front():
1489 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
1490 [[1, 2], [3, 4], [5, 6]])
1491
1492 test_nested_front()
1493
1494 check_syntax_error(self, "[i, s for i in nums for s in strs]")
1495 check_syntax_error(self, "[x if y]")
1496
1497 suppliers = [
1498 (1, "Boeing"),
1499 (2, "Ford"),
1500 (3, "Macdonalds")
1501 ]
1502
1503 parts = [
1504 (10, "Airliner"),
1505 (20, "Engine"),
1506 (30, "Cheeseburger")
1507 ]
1508
1509 suppart = [
1510 (1, 10), (1, 20), (2, 20), (3, 30)
1511 ]
1512
1513 x = [
1514 (sname, pname)
1515 for (sno, sname) in suppliers
1516 for (pno, pname) in parts
1517 for (sp_sno, sp_pno) in suppart
1518 if sno == sp_sno and pno == sp_pno
1519 ]
1520
1521 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
1522 ('Macdonalds', 'Cheeseburger')])
1523
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001524 def test_genexps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001525 # generator expression tests
1526 g = ([x for x in range(10)] for x in range(1))
Georg Brandla18af4e2007-04-21 15:47:16 +00001527 self.assertEqual(next(g), [x for x in range(10)])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001528 try:
Georg Brandla18af4e2007-04-21 15:47:16 +00001529 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001530 self.fail('should produce StopIteration exception')
1531 except StopIteration:
1532 pass
1533
1534 a = 1
1535 try:
1536 g = (a for d in a)
Georg Brandla18af4e2007-04-21 15:47:16 +00001537 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001538 self.fail('should produce TypeError')
1539 except TypeError:
1540 pass
1541
1542 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
1543 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
1544
1545 a = [x for x in range(10)]
1546 b = (x for x in (y for y in a))
1547 self.assertEqual(sum(b), sum([x for x in range(10)]))
1548
1549 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
1550 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
1551 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
1552 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
1553 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
1554 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)]))
1555 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
1556 check_syntax_error(self, "foo(x for x in range(10), 100)")
1557 check_syntax_error(self, "foo(100, x for x in range(10))")
1558
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001559 def test_comprehension_specials(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001560 # test for outmost iterable precomputation
1561 x = 10; g = (i for i in range(x)); x = 5
1562 self.assertEqual(len(list(g)), 10)
1563
1564 # This should hold, since we're only precomputing outmost iterable.
1565 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
1566 x = 5; t = True;
1567 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
1568
1569 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
1570 # even though it's silly. Make sure it works (ifelse broke this.)
1571 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
1572 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
1573
1574 # verify unpacking single element tuples in listcomp/genexp.
1575 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
1576 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
1577
Benjamin Petersonf17ab892009-05-29 21:55:57 +00001578 def test_with_statement(self):
1579 class manager(object):
1580 def __enter__(self):
1581 return (1, 2)
1582 def __exit__(self, *args):
1583 pass
1584
1585 with manager():
1586 pass
1587 with manager() as x:
1588 pass
1589 with manager() as (x, y):
1590 pass
1591 with manager(), manager():
1592 pass
1593 with manager() as x, manager() as y:
1594 pass
1595 with manager() as x, manager():
1596 pass
1597
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001598 def test_if_else_expr(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001599 # Test ifelse expressions in various cases
1600 def _checkeval(msg, ret):
1601 "helper to check that evaluation of expressions is done correctly"
Victor Stinnerc6ec54d2016-04-12 18:33:41 +02001602 print(msg)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001603 return ret
1604
Nick Coghlan650f0d02007-04-15 12:05:43 +00001605 # the next line is not allowed anymore
1606 #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001607 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
1608 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])
1609 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
1610 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
1611 self.assertEqual((5 and 6 if 0 else 1), 1)
1612 self.assertEqual(((5 and 6) if 0 else 1), 1)
1613 self.assertEqual((5 and (6 if 1 else 1)), 6)
1614 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
1615 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
1616 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
1617 self.assertEqual((not 5 if 1 else 1), False)
1618 self.assertEqual((not 5 if 0 else 1), 1)
1619 self.assertEqual((6 + 1 if 1 else 2), 7)
1620 self.assertEqual((6 - 1 if 1 else 2), 5)
1621 self.assertEqual((6 * 2 if 1 else 4), 12)
1622 self.assertEqual((6 / 2 if 1 else 3), 3)
1623 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +00001624
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001625 def test_paren_evaluation(self):
1626 self.assertEqual(16 // (4 // 2), 8)
1627 self.assertEqual((16 // 4) // 2, 2)
1628 self.assertEqual(16 // 4 // 2, 2)
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001629 x = 2
1630 y = 3
1631 self.assertTrue(False is (x is y))
1632 self.assertFalse((False is x) is y)
1633 self.assertFalse(False is x is y)
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001634
Benjamin Petersond51374e2014-04-09 23:55:56 -04001635 def test_matrix_mul(self):
1636 # This is not intended to be a comprehensive test, rather just to be few
1637 # samples of the @ operator in test_grammar.py.
1638 class M:
1639 def __matmul__(self, o):
1640 return 4
1641 def __imatmul__(self, o):
1642 self.other = o
1643 return self
1644 m = M()
1645 self.assertEqual(m @ m, 4)
1646 m @= 42
1647 self.assertEqual(m.other, 42)
1648
Yury Selivanov75445082015-05-11 22:57:16 -04001649 def test_async_await(self):
Yury Selivanov75445082015-05-11 22:57:16 -04001650 async def test():
1651 def sum():
Yury Selivanov8fb307c2015-07-22 13:33:45 +03001652 pass
Yury Selivanov75445082015-05-11 22:57:16 -04001653 if 1:
1654 await someobj()
1655
1656 self.assertEqual(test.__name__, 'test')
1657 self.assertTrue(bool(test.__code__.co_flags & inspect.CO_COROUTINE))
1658
1659 def decorator(func):
1660 setattr(func, '_marked', True)
1661 return func
1662
1663 @decorator
1664 async def test2():
1665 return 22
1666 self.assertTrue(test2._marked)
1667 self.assertEqual(test2.__name__, 'test2')
1668 self.assertTrue(bool(test2.__code__.co_flags & inspect.CO_COROUTINE))
1669
1670 def test_async_for(self):
1671 class Done(Exception): pass
1672
1673 class AIter:
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001674 def __aiter__(self):
Yury Selivanov75445082015-05-11 22:57:16 -04001675 return self
1676 async def __anext__(self):
1677 raise StopAsyncIteration
1678
1679 async def foo():
1680 async for i in AIter():
1681 pass
1682 async for i, j in AIter():
1683 pass
1684 async for i in AIter():
1685 pass
1686 else:
1687 pass
1688 raise Done
1689
1690 with self.assertRaises(Done):
1691 foo().send(None)
1692
1693 def test_async_with(self):
1694 class Done(Exception): pass
1695
1696 class manager:
1697 async def __aenter__(self):
1698 return (1, 2)
1699 async def __aexit__(self, *exc):
1700 return False
1701
1702 async def foo():
1703 async with manager():
1704 pass
1705 async with manager() as x:
1706 pass
1707 async with manager() as (x, y):
1708 pass
1709 async with manager(), manager():
1710 pass
1711 async with manager() as x, manager() as y:
1712 pass
1713 async with manager() as x, manager():
1714 pass
1715 raise Done
1716
1717 with self.assertRaises(Done):
1718 foo().send(None)
1719
Guido van Rossum3bead091992-01-27 17:00:37 +00001720
Thomas Wouters89f507f2006-12-13 04:49:30 +00001721if __name__ == '__main__':
Zachary Ware38c707e2015-04-13 15:00:43 -05001722 unittest.main()