blob: 462e77a0be554a65999a2b066ffde84058933f44 [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
Thomas Wouters89f507f2006-12-13 04:49:30 +00008# testing import *
9from sys import *
Guido van Rossum3bead091992-01-27 17:00:37 +000010
Yury Selivanovf8cb8a12016-09-08 20:50:03 -070011# different import patterns to check that __annotations__ does not interfere
12# with import machinery
13import test.ann_module as ann_module
14import typing
15from collections import ChainMap
16from test import ann_module2
17import test
18
Brett Cannona721aba2016-09-09 14:57:09 -070019# These are shared with test_tokenize and other test modules.
20#
21# Note: since several test cases filter out floats by looking for "e" and ".",
22# don't add hexadecimal literals that contain "e" or "E".
23VALID_UNDERSCORE_LITERALS = [
24 '0_0_0',
25 '4_2',
26 '1_0000_0000',
27 '0b1001_0100',
28 '0xffff_ffff',
29 '0o5_7_7',
30 '1_00_00.5',
31 '1_00_00.5e5',
32 '1_00_00e5_1',
33 '1e1_0',
34 '.1_4',
35 '.1_4e1',
36 '0b_0',
37 '0x_f',
38 '0o_5',
39 '1_00_00j',
40 '1_00_00.5j',
41 '1_00_00e5_1j',
42 '.1_4j',
43 '(1_2.5+3_3j)',
44 '(.5_6j)',
45]
46INVALID_UNDERSCORE_LITERALS = [
47 # Trailing underscores:
48 '0_',
49 '42_',
50 '1.4j_',
51 '0x_',
52 '0b1_',
53 '0xf_',
54 '0o5_',
55 '0 if 1_Else 1',
56 # Underscores in the base selector:
57 '0_b0',
58 '0_xf',
59 '0_o5',
60 # Old-style octal, still disallowed:
61 '0_7',
62 '09_99',
63 # Multiple consecutive underscores:
64 '4_______2',
65 '0.1__4',
66 '0.1__4j',
67 '0b1001__0100',
68 '0xffff__ffff',
69 '0x___',
70 '0o5__77',
71 '1e1__0',
72 '1e1__0j',
73 # Underscore right before a dot:
74 '1_.4',
75 '1_.4j',
76 # Underscore right after a dot:
77 '1._4',
78 '1._4j',
79 '._5',
80 '._5j',
81 # Underscore right after a sign:
82 '1.0e+_1',
83 '1.0e+_1j',
84 # Underscore right before j:
85 '1.4_j',
86 '1.4e5_j',
87 # Underscore right before e:
88 '1_e1',
89 '1.4_e1',
90 '1.4_e1j',
91 # Underscore right after e:
92 '1e_1',
93 '1.4e_1',
94 '1.4e_1j',
95 # Complex cases with parens:
96 '(1+1.5_j_)',
97 '(1+1.5_j)',
98]
99
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000100
Thomas Wouters89f507f2006-12-13 04:49:30 +0000101class TokenTests(unittest.TestCase):
Guido van Rossum3bead091992-01-27 17:00:37 +0000102
Serhiy Storchakacf7303e2018-07-09 15:09:35 +0300103 check_syntax_error = check_syntax_error
104
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500105 def test_backslash(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000106 # Backslash means line continuation:
107 x = 1 \
108 + 1
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000109 self.assertEqual(x, 2, 'backslash for line continuation')
Guido van Rossum3bead091992-01-27 17:00:37 +0000110
Thomas Wouters89f507f2006-12-13 04:49:30 +0000111 # Backslash does not means continuation in comments :\
112 x = 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000113 self.assertEqual(x, 0, 'backslash ending comment')
Guido van Rossum3bead091992-01-27 17:00:37 +0000114
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500115 def test_plain_integers(self):
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000116 self.assertEqual(type(000), type(0))
117 self.assertEqual(0xff, 255)
118 self.assertEqual(0o377, 255)
119 self.assertEqual(2147483647, 0o17777777777)
120 self.assertEqual(0b1001, 9)
Georg Brandlfceab5a2008-01-19 20:08:23 +0000121 # "0x" is not a valid literal
122 self.assertRaises(SyntaxError, eval, "0x")
Christian Heimesa37d4c62007-12-04 23:02:19 +0000123 from sys import maxsize
124 if maxsize == 2147483647:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000125 self.assertEqual(-2147483647-1, -0o20000000000)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000126 # XXX -2147483648
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000127 self.assertTrue(0o37777777777 > 0)
128 self.assertTrue(0xffffffff > 0)
129 self.assertTrue(0b1111111111111111111111111111111 > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000130 for s in ('2147483648', '0o40000000000', '0x100000000',
131 '0b10000000000000000000000000000000'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000132 try:
133 x = eval(s)
134 except OverflowError:
135 self.fail("OverflowError on huge integer literal %r" % s)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000136 elif maxsize == 9223372036854775807:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000137 self.assertEqual(-9223372036854775807-1, -0o1000000000000000000000)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000138 self.assertTrue(0o1777777777777777777777 > 0)
139 self.assertTrue(0xffffffffffffffff > 0)
140 self.assertTrue(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000141 for s in '9223372036854775808', '0o2000000000000000000000', \
142 '0x10000000000000000', \
143 '0b100000000000000000000000000000000000000000000000000000000000000':
Thomas Wouters89f507f2006-12-13 04:49:30 +0000144 try:
145 x = eval(s)
146 except OverflowError:
147 self.fail("OverflowError on huge integer literal %r" % s)
148 else:
Christian Heimesa37d4c62007-12-04 23:02:19 +0000149 self.fail('Weird maxsize value %r' % maxsize)
Guido van Rossum3bead091992-01-27 17:00:37 +0000150
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500151 def test_long_integers(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000152 x = 0
Guido van Rossume2a383d2007-01-15 16:59:06 +0000153 x = 0xffffffffffffffff
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000154 x = 0Xffffffffffffffff
155 x = 0o77777777777777777
156 x = 0O77777777777777777
Guido van Rossume2a383d2007-01-15 16:59:06 +0000157 x = 123456789012345678901234567890
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000158 x = 0b100000000000000000000000000000000000000000000000000000000000000000000
159 x = 0B111111111111111111111111111111111111111111111111111111111111111111111
Guido van Rossum3bead091992-01-27 17:00:37 +0000160
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500161 def test_floats(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000162 x = 3.14
163 x = 314.
164 x = 0.314
165 # XXX x = 000.314
166 x = .314
167 x = 3e14
168 x = 3E14
169 x = 3e-14
170 x = 3e+14
171 x = 3.e14
172 x = .3e14
173 x = 3.1e4
Guido van Rossum3bead091992-01-27 17:00:37 +0000174
Benjamin Petersonc4161622014-06-07 12:36:39 -0700175 def test_float_exponent_tokenization(self):
176 # See issue 21642.
177 self.assertEqual(1 if 1else 0, 1)
178 self.assertEqual(1 if 0else 0, 0)
179 self.assertRaises(SyntaxError, eval, "0 if 1Else 0")
180
Brett Cannona721aba2016-09-09 14:57:09 -0700181 def test_underscore_literals(self):
182 for lit in VALID_UNDERSCORE_LITERALS:
183 self.assertEqual(eval(lit), eval(lit.replace('_', '')))
184 for lit in INVALID_UNDERSCORE_LITERALS:
185 self.assertRaises(SyntaxError, eval, lit)
186 # Sanity check: no literal begins with an underscore
187 self.assertRaises(NameError, eval, "_0")
188
Serhiy Storchakacf7303e2018-07-09 15:09:35 +0300189 def test_bad_numerical_literals(self):
190 check = self.check_syntax_error
191 check("0b12", "invalid digit '2' in binary literal")
192 check("0b1_2", "invalid digit '2' in binary literal")
193 check("0b2", "invalid digit '2' in binary literal")
194 check("0b1_", "invalid binary literal")
195 check("0b", "invalid binary literal")
196 check("0o18", "invalid digit '8' in octal literal")
197 check("0o1_8", "invalid digit '8' in octal literal")
198 check("0o8", "invalid digit '8' in octal literal")
199 check("0o1_", "invalid octal literal")
200 check("0o", "invalid octal literal")
201 check("0x1_", "invalid hexadecimal literal")
202 check("0x", "invalid hexadecimal literal")
203 check("1_", "invalid decimal literal")
204 check("012",
205 "leading zeros in decimal integer literals are not permitted; "
206 "use an 0o prefix for octal integers")
207 check("1.2_", "invalid decimal literal")
208 check("1e2_", "invalid decimal literal")
209 check("1e+", "invalid decimal literal")
210
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500211 def test_string_literals(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000212 x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y)
213 x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39)
214 x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000215 x = "doesn't \"shrink\" does it"
216 y = 'doesn\'t "shrink" does it'
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000217 self.assertTrue(len(x) == 24 and x == y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000218 x = "does \"shrink\" doesn't it"
219 y = 'does "shrink" doesn\'t it'
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000220 self.assertTrue(len(x) == 24 and x == y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000221 x = """
Guido van Rossumb6775db1994-08-01 11:34:53 +0000222The "quick"
223brown fox
224jumps over
225the 'lazy' dog.
226"""
Thomas Wouters89f507f2006-12-13 04:49:30 +0000227 y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000228 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000229 y = '''
Guido van Rossumb6775db1994-08-01 11:34:53 +0000230The "quick"
231brown fox
232jumps over
233the 'lazy' dog.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000234'''
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000235 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000236 y = "\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000237The \"quick\"\n\
238brown fox\n\
239jumps over\n\
240the 'lazy' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000241"
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000242 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000243 y = '\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000244The \"quick\"\n\
245brown fox\n\
246jumps over\n\
247the \'lazy\' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000248'
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000249 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000250
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500251 def test_ellipsis(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000252 x = ...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000253 self.assertTrue(x is Ellipsis)
Georg Brandldde00282007-03-18 19:01:53 +0000254 self.assertRaises(SyntaxError, eval, ".. .")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000255
Benjamin Peterson758888d2011-05-30 11:12:38 -0500256 def test_eof_error(self):
257 samples = ("def foo(", "\ndef foo(", "def foo(\n")
258 for s in samples:
259 with self.assertRaises(SyntaxError) as cm:
260 compile(s, "<test>", "exec")
261 self.assertIn("unexpected EOF", str(cm.exception))
262
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700263var_annot_global: int # a global annotated is necessary for test_var_annot
264
265# custom namespace for testing __annotations__
266
267class CNS:
268 def __init__(self):
269 self._dct = {}
270 def __setitem__(self, item, value):
271 self._dct[item.lower()] = value
272 def __getitem__(self, item):
273 return self._dct[item]
274
275
Thomas Wouters89f507f2006-12-13 04:49:30 +0000276class GrammarTests(unittest.TestCase):
277
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200278 check_syntax_error = check_syntax_error
279
Thomas Wouters89f507f2006-12-13 04:49:30 +0000280 # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
281 # XXX can't test in a script -- this rule is only used when interactive
282
283 # file_input: (NEWLINE | stmt)* ENDMARKER
284 # Being tested as this very moment this very module
285
286 # expr_input: testlist NEWLINE
287 # XXX Hard to test -- used only in calls to input()
288
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500289 def test_eval_input(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000290 # testlist ENDMARKER
291 x = eval('1, 0 or 1')
292
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700293 def test_var_annot_basics(self):
294 # all these should be allowed
295 var1: int = 5
296 var2: [int, str]
297 my_lst = [42]
298 def one():
299 return 1
300 int.new_attr: int
301 [list][0]: type
302 my_lst[one()-1]: int = 5
303 self.assertEqual(my_lst, [5])
304
305 def test_var_annot_syntax_errors(self):
306 # parser pass
307 check_syntax_error(self, "def f: int")
308 check_syntax_error(self, "x: int: str")
309 check_syntax_error(self, "def f():\n"
310 " nonlocal x: int\n")
311 # AST pass
312 check_syntax_error(self, "[x, 0]: int\n")
313 check_syntax_error(self, "f(): int\n")
314 check_syntax_error(self, "(x,): int")
315 check_syntax_error(self, "def f():\n"
316 " (x, y): int = (1, 2)\n")
317 # symtable pass
318 check_syntax_error(self, "def f():\n"
319 " x: int\n"
320 " global x\n")
321 check_syntax_error(self, "def f():\n"
322 " global x\n"
323 " x: int\n")
324
325 def test_var_annot_basic_semantics(self):
326 # execution order
327 with self.assertRaises(ZeroDivisionError):
328 no_name[does_not_exist]: no_name_again = 1/0
329 with self.assertRaises(NameError):
330 no_name[does_not_exist]: 1/0 = 0
331 global var_annot_global
332
333 # function semantics
334 def f():
335 st: str = "Hello"
336 a.b: int = (1, 2)
337 return st
338 self.assertEqual(f.__annotations__, {})
339 def f_OK():
340 x: 1/0
341 f_OK()
342 def fbad():
343 x: int
344 print(x)
345 with self.assertRaises(UnboundLocalError):
346 fbad()
347 def f2bad():
348 (no_such_global): int
349 print(no_such_global)
350 try:
351 f2bad()
352 except Exception as e:
353 self.assertIs(type(e), NameError)
354
355 # class semantics
356 class C:
Guido van Rossum015d8742016-09-11 09:45:24 -0700357 __foo: int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700358 s: str = "attr"
359 z = 2
360 def __init__(self, x):
361 self.x: int = x
Guido van Rossum015d8742016-09-11 09:45:24 -0700362 self.assertEqual(C.__annotations__, {'_C__foo': int, 's': str})
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700363 with self.assertRaises(NameError):
364 class CBad:
365 no_such_name_defined.attr: int = 0
366 with self.assertRaises(NameError):
367 class Cbad2(C):
368 x: int
369 x.y: list = []
370
371 def test_var_annot_metaclass_semantics(self):
372 class CMeta(type):
373 @classmethod
374 def __prepare__(metacls, name, bases, **kwds):
375 return {'__annotations__': CNS()}
376 class CC(metaclass=CMeta):
377 XX: 'ANNOT'
378 self.assertEqual(CC.__annotations__['xx'], 'ANNOT')
379
380 def test_var_annot_module_semantics(self):
381 with self.assertRaises(AttributeError):
382 print(test.__annotations__)
383 self.assertEqual(ann_module.__annotations__,
384 {1: 2, 'x': int, 'y': str, 'f': typing.Tuple[int, int]})
385 self.assertEqual(ann_module.M.__annotations__,
386 {'123': 123, 'o': type})
387 self.assertEqual(ann_module2.__annotations__, {})
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700388
389 def test_var_annot_in_module(self):
390 # check that functions fail the same way when executed
391 # outside of module where they were defined
392 from test.ann_module3 import f_bad_ann, g_bad_ann, D_bad_ann
393 with self.assertRaises(NameError):
394 f_bad_ann()
395 with self.assertRaises(NameError):
396 g_bad_ann()
397 with self.assertRaises(NameError):
398 D_bad_ann(5)
399
400 def test_var_annot_simple_exec(self):
401 gns = {}; lns= {}
402 exec("'docstring'\n"
403 "__annotations__[1] = 2\n"
404 "x: int = 5\n", gns, lns)
405 self.assertEqual(lns["__annotations__"], {1: 2, 'x': int})
406 with self.assertRaises(KeyError):
407 gns['__annotations__']
408
409 def test_var_annot_custom_maps(self):
410 # tests with custom locals() and __annotations__
411 ns = {'__annotations__': CNS()}
412 exec('X: int; Z: str = "Z"; (w): complex = 1j', ns)
413 self.assertEqual(ns['__annotations__']['x'], int)
414 self.assertEqual(ns['__annotations__']['z'], str)
415 with self.assertRaises(KeyError):
416 ns['__annotations__']['w']
417 nonloc_ns = {}
418 class CNS2:
419 def __init__(self):
420 self._dct = {}
421 def __setitem__(self, item, value):
422 nonlocal nonloc_ns
423 self._dct[item] = value
424 nonloc_ns[item] = value
425 def __getitem__(self, item):
426 return self._dct[item]
427 exec('x: int = 1', {}, CNS2())
428 self.assertEqual(nonloc_ns['__annotations__']['x'], int)
429
430 def test_var_annot_refleak(self):
431 # complex case: custom locals plus custom __annotations__
432 # this was causing refleak
433 cns = CNS()
434 nonloc_ns = {'__annotations__': cns}
435 class CNS2:
436 def __init__(self):
437 self._dct = {'__annotations__': cns}
438 def __setitem__(self, item, value):
439 nonlocal nonloc_ns
440 self._dct[item] = value
441 nonloc_ns[item] = value
442 def __getitem__(self, item):
443 return self._dct[item]
444 exec('X: str', {}, CNS2())
445 self.assertEqual(nonloc_ns['__annotations__']['x'], str)
446
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500447 def test_funcdef(self):
Neal Norwitzc1505362006-12-28 06:47:50 +0000448 ### [decorators] 'def' NAME parameters ['->' test] ':' suite
449 ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
450 ### decorators: decorator+
451 ### parameters: '(' [typedargslist] ')'
452 ### typedargslist: ((tfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000453 ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000454 ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000455 ### tfpdef: NAME [':' test]
Neal Norwitzc1505362006-12-28 06:47:50 +0000456 ### varargslist: ((vfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000457 ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000458 ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000459 ### vfpdef: NAME
Thomas Wouters89f507f2006-12-13 04:49:30 +0000460 def f1(): pass
461 f1()
462 f1(*())
463 f1(*(), **{})
464 def f2(one_argument): pass
465 def f3(two, arguments): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000466 self.assertEqual(f2.__code__.co_varnames, ('one_argument',))
467 self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments'))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000468 def a1(one_arg,): pass
469 def a2(two, args,): pass
470 def v0(*rest): pass
471 def v1(a, *rest): pass
472 def v2(a, b, *rest): pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000473
474 f1()
475 f2(1)
476 f2(1,)
477 f3(1, 2)
478 f3(1, 2,)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000479 v0()
480 v0(1)
481 v0(1,)
482 v0(1,2)
483 v0(1,2,3,4,5,6,7,8,9,0)
484 v1(1)
485 v1(1,)
486 v1(1,2)
487 v1(1,2,3)
488 v1(1,2,3,4,5,6,7,8,9,0)
489 v2(1,2)
490 v2(1,2,3)
491 v2(1,2,3,4)
492 v2(1,2,3,4,5,6,7,8,9,0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000493
Thomas Wouters89f507f2006-12-13 04:49:30 +0000494 def d01(a=1): pass
495 d01()
496 d01(1)
497 d01(*(1,))
Yury Selivanov14acf5f2015-08-05 17:54:10 -0400498 d01(*[] or [2])
499 d01(*() or (), *{} and (), **() or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000500 d01(**{'a':2})
Benjamin Petersonde12b792015-05-16 09:44:45 -0400501 d01(**{'a':2} or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000502 def d11(a, b=1): pass
503 d11(1)
504 d11(1, 2)
505 d11(1, **{'b':2})
506 def d21(a, b, c=1): pass
507 d21(1, 2)
508 d21(1, 2, 3)
509 d21(*(1, 2, 3))
510 d21(1, *(2, 3))
511 d21(1, 2, *(3,))
512 d21(1, 2, **{'c':3})
513 def d02(a=1, b=2): pass
514 d02()
515 d02(1)
516 d02(1, 2)
517 d02(*(1, 2))
518 d02(1, *(2,))
519 d02(1, **{'b':2})
520 d02(**{'a': 1, 'b': 2})
521 def d12(a, b=1, c=2): pass
522 d12(1)
523 d12(1, 2)
524 d12(1, 2, 3)
525 def d22(a, b, c=1, d=2): pass
526 d22(1, 2)
527 d22(1, 2, 3)
528 d22(1, 2, 3, 4)
529 def d01v(a=1, *rest): pass
530 d01v()
531 d01v(1)
532 d01v(1, 2)
533 d01v(*(1, 2, 3, 4))
534 d01v(*(1,))
535 d01v(**{'a':2})
536 def d11v(a, b=1, *rest): pass
537 d11v(1)
538 d11v(1, 2)
539 d11v(1, 2, 3)
540 def d21v(a, b, c=1, *rest): pass
541 d21v(1, 2)
542 d21v(1, 2, 3)
543 d21v(1, 2, 3, 4)
544 d21v(*(1, 2, 3, 4))
545 d21v(1, 2, **{'c': 3})
546 def d02v(a=1, b=2, *rest): pass
547 d02v()
548 d02v(1)
549 d02v(1, 2)
550 d02v(1, 2, 3)
551 d02v(1, *(2, 3, 4))
552 d02v(**{'a': 1, 'b': 2})
553 def d12v(a, b=1, c=2, *rest): pass
554 d12v(1)
555 d12v(1, 2)
556 d12v(1, 2, 3)
557 d12v(1, 2, 3, 4)
558 d12v(*(1, 2, 3, 4))
559 d12v(1, 2, *(3, 4, 5))
560 d12v(1, *(2,), **{'c': 3})
561 def d22v(a, b, c=1, d=2, *rest): pass
562 d22v(1, 2)
563 d22v(1, 2, 3)
564 d22v(1, 2, 3, 4)
565 d22v(1, 2, 3, 4, 5)
566 d22v(*(1, 2, 3, 4))
567 d22v(1, 2, *(3, 4, 5))
568 d22v(1, *(2, 3), **{'d': 4})
Georg Brandld8b690f2008-05-16 17:28:50 +0000569
570 # keyword argument type tests
571 try:
572 str('x', **{b'foo':1 })
573 except TypeError:
574 pass
575 else:
576 self.fail('Bytes should not work as keyword argument names')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000577 # keyword only argument tests
578 def pos0key1(*, key): return key
579 pos0key1(key=100)
580 def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
581 pos2key2(1, 2, k1=100)
582 pos2key2(1, 2, k1=100, k2=200)
583 pos2key2(1, 2, k2=100, k1=200)
584 def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
585 pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
586 pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
587
Robert Collinsdf395992015-08-12 08:00:06 +1200588 self.assertRaises(SyntaxError, eval, "def f(*): pass")
589 self.assertRaises(SyntaxError, eval, "def f(*,): pass")
590 self.assertRaises(SyntaxError, eval, "def f(*, **kwds): pass")
591
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000592 # keyword arguments after *arglist
593 def f(*args, **kwargs):
594 return args, kwargs
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000595 self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000596 {'x':2, 'y':5}))
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400597 self.assertEqual(f(1, *(2,3), 4), ((1, 2, 3, 4), {}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000598 self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400599 self.assertEqual(f(**{'eggs':'scrambled', 'spam':'fried'}),
600 ((), {'eggs':'scrambled', 'spam':'fried'}))
601 self.assertEqual(f(spam='fried', **{'eggs':'scrambled'}),
602 ((), {'eggs':'scrambled', 'spam':'fried'}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000603
Serhiy Storchaka0cc99c82018-01-04 10:36:35 +0200604 # Check ast errors in *args and *kwargs
605 check_syntax_error(self, "f(*g(1=2))")
606 check_syntax_error(self, "f(**g(1=2))")
607
Neal Norwitzc1505362006-12-28 06:47:50 +0000608 # argument annotation tests
609 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000610 self.assertEqual(f.__annotations__, {'return': list})
Zachary Warece17f762015-08-01 21:55:36 -0500611 def f(x: int): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000612 self.assertEqual(f.__annotations__, {'x': int})
Zachary Warece17f762015-08-01 21:55:36 -0500613 def f(*x: str): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000614 self.assertEqual(f.__annotations__, {'x': str})
Zachary Warece17f762015-08-01 21:55:36 -0500615 def f(**x: float): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000616 self.assertEqual(f.__annotations__, {'x': float})
Zachary Warece17f762015-08-01 21:55:36 -0500617 def f(x, y: 1+2): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000618 self.assertEqual(f.__annotations__, {'y': 3})
Zachary Warece17f762015-08-01 21:55:36 -0500619 def f(a, b: 1, c: 2, d): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000620 self.assertEqual(f.__annotations__, {'b': 1, 'c': 2})
Zachary Warece17f762015-08-01 21:55:36 -0500621 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000622 self.assertEqual(f.__annotations__,
Zachary Warece17f762015-08-01 21:55:36 -0500623 {'b': 1, 'c': 2, 'e': 3, 'g': 6})
624 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6, h: 7, i=8, j: 9 = 10,
625 **k: 11) -> 12: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000626 self.assertEqual(f.__annotations__,
Zachary Warece17f762015-08-01 21:55:36 -0500627 {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
628 'k': 11, 'return': 12})
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500629 # Check for issue #20625 -- annotations mangling
630 class Spam:
Zachary Warece17f762015-08-01 21:55:36 -0500631 def f(self, *, __kw: 1):
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500632 pass
633 class Ham(Spam): pass
Benjamin Petersonbcfcfc52014-03-09 20:59:24 -0500634 self.assertEqual(Spam.f.__annotations__, {'_Spam__kw': 1})
635 self.assertEqual(Ham.f.__annotations__, {'_Spam__kw': 1})
Nick Coghlan71011e22007-04-23 11:05:01 +0000636 # Check for SF Bug #1697248 - mixing decorators and a return annotation
637 def null(x): return x
638 @null
639 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000640 self.assertEqual(f.__annotations__, {'return': list})
Nick Coghlan71011e22007-04-23 11:05:01 +0000641
Serhiy Storchaka64204de2016-06-12 17:36:24 +0300642 # test closures with a variety of opargs
Guido van Rossum0240b922007-02-26 21:23:50 +0000643 closure = 1
644 def f(): return closure
645 def f(x=1): return closure
646 def f(*, k=1): return closure
647 def f() -> int: return closure
Neal Norwitzc1505362006-12-28 06:47:50 +0000648
Robert Collinsdf395992015-08-12 08:00:06 +1200649 # Check trailing commas are permitted in funcdef argument list
650 def f(a,): pass
651 def f(*args,): pass
652 def f(**kwds,): pass
653 def f(a, *args,): pass
654 def f(a, **kwds,): pass
655 def f(*args, b,): pass
656 def f(*, b,): pass
657 def f(*args, **kwds,): pass
658 def f(a, *args, b,): pass
659 def f(a, *, b,): pass
660 def f(a, *args, **kwds,): pass
661 def f(*args, b, **kwds,): pass
662 def f(*, b, **kwds,): pass
663 def f(a, *args, b, **kwds,): pass
664 def f(a, *, b, **kwds,): pass
665
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500666 def test_lambdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000667 ### lambdef: 'lambda' [varargslist] ':' test
668 l1 = lambda : 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000669 self.assertEqual(l1(), 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000670 l2 = lambda : a[d] # XXX just testing the expression
Guido van Rossume2a383d2007-01-15 16:59:06 +0000671 l3 = lambda : [2 < x for x in [-1, 3, 0]]
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000672 self.assertEqual(l3(), [0, 1, 0])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000673 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000674 self.assertEqual(l4(), 1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000675 l5 = lambda x, y, z=2: x + y + z
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000676 self.assertEqual(l5(1, 2), 5)
677 self.assertEqual(l5(1, 2, 3), 6)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000678 check_syntax_error(self, "lambda x: x = 2")
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000679 check_syntax_error(self, "lambda (None,): None")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000680 l6 = lambda x, y, *, k=20: x+y+k
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000681 self.assertEqual(l6(1,2), 1+2+20)
682 self.assertEqual(l6(1,2,k=10), 1+2+10)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000683
Robert Collinsdf395992015-08-12 08:00:06 +1200684 # check that trailing commas are permitted
685 l10 = lambda a,: 0
686 l11 = lambda *args,: 0
687 l12 = lambda **kwds,: 0
688 l13 = lambda a, *args,: 0
689 l14 = lambda a, **kwds,: 0
690 l15 = lambda *args, b,: 0
691 l16 = lambda *, b,: 0
692 l17 = lambda *args, **kwds,: 0
693 l18 = lambda a, *args, b,: 0
694 l19 = lambda a, *, b,: 0
695 l20 = lambda a, *args, **kwds,: 0
696 l21 = lambda *args, b, **kwds,: 0
697 l22 = lambda *, b, **kwds,: 0
698 l23 = lambda a, *args, b, **kwds,: 0
699 l24 = lambda a, *, b, **kwds,: 0
700
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000701
Thomas Wouters89f507f2006-12-13 04:49:30 +0000702 ### stmt: simple_stmt | compound_stmt
703 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000704
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500705 def test_simple_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000706 ### simple_stmt: small_stmt (';' small_stmt)* [';']
707 x = 1; pass; del x
708 def foo():
Ezio Melotti13925002011-03-16 11:05:33 +0200709 # verify statements that end with semi-colons
Thomas Wouters89f507f2006-12-13 04:49:30 +0000710 x = 1; pass; del x;
711 foo()
Georg Brandl52318d62006-09-06 07:06:08 +0000712
Guido van Rossumd8faa362007-04-27 19:54:29 +0000713 ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
Thomas Wouters89f507f2006-12-13 04:49:30 +0000714 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000715
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500716 def test_expr_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000717 # (exprlist '=')* exprlist
Victor Stinner15a30952016-02-08 22:45:06 +0100718 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000719 1, 2, 3
720 x = 1
721 x = 1, 2, 3
722 x = y = z = 1, 2, 3
723 x, y, z = 1, 2, 3
724 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000725
Thomas Wouters89f507f2006-12-13 04:49:30 +0000726 check_syntax_error(self, "x + 1 = 1")
727 check_syntax_error(self, "a + 1 = b + 2")
Guido van Rossum3bead091992-01-27 17:00:37 +0000728
Nick Coghlan5b1fdc12014-06-16 19:48:02 +1000729 # Check the heuristic for print & exec covers significant cases
730 # As well as placing some limits on false positives
731 def test_former_statements_refer_to_builtins(self):
732 keywords = "print", "exec"
733 # Cases where we want the custom error
734 cases = [
735 "{} foo",
736 "{} {{1:foo}}",
737 "if 1: {} foo",
738 "if 1: {} {{1:foo}}",
739 "if 1:\n {} foo",
740 "if 1:\n {} {{1:foo}}",
741 ]
742 for keyword in keywords:
743 custom_msg = "call to '{}'".format(keyword)
744 for case in cases:
745 source = case.format(keyword)
746 with self.subTest(source=source):
747 with self.assertRaisesRegex(SyntaxError, custom_msg):
748 exec(source)
749 source = source.replace("foo", "(foo.)")
750 with self.subTest(source=source):
751 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
752 exec(source)
753
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500754 def test_del_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000755 # 'del' exprlist
756 abc = [1,2,3]
757 x, y, z = abc
758 xyz = x, y, z
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000759
Thomas Wouters89f507f2006-12-13 04:49:30 +0000760 del abc
761 del x, y, (z, xyz)
Barry Warsaw9182b452000-08-29 04:57:10 +0000762
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500763 def test_pass_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000764 # 'pass'
765 pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000766
Thomas Wouters89f507f2006-12-13 04:49:30 +0000767 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
768 # Tested below
Barry Warsaw9182b452000-08-29 04:57:10 +0000769
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500770 def test_break_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000771 # 'break'
772 while 1: break
Barry Warsaw9182b452000-08-29 04:57:10 +0000773
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500774 def test_continue_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000775 # 'continue'
776 i = 1
777 while i: i = 0; continue
Barry Warsaw9182b452000-08-29 04:57:10 +0000778
Thomas Wouters89f507f2006-12-13 04:49:30 +0000779 msg = ""
780 while not msg:
781 msg = "ok"
782 try:
783 continue
784 msg = "continue failed to continue inside try"
785 except:
786 msg = "continue inside try called except block"
787 if msg != "ok":
788 self.fail(msg)
Barry Warsawefc92ee2000-08-21 15:46:50 +0000789
Thomas Wouters89f507f2006-12-13 04:49:30 +0000790 msg = ""
791 while not msg:
792 msg = "finally block not called"
793 try:
794 continue
795 finally:
796 msg = "ok"
797 if msg != "ok":
798 self.fail(msg)
Guido van Rossum3bead091992-01-27 17:00:37 +0000799
Thomas Wouters89f507f2006-12-13 04:49:30 +0000800 def test_break_continue_loop(self):
801 # This test warrants an explanation. It is a test specifically for SF bugs
802 # #463359 and #462937. The bug is that a 'break' statement executed or
803 # exception raised inside a try/except inside a loop, *after* a continue
804 # statement has been executed in that loop, will cause the wrong number of
805 # arguments to be popped off the stack and the instruction pointer reset to
806 # a very small number (usually 0.) Because of this, the following test
807 # *must* written as a function, and the tracking vars *must* be function
808 # arguments with default values. Otherwise, the test will loop and loop.
Guido van Rossum3bead091992-01-27 17:00:37 +0000809
Thomas Wouters89f507f2006-12-13 04:49:30 +0000810 def test_inner(extra_burning_oil = 1, count=0):
811 big_hippo = 2
812 while big_hippo:
813 count += 1
814 try:
815 if extra_burning_oil and big_hippo == 1:
816 extra_burning_oil -= 1
817 break
818 big_hippo -= 1
819 continue
820 except:
821 raise
822 if count > 2 or big_hippo != 1:
823 self.fail("continue then break in try/except in loop broken!")
824 test_inner()
Guido van Rossum3bead091992-01-27 17:00:37 +0000825
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500826 def test_return(self):
David Cuthbertfd97d1f2018-09-21 18:31:15 -0700827 # 'return' [testlist_star_expr]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000828 def g1(): return
829 def g2(): return 1
David Cuthbertfd97d1f2018-09-21 18:31:15 -0700830 def g3():
831 z = [2, 3]
832 return 1, *z
833
Thomas Wouters89f507f2006-12-13 04:49:30 +0000834 g1()
835 x = g2()
David Cuthbertfd97d1f2018-09-21 18:31:15 -0700836 y = g3()
837 self.assertEqual(y, (1, 2, 3), "unparenthesized star expr return")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000838 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000839
Serhiy Storchaka7cc42c32018-01-02 02:38:35 +0200840 def test_break_in_finally(self):
841 count = 0
842 while count < 2:
843 count += 1
844 try:
845 pass
846 finally:
847 break
848 self.assertEqual(count, 1)
849
850 count = 0
851 while count < 2:
852 count += 1
853 try:
854 continue
855 finally:
856 break
857 self.assertEqual(count, 1)
858
859 count = 0
860 while count < 2:
861 count += 1
862 try:
863 1/0
864 finally:
865 break
866 self.assertEqual(count, 1)
867
868 for count in [0, 1]:
869 self.assertEqual(count, 0)
870 try:
871 pass
872 finally:
873 break
874 self.assertEqual(count, 0)
875
876 for count in [0, 1]:
877 self.assertEqual(count, 0)
878 try:
879 continue
880 finally:
881 break
882 self.assertEqual(count, 0)
883
884 for count in [0, 1]:
885 self.assertEqual(count, 0)
886 try:
887 1/0
888 finally:
889 break
890 self.assertEqual(count, 0)
891
Serhiy Storchakafe2bbb12018-03-18 09:56:52 +0200892 def test_continue_in_finally(self):
893 count = 0
894 while count < 2:
895 count += 1
896 try:
897 pass
898 finally:
899 continue
900 break
901 self.assertEqual(count, 2)
902
903 count = 0
904 while count < 2:
905 count += 1
906 try:
907 break
908 finally:
909 continue
910 self.assertEqual(count, 2)
911
912 count = 0
913 while count < 2:
914 count += 1
915 try:
916 1/0
917 finally:
918 continue
919 break
920 self.assertEqual(count, 2)
921
922 for count in [0, 1]:
923 try:
924 pass
925 finally:
926 continue
927 break
928 self.assertEqual(count, 1)
929
930 for count in [0, 1]:
931 try:
932 break
933 finally:
934 continue
935 self.assertEqual(count, 1)
936
937 for count in [0, 1]:
938 try:
939 1/0
940 finally:
941 continue
942 break
943 self.assertEqual(count, 1)
944
Serhiy Storchaka7cc42c32018-01-02 02:38:35 +0200945 def test_return_in_finally(self):
946 def g1():
947 try:
948 pass
949 finally:
950 return 1
951 self.assertEqual(g1(), 1)
952
953 def g2():
954 try:
955 return 2
956 finally:
957 return 3
958 self.assertEqual(g2(), 3)
959
960 def g3():
961 try:
962 1/0
963 finally:
964 return 4
965 self.assertEqual(g3(), 4)
966
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500967 def test_yield(self):
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000968 # Allowed as standalone statement
969 def g(): yield 1
970 def g(): yield from ()
971 # Allowed as RHS of assignment
972 def g(): x = yield 1
973 def g(): x = yield from ()
974 # Ordinary yield accepts implicit tuples
975 def g(): yield 1, 1
976 def g(): x = yield 1, 1
977 # 'yield from' does not
978 check_syntax_error(self, "def g(): yield from (), 1")
979 check_syntax_error(self, "def g(): x = yield from (), 1")
980 # Requires parentheses as subexpression
981 def g(): 1, (yield 1)
982 def g(): 1, (yield from ())
983 check_syntax_error(self, "def g(): 1, yield 1")
984 check_syntax_error(self, "def g(): 1, yield from ()")
985 # Requires parentheses as call argument
986 def g(): f((yield 1))
987 def g(): f((yield 1), 1)
988 def g(): f((yield from ()))
989 def g(): f((yield from ()), 1)
David Cuthbertfd97d1f2018-09-21 18:31:15 -0700990 # Do not require parenthesis for tuple unpacking
991 def g(): rest = 4, 5, 6; yield 1, 2, 3, *rest
992 self.assertEquals(list(g()), [(1, 2, 3, 4, 5, 6)])
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000993 check_syntax_error(self, "def g(): f(yield 1)")
994 check_syntax_error(self, "def g(): f(yield 1, 1)")
995 check_syntax_error(self, "def g(): f(yield from ())")
996 check_syntax_error(self, "def g(): f(yield from (), 1)")
997 # Not allowed at top level
998 check_syntax_error(self, "yield")
999 check_syntax_error(self, "yield from")
1000 # Not allowed at class scope
Thomas Wouters89f507f2006-12-13 04:49:30 +00001001 check_syntax_error(self, "class foo:yield 1")
Nick Coghlan1f7ce622012-01-13 21:43:40 +10001002 check_syntax_error(self, "class foo:yield from ()")
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001003 # Check annotation refleak on SyntaxError
1004 check_syntax_error(self, "def g(a:(yield)): pass")
Guido van Rossum3bead091992-01-27 17:00:37 +00001005
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +02001006 def test_yield_in_comprehensions(self):
1007 # Check yield in comprehensions
1008 def g(): [x for x in [(yield 1)]]
1009 def g(): [x for x in [(yield from ())]]
1010
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +02001011 check = self.check_syntax_error
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +02001012 check("def g(): [(yield x) for x in ()]",
1013 "'yield' inside list comprehension")
1014 check("def g(): [x for x in () if not (yield x)]",
1015 "'yield' inside list comprehension")
1016 check("def g(): [y for x in () for y in [(yield x)]]",
1017 "'yield' inside list comprehension")
1018 check("def g(): {(yield x) for x in ()}",
1019 "'yield' inside set comprehension")
1020 check("def g(): {(yield x): x for x in ()}",
1021 "'yield' inside dict comprehension")
1022 check("def g(): {x: (yield x) for x in ()}",
1023 "'yield' inside dict comprehension")
1024 check("def g(): ((yield x) for x in ())",
1025 "'yield' inside generator expression")
1026 check("def g(): [(yield from x) for x in ()]",
1027 "'yield' inside list comprehension")
1028 check("class C: [(yield x) for x in ()]",
1029 "'yield' inside list comprehension")
1030 check("[(yield x) for x in ()]",
1031 "'yield' inside list comprehension")
1032
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001033 def test_raise(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001034 # 'raise' test [',' test]
Collin Winter828f04a2007-08-31 00:04:24 +00001035 try: raise RuntimeError('just testing')
Thomas Wouters89f507f2006-12-13 04:49:30 +00001036 except RuntimeError: pass
1037 try: raise KeyboardInterrupt
1038 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +00001039
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001040 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001041 # 'import' dotted_as_names
1042 import sys
1043 import time, sys
1044 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
1045 from time import time
1046 from time import (time)
1047 # not testable inside a function, but already done at top of the module
1048 # from sys import *
1049 from sys import path, argv
1050 from sys import (path, argv)
1051 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +00001052
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001053 def test_global(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001054 # 'global' NAME (',' NAME)*
1055 global a
1056 global a, b
1057 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +00001058
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001059 def test_nonlocal(self):
Benjamin Petersona933e522008-10-24 22:16:39 +00001060 # 'nonlocal' NAME (',' NAME)*
1061 x = 0
1062 y = 0
1063 def f():
1064 nonlocal x
1065 nonlocal x, y
1066
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001067 def test_assert(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001068 # assertTruestmt: 'assert' test [',' test]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001069 assert 1
1070 assert 1, 1
1071 assert lambda x:x
1072 assert 1, lambda x:x+1
Ezio Melotti6cc5bf72011-12-02 18:22:52 +02001073
1074 try:
1075 assert True
1076 except AssertionError as e:
1077 self.fail("'assert True' should not have raised an AssertionError")
1078
1079 try:
1080 assert True, 'this should always pass'
1081 except AssertionError as e:
1082 self.fail("'assert True, msg' should not have "
1083 "raised an AssertionError")
1084
1085 # these tests fail if python is run with -O, so check __debug__
1086 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
1087 def testAssert2(self):
Thomas Wouters80d373c2001-09-26 12:43:39 +00001088 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001089 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +00001090 except AssertionError as e:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001091 self.assertEqual(e.args[0], "msg")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001092 else:
Ezio Melotti6cc5bf72011-12-02 18:22:52 +02001093 self.fail("AssertionError not raised by assert 0")
1094
1095 try:
1096 assert False
1097 except AssertionError as e:
1098 self.assertEqual(len(e.args), 0)
1099 else:
1100 self.fail("AssertionError not raised by 'assert False'")
1101
Thomas Wouters80d373c2001-09-26 12:43:39 +00001102
Thomas Wouters89f507f2006-12-13 04:49:30 +00001103 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
1104 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001105
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001106 def test_if(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001107 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
1108 if 1: pass
1109 if 1: pass
1110 else: pass
1111 if 0: pass
1112 elif 0: pass
1113 if 0: pass
1114 elif 0: pass
1115 elif 0: pass
1116 elif 0: pass
1117 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001118
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001119 def test_while(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001120 # 'while' test ':' suite ['else' ':' suite]
1121 while 0: pass
1122 while 0: pass
1123 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001124
Christian Heimes969fe572008-01-25 11:23:10 +00001125 # Issue1920: "while 0" is optimized away,
1126 # ensure that the "else" clause is still present.
1127 x = 0
1128 while 0:
1129 x = 1
1130 else:
1131 x = 2
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001132 self.assertEqual(x, 2)
Christian Heimes969fe572008-01-25 11:23:10 +00001133
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001134 def test_for(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001135 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
1136 for i in 1, 2, 3: pass
1137 for i, j, k in (): pass
1138 else: pass
1139 class Squares:
1140 def __init__(self, max):
1141 self.max = max
1142 self.sofar = []
1143 def __len__(self): return len(self.sofar)
1144 def __getitem__(self, i):
1145 if not 0 <= i < self.max: raise IndexError
1146 n = len(self.sofar)
1147 while n <= i:
1148 self.sofar.append(n*n)
1149 n = n+1
1150 return self.sofar[i]
1151 n = 0
1152 for x in Squares(10): n = n+x
1153 if n != 285:
1154 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +00001155
Thomas Wouters89f507f2006-12-13 04:49:30 +00001156 result = []
1157 for x, in [(1,), (2,), (3,)]:
1158 result.append(x)
1159 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +00001160
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001161 def test_try(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001162 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
1163 ### | 'try' ':' suite 'finally' ':' suite
Guido van Rossumb940e112007-01-10 16:19:56 +00001164 ### except_clause: 'except' [expr ['as' expr]]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001165 try:
1166 1/0
1167 except ZeroDivisionError:
1168 pass
1169 else:
1170 pass
1171 try: 1/0
1172 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +00001173 except TypeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +00001174 except: pass
1175 else: pass
1176 try: 1/0
1177 except (EOFError, TypeError, ZeroDivisionError): pass
1178 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +00001179 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +00001180 try: pass
1181 finally: pass
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +00001182
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001183 def test_suite(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001184 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
1185 if 1: pass
1186 if 1:
1187 pass
1188 if 1:
1189 #
1190 #
1191 #
1192 pass
1193 pass
1194 #
1195 pass
1196 #
Guido van Rossum3bead091992-01-27 17:00:37 +00001197
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001198 def test_test(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001199 ### and_test ('or' and_test)*
1200 ### and_test: not_test ('and' not_test)*
1201 ### not_test: 'not' not_test | comparison
1202 if not 1: pass
1203 if 1 and 1: pass
1204 if 1 or 1: pass
1205 if not not not 1: pass
1206 if not 1 and 1 and 1: pass
1207 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001208
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001209 def test_comparison(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001210 ### comparison: expr (comp_op expr)*
1211 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
1212 if 1: pass
1213 x = (1 == 1)
1214 if 1 == 1: pass
1215 if 1 != 1: pass
1216 if 1 < 1: pass
1217 if 1 > 1: pass
1218 if 1 <= 1: pass
1219 if 1 >= 1: pass
1220 if 1 is 1: pass
1221 if 1 is not 1: pass
1222 if 1 in (): pass
1223 if 1 not in (): pass
1224 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 +00001225
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001226 def test_binary_mask_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001227 x = 1 & 1
1228 x = 1 ^ 1
1229 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001230
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001231 def test_shift_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001232 x = 1 << 1
1233 x = 1 >> 1
1234 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001235
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001236 def test_additive_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001237 x = 1
1238 x = 1 + 1
1239 x = 1 - 1 - 1
1240 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001241
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001242 def test_multiplicative_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001243 x = 1 * 1
1244 x = 1 / 1
1245 x = 1 % 1
1246 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001247
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001248 def test_unary_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001249 x = +1
1250 x = -1
1251 x = ~1
1252 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
1253 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +00001254
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001255 def test_selectors(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001256 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
1257 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +00001258
Thomas Wouters89f507f2006-12-13 04:49:30 +00001259 import sys, time
1260 c = sys.path[0]
1261 x = time.time()
1262 x = sys.modules['time'].time()
1263 a = '01234'
1264 c = a[0]
1265 c = a[-1]
1266 s = a[0:5]
1267 s = a[:5]
1268 s = a[0:]
1269 s = a[:]
1270 s = a[-5:]
1271 s = a[:-1]
1272 s = a[-4:-3]
1273 # A rough test of SF bug 1333982. http://python.org/sf/1333982
1274 # The testing here is fairly incomplete.
1275 # Test cases should include: commas with 1 and 2 colons
1276 d = {}
1277 d[1] = 1
1278 d[1,] = 2
1279 d[1,2] = 3
1280 d[1,2,3] = 4
1281 L = list(d)
Serhiy Storchaka0cc99c82018-01-04 10:36:35 +02001282 L.sort(key=lambda x: (type(x).__name__, x))
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001283 self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +00001284
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001285 def test_atoms(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001286 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
1287 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +00001288
Thomas Wouters89f507f2006-12-13 04:49:30 +00001289 x = (1)
1290 x = (1 or 2 or 3)
1291 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +00001292
Thomas Wouters89f507f2006-12-13 04:49:30 +00001293 x = []
1294 x = [1]
1295 x = [1 or 2 or 3]
1296 x = [1 or 2 or 3, 2, 3]
1297 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +00001298
Thomas Wouters89f507f2006-12-13 04:49:30 +00001299 x = {}
1300 x = {'one': 1}
1301 x = {'one': 1,}
1302 x = {'one' or 'two': 1 or 2}
1303 x = {'one': 1, 'two': 2}
1304 x = {'one': 1, 'two': 2,}
1305 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +00001306
Thomas Wouters89f507f2006-12-13 04:49:30 +00001307 x = {'one'}
1308 x = {'one', 1,}
1309 x = {'one', 'two', 'three'}
1310 x = {2, 3, 4,}
1311
1312 x = x
1313 x = 'x'
1314 x = 123
1315
1316 ### exprlist: expr (',' expr)* [',']
1317 ### testlist: test (',' test)* [',']
1318 # These have been exercised enough above
1319
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001320 def test_classdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001321 # 'class' NAME ['(' [testlist] ')'] ':' suite
1322 class B: pass
1323 class B2(): pass
1324 class C1(B): pass
1325 class C2(B): pass
1326 class D(C1, C2, B): pass
1327 class C:
1328 def meth1(self): pass
1329 def meth2(self, arg): pass
1330 def meth3(self, a1, a2): pass
1331
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001332 # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
1333 # decorators: decorator+
1334 # decorated: decorators (classdef | funcdef)
1335 def class_decorator(x): return x
1336 @class_decorator
1337 class G: pass
1338
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001339 def test_dictcomps(self):
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001340 # dictorsetmaker: ( (test ':' test (comp_for |
1341 # (',' test ':' test)* [','])) |
1342 # (test (comp_for | (',' test)* [','])) )
1343 nums = [1, 2, 3]
1344 self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
1345
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001346 def test_listcomps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001347 # list comprehension tests
1348 nums = [1, 2, 3, 4, 5]
1349 strs = ["Apple", "Banana", "Coconut"]
1350 spcs = [" Apple", " Banana ", "Coco nut "]
1351
1352 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
1353 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
1354 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
1355 self.assertEqual([(i, s) for i in nums for s in strs],
1356 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
1357 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
1358 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
1359 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
1360 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
1361 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
1362 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
1363 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
1364 (5, 'Banana'), (5, 'Coconut')])
1365 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
1366 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
1367
1368 def test_in_func(l):
1369 return [0 < x < 3 for x in l if x > 2]
1370
1371 self.assertEqual(test_in_func(nums), [False, False, False])
1372
1373 def test_nested_front():
1374 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
1375 [[1, 2], [3, 4], [5, 6]])
1376
1377 test_nested_front()
1378
1379 check_syntax_error(self, "[i, s for i in nums for s in strs]")
1380 check_syntax_error(self, "[x if y]")
1381
1382 suppliers = [
1383 (1, "Boeing"),
1384 (2, "Ford"),
1385 (3, "Macdonalds")
1386 ]
1387
1388 parts = [
1389 (10, "Airliner"),
1390 (20, "Engine"),
1391 (30, "Cheeseburger")
1392 ]
1393
1394 suppart = [
1395 (1, 10), (1, 20), (2, 20), (3, 30)
1396 ]
1397
1398 x = [
1399 (sname, pname)
1400 for (sno, sname) in suppliers
1401 for (pno, pname) in parts
1402 for (sp_sno, sp_pno) in suppart
1403 if sno == sp_sno and pno == sp_pno
1404 ]
1405
1406 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
1407 ('Macdonalds', 'Cheeseburger')])
1408
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001409 def test_genexps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001410 # generator expression tests
1411 g = ([x for x in range(10)] for x in range(1))
Georg Brandla18af4e2007-04-21 15:47:16 +00001412 self.assertEqual(next(g), [x for x in range(10)])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001413 try:
Georg Brandla18af4e2007-04-21 15:47:16 +00001414 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001415 self.fail('should produce StopIteration exception')
1416 except StopIteration:
1417 pass
1418
1419 a = 1
1420 try:
1421 g = (a for d in a)
Georg Brandla18af4e2007-04-21 15:47:16 +00001422 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001423 self.fail('should produce TypeError')
1424 except TypeError:
1425 pass
1426
1427 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
1428 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
1429
1430 a = [x for x in range(10)]
1431 b = (x for x in (y for y in a))
1432 self.assertEqual(sum(b), sum([x for x in range(10)]))
1433
1434 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
1435 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
1436 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
1437 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
1438 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
1439 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)]))
1440 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
1441 check_syntax_error(self, "foo(x for x in range(10), 100)")
1442 check_syntax_error(self, "foo(100, x for x in range(10))")
1443
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001444 def test_comprehension_specials(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001445 # test for outmost iterable precomputation
1446 x = 10; g = (i for i in range(x)); x = 5
1447 self.assertEqual(len(list(g)), 10)
1448
1449 # This should hold, since we're only precomputing outmost iterable.
1450 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
1451 x = 5; t = True;
1452 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
1453
1454 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
1455 # even though it's silly. Make sure it works (ifelse broke this.)
1456 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
1457 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
1458
1459 # verify unpacking single element tuples in listcomp/genexp.
1460 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
1461 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
1462
Benjamin Petersonf17ab892009-05-29 21:55:57 +00001463 def test_with_statement(self):
1464 class manager(object):
1465 def __enter__(self):
1466 return (1, 2)
1467 def __exit__(self, *args):
1468 pass
1469
1470 with manager():
1471 pass
1472 with manager() as x:
1473 pass
1474 with manager() as (x, y):
1475 pass
1476 with manager(), manager():
1477 pass
1478 with manager() as x, manager() as y:
1479 pass
1480 with manager() as x, manager():
1481 pass
1482
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001483 def test_if_else_expr(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001484 # Test ifelse expressions in various cases
1485 def _checkeval(msg, ret):
1486 "helper to check that evaluation of expressions is done correctly"
Victor Stinnerc6ec54d2016-04-12 18:33:41 +02001487 print(msg)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001488 return ret
1489
Nick Coghlan650f0d02007-04-15 12:05:43 +00001490 # the next line is not allowed anymore
1491 #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001492 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
1493 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])
1494 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
1495 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
1496 self.assertEqual((5 and 6 if 0 else 1), 1)
1497 self.assertEqual(((5 and 6) if 0 else 1), 1)
1498 self.assertEqual((5 and (6 if 1 else 1)), 6)
1499 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
1500 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
1501 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
1502 self.assertEqual((not 5 if 1 else 1), False)
1503 self.assertEqual((not 5 if 0 else 1), 1)
1504 self.assertEqual((6 + 1 if 1 else 2), 7)
1505 self.assertEqual((6 - 1 if 1 else 2), 5)
1506 self.assertEqual((6 * 2 if 1 else 4), 12)
1507 self.assertEqual((6 / 2 if 1 else 3), 3)
1508 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +00001509
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001510 def test_paren_evaluation(self):
1511 self.assertEqual(16 // (4 // 2), 8)
1512 self.assertEqual((16 // 4) // 2, 2)
1513 self.assertEqual(16 // 4 // 2, 2)
1514 self.assertTrue(False is (2 is 3))
1515 self.assertFalse((False is 2) is 3)
1516 self.assertFalse(False is 2 is 3)
1517
Benjamin Petersond51374e2014-04-09 23:55:56 -04001518 def test_matrix_mul(self):
1519 # This is not intended to be a comprehensive test, rather just to be few
1520 # samples of the @ operator in test_grammar.py.
1521 class M:
1522 def __matmul__(self, o):
1523 return 4
1524 def __imatmul__(self, o):
1525 self.other = o
1526 return self
1527 m = M()
1528 self.assertEqual(m @ m, 4)
1529 m @= 42
1530 self.assertEqual(m.other, 42)
1531
Yury Selivanov75445082015-05-11 22:57:16 -04001532 def test_async_await(self):
Yury Selivanov75445082015-05-11 22:57:16 -04001533 async def test():
1534 def sum():
Yury Selivanov8fb307c2015-07-22 13:33:45 +03001535 pass
Yury Selivanov75445082015-05-11 22:57:16 -04001536 if 1:
1537 await someobj()
1538
1539 self.assertEqual(test.__name__, 'test')
1540 self.assertTrue(bool(test.__code__.co_flags & inspect.CO_COROUTINE))
1541
1542 def decorator(func):
1543 setattr(func, '_marked', True)
1544 return func
1545
1546 @decorator
1547 async def test2():
1548 return 22
1549 self.assertTrue(test2._marked)
1550 self.assertEqual(test2.__name__, 'test2')
1551 self.assertTrue(bool(test2.__code__.co_flags & inspect.CO_COROUTINE))
1552
1553 def test_async_for(self):
1554 class Done(Exception): pass
1555
1556 class AIter:
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001557 def __aiter__(self):
Yury Selivanov75445082015-05-11 22:57:16 -04001558 return self
1559 async def __anext__(self):
1560 raise StopAsyncIteration
1561
1562 async def foo():
1563 async for i in AIter():
1564 pass
1565 async for i, j in AIter():
1566 pass
1567 async for i in AIter():
1568 pass
1569 else:
1570 pass
1571 raise Done
1572
1573 with self.assertRaises(Done):
1574 foo().send(None)
1575
1576 def test_async_with(self):
1577 class Done(Exception): pass
1578
1579 class manager:
1580 async def __aenter__(self):
1581 return (1, 2)
1582 async def __aexit__(self, *exc):
1583 return False
1584
1585 async def foo():
1586 async with manager():
1587 pass
1588 async with manager() as x:
1589 pass
1590 async with manager() as (x, y):
1591 pass
1592 async with manager(), manager():
1593 pass
1594 async with manager() as x, manager() as y:
1595 pass
1596 async with manager() as x, manager():
1597 pass
1598 raise Done
1599
1600 with self.assertRaises(Done):
1601 foo().send(None)
1602
Guido van Rossum3bead091992-01-27 17:00:37 +00001603
Thomas Wouters89f507f2006-12-13 04:49:30 +00001604if __name__ == '__main__':
Zachary Ware38c707e2015-04-13 15:00:43 -05001605 unittest.main()