blob: 3d8b1514f0cd117fec780e3395409d9cdb877fd6 [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
Zachary Ware38c707e2015-04-13 15:00:43 -05004from test.support import check_syntax_error
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 Storchakacf7303e2018-07-09 15:09:35 +0300104 check_syntax_error = check_syntax_error
105
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 Storchaka07ca9af2018-02-04 10:53:48 +0200279 check_syntax_error = check_syntax_error
280
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
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500448 def test_funcdef(self):
Neal Norwitzc1505362006-12-28 06:47:50 +0000449 ### [decorators] 'def' NAME parameters ['->' test] ':' suite
450 ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
451 ### decorators: decorator+
452 ### parameters: '(' [typedargslist] ')'
453 ### typedargslist: ((tfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000454 ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000455 ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000456 ### tfpdef: NAME [':' test]
Neal Norwitzc1505362006-12-28 06:47:50 +0000457 ### varargslist: ((vfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000458 ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000459 ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000460 ### vfpdef: NAME
Thomas Wouters89f507f2006-12-13 04:49:30 +0000461 def f1(): pass
462 f1()
463 f1(*())
464 f1(*(), **{})
465 def f2(one_argument): pass
466 def f3(two, arguments): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000467 self.assertEqual(f2.__code__.co_varnames, ('one_argument',))
468 self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments'))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000469 def a1(one_arg,): pass
470 def a2(two, args,): pass
471 def v0(*rest): pass
472 def v1(a, *rest): pass
473 def v2(a, b, *rest): pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000474
475 f1()
476 f2(1)
477 f2(1,)
478 f3(1, 2)
479 f3(1, 2,)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000480 v0()
481 v0(1)
482 v0(1,)
483 v0(1,2)
484 v0(1,2,3,4,5,6,7,8,9,0)
485 v1(1)
486 v1(1,)
487 v1(1,2)
488 v1(1,2,3)
489 v1(1,2,3,4,5,6,7,8,9,0)
490 v2(1,2)
491 v2(1,2,3)
492 v2(1,2,3,4)
493 v2(1,2,3,4,5,6,7,8,9,0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000494
Thomas Wouters89f507f2006-12-13 04:49:30 +0000495 def d01(a=1): pass
496 d01()
497 d01(1)
498 d01(*(1,))
Yury Selivanov14acf5f2015-08-05 17:54:10 -0400499 d01(*[] or [2])
500 d01(*() or (), *{} and (), **() or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000501 d01(**{'a':2})
Benjamin Petersonde12b792015-05-16 09:44:45 -0400502 d01(**{'a':2} or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000503 def d11(a, b=1): pass
504 d11(1)
505 d11(1, 2)
506 d11(1, **{'b':2})
507 def d21(a, b, c=1): pass
508 d21(1, 2)
509 d21(1, 2, 3)
510 d21(*(1, 2, 3))
511 d21(1, *(2, 3))
512 d21(1, 2, *(3,))
513 d21(1, 2, **{'c':3})
514 def d02(a=1, b=2): pass
515 d02()
516 d02(1)
517 d02(1, 2)
518 d02(*(1, 2))
519 d02(1, *(2,))
520 d02(1, **{'b':2})
521 d02(**{'a': 1, 'b': 2})
522 def d12(a, b=1, c=2): pass
523 d12(1)
524 d12(1, 2)
525 d12(1, 2, 3)
526 def d22(a, b, c=1, d=2): pass
527 d22(1, 2)
528 d22(1, 2, 3)
529 d22(1, 2, 3, 4)
530 def d01v(a=1, *rest): pass
531 d01v()
532 d01v(1)
533 d01v(1, 2)
534 d01v(*(1, 2, 3, 4))
535 d01v(*(1,))
536 d01v(**{'a':2})
537 def d11v(a, b=1, *rest): pass
538 d11v(1)
539 d11v(1, 2)
540 d11v(1, 2, 3)
541 def d21v(a, b, c=1, *rest): pass
542 d21v(1, 2)
543 d21v(1, 2, 3)
544 d21v(1, 2, 3, 4)
545 d21v(*(1, 2, 3, 4))
546 d21v(1, 2, **{'c': 3})
547 def d02v(a=1, b=2, *rest): pass
548 d02v()
549 d02v(1)
550 d02v(1, 2)
551 d02v(1, 2, 3)
552 d02v(1, *(2, 3, 4))
553 d02v(**{'a': 1, 'b': 2})
554 def d12v(a, b=1, c=2, *rest): pass
555 d12v(1)
556 d12v(1, 2)
557 d12v(1, 2, 3)
558 d12v(1, 2, 3, 4)
559 d12v(*(1, 2, 3, 4))
560 d12v(1, 2, *(3, 4, 5))
561 d12v(1, *(2,), **{'c': 3})
562 def d22v(a, b, c=1, d=2, *rest): pass
563 d22v(1, 2)
564 d22v(1, 2, 3)
565 d22v(1, 2, 3, 4)
566 d22v(1, 2, 3, 4, 5)
567 d22v(*(1, 2, 3, 4))
568 d22v(1, 2, *(3, 4, 5))
569 d22v(1, *(2, 3), **{'d': 4})
Georg Brandld8b690f2008-05-16 17:28:50 +0000570
571 # keyword argument type tests
572 try:
573 str('x', **{b'foo':1 })
574 except TypeError:
575 pass
576 else:
577 self.fail('Bytes should not work as keyword argument names')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000578 # keyword only argument tests
579 def pos0key1(*, key): return key
580 pos0key1(key=100)
581 def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
582 pos2key2(1, 2, k1=100)
583 pos2key2(1, 2, k1=100, k2=200)
584 pos2key2(1, 2, k2=100, k1=200)
585 def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
586 pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
587 pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
588
Robert Collinsdf395992015-08-12 08:00:06 +1200589 self.assertRaises(SyntaxError, eval, "def f(*): pass")
590 self.assertRaises(SyntaxError, eval, "def f(*,): pass")
591 self.assertRaises(SyntaxError, eval, "def f(*, **kwds): pass")
592
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000593 # keyword arguments after *arglist
594 def f(*args, **kwargs):
595 return args, kwargs
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000596 self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000597 {'x':2, 'y':5}))
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400598 self.assertEqual(f(1, *(2,3), 4), ((1, 2, 3, 4), {}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000599 self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400600 self.assertEqual(f(**{'eggs':'scrambled', 'spam':'fried'}),
601 ((), {'eggs':'scrambled', 'spam':'fried'}))
602 self.assertEqual(f(spam='fried', **{'eggs':'scrambled'}),
603 ((), {'eggs':'scrambled', 'spam':'fried'}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000604
Serhiy Storchaka0cc99c82018-01-04 10:36:35 +0200605 # Check ast errors in *args and *kwargs
606 check_syntax_error(self, "f(*g(1=2))")
607 check_syntax_error(self, "f(**g(1=2))")
608
Neal Norwitzc1505362006-12-28 06:47:50 +0000609 # argument annotation tests
610 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000611 self.assertEqual(f.__annotations__, {'return': list})
Zachary Warece17f762015-08-01 21:55:36 -0500612 def f(x: int): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000613 self.assertEqual(f.__annotations__, {'x': int})
Zachary Warece17f762015-08-01 21:55:36 -0500614 def f(*x: str): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000615 self.assertEqual(f.__annotations__, {'x': str})
Zachary Warece17f762015-08-01 21:55:36 -0500616 def f(**x: float): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000617 self.assertEqual(f.__annotations__, {'x': float})
Zachary Warece17f762015-08-01 21:55:36 -0500618 def f(x, y: 1+2): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000619 self.assertEqual(f.__annotations__, {'y': 3})
Zachary Warece17f762015-08-01 21:55:36 -0500620 def f(a, b: 1, c: 2, d): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000621 self.assertEqual(f.__annotations__, {'b': 1, 'c': 2})
Zachary Warece17f762015-08-01 21:55:36 -0500622 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000623 self.assertEqual(f.__annotations__,
Zachary Warece17f762015-08-01 21:55:36 -0500624 {'b': 1, 'c': 2, 'e': 3, 'g': 6})
625 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6, h: 7, i=8, j: 9 = 10,
626 **k: 11) -> 12: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000627 self.assertEqual(f.__annotations__,
Zachary Warece17f762015-08-01 21:55:36 -0500628 {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
629 'k': 11, 'return': 12})
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500630 # Check for issue #20625 -- annotations mangling
631 class Spam:
Zachary Warece17f762015-08-01 21:55:36 -0500632 def f(self, *, __kw: 1):
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500633 pass
634 class Ham(Spam): pass
Benjamin Petersonbcfcfc52014-03-09 20:59:24 -0500635 self.assertEqual(Spam.f.__annotations__, {'_Spam__kw': 1})
636 self.assertEqual(Ham.f.__annotations__, {'_Spam__kw': 1})
Nick Coghlan71011e22007-04-23 11:05:01 +0000637 # Check for SF Bug #1697248 - mixing decorators and a return annotation
638 def null(x): return x
639 @null
640 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000641 self.assertEqual(f.__annotations__, {'return': list})
Nick Coghlan71011e22007-04-23 11:05:01 +0000642
Serhiy Storchaka64204de2016-06-12 17:36:24 +0300643 # test closures with a variety of opargs
Guido van Rossum0240b922007-02-26 21:23:50 +0000644 closure = 1
645 def f(): return closure
646 def f(x=1): return closure
647 def f(*, k=1): return closure
648 def f() -> int: return closure
Neal Norwitzc1505362006-12-28 06:47:50 +0000649
Robert Collinsdf395992015-08-12 08:00:06 +1200650 # Check trailing commas are permitted in funcdef argument list
651 def f(a,): pass
652 def f(*args,): pass
653 def f(**kwds,): pass
654 def f(a, *args,): pass
655 def f(a, **kwds,): pass
656 def f(*args, b,): pass
657 def f(*, b,): pass
658 def f(*args, **kwds,): pass
659 def f(a, *args, b,): pass
660 def f(a, *, b,): pass
661 def f(a, *args, **kwds,): pass
662 def f(*args, b, **kwds,): pass
663 def f(*, b, **kwds,): pass
664 def f(a, *args, b, **kwds,): pass
665 def f(a, *, b, **kwds,): pass
666
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500667 def test_lambdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000668 ### lambdef: 'lambda' [varargslist] ':' test
669 l1 = lambda : 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000670 self.assertEqual(l1(), 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000671 l2 = lambda : a[d] # XXX just testing the expression
Guido van Rossume2a383d2007-01-15 16:59:06 +0000672 l3 = lambda : [2 < x for x in [-1, 3, 0]]
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000673 self.assertEqual(l3(), [0, 1, 0])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000674 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000675 self.assertEqual(l4(), 1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000676 l5 = lambda x, y, z=2: x + y + z
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000677 self.assertEqual(l5(1, 2), 5)
678 self.assertEqual(l5(1, 2, 3), 6)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000679 check_syntax_error(self, "lambda x: x = 2")
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000680 check_syntax_error(self, "lambda (None,): None")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000681 l6 = lambda x, y, *, k=20: x+y+k
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000682 self.assertEqual(l6(1,2), 1+2+20)
683 self.assertEqual(l6(1,2,k=10), 1+2+10)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000684
Robert Collinsdf395992015-08-12 08:00:06 +1200685 # check that trailing commas are permitted
686 l10 = lambda a,: 0
687 l11 = lambda *args,: 0
688 l12 = lambda **kwds,: 0
689 l13 = lambda a, *args,: 0
690 l14 = lambda a, **kwds,: 0
691 l15 = lambda *args, b,: 0
692 l16 = lambda *, b,: 0
693 l17 = lambda *args, **kwds,: 0
694 l18 = lambda a, *args, b,: 0
695 l19 = lambda a, *, b,: 0
696 l20 = lambda a, *args, **kwds,: 0
697 l21 = lambda *args, b, **kwds,: 0
698 l22 = lambda *, b, **kwds,: 0
699 l23 = lambda a, *args, b, **kwds,: 0
700 l24 = lambda a, *, b, **kwds,: 0
701
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000702
Thomas Wouters89f507f2006-12-13 04:49:30 +0000703 ### stmt: simple_stmt | compound_stmt
704 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000705
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500706 def test_simple_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000707 ### simple_stmt: small_stmt (';' small_stmt)* [';']
708 x = 1; pass; del x
709 def foo():
Ezio Melotti13925002011-03-16 11:05:33 +0200710 # verify statements that end with semi-colons
Thomas Wouters89f507f2006-12-13 04:49:30 +0000711 x = 1; pass; del x;
712 foo()
Georg Brandl52318d62006-09-06 07:06:08 +0000713
Guido van Rossumd8faa362007-04-27 19:54:29 +0000714 ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
Thomas Wouters89f507f2006-12-13 04:49:30 +0000715 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000716
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500717 def test_expr_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000718 # (exprlist '=')* exprlist
Victor Stinner15a30952016-02-08 22:45:06 +0100719 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000720 1, 2, 3
721 x = 1
722 x = 1, 2, 3
723 x = y = z = 1, 2, 3
724 x, y, z = 1, 2, 3
725 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000726
Thomas Wouters89f507f2006-12-13 04:49:30 +0000727 check_syntax_error(self, "x + 1 = 1")
728 check_syntax_error(self, "a + 1 = b + 2")
Guido van Rossum3bead091992-01-27 17:00:37 +0000729
Nick Coghlan5b1fdc12014-06-16 19:48:02 +1000730 # Check the heuristic for print & exec covers significant cases
731 # As well as placing some limits on false positives
732 def test_former_statements_refer_to_builtins(self):
733 keywords = "print", "exec"
734 # Cases where we want the custom error
735 cases = [
736 "{} foo",
737 "{} {{1:foo}}",
738 "if 1: {} foo",
739 "if 1: {} {{1:foo}}",
740 "if 1:\n {} foo",
741 "if 1:\n {} {{1:foo}}",
742 ]
743 for keyword in keywords:
744 custom_msg = "call to '{}'".format(keyword)
745 for case in cases:
746 source = case.format(keyword)
747 with self.subTest(source=source):
748 with self.assertRaisesRegex(SyntaxError, custom_msg):
749 exec(source)
750 source = source.replace("foo", "(foo.)")
751 with self.subTest(source=source):
752 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
753 exec(source)
754
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500755 def test_del_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000756 # 'del' exprlist
757 abc = [1,2,3]
758 x, y, z = abc
759 xyz = x, y, z
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000760
Thomas Wouters89f507f2006-12-13 04:49:30 +0000761 del abc
762 del x, y, (z, xyz)
Barry Warsaw9182b452000-08-29 04:57:10 +0000763
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500764 def test_pass_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000765 # 'pass'
766 pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000767
Thomas Wouters89f507f2006-12-13 04:49:30 +0000768 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
769 # Tested below
Barry Warsaw9182b452000-08-29 04:57:10 +0000770
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500771 def test_break_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000772 # 'break'
773 while 1: break
Barry Warsaw9182b452000-08-29 04:57:10 +0000774
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500775 def test_continue_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000776 # 'continue'
777 i = 1
778 while i: i = 0; continue
Barry Warsaw9182b452000-08-29 04:57:10 +0000779
Thomas Wouters89f507f2006-12-13 04:49:30 +0000780 msg = ""
781 while not msg:
782 msg = "ok"
783 try:
784 continue
785 msg = "continue failed to continue inside try"
786 except:
787 msg = "continue inside try called except block"
788 if msg != "ok":
789 self.fail(msg)
Barry Warsawefc92ee2000-08-21 15:46:50 +0000790
Thomas Wouters89f507f2006-12-13 04:49:30 +0000791 msg = ""
792 while not msg:
793 msg = "finally block not called"
794 try:
795 continue
796 finally:
797 msg = "ok"
798 if msg != "ok":
799 self.fail(msg)
Guido van Rossum3bead091992-01-27 17:00:37 +0000800
Thomas Wouters89f507f2006-12-13 04:49:30 +0000801 def test_break_continue_loop(self):
802 # This test warrants an explanation. It is a test specifically for SF bugs
803 # #463359 and #462937. The bug is that a 'break' statement executed or
804 # exception raised inside a try/except inside a loop, *after* a continue
805 # statement has been executed in that loop, will cause the wrong number of
806 # arguments to be popped off the stack and the instruction pointer reset to
807 # a very small number (usually 0.) Because of this, the following test
808 # *must* written as a function, and the tracking vars *must* be function
809 # arguments with default values. Otherwise, the test will loop and loop.
Guido van Rossum3bead091992-01-27 17:00:37 +0000810
Thomas Wouters89f507f2006-12-13 04:49:30 +0000811 def test_inner(extra_burning_oil = 1, count=0):
812 big_hippo = 2
813 while big_hippo:
814 count += 1
815 try:
816 if extra_burning_oil and big_hippo == 1:
817 extra_burning_oil -= 1
818 break
819 big_hippo -= 1
820 continue
821 except:
822 raise
823 if count > 2 or big_hippo != 1:
824 self.fail("continue then break in try/except in loop broken!")
825 test_inner()
Guido van Rossum3bead091992-01-27 17:00:37 +0000826
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500827 def test_return(self):
David Cuthbertfd97d1f2018-09-21 18:31:15 -0700828 # 'return' [testlist_star_expr]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000829 def g1(): return
830 def g2(): return 1
David Cuthbertfd97d1f2018-09-21 18:31:15 -0700831 def g3():
832 z = [2, 3]
833 return 1, *z
834
Thomas Wouters89f507f2006-12-13 04:49:30 +0000835 g1()
836 x = g2()
David Cuthbertfd97d1f2018-09-21 18:31:15 -0700837 y = g3()
838 self.assertEqual(y, (1, 2, 3), "unparenthesized star expr return")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000839 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000840
Serhiy Storchaka7cc42c32018-01-02 02:38:35 +0200841 def test_break_in_finally(self):
842 count = 0
843 while count < 2:
844 count += 1
845 try:
846 pass
847 finally:
848 break
849 self.assertEqual(count, 1)
850
851 count = 0
852 while count < 2:
853 count += 1
854 try:
855 continue
856 finally:
857 break
858 self.assertEqual(count, 1)
859
860 count = 0
861 while count < 2:
862 count += 1
863 try:
864 1/0
865 finally:
866 break
867 self.assertEqual(count, 1)
868
869 for count in [0, 1]:
870 self.assertEqual(count, 0)
871 try:
872 pass
873 finally:
874 break
875 self.assertEqual(count, 0)
876
877 for count in [0, 1]:
878 self.assertEqual(count, 0)
879 try:
880 continue
881 finally:
882 break
883 self.assertEqual(count, 0)
884
885 for count in [0, 1]:
886 self.assertEqual(count, 0)
887 try:
888 1/0
889 finally:
890 break
891 self.assertEqual(count, 0)
892
Serhiy Storchakafe2bbb12018-03-18 09:56:52 +0200893 def test_continue_in_finally(self):
894 count = 0
895 while count < 2:
896 count += 1
897 try:
898 pass
899 finally:
900 continue
901 break
902 self.assertEqual(count, 2)
903
904 count = 0
905 while count < 2:
906 count += 1
907 try:
908 break
909 finally:
910 continue
911 self.assertEqual(count, 2)
912
913 count = 0
914 while count < 2:
915 count += 1
916 try:
917 1/0
918 finally:
919 continue
920 break
921 self.assertEqual(count, 2)
922
923 for count in [0, 1]:
924 try:
925 pass
926 finally:
927 continue
928 break
929 self.assertEqual(count, 1)
930
931 for count in [0, 1]:
932 try:
933 break
934 finally:
935 continue
936 self.assertEqual(count, 1)
937
938 for count in [0, 1]:
939 try:
940 1/0
941 finally:
942 continue
943 break
944 self.assertEqual(count, 1)
945
Serhiy Storchaka7cc42c32018-01-02 02:38:35 +0200946 def test_return_in_finally(self):
947 def g1():
948 try:
949 pass
950 finally:
951 return 1
952 self.assertEqual(g1(), 1)
953
954 def g2():
955 try:
956 return 2
957 finally:
958 return 3
959 self.assertEqual(g2(), 3)
960
961 def g3():
962 try:
963 1/0
964 finally:
965 return 4
966 self.assertEqual(g3(), 4)
967
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500968 def test_yield(self):
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000969 # Allowed as standalone statement
970 def g(): yield 1
971 def g(): yield from ()
972 # Allowed as RHS of assignment
973 def g(): x = yield 1
974 def g(): x = yield from ()
975 # Ordinary yield accepts implicit tuples
976 def g(): yield 1, 1
977 def g(): x = yield 1, 1
978 # 'yield from' does not
979 check_syntax_error(self, "def g(): yield from (), 1")
980 check_syntax_error(self, "def g(): x = yield from (), 1")
981 # Requires parentheses as subexpression
982 def g(): 1, (yield 1)
983 def g(): 1, (yield from ())
984 check_syntax_error(self, "def g(): 1, yield 1")
985 check_syntax_error(self, "def g(): 1, yield from ()")
986 # Requires parentheses as call argument
987 def g(): f((yield 1))
988 def g(): f((yield 1), 1)
989 def g(): f((yield from ()))
990 def g(): f((yield from ()), 1)
David Cuthbertfd97d1f2018-09-21 18:31:15 -0700991 # Do not require parenthesis for tuple unpacking
992 def g(): rest = 4, 5, 6; yield 1, 2, 3, *rest
Serhiy Storchaka4642d5f2018-10-05 21:09:56 +0300993 self.assertEqual(list(g()), [(1, 2, 3, 4, 5, 6)])
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000994 check_syntax_error(self, "def g(): f(yield 1)")
995 check_syntax_error(self, "def g(): f(yield 1, 1)")
996 check_syntax_error(self, "def g(): f(yield from ())")
997 check_syntax_error(self, "def g(): f(yield from (), 1)")
998 # Not allowed at top level
999 check_syntax_error(self, "yield")
1000 check_syntax_error(self, "yield from")
1001 # Not allowed at class scope
Thomas Wouters89f507f2006-12-13 04:49:30 +00001002 check_syntax_error(self, "class foo:yield 1")
Nick Coghlan1f7ce622012-01-13 21:43:40 +10001003 check_syntax_error(self, "class foo:yield from ()")
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001004 # Check annotation refleak on SyntaxError
1005 check_syntax_error(self, "def g(a:(yield)): pass")
Guido van Rossum3bead091992-01-27 17:00:37 +00001006
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +02001007 def test_yield_in_comprehensions(self):
1008 # Check yield in comprehensions
1009 def g(): [x for x in [(yield 1)]]
1010 def g(): [x for x in [(yield from ())]]
1011
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +02001012 check = self.check_syntax_error
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +02001013 check("def g(): [(yield x) for x in ()]",
1014 "'yield' inside list comprehension")
1015 check("def g(): [x for x in () if not (yield x)]",
1016 "'yield' inside list comprehension")
1017 check("def g(): [y for x in () for y in [(yield x)]]",
1018 "'yield' inside list comprehension")
1019 check("def g(): {(yield x) for x in ()}",
1020 "'yield' inside set comprehension")
1021 check("def g(): {(yield x): x for x in ()}",
1022 "'yield' inside dict comprehension")
1023 check("def g(): {x: (yield x) for x in ()}",
1024 "'yield' inside dict comprehension")
1025 check("def g(): ((yield x) for x in ())",
1026 "'yield' inside generator expression")
1027 check("def g(): [(yield from x) for x in ()]",
1028 "'yield' inside list comprehension")
1029 check("class C: [(yield x) for x in ()]",
1030 "'yield' inside list comprehension")
1031 check("[(yield x) for x in ()]",
1032 "'yield' inside list comprehension")
1033
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001034 def test_raise(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001035 # 'raise' test [',' test]
Collin Winter828f04a2007-08-31 00:04:24 +00001036 try: raise RuntimeError('just testing')
Thomas Wouters89f507f2006-12-13 04:49:30 +00001037 except RuntimeError: pass
1038 try: raise KeyboardInterrupt
1039 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +00001040
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001041 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001042 # 'import' dotted_as_names
1043 import sys
1044 import time, sys
1045 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
1046 from time import time
1047 from time import (time)
1048 # not testable inside a function, but already done at top of the module
1049 # from sys import *
1050 from sys import path, argv
1051 from sys import (path, argv)
1052 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +00001053
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001054 def test_global(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001055 # 'global' NAME (',' NAME)*
1056 global a
1057 global a, b
1058 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +00001059
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001060 def test_nonlocal(self):
Benjamin Petersona933e522008-10-24 22:16:39 +00001061 # 'nonlocal' NAME (',' NAME)*
1062 x = 0
1063 y = 0
1064 def f():
1065 nonlocal x
1066 nonlocal x, y
1067
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001068 def test_assert(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001069 # assertTruestmt: 'assert' test [',' test]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001070 assert 1
1071 assert 1, 1
1072 assert lambda x:x
1073 assert 1, lambda x:x+1
Ezio Melotti6cc5bf72011-12-02 18:22:52 +02001074
1075 try:
1076 assert True
1077 except AssertionError as e:
1078 self.fail("'assert True' should not have raised an AssertionError")
1079
1080 try:
1081 assert True, 'this should always pass'
1082 except AssertionError as e:
1083 self.fail("'assert True, msg' should not have "
1084 "raised an AssertionError")
1085
1086 # these tests fail if python is run with -O, so check __debug__
1087 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
1088 def testAssert2(self):
Thomas Wouters80d373c2001-09-26 12:43:39 +00001089 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001090 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +00001091 except AssertionError as e:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001092 self.assertEqual(e.args[0], "msg")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001093 else:
Ezio Melotti6cc5bf72011-12-02 18:22:52 +02001094 self.fail("AssertionError not raised by assert 0")
1095
1096 try:
1097 assert False
1098 except AssertionError as e:
1099 self.assertEqual(len(e.args), 0)
1100 else:
1101 self.fail("AssertionError not raised by 'assert False'")
1102
Serhiy Storchakad31e7732018-10-21 10:09:39 +03001103 with self.assertWarnsRegex(SyntaxWarning, 'assertion is always true'):
1104 compile('assert(x, "msg")', '<testcase>', 'exec')
1105 with warnings.catch_warnings():
1106 warnings.filterwarnings('error', category=SyntaxWarning)
1107 with self.assertRaisesRegex(SyntaxError, 'assertion is always true'):
1108 compile('assert(x, "msg")', '<testcase>', 'exec')
1109 compile('assert x, "msg"', '<testcase>', 'exec')
1110
Thomas Wouters80d373c2001-09-26 12:43:39 +00001111
Thomas Wouters89f507f2006-12-13 04:49:30 +00001112 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
1113 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001114
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001115 def test_if(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001116 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
1117 if 1: pass
1118 if 1: pass
1119 else: pass
1120 if 0: pass
1121 elif 0: pass
1122 if 0: pass
1123 elif 0: pass
1124 elif 0: pass
1125 elif 0: pass
1126 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001127
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001128 def test_while(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001129 # 'while' test ':' suite ['else' ':' suite]
1130 while 0: pass
1131 while 0: pass
1132 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001133
Christian Heimes969fe572008-01-25 11:23:10 +00001134 # Issue1920: "while 0" is optimized away,
1135 # ensure that the "else" clause is still present.
1136 x = 0
1137 while 0:
1138 x = 1
1139 else:
1140 x = 2
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001141 self.assertEqual(x, 2)
Christian Heimes969fe572008-01-25 11:23:10 +00001142
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001143 def test_for(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001144 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
1145 for i in 1, 2, 3: pass
1146 for i, j, k in (): pass
1147 else: pass
1148 class Squares:
1149 def __init__(self, max):
1150 self.max = max
1151 self.sofar = []
1152 def __len__(self): return len(self.sofar)
1153 def __getitem__(self, i):
1154 if not 0 <= i < self.max: raise IndexError
1155 n = len(self.sofar)
1156 while n <= i:
1157 self.sofar.append(n*n)
1158 n = n+1
1159 return self.sofar[i]
1160 n = 0
1161 for x in Squares(10): n = n+x
1162 if n != 285:
1163 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +00001164
Thomas Wouters89f507f2006-12-13 04:49:30 +00001165 result = []
1166 for x, in [(1,), (2,), (3,)]:
1167 result.append(x)
1168 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +00001169
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001170 def test_try(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001171 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
1172 ### | 'try' ':' suite 'finally' ':' suite
Guido van Rossumb940e112007-01-10 16:19:56 +00001173 ### except_clause: 'except' [expr ['as' expr]]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001174 try:
1175 1/0
1176 except ZeroDivisionError:
1177 pass
1178 else:
1179 pass
1180 try: 1/0
1181 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +00001182 except TypeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +00001183 except: pass
1184 else: pass
1185 try: 1/0
1186 except (EOFError, TypeError, ZeroDivisionError): pass
1187 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +00001188 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +00001189 try: pass
1190 finally: pass
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +00001191
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001192 def test_suite(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001193 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
1194 if 1: pass
1195 if 1:
1196 pass
1197 if 1:
1198 #
1199 #
1200 #
1201 pass
1202 pass
1203 #
1204 pass
1205 #
Guido van Rossum3bead091992-01-27 17:00:37 +00001206
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001207 def test_test(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001208 ### and_test ('or' and_test)*
1209 ### and_test: not_test ('and' not_test)*
1210 ### not_test: 'not' not_test | comparison
1211 if not 1: pass
1212 if 1 and 1: pass
1213 if 1 or 1: pass
1214 if not not not 1: pass
1215 if not 1 and 1 and 1: pass
1216 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001217
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001218 def test_comparison(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001219 ### comparison: expr (comp_op expr)*
1220 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
1221 if 1: pass
1222 x = (1 == 1)
1223 if 1 == 1: pass
1224 if 1 != 1: pass
1225 if 1 < 1: pass
1226 if 1 > 1: pass
1227 if 1 <= 1: pass
1228 if 1 >= 1: pass
1229 if 1 is 1: pass
1230 if 1 is not 1: pass
1231 if 1 in (): pass
1232 if 1 not in (): pass
1233 if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001234
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001235 def test_binary_mask_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001236 x = 1 & 1
1237 x = 1 ^ 1
1238 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001239
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001240 def test_shift_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001241 x = 1 << 1
1242 x = 1 >> 1
1243 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001244
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001245 def test_additive_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001246 x = 1
1247 x = 1 + 1
1248 x = 1 - 1 - 1
1249 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001250
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001251 def test_multiplicative_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001252 x = 1 * 1
1253 x = 1 / 1
1254 x = 1 % 1
1255 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001256
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001257 def test_unary_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001258 x = +1
1259 x = -1
1260 x = ~1
1261 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
1262 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +00001263
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001264 def test_selectors(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001265 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
1266 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +00001267
Thomas Wouters89f507f2006-12-13 04:49:30 +00001268 import sys, time
1269 c = sys.path[0]
1270 x = time.time()
1271 x = sys.modules['time'].time()
1272 a = '01234'
1273 c = a[0]
1274 c = a[-1]
1275 s = a[0:5]
1276 s = a[:5]
1277 s = a[0:]
1278 s = a[:]
1279 s = a[-5:]
1280 s = a[:-1]
1281 s = a[-4:-3]
1282 # A rough test of SF bug 1333982. http://python.org/sf/1333982
1283 # The testing here is fairly incomplete.
1284 # Test cases should include: commas with 1 and 2 colons
1285 d = {}
1286 d[1] = 1
1287 d[1,] = 2
1288 d[1,2] = 3
1289 d[1,2,3] = 4
1290 L = list(d)
Serhiy Storchaka0cc99c82018-01-04 10:36:35 +02001291 L.sort(key=lambda x: (type(x).__name__, x))
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001292 self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +00001293
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001294 def test_atoms(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001295 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
1296 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +00001297
Thomas Wouters89f507f2006-12-13 04:49:30 +00001298 x = (1)
1299 x = (1 or 2 or 3)
1300 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +00001301
Thomas Wouters89f507f2006-12-13 04:49:30 +00001302 x = []
1303 x = [1]
1304 x = [1 or 2 or 3]
1305 x = [1 or 2 or 3, 2, 3]
1306 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +00001307
Thomas Wouters89f507f2006-12-13 04:49:30 +00001308 x = {}
1309 x = {'one': 1}
1310 x = {'one': 1,}
1311 x = {'one' or 'two': 1 or 2}
1312 x = {'one': 1, 'two': 2}
1313 x = {'one': 1, 'two': 2,}
1314 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +00001315
Thomas Wouters89f507f2006-12-13 04:49:30 +00001316 x = {'one'}
1317 x = {'one', 1,}
1318 x = {'one', 'two', 'three'}
1319 x = {2, 3, 4,}
1320
1321 x = x
1322 x = 'x'
1323 x = 123
1324
1325 ### exprlist: expr (',' expr)* [',']
1326 ### testlist: test (',' test)* [',']
1327 # These have been exercised enough above
1328
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001329 def test_classdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001330 # 'class' NAME ['(' [testlist] ')'] ':' suite
1331 class B: pass
1332 class B2(): pass
1333 class C1(B): pass
1334 class C2(B): pass
1335 class D(C1, C2, B): pass
1336 class C:
1337 def meth1(self): pass
1338 def meth2(self, arg): pass
1339 def meth3(self, a1, a2): pass
1340
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001341 # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
1342 # decorators: decorator+
1343 # decorated: decorators (classdef | funcdef)
1344 def class_decorator(x): return x
1345 @class_decorator
1346 class G: pass
1347
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001348 def test_dictcomps(self):
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001349 # dictorsetmaker: ( (test ':' test (comp_for |
1350 # (',' test ':' test)* [','])) |
1351 # (test (comp_for | (',' test)* [','])) )
1352 nums = [1, 2, 3]
1353 self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
1354
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001355 def test_listcomps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001356 # list comprehension tests
1357 nums = [1, 2, 3, 4, 5]
1358 strs = ["Apple", "Banana", "Coconut"]
1359 spcs = [" Apple", " Banana ", "Coco nut "]
1360
1361 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
1362 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
1363 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
1364 self.assertEqual([(i, s) for i in nums for s in strs],
1365 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
1366 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
1367 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
1368 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
1369 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
1370 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
1371 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
1372 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
1373 (5, 'Banana'), (5, 'Coconut')])
1374 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
1375 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
1376
1377 def test_in_func(l):
1378 return [0 < x < 3 for x in l if x > 2]
1379
1380 self.assertEqual(test_in_func(nums), [False, False, False])
1381
1382 def test_nested_front():
1383 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
1384 [[1, 2], [3, 4], [5, 6]])
1385
1386 test_nested_front()
1387
1388 check_syntax_error(self, "[i, s for i in nums for s in strs]")
1389 check_syntax_error(self, "[x if y]")
1390
1391 suppliers = [
1392 (1, "Boeing"),
1393 (2, "Ford"),
1394 (3, "Macdonalds")
1395 ]
1396
1397 parts = [
1398 (10, "Airliner"),
1399 (20, "Engine"),
1400 (30, "Cheeseburger")
1401 ]
1402
1403 suppart = [
1404 (1, 10), (1, 20), (2, 20), (3, 30)
1405 ]
1406
1407 x = [
1408 (sname, pname)
1409 for (sno, sname) in suppliers
1410 for (pno, pname) in parts
1411 for (sp_sno, sp_pno) in suppart
1412 if sno == sp_sno and pno == sp_pno
1413 ]
1414
1415 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
1416 ('Macdonalds', 'Cheeseburger')])
1417
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001418 def test_genexps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001419 # generator expression tests
1420 g = ([x for x in range(10)] for x in range(1))
Georg Brandla18af4e2007-04-21 15:47:16 +00001421 self.assertEqual(next(g), [x for x in range(10)])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001422 try:
Georg Brandla18af4e2007-04-21 15:47:16 +00001423 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001424 self.fail('should produce StopIteration exception')
1425 except StopIteration:
1426 pass
1427
1428 a = 1
1429 try:
1430 g = (a for d in a)
Georg Brandla18af4e2007-04-21 15:47:16 +00001431 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001432 self.fail('should produce TypeError')
1433 except TypeError:
1434 pass
1435
1436 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
1437 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
1438
1439 a = [x for x in range(10)]
1440 b = (x for x in (y for y in a))
1441 self.assertEqual(sum(b), sum([x for x in range(10)]))
1442
1443 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
1444 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
1445 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
1446 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
1447 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
1448 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)]))
1449 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
1450 check_syntax_error(self, "foo(x for x in range(10), 100)")
1451 check_syntax_error(self, "foo(100, x for x in range(10))")
1452
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001453 def test_comprehension_specials(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001454 # test for outmost iterable precomputation
1455 x = 10; g = (i for i in range(x)); x = 5
1456 self.assertEqual(len(list(g)), 10)
1457
1458 # This should hold, since we're only precomputing outmost iterable.
1459 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
1460 x = 5; t = True;
1461 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
1462
1463 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
1464 # even though it's silly. Make sure it works (ifelse broke this.)
1465 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
1466 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
1467
1468 # verify unpacking single element tuples in listcomp/genexp.
1469 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
1470 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
1471
Benjamin Petersonf17ab892009-05-29 21:55:57 +00001472 def test_with_statement(self):
1473 class manager(object):
1474 def __enter__(self):
1475 return (1, 2)
1476 def __exit__(self, *args):
1477 pass
1478
1479 with manager():
1480 pass
1481 with manager() as x:
1482 pass
1483 with manager() as (x, y):
1484 pass
1485 with manager(), manager():
1486 pass
1487 with manager() as x, manager() as y:
1488 pass
1489 with manager() as x, manager():
1490 pass
1491
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001492 def test_if_else_expr(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001493 # Test ifelse expressions in various cases
1494 def _checkeval(msg, ret):
1495 "helper to check that evaluation of expressions is done correctly"
Victor Stinnerc6ec54d2016-04-12 18:33:41 +02001496 print(msg)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001497 return ret
1498
Nick Coghlan650f0d02007-04-15 12:05:43 +00001499 # the next line is not allowed anymore
1500 #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001501 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
1502 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])
1503 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
1504 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
1505 self.assertEqual((5 and 6 if 0 else 1), 1)
1506 self.assertEqual(((5 and 6) if 0 else 1), 1)
1507 self.assertEqual((5 and (6 if 1 else 1)), 6)
1508 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
1509 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
1510 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
1511 self.assertEqual((not 5 if 1 else 1), False)
1512 self.assertEqual((not 5 if 0 else 1), 1)
1513 self.assertEqual((6 + 1 if 1 else 2), 7)
1514 self.assertEqual((6 - 1 if 1 else 2), 5)
1515 self.assertEqual((6 * 2 if 1 else 4), 12)
1516 self.assertEqual((6 / 2 if 1 else 3), 3)
1517 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +00001518
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001519 def test_paren_evaluation(self):
1520 self.assertEqual(16 // (4 // 2), 8)
1521 self.assertEqual((16 // 4) // 2, 2)
1522 self.assertEqual(16 // 4 // 2, 2)
1523 self.assertTrue(False is (2 is 3))
1524 self.assertFalse((False is 2) is 3)
1525 self.assertFalse(False is 2 is 3)
1526
Benjamin Petersond51374e2014-04-09 23:55:56 -04001527 def test_matrix_mul(self):
1528 # This is not intended to be a comprehensive test, rather just to be few
1529 # samples of the @ operator in test_grammar.py.
1530 class M:
1531 def __matmul__(self, o):
1532 return 4
1533 def __imatmul__(self, o):
1534 self.other = o
1535 return self
1536 m = M()
1537 self.assertEqual(m @ m, 4)
1538 m @= 42
1539 self.assertEqual(m.other, 42)
1540
Yury Selivanov75445082015-05-11 22:57:16 -04001541 def test_async_await(self):
Yury Selivanov75445082015-05-11 22:57:16 -04001542 async def test():
1543 def sum():
Yury Selivanov8fb307c2015-07-22 13:33:45 +03001544 pass
Yury Selivanov75445082015-05-11 22:57:16 -04001545 if 1:
1546 await someobj()
1547
1548 self.assertEqual(test.__name__, 'test')
1549 self.assertTrue(bool(test.__code__.co_flags & inspect.CO_COROUTINE))
1550
1551 def decorator(func):
1552 setattr(func, '_marked', True)
1553 return func
1554
1555 @decorator
1556 async def test2():
1557 return 22
1558 self.assertTrue(test2._marked)
1559 self.assertEqual(test2.__name__, 'test2')
1560 self.assertTrue(bool(test2.__code__.co_flags & inspect.CO_COROUTINE))
1561
1562 def test_async_for(self):
1563 class Done(Exception): pass
1564
1565 class AIter:
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001566 def __aiter__(self):
Yury Selivanov75445082015-05-11 22:57:16 -04001567 return self
1568 async def __anext__(self):
1569 raise StopAsyncIteration
1570
1571 async def foo():
1572 async for i in AIter():
1573 pass
1574 async for i, j in AIter():
1575 pass
1576 async for i in AIter():
1577 pass
1578 else:
1579 pass
1580 raise Done
1581
1582 with self.assertRaises(Done):
1583 foo().send(None)
1584
1585 def test_async_with(self):
1586 class Done(Exception): pass
1587
1588 class manager:
1589 async def __aenter__(self):
1590 return (1, 2)
1591 async def __aexit__(self, *exc):
1592 return False
1593
1594 async def foo():
1595 async with manager():
1596 pass
1597 async with manager() as x:
1598 pass
1599 async with manager() as (x, y):
1600 pass
1601 async with manager(), manager():
1602 pass
1603 async with manager() as x, manager() as y:
1604 pass
1605 async with manager() as x, manager():
1606 pass
1607 raise Done
1608
1609 with self.assertRaises(Done):
1610 foo().send(None)
1611
Guido van Rossum3bead091992-01-27 17:00:37 +00001612
Thomas Wouters89f507f2006-12-13 04:49:30 +00001613if __name__ == '__main__':
Zachary Ware38c707e2015-04-13 15:00:43 -05001614 unittest.main()