blob: 67a61d4ab5b65edb0277744f4a5b6547a94fa20d [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
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500103 def test_backslash(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000104 # Backslash means line continuation:
105 x = 1 \
106 + 1
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000107 self.assertEqual(x, 2, 'backslash for line continuation')
Guido van Rossum3bead091992-01-27 17:00:37 +0000108
Thomas Wouters89f507f2006-12-13 04:49:30 +0000109 # Backslash does not means continuation in comments :\
110 x = 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000111 self.assertEqual(x, 0, 'backslash ending comment')
Guido van Rossum3bead091992-01-27 17:00:37 +0000112
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500113 def test_plain_integers(self):
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000114 self.assertEqual(type(000), type(0))
115 self.assertEqual(0xff, 255)
116 self.assertEqual(0o377, 255)
117 self.assertEqual(2147483647, 0o17777777777)
118 self.assertEqual(0b1001, 9)
Georg Brandlfceab5a2008-01-19 20:08:23 +0000119 # "0x" is not a valid literal
120 self.assertRaises(SyntaxError, eval, "0x")
Christian Heimesa37d4c62007-12-04 23:02:19 +0000121 from sys import maxsize
122 if maxsize == 2147483647:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000123 self.assertEqual(-2147483647-1, -0o20000000000)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000124 # XXX -2147483648
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000125 self.assertTrue(0o37777777777 > 0)
126 self.assertTrue(0xffffffff > 0)
127 self.assertTrue(0b1111111111111111111111111111111 > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000128 for s in ('2147483648', '0o40000000000', '0x100000000',
129 '0b10000000000000000000000000000000'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000130 try:
131 x = eval(s)
132 except OverflowError:
133 self.fail("OverflowError on huge integer literal %r" % s)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000134 elif maxsize == 9223372036854775807:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000135 self.assertEqual(-9223372036854775807-1, -0o1000000000000000000000)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000136 self.assertTrue(0o1777777777777777777777 > 0)
137 self.assertTrue(0xffffffffffffffff > 0)
138 self.assertTrue(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000139 for s in '9223372036854775808', '0o2000000000000000000000', \
140 '0x10000000000000000', \
141 '0b100000000000000000000000000000000000000000000000000000000000000':
Thomas Wouters89f507f2006-12-13 04:49:30 +0000142 try:
143 x = eval(s)
144 except OverflowError:
145 self.fail("OverflowError on huge integer literal %r" % s)
146 else:
Christian Heimesa37d4c62007-12-04 23:02:19 +0000147 self.fail('Weird maxsize value %r' % maxsize)
Guido van Rossum3bead091992-01-27 17:00:37 +0000148
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500149 def test_long_integers(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000150 x = 0
Guido van Rossume2a383d2007-01-15 16:59:06 +0000151 x = 0xffffffffffffffff
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000152 x = 0Xffffffffffffffff
153 x = 0o77777777777777777
154 x = 0O77777777777777777
Guido van Rossume2a383d2007-01-15 16:59:06 +0000155 x = 123456789012345678901234567890
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000156 x = 0b100000000000000000000000000000000000000000000000000000000000000000000
157 x = 0B111111111111111111111111111111111111111111111111111111111111111111111
Guido van Rossum3bead091992-01-27 17:00:37 +0000158
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500159 def test_floats(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000160 x = 3.14
161 x = 314.
162 x = 0.314
163 # XXX x = 000.314
164 x = .314
165 x = 3e14
166 x = 3E14
167 x = 3e-14
168 x = 3e+14
169 x = 3.e14
170 x = .3e14
171 x = 3.1e4
Guido van Rossum3bead091992-01-27 17:00:37 +0000172
Benjamin Petersonc4161622014-06-07 12:36:39 -0700173 def test_float_exponent_tokenization(self):
174 # See issue 21642.
175 self.assertEqual(1 if 1else 0, 1)
176 self.assertEqual(1 if 0else 0, 0)
177 self.assertRaises(SyntaxError, eval, "0 if 1Else 0")
178
Brett Cannona721aba2016-09-09 14:57:09 -0700179 def test_underscore_literals(self):
180 for lit in VALID_UNDERSCORE_LITERALS:
181 self.assertEqual(eval(lit), eval(lit.replace('_', '')))
182 for lit in INVALID_UNDERSCORE_LITERALS:
183 self.assertRaises(SyntaxError, eval, lit)
184 # Sanity check: no literal begins with an underscore
185 self.assertRaises(NameError, eval, "_0")
186
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500187 def test_string_literals(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000188 x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y)
189 x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39)
190 x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000191 x = "doesn't \"shrink\" does it"
192 y = 'doesn\'t "shrink" does it'
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000193 self.assertTrue(len(x) == 24 and x == y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000194 x = "does \"shrink\" doesn't it"
195 y = 'does "shrink" doesn\'t it'
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000196 self.assertTrue(len(x) == 24 and x == y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000197 x = """
Guido van Rossumb6775db1994-08-01 11:34:53 +0000198The "quick"
199brown fox
200jumps over
201the 'lazy' dog.
202"""
Thomas Wouters89f507f2006-12-13 04:49:30 +0000203 y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000204 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000205 y = '''
Guido van Rossumb6775db1994-08-01 11:34:53 +0000206The "quick"
207brown fox
208jumps over
209the 'lazy' dog.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000210'''
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000211 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000212 y = "\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000213The \"quick\"\n\
214brown fox\n\
215jumps over\n\
216the 'lazy' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000217"
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000218 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000219 y = '\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000220The \"quick\"\n\
221brown fox\n\
222jumps over\n\
223the \'lazy\' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000224'
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000225 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000226
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500227 def test_ellipsis(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000228 x = ...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000229 self.assertTrue(x is Ellipsis)
Georg Brandldde00282007-03-18 19:01:53 +0000230 self.assertRaises(SyntaxError, eval, ".. .")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000231
Benjamin Peterson758888d2011-05-30 11:12:38 -0500232 def test_eof_error(self):
233 samples = ("def foo(", "\ndef foo(", "def foo(\n")
234 for s in samples:
235 with self.assertRaises(SyntaxError) as cm:
236 compile(s, "<test>", "exec")
237 self.assertIn("unexpected EOF", str(cm.exception))
238
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700239var_annot_global: int # a global annotated is necessary for test_var_annot
240
241# custom namespace for testing __annotations__
242
243class CNS:
244 def __init__(self):
245 self._dct = {}
246 def __setitem__(self, item, value):
247 self._dct[item.lower()] = value
248 def __getitem__(self, item):
249 return self._dct[item]
250
251
Thomas Wouters89f507f2006-12-13 04:49:30 +0000252class GrammarTests(unittest.TestCase):
253
254 # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
255 # XXX can't test in a script -- this rule is only used when interactive
256
257 # file_input: (NEWLINE | stmt)* ENDMARKER
258 # Being tested as this very moment this very module
259
260 # expr_input: testlist NEWLINE
261 # XXX Hard to test -- used only in calls to input()
262
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500263 def test_eval_input(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000264 # testlist ENDMARKER
265 x = eval('1, 0 or 1')
266
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700267 def test_var_annot_basics(self):
268 # all these should be allowed
269 var1: int = 5
270 var2: [int, str]
271 my_lst = [42]
272 def one():
273 return 1
274 int.new_attr: int
275 [list][0]: type
276 my_lst[one()-1]: int = 5
277 self.assertEqual(my_lst, [5])
278
279 def test_var_annot_syntax_errors(self):
280 # parser pass
281 check_syntax_error(self, "def f: int")
282 check_syntax_error(self, "x: int: str")
283 check_syntax_error(self, "def f():\n"
284 " nonlocal x: int\n")
285 # AST pass
286 check_syntax_error(self, "[x, 0]: int\n")
287 check_syntax_error(self, "f(): int\n")
288 check_syntax_error(self, "(x,): int")
289 check_syntax_error(self, "def f():\n"
290 " (x, y): int = (1, 2)\n")
291 # symtable pass
292 check_syntax_error(self, "def f():\n"
293 " x: int\n"
294 " global x\n")
295 check_syntax_error(self, "def f():\n"
296 " global x\n"
297 " x: int\n")
298
299 def test_var_annot_basic_semantics(self):
300 # execution order
301 with self.assertRaises(ZeroDivisionError):
302 no_name[does_not_exist]: no_name_again = 1/0
303 with self.assertRaises(NameError):
304 no_name[does_not_exist]: 1/0 = 0
305 global var_annot_global
306
307 # function semantics
308 def f():
309 st: str = "Hello"
310 a.b: int = (1, 2)
311 return st
312 self.assertEqual(f.__annotations__, {})
313 def f_OK():
314 x: 1/0
315 f_OK()
316 def fbad():
317 x: int
318 print(x)
319 with self.assertRaises(UnboundLocalError):
320 fbad()
321 def f2bad():
322 (no_such_global): int
323 print(no_such_global)
324 try:
325 f2bad()
326 except Exception as e:
327 self.assertIs(type(e), NameError)
328
329 # class semantics
330 class C:
Guido van Rossum015d8742016-09-11 09:45:24 -0700331 __foo: int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700332 s: str = "attr"
333 z = 2
334 def __init__(self, x):
335 self.x: int = x
Guido van Rossum015d8742016-09-11 09:45:24 -0700336 self.assertEqual(C.__annotations__, {'_C__foo': int, 's': str})
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700337 with self.assertRaises(NameError):
338 class CBad:
339 no_such_name_defined.attr: int = 0
340 with self.assertRaises(NameError):
341 class Cbad2(C):
342 x: int
343 x.y: list = []
344
345 def test_var_annot_metaclass_semantics(self):
346 class CMeta(type):
347 @classmethod
348 def __prepare__(metacls, name, bases, **kwds):
349 return {'__annotations__': CNS()}
350 class CC(metaclass=CMeta):
351 XX: 'ANNOT'
352 self.assertEqual(CC.__annotations__['xx'], 'ANNOT')
353
354 def test_var_annot_module_semantics(self):
355 with self.assertRaises(AttributeError):
356 print(test.__annotations__)
357 self.assertEqual(ann_module.__annotations__,
358 {1: 2, 'x': int, 'y': str, 'f': typing.Tuple[int, int]})
359 self.assertEqual(ann_module.M.__annotations__,
360 {'123': 123, 'o': type})
361 self.assertEqual(ann_module2.__annotations__, {})
362 self.assertEqual(typing.get_type_hints(ann_module2.CV,
363 ann_module2.__dict__),
364 ChainMap({'var': typing.ClassVar[ann_module2.CV]}, {}))
365
366 def test_var_annot_in_module(self):
367 # check that functions fail the same way when executed
368 # outside of module where they were defined
369 from test.ann_module3 import f_bad_ann, g_bad_ann, D_bad_ann
370 with self.assertRaises(NameError):
371 f_bad_ann()
372 with self.assertRaises(NameError):
373 g_bad_ann()
374 with self.assertRaises(NameError):
375 D_bad_ann(5)
376
377 def test_var_annot_simple_exec(self):
378 gns = {}; lns= {}
379 exec("'docstring'\n"
380 "__annotations__[1] = 2\n"
381 "x: int = 5\n", gns, lns)
382 self.assertEqual(lns["__annotations__"], {1: 2, 'x': int})
383 with self.assertRaises(KeyError):
384 gns['__annotations__']
385
386 def test_var_annot_custom_maps(self):
387 # tests with custom locals() and __annotations__
388 ns = {'__annotations__': CNS()}
389 exec('X: int; Z: str = "Z"; (w): complex = 1j', ns)
390 self.assertEqual(ns['__annotations__']['x'], int)
391 self.assertEqual(ns['__annotations__']['z'], str)
392 with self.assertRaises(KeyError):
393 ns['__annotations__']['w']
394 nonloc_ns = {}
395 class CNS2:
396 def __init__(self):
397 self._dct = {}
398 def __setitem__(self, item, value):
399 nonlocal nonloc_ns
400 self._dct[item] = value
401 nonloc_ns[item] = value
402 def __getitem__(self, item):
403 return self._dct[item]
404 exec('x: int = 1', {}, CNS2())
405 self.assertEqual(nonloc_ns['__annotations__']['x'], int)
406
407 def test_var_annot_refleak(self):
408 # complex case: custom locals plus custom __annotations__
409 # this was causing refleak
410 cns = CNS()
411 nonloc_ns = {'__annotations__': cns}
412 class CNS2:
413 def __init__(self):
414 self._dct = {'__annotations__': cns}
415 def __setitem__(self, item, value):
416 nonlocal nonloc_ns
417 self._dct[item] = value
418 nonloc_ns[item] = value
419 def __getitem__(self, item):
420 return self._dct[item]
421 exec('X: str', {}, CNS2())
422 self.assertEqual(nonloc_ns['__annotations__']['x'], str)
423
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500424 def test_funcdef(self):
Neal Norwitzc1505362006-12-28 06:47:50 +0000425 ### [decorators] 'def' NAME parameters ['->' test] ':' suite
426 ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
427 ### decorators: decorator+
428 ### parameters: '(' [typedargslist] ')'
429 ### typedargslist: ((tfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000430 ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000431 ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000432 ### tfpdef: NAME [':' test]
Neal Norwitzc1505362006-12-28 06:47:50 +0000433 ### varargslist: ((vfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000434 ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000435 ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000436 ### vfpdef: NAME
Thomas Wouters89f507f2006-12-13 04:49:30 +0000437 def f1(): pass
438 f1()
439 f1(*())
440 f1(*(), **{})
441 def f2(one_argument): pass
442 def f3(two, arguments): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000443 self.assertEqual(f2.__code__.co_varnames, ('one_argument',))
444 self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments'))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000445 def a1(one_arg,): pass
446 def a2(two, args,): pass
447 def v0(*rest): pass
448 def v1(a, *rest): pass
449 def v2(a, b, *rest): pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000450
451 f1()
452 f2(1)
453 f2(1,)
454 f3(1, 2)
455 f3(1, 2,)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000456 v0()
457 v0(1)
458 v0(1,)
459 v0(1,2)
460 v0(1,2,3,4,5,6,7,8,9,0)
461 v1(1)
462 v1(1,)
463 v1(1,2)
464 v1(1,2,3)
465 v1(1,2,3,4,5,6,7,8,9,0)
466 v2(1,2)
467 v2(1,2,3)
468 v2(1,2,3,4)
469 v2(1,2,3,4,5,6,7,8,9,0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000470
Thomas Wouters89f507f2006-12-13 04:49:30 +0000471 def d01(a=1): pass
472 d01()
473 d01(1)
474 d01(*(1,))
Yury Selivanov14acf5f2015-08-05 17:54:10 -0400475 d01(*[] or [2])
476 d01(*() or (), *{} and (), **() or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000477 d01(**{'a':2})
Benjamin Petersonde12b792015-05-16 09:44:45 -0400478 d01(**{'a':2} or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000479 def d11(a, b=1): pass
480 d11(1)
481 d11(1, 2)
482 d11(1, **{'b':2})
483 def d21(a, b, c=1): pass
484 d21(1, 2)
485 d21(1, 2, 3)
486 d21(*(1, 2, 3))
487 d21(1, *(2, 3))
488 d21(1, 2, *(3,))
489 d21(1, 2, **{'c':3})
490 def d02(a=1, b=2): pass
491 d02()
492 d02(1)
493 d02(1, 2)
494 d02(*(1, 2))
495 d02(1, *(2,))
496 d02(1, **{'b':2})
497 d02(**{'a': 1, 'b': 2})
498 def d12(a, b=1, c=2): pass
499 d12(1)
500 d12(1, 2)
501 d12(1, 2, 3)
502 def d22(a, b, c=1, d=2): pass
503 d22(1, 2)
504 d22(1, 2, 3)
505 d22(1, 2, 3, 4)
506 def d01v(a=1, *rest): pass
507 d01v()
508 d01v(1)
509 d01v(1, 2)
510 d01v(*(1, 2, 3, 4))
511 d01v(*(1,))
512 d01v(**{'a':2})
513 def d11v(a, b=1, *rest): pass
514 d11v(1)
515 d11v(1, 2)
516 d11v(1, 2, 3)
517 def d21v(a, b, c=1, *rest): pass
518 d21v(1, 2)
519 d21v(1, 2, 3)
520 d21v(1, 2, 3, 4)
521 d21v(*(1, 2, 3, 4))
522 d21v(1, 2, **{'c': 3})
523 def d02v(a=1, b=2, *rest): pass
524 d02v()
525 d02v(1)
526 d02v(1, 2)
527 d02v(1, 2, 3)
528 d02v(1, *(2, 3, 4))
529 d02v(**{'a': 1, 'b': 2})
530 def d12v(a, b=1, c=2, *rest): pass
531 d12v(1)
532 d12v(1, 2)
533 d12v(1, 2, 3)
534 d12v(1, 2, 3, 4)
535 d12v(*(1, 2, 3, 4))
536 d12v(1, 2, *(3, 4, 5))
537 d12v(1, *(2,), **{'c': 3})
538 def d22v(a, b, c=1, d=2, *rest): pass
539 d22v(1, 2)
540 d22v(1, 2, 3)
541 d22v(1, 2, 3, 4)
542 d22v(1, 2, 3, 4, 5)
543 d22v(*(1, 2, 3, 4))
544 d22v(1, 2, *(3, 4, 5))
545 d22v(1, *(2, 3), **{'d': 4})
Georg Brandld8b690f2008-05-16 17:28:50 +0000546
547 # keyword argument type tests
548 try:
549 str('x', **{b'foo':1 })
550 except TypeError:
551 pass
552 else:
553 self.fail('Bytes should not work as keyword argument names')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000554 # keyword only argument tests
555 def pos0key1(*, key): return key
556 pos0key1(key=100)
557 def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
558 pos2key2(1, 2, k1=100)
559 pos2key2(1, 2, k1=100, k2=200)
560 pos2key2(1, 2, k2=100, k1=200)
561 def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
562 pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
563 pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
564
Robert Collinsdf395992015-08-12 08:00:06 +1200565 self.assertRaises(SyntaxError, eval, "def f(*): pass")
566 self.assertRaises(SyntaxError, eval, "def f(*,): pass")
567 self.assertRaises(SyntaxError, eval, "def f(*, **kwds): pass")
568
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000569 # keyword arguments after *arglist
570 def f(*args, **kwargs):
571 return args, kwargs
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000572 self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000573 {'x':2, 'y':5}))
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400574 self.assertEqual(f(1, *(2,3), 4), ((1, 2, 3, 4), {}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000575 self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400576 self.assertEqual(f(**{'eggs':'scrambled', 'spam':'fried'}),
577 ((), {'eggs':'scrambled', 'spam':'fried'}))
578 self.assertEqual(f(spam='fried', **{'eggs':'scrambled'}),
579 ((), {'eggs':'scrambled', 'spam':'fried'}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000580
Neal Norwitzc1505362006-12-28 06:47:50 +0000581 # argument annotation tests
582 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000583 self.assertEqual(f.__annotations__, {'return': list})
Zachary Warece17f762015-08-01 21:55:36 -0500584 def f(x: int): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000585 self.assertEqual(f.__annotations__, {'x': int})
Zachary Warece17f762015-08-01 21:55:36 -0500586 def f(*x: str): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000587 self.assertEqual(f.__annotations__, {'x': str})
Zachary Warece17f762015-08-01 21:55:36 -0500588 def f(**x: float): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000589 self.assertEqual(f.__annotations__, {'x': float})
Zachary Warece17f762015-08-01 21:55:36 -0500590 def f(x, y: 1+2): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000591 self.assertEqual(f.__annotations__, {'y': 3})
Zachary Warece17f762015-08-01 21:55:36 -0500592 def f(a, b: 1, c: 2, d): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000593 self.assertEqual(f.__annotations__, {'b': 1, 'c': 2})
Zachary Warece17f762015-08-01 21:55:36 -0500594 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000595 self.assertEqual(f.__annotations__,
Zachary Warece17f762015-08-01 21:55:36 -0500596 {'b': 1, 'c': 2, 'e': 3, 'g': 6})
597 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6, h: 7, i=8, j: 9 = 10,
598 **k: 11) -> 12: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000599 self.assertEqual(f.__annotations__,
Zachary Warece17f762015-08-01 21:55:36 -0500600 {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
601 'k': 11, 'return': 12})
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500602 # Check for issue #20625 -- annotations mangling
603 class Spam:
Zachary Warece17f762015-08-01 21:55:36 -0500604 def f(self, *, __kw: 1):
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500605 pass
606 class Ham(Spam): pass
Benjamin Petersonbcfcfc52014-03-09 20:59:24 -0500607 self.assertEqual(Spam.f.__annotations__, {'_Spam__kw': 1})
608 self.assertEqual(Ham.f.__annotations__, {'_Spam__kw': 1})
Nick Coghlan71011e22007-04-23 11:05:01 +0000609 # Check for SF Bug #1697248 - mixing decorators and a return annotation
610 def null(x): return x
611 @null
612 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000613 self.assertEqual(f.__annotations__, {'return': list})
Nick Coghlan71011e22007-04-23 11:05:01 +0000614
Serhiy Storchaka64204de2016-06-12 17:36:24 +0300615 # test closures with a variety of opargs
Guido van Rossum0240b922007-02-26 21:23:50 +0000616 closure = 1
617 def f(): return closure
618 def f(x=1): return closure
619 def f(*, k=1): return closure
620 def f() -> int: return closure
Neal Norwitzc1505362006-12-28 06:47:50 +0000621
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000622 # Check ast errors in *args and *kwargs
623 check_syntax_error(self, "f(*g(1=2))")
624 check_syntax_error(self, "f(**g(1=2))")
625
Robert Collinsdf395992015-08-12 08:00:06 +1200626 # Check trailing commas are permitted in funcdef argument list
627 def f(a,): pass
628 def f(*args,): pass
629 def f(**kwds,): pass
630 def f(a, *args,): pass
631 def f(a, **kwds,): pass
632 def f(*args, b,): pass
633 def f(*, b,): pass
634 def f(*args, **kwds,): pass
635 def f(a, *args, b,): pass
636 def f(a, *, b,): pass
637 def f(a, *args, **kwds,): pass
638 def f(*args, b, **kwds,): pass
639 def f(*, b, **kwds,): pass
640 def f(a, *args, b, **kwds,): pass
641 def f(a, *, b, **kwds,): pass
642
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500643 def test_lambdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000644 ### lambdef: 'lambda' [varargslist] ':' test
645 l1 = lambda : 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000646 self.assertEqual(l1(), 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000647 l2 = lambda : a[d] # XXX just testing the expression
Guido van Rossume2a383d2007-01-15 16:59:06 +0000648 l3 = lambda : [2 < x for x in [-1, 3, 0]]
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000649 self.assertEqual(l3(), [0, 1, 0])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000650 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000651 self.assertEqual(l4(), 1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000652 l5 = lambda x, y, z=2: x + y + z
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000653 self.assertEqual(l5(1, 2), 5)
654 self.assertEqual(l5(1, 2, 3), 6)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000655 check_syntax_error(self, "lambda x: x = 2")
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000656 check_syntax_error(self, "lambda (None,): None")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000657 l6 = lambda x, y, *, k=20: x+y+k
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000658 self.assertEqual(l6(1,2), 1+2+20)
659 self.assertEqual(l6(1,2,k=10), 1+2+10)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000660
Robert Collinsdf395992015-08-12 08:00:06 +1200661 # check that trailing commas are permitted
662 l10 = lambda a,: 0
663 l11 = lambda *args,: 0
664 l12 = lambda **kwds,: 0
665 l13 = lambda a, *args,: 0
666 l14 = lambda a, **kwds,: 0
667 l15 = lambda *args, b,: 0
668 l16 = lambda *, b,: 0
669 l17 = lambda *args, **kwds,: 0
670 l18 = lambda a, *args, b,: 0
671 l19 = lambda a, *, b,: 0
672 l20 = lambda a, *args, **kwds,: 0
673 l21 = lambda *args, b, **kwds,: 0
674 l22 = lambda *, b, **kwds,: 0
675 l23 = lambda a, *args, b, **kwds,: 0
676 l24 = lambda a, *, b, **kwds,: 0
677
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000678
Thomas Wouters89f507f2006-12-13 04:49:30 +0000679 ### stmt: simple_stmt | compound_stmt
680 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000681
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500682 def test_simple_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000683 ### simple_stmt: small_stmt (';' small_stmt)* [';']
684 x = 1; pass; del x
685 def foo():
Ezio Melotti13925002011-03-16 11:05:33 +0200686 # verify statements that end with semi-colons
Thomas Wouters89f507f2006-12-13 04:49:30 +0000687 x = 1; pass; del x;
688 foo()
Georg Brandl52318d62006-09-06 07:06:08 +0000689
Guido van Rossumd8faa362007-04-27 19:54:29 +0000690 ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
Thomas Wouters89f507f2006-12-13 04:49:30 +0000691 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000692
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500693 def test_expr_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000694 # (exprlist '=')* exprlist
Victor Stinner15a30952016-02-08 22:45:06 +0100695 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000696 1, 2, 3
697 x = 1
698 x = 1, 2, 3
699 x = y = z = 1, 2, 3
700 x, y, z = 1, 2, 3
701 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000702
Thomas Wouters89f507f2006-12-13 04:49:30 +0000703 check_syntax_error(self, "x + 1 = 1")
704 check_syntax_error(self, "a + 1 = b + 2")
Guido van Rossum3bead091992-01-27 17:00:37 +0000705
Nick Coghlan5b1fdc12014-06-16 19:48:02 +1000706 # Check the heuristic for print & exec covers significant cases
707 # As well as placing some limits on false positives
708 def test_former_statements_refer_to_builtins(self):
709 keywords = "print", "exec"
710 # Cases where we want the custom error
711 cases = [
712 "{} foo",
713 "{} {{1:foo}}",
714 "if 1: {} foo",
715 "if 1: {} {{1:foo}}",
716 "if 1:\n {} foo",
717 "if 1:\n {} {{1:foo}}",
718 ]
719 for keyword in keywords:
720 custom_msg = "call to '{}'".format(keyword)
721 for case in cases:
722 source = case.format(keyword)
723 with self.subTest(source=source):
724 with self.assertRaisesRegex(SyntaxError, custom_msg):
725 exec(source)
726 source = source.replace("foo", "(foo.)")
727 with self.subTest(source=source):
728 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
729 exec(source)
730
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500731 def test_del_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000732 # 'del' exprlist
733 abc = [1,2,3]
734 x, y, z = abc
735 xyz = x, y, z
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000736
Thomas Wouters89f507f2006-12-13 04:49:30 +0000737 del abc
738 del x, y, (z, xyz)
Barry Warsaw9182b452000-08-29 04:57:10 +0000739
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500740 def test_pass_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000741 # 'pass'
742 pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000743
Thomas Wouters89f507f2006-12-13 04:49:30 +0000744 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
745 # Tested below
Barry Warsaw9182b452000-08-29 04:57:10 +0000746
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500747 def test_break_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000748 # 'break'
749 while 1: break
Barry Warsaw9182b452000-08-29 04:57:10 +0000750
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500751 def test_continue_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000752 # 'continue'
753 i = 1
754 while i: i = 0; continue
Barry Warsaw9182b452000-08-29 04:57:10 +0000755
Thomas Wouters89f507f2006-12-13 04:49:30 +0000756 msg = ""
757 while not msg:
758 msg = "ok"
759 try:
760 continue
761 msg = "continue failed to continue inside try"
762 except:
763 msg = "continue inside try called except block"
764 if msg != "ok":
765 self.fail(msg)
Barry Warsawefc92ee2000-08-21 15:46:50 +0000766
Thomas Wouters89f507f2006-12-13 04:49:30 +0000767 msg = ""
768 while not msg:
769 msg = "finally block not called"
770 try:
771 continue
772 finally:
773 msg = "ok"
774 if msg != "ok":
775 self.fail(msg)
Guido van Rossum3bead091992-01-27 17:00:37 +0000776
Thomas Wouters89f507f2006-12-13 04:49:30 +0000777 def test_break_continue_loop(self):
778 # This test warrants an explanation. It is a test specifically for SF bugs
779 # #463359 and #462937. The bug is that a 'break' statement executed or
780 # exception raised inside a try/except inside a loop, *after* a continue
781 # statement has been executed in that loop, will cause the wrong number of
782 # arguments to be popped off the stack and the instruction pointer reset to
783 # a very small number (usually 0.) Because of this, the following test
784 # *must* written as a function, and the tracking vars *must* be function
785 # arguments with default values. Otherwise, the test will loop and loop.
Guido van Rossum3bead091992-01-27 17:00:37 +0000786
Thomas Wouters89f507f2006-12-13 04:49:30 +0000787 def test_inner(extra_burning_oil = 1, count=0):
788 big_hippo = 2
789 while big_hippo:
790 count += 1
791 try:
792 if extra_burning_oil and big_hippo == 1:
793 extra_burning_oil -= 1
794 break
795 big_hippo -= 1
796 continue
797 except:
798 raise
799 if count > 2 or big_hippo != 1:
800 self.fail("continue then break in try/except in loop broken!")
801 test_inner()
Guido van Rossum3bead091992-01-27 17:00:37 +0000802
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500803 def test_return(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000804 # 'return' [testlist]
805 def g1(): return
806 def g2(): return 1
807 g1()
808 x = g2()
809 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000810
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500811 def test_yield(self):
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000812 # Allowed as standalone statement
813 def g(): yield 1
814 def g(): yield from ()
815 # Allowed as RHS of assignment
816 def g(): x = yield 1
817 def g(): x = yield from ()
818 # Ordinary yield accepts implicit tuples
819 def g(): yield 1, 1
820 def g(): x = yield 1, 1
821 # 'yield from' does not
822 check_syntax_error(self, "def g(): yield from (), 1")
823 check_syntax_error(self, "def g(): x = yield from (), 1")
824 # Requires parentheses as subexpression
825 def g(): 1, (yield 1)
826 def g(): 1, (yield from ())
827 check_syntax_error(self, "def g(): 1, yield 1")
828 check_syntax_error(self, "def g(): 1, yield from ()")
829 # Requires parentheses as call argument
830 def g(): f((yield 1))
831 def g(): f((yield 1), 1)
832 def g(): f((yield from ()))
833 def g(): f((yield from ()), 1)
834 check_syntax_error(self, "def g(): f(yield 1)")
835 check_syntax_error(self, "def g(): f(yield 1, 1)")
836 check_syntax_error(self, "def g(): f(yield from ())")
837 check_syntax_error(self, "def g(): f(yield from (), 1)")
838 # Not allowed at top level
839 check_syntax_error(self, "yield")
840 check_syntax_error(self, "yield from")
841 # Not allowed at class scope
Thomas Wouters89f507f2006-12-13 04:49:30 +0000842 check_syntax_error(self, "class foo:yield 1")
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000843 check_syntax_error(self, "class foo:yield from ()")
Yury Selivanovf315c1c2015-07-23 09:10:44 +0300844 # Check annotation refleak on SyntaxError
845 check_syntax_error(self, "def g(a:(yield)): pass")
Guido van Rossum3bead091992-01-27 17:00:37 +0000846
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500847 def test_raise(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000848 # 'raise' test [',' test]
Collin Winter828f04a2007-08-31 00:04:24 +0000849 try: raise RuntimeError('just testing')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000850 except RuntimeError: pass
851 try: raise KeyboardInterrupt
852 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000853
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500854 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000855 # 'import' dotted_as_names
856 import sys
857 import time, sys
858 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
859 from time import time
860 from time import (time)
861 # not testable inside a function, but already done at top of the module
862 # from sys import *
863 from sys import path, argv
864 from sys import (path, argv)
865 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +0000866
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500867 def test_global(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000868 # 'global' NAME (',' NAME)*
869 global a
870 global a, b
871 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +0000872
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500873 def test_nonlocal(self):
Benjamin Petersona933e522008-10-24 22:16:39 +0000874 # 'nonlocal' NAME (',' NAME)*
875 x = 0
876 y = 0
877 def f():
878 nonlocal x
879 nonlocal x, y
880
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500881 def test_assert(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000882 # assertTruestmt: 'assert' test [',' test]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000883 assert 1
884 assert 1, 1
885 assert lambda x:x
886 assert 1, lambda x:x+1
Ezio Melotti6cc5bf72011-12-02 18:22:52 +0200887
888 try:
889 assert True
890 except AssertionError as e:
891 self.fail("'assert True' should not have raised an AssertionError")
892
893 try:
894 assert True, 'this should always pass'
895 except AssertionError as e:
896 self.fail("'assert True, msg' should not have "
897 "raised an AssertionError")
898
899 # these tests fail if python is run with -O, so check __debug__
900 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
901 def testAssert2(self):
Thomas Wouters80d373c2001-09-26 12:43:39 +0000902 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000903 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +0000904 except AssertionError as e:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000905 self.assertEqual(e.args[0], "msg")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000906 else:
Ezio Melotti6cc5bf72011-12-02 18:22:52 +0200907 self.fail("AssertionError not raised by assert 0")
908
909 try:
910 assert False
911 except AssertionError as e:
912 self.assertEqual(len(e.args), 0)
913 else:
914 self.fail("AssertionError not raised by 'assert False'")
915
Thomas Wouters80d373c2001-09-26 12:43:39 +0000916
Thomas Wouters89f507f2006-12-13 04:49:30 +0000917 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
918 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000919
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500920 def test_if(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000921 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
922 if 1: pass
923 if 1: pass
924 else: pass
925 if 0: pass
926 elif 0: pass
927 if 0: pass
928 elif 0: pass
929 elif 0: pass
930 elif 0: pass
931 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000932
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500933 def test_while(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000934 # 'while' test ':' suite ['else' ':' suite]
935 while 0: pass
936 while 0: pass
937 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000938
Christian Heimes969fe572008-01-25 11:23:10 +0000939 # Issue1920: "while 0" is optimized away,
940 # ensure that the "else" clause is still present.
941 x = 0
942 while 0:
943 x = 1
944 else:
945 x = 2
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000946 self.assertEqual(x, 2)
Christian Heimes969fe572008-01-25 11:23:10 +0000947
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500948 def test_for(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000949 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
950 for i in 1, 2, 3: pass
951 for i, j, k in (): pass
952 else: pass
953 class Squares:
954 def __init__(self, max):
955 self.max = max
956 self.sofar = []
957 def __len__(self): return len(self.sofar)
958 def __getitem__(self, i):
959 if not 0 <= i < self.max: raise IndexError
960 n = len(self.sofar)
961 while n <= i:
962 self.sofar.append(n*n)
963 n = n+1
964 return self.sofar[i]
965 n = 0
966 for x in Squares(10): n = n+x
967 if n != 285:
968 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000969
Thomas Wouters89f507f2006-12-13 04:49:30 +0000970 result = []
971 for x, in [(1,), (2,), (3,)]:
972 result.append(x)
973 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000974
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500975 def test_try(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000976 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
977 ### | 'try' ':' suite 'finally' ':' suite
Guido van Rossumb940e112007-01-10 16:19:56 +0000978 ### except_clause: 'except' [expr ['as' expr]]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000979 try:
980 1/0
981 except ZeroDivisionError:
982 pass
983 else:
984 pass
985 try: 1/0
986 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000987 except TypeError as msg: pass
988 except RuntimeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000989 except: pass
990 else: pass
991 try: 1/0
992 except (EOFError, TypeError, ZeroDivisionError): pass
993 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000994 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000995 try: pass
996 finally: pass
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000997
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500998 def test_suite(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000999 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
1000 if 1: pass
1001 if 1:
1002 pass
1003 if 1:
1004 #
1005 #
1006 #
1007 pass
1008 pass
1009 #
1010 pass
1011 #
Guido van Rossum3bead091992-01-27 17:00:37 +00001012
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001013 def test_test(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001014 ### and_test ('or' and_test)*
1015 ### and_test: not_test ('and' not_test)*
1016 ### not_test: 'not' not_test | comparison
1017 if not 1: pass
1018 if 1 and 1: pass
1019 if 1 or 1: pass
1020 if not not not 1: pass
1021 if not 1 and 1 and 1: pass
1022 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001023
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001024 def test_comparison(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001025 ### comparison: expr (comp_op expr)*
1026 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
1027 if 1: pass
1028 x = (1 == 1)
1029 if 1 == 1: pass
1030 if 1 != 1: pass
1031 if 1 < 1: pass
1032 if 1 > 1: pass
1033 if 1 <= 1: pass
1034 if 1 >= 1: pass
1035 if 1 is 1: pass
1036 if 1 is not 1: pass
1037 if 1 in (): pass
1038 if 1 not in (): pass
1039 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 +00001040
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001041 def test_binary_mask_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001042 x = 1 & 1
1043 x = 1 ^ 1
1044 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001045
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001046 def test_shift_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001047 x = 1 << 1
1048 x = 1 >> 1
1049 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001050
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001051 def test_additive_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001052 x = 1
1053 x = 1 + 1
1054 x = 1 - 1 - 1
1055 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001056
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001057 def test_multiplicative_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001058 x = 1 * 1
1059 x = 1 / 1
1060 x = 1 % 1
1061 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001062
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001063 def test_unary_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001064 x = +1
1065 x = -1
1066 x = ~1
1067 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
1068 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +00001069
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001070 def test_selectors(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001071 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
1072 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +00001073
Thomas Wouters89f507f2006-12-13 04:49:30 +00001074 import sys, time
1075 c = sys.path[0]
1076 x = time.time()
1077 x = sys.modules['time'].time()
1078 a = '01234'
1079 c = a[0]
1080 c = a[-1]
1081 s = a[0:5]
1082 s = a[:5]
1083 s = a[0:]
1084 s = a[:]
1085 s = a[-5:]
1086 s = a[:-1]
1087 s = a[-4:-3]
1088 # A rough test of SF bug 1333982. http://python.org/sf/1333982
1089 # The testing here is fairly incomplete.
1090 # Test cases should include: commas with 1 and 2 colons
1091 d = {}
1092 d[1] = 1
1093 d[1,] = 2
1094 d[1,2] = 3
1095 d[1,2,3] = 4
1096 L = list(d)
1097 L.sort(key=lambda x: x if isinstance(x, tuple) else ())
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001098 self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +00001099
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001100 def test_atoms(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001101 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
1102 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +00001103
Thomas Wouters89f507f2006-12-13 04:49:30 +00001104 x = (1)
1105 x = (1 or 2 or 3)
1106 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +00001107
Thomas Wouters89f507f2006-12-13 04:49:30 +00001108 x = []
1109 x = [1]
1110 x = [1 or 2 or 3]
1111 x = [1 or 2 or 3, 2, 3]
1112 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +00001113
Thomas Wouters89f507f2006-12-13 04:49:30 +00001114 x = {}
1115 x = {'one': 1}
1116 x = {'one': 1,}
1117 x = {'one' or 'two': 1 or 2}
1118 x = {'one': 1, 'two': 2}
1119 x = {'one': 1, 'two': 2,}
1120 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +00001121
Thomas Wouters89f507f2006-12-13 04:49:30 +00001122 x = {'one'}
1123 x = {'one', 1,}
1124 x = {'one', 'two', 'three'}
1125 x = {2, 3, 4,}
1126
1127 x = x
1128 x = 'x'
1129 x = 123
1130
1131 ### exprlist: expr (',' expr)* [',']
1132 ### testlist: test (',' test)* [',']
1133 # These have been exercised enough above
1134
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001135 def test_classdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001136 # 'class' NAME ['(' [testlist] ')'] ':' suite
1137 class B: pass
1138 class B2(): pass
1139 class C1(B): pass
1140 class C2(B): pass
1141 class D(C1, C2, B): pass
1142 class C:
1143 def meth1(self): pass
1144 def meth2(self, arg): pass
1145 def meth3(self, a1, a2): pass
1146
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001147 # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
1148 # decorators: decorator+
1149 # decorated: decorators (classdef | funcdef)
1150 def class_decorator(x): return x
1151 @class_decorator
1152 class G: pass
1153
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001154 def test_dictcomps(self):
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001155 # dictorsetmaker: ( (test ':' test (comp_for |
1156 # (',' test ':' test)* [','])) |
1157 # (test (comp_for | (',' test)* [','])) )
1158 nums = [1, 2, 3]
1159 self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
1160
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001161 def test_listcomps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001162 # list comprehension tests
1163 nums = [1, 2, 3, 4, 5]
1164 strs = ["Apple", "Banana", "Coconut"]
1165 spcs = [" Apple", " Banana ", "Coco nut "]
1166
1167 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
1168 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
1169 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
1170 self.assertEqual([(i, s) for i in nums for s in strs],
1171 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
1172 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
1173 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
1174 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
1175 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
1176 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
1177 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
1178 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
1179 (5, 'Banana'), (5, 'Coconut')])
1180 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
1181 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
1182
1183 def test_in_func(l):
1184 return [0 < x < 3 for x in l if x > 2]
1185
1186 self.assertEqual(test_in_func(nums), [False, False, False])
1187
1188 def test_nested_front():
1189 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
1190 [[1, 2], [3, 4], [5, 6]])
1191
1192 test_nested_front()
1193
1194 check_syntax_error(self, "[i, s for i in nums for s in strs]")
1195 check_syntax_error(self, "[x if y]")
1196
1197 suppliers = [
1198 (1, "Boeing"),
1199 (2, "Ford"),
1200 (3, "Macdonalds")
1201 ]
1202
1203 parts = [
1204 (10, "Airliner"),
1205 (20, "Engine"),
1206 (30, "Cheeseburger")
1207 ]
1208
1209 suppart = [
1210 (1, 10), (1, 20), (2, 20), (3, 30)
1211 ]
1212
1213 x = [
1214 (sname, pname)
1215 for (sno, sname) in suppliers
1216 for (pno, pname) in parts
1217 for (sp_sno, sp_pno) in suppart
1218 if sno == sp_sno and pno == sp_pno
1219 ]
1220
1221 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
1222 ('Macdonalds', 'Cheeseburger')])
1223
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001224 def test_genexps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001225 # generator expression tests
1226 g = ([x for x in range(10)] for x in range(1))
Georg Brandla18af4e2007-04-21 15:47:16 +00001227 self.assertEqual(next(g), [x for x in range(10)])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001228 try:
Georg Brandla18af4e2007-04-21 15:47:16 +00001229 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001230 self.fail('should produce StopIteration exception')
1231 except StopIteration:
1232 pass
1233
1234 a = 1
1235 try:
1236 g = (a for d in a)
Georg Brandla18af4e2007-04-21 15:47:16 +00001237 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001238 self.fail('should produce TypeError')
1239 except TypeError:
1240 pass
1241
1242 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
1243 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
1244
1245 a = [x for x in range(10)]
1246 b = (x for x in (y for y in a))
1247 self.assertEqual(sum(b), sum([x for x in range(10)]))
1248
1249 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
1250 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
1251 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
1252 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
1253 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
1254 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)]))
1255 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
1256 check_syntax_error(self, "foo(x for x in range(10), 100)")
1257 check_syntax_error(self, "foo(100, x for x in range(10))")
1258
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001259 def test_comprehension_specials(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001260 # test for outmost iterable precomputation
1261 x = 10; g = (i for i in range(x)); x = 5
1262 self.assertEqual(len(list(g)), 10)
1263
1264 # This should hold, since we're only precomputing outmost iterable.
1265 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
1266 x = 5; t = True;
1267 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
1268
1269 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
1270 # even though it's silly. Make sure it works (ifelse broke this.)
1271 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
1272 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
1273
1274 # verify unpacking single element tuples in listcomp/genexp.
1275 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
1276 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
1277
Benjamin Petersonf17ab892009-05-29 21:55:57 +00001278 def test_with_statement(self):
1279 class manager(object):
1280 def __enter__(self):
1281 return (1, 2)
1282 def __exit__(self, *args):
1283 pass
1284
1285 with manager():
1286 pass
1287 with manager() as x:
1288 pass
1289 with manager() as (x, y):
1290 pass
1291 with manager(), manager():
1292 pass
1293 with manager() as x, manager() as y:
1294 pass
1295 with manager() as x, manager():
1296 pass
1297
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001298 def test_if_else_expr(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001299 # Test ifelse expressions in various cases
1300 def _checkeval(msg, ret):
1301 "helper to check that evaluation of expressions is done correctly"
Victor Stinnerc6ec54d2016-04-12 18:33:41 +02001302 print(msg)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001303 return ret
1304
Nick Coghlan650f0d02007-04-15 12:05:43 +00001305 # the next line is not allowed anymore
1306 #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001307 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
1308 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])
1309 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
1310 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
1311 self.assertEqual((5 and 6 if 0 else 1), 1)
1312 self.assertEqual(((5 and 6) if 0 else 1), 1)
1313 self.assertEqual((5 and (6 if 1 else 1)), 6)
1314 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
1315 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
1316 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
1317 self.assertEqual((not 5 if 1 else 1), False)
1318 self.assertEqual((not 5 if 0 else 1), 1)
1319 self.assertEqual((6 + 1 if 1 else 2), 7)
1320 self.assertEqual((6 - 1 if 1 else 2), 5)
1321 self.assertEqual((6 * 2 if 1 else 4), 12)
1322 self.assertEqual((6 / 2 if 1 else 3), 3)
1323 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +00001324
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001325 def test_paren_evaluation(self):
1326 self.assertEqual(16 // (4 // 2), 8)
1327 self.assertEqual((16 // 4) // 2, 2)
1328 self.assertEqual(16 // 4 // 2, 2)
1329 self.assertTrue(False is (2 is 3))
1330 self.assertFalse((False is 2) is 3)
1331 self.assertFalse(False is 2 is 3)
1332
Benjamin Petersond51374e2014-04-09 23:55:56 -04001333 def test_matrix_mul(self):
1334 # This is not intended to be a comprehensive test, rather just to be few
1335 # samples of the @ operator in test_grammar.py.
1336 class M:
1337 def __matmul__(self, o):
1338 return 4
1339 def __imatmul__(self, o):
1340 self.other = o
1341 return self
1342 m = M()
1343 self.assertEqual(m @ m, 4)
1344 m @= 42
1345 self.assertEqual(m.other, 42)
1346
Yury Selivanov75445082015-05-11 22:57:16 -04001347 def test_async_await(self):
1348 async = 1
1349 await = 2
1350 self.assertEqual(async, 1)
1351
1352 def async():
1353 nonlocal await
1354 await = 10
1355 async()
1356 self.assertEqual(await, 10)
1357
1358 self.assertFalse(bool(async.__code__.co_flags & inspect.CO_COROUTINE))
1359
1360 async def test():
1361 def sum():
Yury Selivanov8fb307c2015-07-22 13:33:45 +03001362 pass
Yury Selivanov75445082015-05-11 22:57:16 -04001363 if 1:
1364 await someobj()
1365
1366 self.assertEqual(test.__name__, 'test')
1367 self.assertTrue(bool(test.__code__.co_flags & inspect.CO_COROUTINE))
1368
1369 def decorator(func):
1370 setattr(func, '_marked', True)
1371 return func
1372
1373 @decorator
1374 async def test2():
1375 return 22
1376 self.assertTrue(test2._marked)
1377 self.assertEqual(test2.__name__, 'test2')
1378 self.assertTrue(bool(test2.__code__.co_flags & inspect.CO_COROUTINE))
1379
1380 def test_async_for(self):
1381 class Done(Exception): pass
1382
1383 class AIter:
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001384 def __aiter__(self):
Yury Selivanov75445082015-05-11 22:57:16 -04001385 return self
1386 async def __anext__(self):
1387 raise StopAsyncIteration
1388
1389 async def foo():
1390 async for i in AIter():
1391 pass
1392 async for i, j in AIter():
1393 pass
1394 async for i in AIter():
1395 pass
1396 else:
1397 pass
1398 raise Done
1399
1400 with self.assertRaises(Done):
1401 foo().send(None)
1402
1403 def test_async_with(self):
1404 class Done(Exception): pass
1405
1406 class manager:
1407 async def __aenter__(self):
1408 return (1, 2)
1409 async def __aexit__(self, *exc):
1410 return False
1411
1412 async def foo():
1413 async with manager():
1414 pass
1415 async with manager() as x:
1416 pass
1417 async with manager() as (x, y):
1418 pass
1419 async with manager(), manager():
1420 pass
1421 async with manager() as x, manager() as y:
1422 pass
1423 async with manager() as x, manager():
1424 pass
1425 raise Done
1426
1427 with self.assertRaises(Done):
1428 foo().send(None)
1429
Guido van Rossum3bead091992-01-27 17:00:37 +00001430
Thomas Wouters89f507f2006-12-13 04:49:30 +00001431if __name__ == '__main__':
Zachary Ware38c707e2015-04-13 15:00:43 -05001432 unittest.main()