blob: 78918ae250c4a30b2fe949c3d53bdbb414fecaf8 [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):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000827 # 'return' [testlist]
828 def g1(): return
829 def g2(): return 1
830 g1()
831 x = g2()
832 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000833
Serhiy Storchaka7cc42c32018-01-02 02:38:35 +0200834 def test_break_in_finally(self):
835 count = 0
836 while count < 2:
837 count += 1
838 try:
839 pass
840 finally:
841 break
842 self.assertEqual(count, 1)
843
844 count = 0
845 while count < 2:
846 count += 1
847 try:
848 continue
849 finally:
850 break
851 self.assertEqual(count, 1)
852
853 count = 0
854 while count < 2:
855 count += 1
856 try:
857 1/0
858 finally:
859 break
860 self.assertEqual(count, 1)
861
862 for count in [0, 1]:
863 self.assertEqual(count, 0)
864 try:
865 pass
866 finally:
867 break
868 self.assertEqual(count, 0)
869
870 for count in [0, 1]:
871 self.assertEqual(count, 0)
872 try:
873 continue
874 finally:
875 break
876 self.assertEqual(count, 0)
877
878 for count in [0, 1]:
879 self.assertEqual(count, 0)
880 try:
881 1/0
882 finally:
883 break
884 self.assertEqual(count, 0)
885
Serhiy Storchakafe2bbb12018-03-18 09:56:52 +0200886 def test_continue_in_finally(self):
887 count = 0
888 while count < 2:
889 count += 1
890 try:
891 pass
892 finally:
893 continue
894 break
895 self.assertEqual(count, 2)
896
897 count = 0
898 while count < 2:
899 count += 1
900 try:
901 break
902 finally:
903 continue
904 self.assertEqual(count, 2)
905
906 count = 0
907 while count < 2:
908 count += 1
909 try:
910 1/0
911 finally:
912 continue
913 break
914 self.assertEqual(count, 2)
915
916 for count in [0, 1]:
917 try:
918 pass
919 finally:
920 continue
921 break
922 self.assertEqual(count, 1)
923
924 for count in [0, 1]:
925 try:
926 break
927 finally:
928 continue
929 self.assertEqual(count, 1)
930
931 for count in [0, 1]:
932 try:
933 1/0
934 finally:
935 continue
936 break
937 self.assertEqual(count, 1)
938
Serhiy Storchaka7cc42c32018-01-02 02:38:35 +0200939 def test_return_in_finally(self):
940 def g1():
941 try:
942 pass
943 finally:
944 return 1
945 self.assertEqual(g1(), 1)
946
947 def g2():
948 try:
949 return 2
950 finally:
951 return 3
952 self.assertEqual(g2(), 3)
953
954 def g3():
955 try:
956 1/0
957 finally:
958 return 4
959 self.assertEqual(g3(), 4)
960
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500961 def test_yield(self):
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000962 # Allowed as standalone statement
963 def g(): yield 1
964 def g(): yield from ()
965 # Allowed as RHS of assignment
966 def g(): x = yield 1
967 def g(): x = yield from ()
968 # Ordinary yield accepts implicit tuples
969 def g(): yield 1, 1
970 def g(): x = yield 1, 1
971 # 'yield from' does not
972 check_syntax_error(self, "def g(): yield from (), 1")
973 check_syntax_error(self, "def g(): x = yield from (), 1")
974 # Requires parentheses as subexpression
975 def g(): 1, (yield 1)
976 def g(): 1, (yield from ())
977 check_syntax_error(self, "def g(): 1, yield 1")
978 check_syntax_error(self, "def g(): 1, yield from ()")
979 # Requires parentheses as call argument
980 def g(): f((yield 1))
981 def g(): f((yield 1), 1)
982 def g(): f((yield from ()))
983 def g(): f((yield from ()), 1)
984 check_syntax_error(self, "def g(): f(yield 1)")
985 check_syntax_error(self, "def g(): f(yield 1, 1)")
986 check_syntax_error(self, "def g(): f(yield from ())")
987 check_syntax_error(self, "def g(): f(yield from (), 1)")
988 # Not allowed at top level
989 check_syntax_error(self, "yield")
990 check_syntax_error(self, "yield from")
991 # Not allowed at class scope
Thomas Wouters89f507f2006-12-13 04:49:30 +0000992 check_syntax_error(self, "class foo:yield 1")
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000993 check_syntax_error(self, "class foo:yield from ()")
Yury Selivanovf315c1c2015-07-23 09:10:44 +0300994 # Check annotation refleak on SyntaxError
995 check_syntax_error(self, "def g(a:(yield)): pass")
Guido van Rossum3bead091992-01-27 17:00:37 +0000996
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200997 def test_yield_in_comprehensions(self):
998 # Check yield in comprehensions
999 def g(): [x for x in [(yield 1)]]
1000 def g(): [x for x in [(yield from ())]]
1001
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +02001002 check = self.check_syntax_error
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +02001003 check("def g(): [(yield x) for x in ()]",
1004 "'yield' inside list comprehension")
1005 check("def g(): [x for x in () if not (yield x)]",
1006 "'yield' inside list comprehension")
1007 check("def g(): [y for x in () for y in [(yield x)]]",
1008 "'yield' inside list comprehension")
1009 check("def g(): {(yield x) for x in ()}",
1010 "'yield' inside set comprehension")
1011 check("def g(): {(yield x): x for x in ()}",
1012 "'yield' inside dict comprehension")
1013 check("def g(): {x: (yield x) for x in ()}",
1014 "'yield' inside dict comprehension")
1015 check("def g(): ((yield x) for x in ())",
1016 "'yield' inside generator expression")
1017 check("def g(): [(yield from x) for x in ()]",
1018 "'yield' inside list comprehension")
1019 check("class C: [(yield x) for x in ()]",
1020 "'yield' inside list comprehension")
1021 check("[(yield x) for x in ()]",
1022 "'yield' inside list comprehension")
1023
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001024 def test_raise(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001025 # 'raise' test [',' test]
Collin Winter828f04a2007-08-31 00:04:24 +00001026 try: raise RuntimeError('just testing')
Thomas Wouters89f507f2006-12-13 04:49:30 +00001027 except RuntimeError: pass
1028 try: raise KeyboardInterrupt
1029 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +00001030
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001031 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001032 # 'import' dotted_as_names
1033 import sys
1034 import time, sys
1035 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
1036 from time import time
1037 from time import (time)
1038 # not testable inside a function, but already done at top of the module
1039 # from sys import *
1040 from sys import path, argv
1041 from sys import (path, argv)
1042 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +00001043
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001044 def test_global(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001045 # 'global' NAME (',' NAME)*
1046 global a
1047 global a, b
1048 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +00001049
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001050 def test_nonlocal(self):
Benjamin Petersona933e522008-10-24 22:16:39 +00001051 # 'nonlocal' NAME (',' NAME)*
1052 x = 0
1053 y = 0
1054 def f():
1055 nonlocal x
1056 nonlocal x, y
1057
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001058 def test_assert(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001059 # assertTruestmt: 'assert' test [',' test]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001060 assert 1
1061 assert 1, 1
1062 assert lambda x:x
1063 assert 1, lambda x:x+1
Ezio Melotti6cc5bf72011-12-02 18:22:52 +02001064
1065 try:
1066 assert True
1067 except AssertionError as e:
1068 self.fail("'assert True' should not have raised an AssertionError")
1069
1070 try:
1071 assert True, 'this should always pass'
1072 except AssertionError as e:
1073 self.fail("'assert True, msg' should not have "
1074 "raised an AssertionError")
1075
1076 # these tests fail if python is run with -O, so check __debug__
1077 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
1078 def testAssert2(self):
Thomas Wouters80d373c2001-09-26 12:43:39 +00001079 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001080 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +00001081 except AssertionError as e:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001082 self.assertEqual(e.args[0], "msg")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001083 else:
Ezio Melotti6cc5bf72011-12-02 18:22:52 +02001084 self.fail("AssertionError not raised by assert 0")
1085
1086 try:
1087 assert False
1088 except AssertionError as e:
1089 self.assertEqual(len(e.args), 0)
1090 else:
1091 self.fail("AssertionError not raised by 'assert False'")
1092
Thomas Wouters80d373c2001-09-26 12:43:39 +00001093
Thomas Wouters89f507f2006-12-13 04:49:30 +00001094 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
1095 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001096
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001097 def test_if(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001098 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
1099 if 1: pass
1100 if 1: pass
1101 else: pass
1102 if 0: pass
1103 elif 0: pass
1104 if 0: pass
1105 elif 0: pass
1106 elif 0: pass
1107 elif 0: pass
1108 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001109
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001110 def test_while(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001111 # 'while' test ':' suite ['else' ':' suite]
1112 while 0: pass
1113 while 0: pass
1114 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001115
Christian Heimes969fe572008-01-25 11:23:10 +00001116 # Issue1920: "while 0" is optimized away,
1117 # ensure that the "else" clause is still present.
1118 x = 0
1119 while 0:
1120 x = 1
1121 else:
1122 x = 2
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001123 self.assertEqual(x, 2)
Christian Heimes969fe572008-01-25 11:23:10 +00001124
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001125 def test_for(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001126 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
1127 for i in 1, 2, 3: pass
1128 for i, j, k in (): pass
1129 else: pass
1130 class Squares:
1131 def __init__(self, max):
1132 self.max = max
1133 self.sofar = []
1134 def __len__(self): return len(self.sofar)
1135 def __getitem__(self, i):
1136 if not 0 <= i < self.max: raise IndexError
1137 n = len(self.sofar)
1138 while n <= i:
1139 self.sofar.append(n*n)
1140 n = n+1
1141 return self.sofar[i]
1142 n = 0
1143 for x in Squares(10): n = n+x
1144 if n != 285:
1145 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +00001146
Thomas Wouters89f507f2006-12-13 04:49:30 +00001147 result = []
1148 for x, in [(1,), (2,), (3,)]:
1149 result.append(x)
1150 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +00001151
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001152 def test_try(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001153 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
1154 ### | 'try' ':' suite 'finally' ':' suite
Guido van Rossumb940e112007-01-10 16:19:56 +00001155 ### except_clause: 'except' [expr ['as' expr]]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001156 try:
1157 1/0
1158 except ZeroDivisionError:
1159 pass
1160 else:
1161 pass
1162 try: 1/0
1163 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +00001164 except TypeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +00001165 except: pass
1166 else: pass
1167 try: 1/0
1168 except (EOFError, TypeError, ZeroDivisionError): pass
1169 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +00001170 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +00001171 try: pass
1172 finally: pass
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +00001173
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001174 def test_suite(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001175 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
1176 if 1: pass
1177 if 1:
1178 pass
1179 if 1:
1180 #
1181 #
1182 #
1183 pass
1184 pass
1185 #
1186 pass
1187 #
Guido van Rossum3bead091992-01-27 17:00:37 +00001188
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001189 def test_test(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001190 ### and_test ('or' and_test)*
1191 ### and_test: not_test ('and' not_test)*
1192 ### not_test: 'not' not_test | comparison
1193 if not 1: pass
1194 if 1 and 1: pass
1195 if 1 or 1: pass
1196 if not not not 1: pass
1197 if not 1 and 1 and 1: pass
1198 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001199
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001200 def test_comparison(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001201 ### comparison: expr (comp_op expr)*
1202 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
1203 if 1: pass
1204 x = (1 == 1)
1205 if 1 == 1: pass
1206 if 1 != 1: pass
1207 if 1 < 1: pass
1208 if 1 > 1: pass
1209 if 1 <= 1: pass
1210 if 1 >= 1: pass
1211 if 1 is 1: pass
1212 if 1 is not 1: pass
1213 if 1 in (): pass
1214 if 1 not in (): pass
1215 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 +00001216
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001217 def test_binary_mask_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001218 x = 1 & 1
1219 x = 1 ^ 1
1220 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001221
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001222 def test_shift_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001223 x = 1 << 1
1224 x = 1 >> 1
1225 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001226
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001227 def test_additive_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001228 x = 1
1229 x = 1 + 1
1230 x = 1 - 1 - 1
1231 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001232
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001233 def test_multiplicative_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001234 x = 1 * 1
1235 x = 1 / 1
1236 x = 1 % 1
1237 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001238
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001239 def test_unary_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001240 x = +1
1241 x = -1
1242 x = ~1
1243 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
1244 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +00001245
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001246 def test_selectors(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001247 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
1248 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +00001249
Thomas Wouters89f507f2006-12-13 04:49:30 +00001250 import sys, time
1251 c = sys.path[0]
1252 x = time.time()
1253 x = sys.modules['time'].time()
1254 a = '01234'
1255 c = a[0]
1256 c = a[-1]
1257 s = a[0:5]
1258 s = a[:5]
1259 s = a[0:]
1260 s = a[:]
1261 s = a[-5:]
1262 s = a[:-1]
1263 s = a[-4:-3]
1264 # A rough test of SF bug 1333982. http://python.org/sf/1333982
1265 # The testing here is fairly incomplete.
1266 # Test cases should include: commas with 1 and 2 colons
1267 d = {}
1268 d[1] = 1
1269 d[1,] = 2
1270 d[1,2] = 3
1271 d[1,2,3] = 4
1272 L = list(d)
Serhiy Storchaka0cc99c82018-01-04 10:36:35 +02001273 L.sort(key=lambda x: (type(x).__name__, x))
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001274 self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +00001275
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001276 def test_atoms(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001277 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
1278 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +00001279
Thomas Wouters89f507f2006-12-13 04:49:30 +00001280 x = (1)
1281 x = (1 or 2 or 3)
1282 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +00001283
Thomas Wouters89f507f2006-12-13 04:49:30 +00001284 x = []
1285 x = [1]
1286 x = [1 or 2 or 3]
1287 x = [1 or 2 or 3, 2, 3]
1288 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +00001289
Thomas Wouters89f507f2006-12-13 04:49:30 +00001290 x = {}
1291 x = {'one': 1}
1292 x = {'one': 1,}
1293 x = {'one' or 'two': 1 or 2}
1294 x = {'one': 1, 'two': 2}
1295 x = {'one': 1, 'two': 2,}
1296 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +00001297
Thomas Wouters89f507f2006-12-13 04:49:30 +00001298 x = {'one'}
1299 x = {'one', 1,}
1300 x = {'one', 'two', 'three'}
1301 x = {2, 3, 4,}
1302
1303 x = x
1304 x = 'x'
1305 x = 123
1306
1307 ### exprlist: expr (',' expr)* [',']
1308 ### testlist: test (',' test)* [',']
1309 # These have been exercised enough above
1310
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001311 def test_classdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001312 # 'class' NAME ['(' [testlist] ')'] ':' suite
1313 class B: pass
1314 class B2(): pass
1315 class C1(B): pass
1316 class C2(B): pass
1317 class D(C1, C2, B): pass
1318 class C:
1319 def meth1(self): pass
1320 def meth2(self, arg): pass
1321 def meth3(self, a1, a2): pass
1322
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001323 # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
1324 # decorators: decorator+
1325 # decorated: decorators (classdef | funcdef)
1326 def class_decorator(x): return x
1327 @class_decorator
1328 class G: pass
1329
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001330 def test_dictcomps(self):
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001331 # dictorsetmaker: ( (test ':' test (comp_for |
1332 # (',' test ':' test)* [','])) |
1333 # (test (comp_for | (',' test)* [','])) )
1334 nums = [1, 2, 3]
1335 self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
1336
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001337 def test_listcomps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001338 # list comprehension tests
1339 nums = [1, 2, 3, 4, 5]
1340 strs = ["Apple", "Banana", "Coconut"]
1341 spcs = [" Apple", " Banana ", "Coco nut "]
1342
1343 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
1344 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
1345 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
1346 self.assertEqual([(i, s) for i in nums for s in strs],
1347 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
1348 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
1349 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
1350 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
1351 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
1352 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
1353 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
1354 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
1355 (5, 'Banana'), (5, 'Coconut')])
1356 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
1357 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
1358
1359 def test_in_func(l):
1360 return [0 < x < 3 for x in l if x > 2]
1361
1362 self.assertEqual(test_in_func(nums), [False, False, False])
1363
1364 def test_nested_front():
1365 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
1366 [[1, 2], [3, 4], [5, 6]])
1367
1368 test_nested_front()
1369
1370 check_syntax_error(self, "[i, s for i in nums for s in strs]")
1371 check_syntax_error(self, "[x if y]")
1372
1373 suppliers = [
1374 (1, "Boeing"),
1375 (2, "Ford"),
1376 (3, "Macdonalds")
1377 ]
1378
1379 parts = [
1380 (10, "Airliner"),
1381 (20, "Engine"),
1382 (30, "Cheeseburger")
1383 ]
1384
1385 suppart = [
1386 (1, 10), (1, 20), (2, 20), (3, 30)
1387 ]
1388
1389 x = [
1390 (sname, pname)
1391 for (sno, sname) in suppliers
1392 for (pno, pname) in parts
1393 for (sp_sno, sp_pno) in suppart
1394 if sno == sp_sno and pno == sp_pno
1395 ]
1396
1397 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
1398 ('Macdonalds', 'Cheeseburger')])
1399
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001400 def test_genexps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001401 # generator expression tests
1402 g = ([x for x in range(10)] for x in range(1))
Georg Brandla18af4e2007-04-21 15:47:16 +00001403 self.assertEqual(next(g), [x for x in range(10)])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001404 try:
Georg Brandla18af4e2007-04-21 15:47:16 +00001405 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001406 self.fail('should produce StopIteration exception')
1407 except StopIteration:
1408 pass
1409
1410 a = 1
1411 try:
1412 g = (a for d in a)
Georg Brandla18af4e2007-04-21 15:47:16 +00001413 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001414 self.fail('should produce TypeError')
1415 except TypeError:
1416 pass
1417
1418 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
1419 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
1420
1421 a = [x for x in range(10)]
1422 b = (x for x in (y for y in a))
1423 self.assertEqual(sum(b), sum([x for x in range(10)]))
1424
1425 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
1426 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
1427 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
1428 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
1429 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
1430 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)]))
1431 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
1432 check_syntax_error(self, "foo(x for x in range(10), 100)")
1433 check_syntax_error(self, "foo(100, x for x in range(10))")
1434
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001435 def test_comprehension_specials(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001436 # test for outmost iterable precomputation
1437 x = 10; g = (i for i in range(x)); x = 5
1438 self.assertEqual(len(list(g)), 10)
1439
1440 # This should hold, since we're only precomputing outmost iterable.
1441 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
1442 x = 5; t = True;
1443 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
1444
1445 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
1446 # even though it's silly. Make sure it works (ifelse broke this.)
1447 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
1448 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
1449
1450 # verify unpacking single element tuples in listcomp/genexp.
1451 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
1452 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
1453
Benjamin Petersonf17ab892009-05-29 21:55:57 +00001454 def test_with_statement(self):
1455 class manager(object):
1456 def __enter__(self):
1457 return (1, 2)
1458 def __exit__(self, *args):
1459 pass
1460
1461 with manager():
1462 pass
1463 with manager() as x:
1464 pass
1465 with manager() as (x, y):
1466 pass
1467 with manager(), manager():
1468 pass
1469 with manager() as x, manager() as y:
1470 pass
1471 with manager() as x, manager():
1472 pass
1473
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001474 def test_if_else_expr(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001475 # Test ifelse expressions in various cases
1476 def _checkeval(msg, ret):
1477 "helper to check that evaluation of expressions is done correctly"
Victor Stinnerc6ec54d2016-04-12 18:33:41 +02001478 print(msg)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001479 return ret
1480
Nick Coghlan650f0d02007-04-15 12:05:43 +00001481 # the next line is not allowed anymore
1482 #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001483 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
1484 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])
1485 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
1486 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
1487 self.assertEqual((5 and 6 if 0 else 1), 1)
1488 self.assertEqual(((5 and 6) if 0 else 1), 1)
1489 self.assertEqual((5 and (6 if 1 else 1)), 6)
1490 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
1491 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
1492 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
1493 self.assertEqual((not 5 if 1 else 1), False)
1494 self.assertEqual((not 5 if 0 else 1), 1)
1495 self.assertEqual((6 + 1 if 1 else 2), 7)
1496 self.assertEqual((6 - 1 if 1 else 2), 5)
1497 self.assertEqual((6 * 2 if 1 else 4), 12)
1498 self.assertEqual((6 / 2 if 1 else 3), 3)
1499 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +00001500
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001501 def test_paren_evaluation(self):
1502 self.assertEqual(16 // (4 // 2), 8)
1503 self.assertEqual((16 // 4) // 2, 2)
1504 self.assertEqual(16 // 4 // 2, 2)
1505 self.assertTrue(False is (2 is 3))
1506 self.assertFalse((False is 2) is 3)
1507 self.assertFalse(False is 2 is 3)
1508
Benjamin Petersond51374e2014-04-09 23:55:56 -04001509 def test_matrix_mul(self):
1510 # This is not intended to be a comprehensive test, rather just to be few
1511 # samples of the @ operator in test_grammar.py.
1512 class M:
1513 def __matmul__(self, o):
1514 return 4
1515 def __imatmul__(self, o):
1516 self.other = o
1517 return self
1518 m = M()
1519 self.assertEqual(m @ m, 4)
1520 m @= 42
1521 self.assertEqual(m.other, 42)
1522
Yury Selivanov75445082015-05-11 22:57:16 -04001523 def test_async_await(self):
Yury Selivanov75445082015-05-11 22:57:16 -04001524 async def test():
1525 def sum():
Yury Selivanov8fb307c2015-07-22 13:33:45 +03001526 pass
Yury Selivanov75445082015-05-11 22:57:16 -04001527 if 1:
1528 await someobj()
1529
1530 self.assertEqual(test.__name__, 'test')
1531 self.assertTrue(bool(test.__code__.co_flags & inspect.CO_COROUTINE))
1532
1533 def decorator(func):
1534 setattr(func, '_marked', True)
1535 return func
1536
1537 @decorator
1538 async def test2():
1539 return 22
1540 self.assertTrue(test2._marked)
1541 self.assertEqual(test2.__name__, 'test2')
1542 self.assertTrue(bool(test2.__code__.co_flags & inspect.CO_COROUTINE))
1543
1544 def test_async_for(self):
1545 class Done(Exception): pass
1546
1547 class AIter:
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001548 def __aiter__(self):
Yury Selivanov75445082015-05-11 22:57:16 -04001549 return self
1550 async def __anext__(self):
1551 raise StopAsyncIteration
1552
1553 async def foo():
1554 async for i in AIter():
1555 pass
1556 async for i, j in AIter():
1557 pass
1558 async for i in AIter():
1559 pass
1560 else:
1561 pass
1562 raise Done
1563
1564 with self.assertRaises(Done):
1565 foo().send(None)
1566
1567 def test_async_with(self):
1568 class Done(Exception): pass
1569
1570 class manager:
1571 async def __aenter__(self):
1572 return (1, 2)
1573 async def __aexit__(self, *exc):
1574 return False
1575
1576 async def foo():
1577 async with manager():
1578 pass
1579 async with manager() as x:
1580 pass
1581 async with manager() as (x, y):
1582 pass
1583 async with manager(), manager():
1584 pass
1585 async with manager() as x, manager() as y:
1586 pass
1587 async with manager() as x, manager():
1588 pass
1589 raise Done
1590
1591 with self.assertRaises(Done):
1592 foo().send(None)
1593
Guido van Rossum3bead091992-01-27 17:00:37 +00001594
Thomas Wouters89f507f2006-12-13 04:49:30 +00001595if __name__ == '__main__':
Zachary Ware38c707e2015-04-13 15:00:43 -05001596 unittest.main()