1# Python test set -- part 1, grammar. 2# This just tests whether the parser accepts them all. 3 4from test.support import check_syntax_error 5from test.support import import_helper 6import inspect 7import unittest 8import sys 9import warnings 10# testing import * 11from sys import * 12 13# different import patterns to check that __annotations__ does not interfere 14# with import machinery 15import test.typinganndata.ann_module as ann_module 16import typing 17from test.typinganndata import ann_module2 18import test 19 20# These are shared with test_tokenize and other test modules. 21# 22# Note: since several test cases filter out floats by looking for "e" and ".", 23# don't add hexadecimal literals that contain "e" or "E". 24VALID_UNDERSCORE_LITERALS = [ 25 '0_0_0', 26 '4_2', 27 '1_0000_0000', 28 '0b1001_0100', 29 '0xffff_ffff', 30 '0o5_7_7', 31 '1_00_00.5', 32 '1_00_00.5e5', 33 '1_00_00e5_1', 34 '1e1_0', 35 '.1_4', 36 '.1_4e1', 37 '0b_0', 38 '0x_f', 39 '0o_5', 40 '1_00_00j', 41 '1_00_00.5j', 42 '1_00_00e5_1j', 43 '.1_4j', 44 '(1_2.5+3_3j)', 45 '(.5_6j)', 46] 47INVALID_UNDERSCORE_LITERALS = [ 48 # Trailing underscores: 49 '0_', 50 '42_', 51 '1.4j_', 52 '0x_', 53 '0b1_', 54 '0xf_', 55 '0o5_', 56 '0 if 1_Else 1', 57 # Underscores in the base selector: 58 '0_b0', 59 '0_xf', 60 '0_o5', 61 # Old-style octal, still disallowed: 62 '0_7', 63 '09_99', 64 # Multiple consecutive underscores: 65 '4_______2', 66 '0.1__4', 67 '0.1__4j', 68 '0b1001__0100', 69 '0xffff__ffff', 70 '0x___', 71 '0o5__77', 72 '1e1__0', 73 '1e1__0j', 74 # Underscore right before a dot: 75 '1_.4', 76 '1_.4j', 77 # Underscore right after a dot: 78 '1._4', 79 '1._4j', 80 '._5', 81 '._5j', 82 # Underscore right after a sign: 83 '1.0e+_1', 84 '1.0e+_1j', 85 # Underscore right before j: 86 '1.4_j', 87 '1.4e5_j', 88 # Underscore right before e: 89 '1_e1', 90 '1.4_e1', 91 '1.4_e1j', 92 # Underscore right after e: 93 '1e_1', 94 '1.4e_1', 95 '1.4e_1j', 96 # Complex cases with parens: 97 '(1+1.5_j_)', 98 '(1+1.5_j)', 99] 100 101 102class TokenTests(unittest.TestCase): 103 104 from test.support import check_syntax_error 105 from test.support.warnings_helper import check_syntax_warning 106 107 def test_backslash(self): 108 # Backslash means line continuation: 109 x = 1 \ 110 + 1 111 self.assertEqual(x, 2, 'backslash for line continuation') 112 113 # Backslash does not means continuation in comments :\ 114 x = 0 115 self.assertEqual(x, 0, 'backslash ending comment') 116 117 def test_plain_integers(self): 118 self.assertEqual(type(000), type(0)) 119 self.assertEqual(0xff, 255) 120 self.assertEqual(0o377, 255) 121 self.assertEqual(2147483647, 0o17777777777) 122 self.assertEqual(0b1001, 9) 123 # "0x" is not a valid literal 124 self.assertRaises(SyntaxError, eval, "0x") 125 from sys import maxsize 126 if maxsize == 2147483647: 127 self.assertEqual(-2147483647-1, -0o20000000000) 128 # XXX -2147483648 129 self.assertTrue(0o37777777777 > 0) 130 self.assertTrue(0xffffffff > 0) 131 self.assertTrue(0b1111111111111111111111111111111 > 0) 132 for s in ('2147483648', '0o40000000000', '0x100000000', 133 '0b10000000000000000000000000000000'): 134 try: 135 x = eval(s) 136 except OverflowError: 137 self.fail("OverflowError on huge integer literal %r" % s) 138 elif maxsize == 9223372036854775807: 139 self.assertEqual(-9223372036854775807-1, -0o1000000000000000000000) 140 self.assertTrue(0o1777777777777777777777 > 0) 141 self.assertTrue(0xffffffffffffffff > 0) 142 self.assertTrue(0b11111111111111111111111111111111111111111111111111111111111111 > 0) 143 for s in '9223372036854775808', '0o2000000000000000000000', \ 144 '0x10000000000000000', \ 145 '0b100000000000000000000000000000000000000000000000000000000000000': 146 try: 147 x = eval(s) 148 except OverflowError: 149 self.fail("OverflowError on huge integer literal %r" % s) 150 else: 151 self.fail('Weird maxsize value %r' % maxsize) 152 153 def test_long_integers(self): 154 x = 0 155 x = 0xffffffffffffffff 156 x = 0Xffffffffffffffff 157 x = 0o77777777777777777 158 x = 0O77777777777777777 159 x = 123456789012345678901234567890 160 x = 0b100000000000000000000000000000000000000000000000000000000000000000000 161 x = 0B111111111111111111111111111111111111111111111111111111111111111111111 162 163 def test_floats(self): 164 x = 3.14 165 x = 314. 166 x = 0.314 167 x = 000.314 168 x = .314 169 x = 3e14 170 x = 3E14 171 x = 3e-14 172 x = 3e+14 173 x = 3.e14 174 x = .3e14 175 x = 3.1e4 176 177 def test_float_exponent_tokenization(self): 178 # See issue 21642. 179 with warnings.catch_warnings(): 180 warnings.simplefilter('ignore', SyntaxWarning) 181 self.assertEqual(eval("1 if 1else 0"), 1) 182 self.assertEqual(eval("1 if 0else 0"), 0) 183 self.assertRaises(SyntaxError, eval, "0 if 1Else 0") 184 185 def test_underscore_literals(self): 186 for lit in VALID_UNDERSCORE_LITERALS: 187 self.assertEqual(eval(lit), eval(lit.replace('_', ''))) 188 for lit in INVALID_UNDERSCORE_LITERALS: 189 self.assertRaises(SyntaxError, eval, lit) 190 # Sanity check: no literal begins with an underscore 191 self.assertRaises(NameError, eval, "_0") 192 193 def test_bad_numerical_literals(self): 194 check = self.check_syntax_error 195 check("0b12", "invalid digit '2' in binary literal") 196 check("0b1_2", "invalid digit '2' in binary literal") 197 check("0b2", "invalid digit '2' in binary literal") 198 check("0b1_", "invalid binary literal") 199 check("0b", "invalid binary literal") 200 check("0o18", "invalid digit '8' in octal literal") 201 check("0o1_8", "invalid digit '8' in octal literal") 202 check("0o8", "invalid digit '8' in octal literal") 203 check("0o1_", "invalid octal literal") 204 check("0o", "invalid octal literal") 205 check("0x1_", "invalid hexadecimal literal") 206 check("0x", "invalid hexadecimal literal") 207 check("1_", "invalid decimal literal") 208 check("012", 209 "leading zeros in decimal integer literals are not permitted; " 210 "use an 0o prefix for octal integers") 211 check("1.2_", "invalid decimal literal") 212 check("1e2_", "invalid decimal literal") 213 check("1e+", "invalid decimal literal") 214 215 def test_end_of_numerical_literals(self): 216 def check(test, error=False): 217 with self.subTest(expr=test): 218 if error: 219 with warnings.catch_warnings(record=True) as w: 220 with self.assertRaisesRegex(SyntaxError, 221 r'invalid \w+ literal'): 222 compile(test, "<testcase>", "eval") 223 self.assertEqual(w, []) 224 else: 225 self.check_syntax_warning(test, 226 errtext=r'invalid \w+ literal') 227 228 for num in "0xf", "0o7", "0b1", "9", "0", "1.", "1e3", "1j": 229 compile(num, "<testcase>", "eval") 230 check(f"{num}and x", error=(num == "0xf")) 231 check(f"{num}or x", error=(num == "0")) 232 check(f"{num}in x") 233 check(f"{num}not in x") 234 check(f"{num}if x else y") 235 check(f"x if {num}else y", error=(num == "0xf")) 236 check(f"[{num}for x in ()]") 237 check(f"{num}spam", error=True) 238 239 # gh-88943: Invalid non-ASCII character following a numerical literal. 240 with self.assertRaisesRegex(SyntaxError, r"invalid character '⁄' \(U\+2044\)"): 241 compile(f"{num}⁄7", "<testcase>", "eval") 242 243 with self.assertWarnsRegex(SyntaxWarning, r'invalid \w+ literal'): 244 compile(f"{num}is x", "<testcase>", "eval") 245 with warnings.catch_warnings(): 246 warnings.simplefilter('error', SyntaxWarning) 247 with self.assertRaisesRegex(SyntaxError, 248 r'invalid \w+ literal'): 249 compile(f"{num}is x", "<testcase>", "eval") 250 251 check("[0x1ffor x in ()]") 252 check("[0x1for x in ()]") 253 check("[0xfor x in ()]") 254 255 def test_string_literals(self): 256 x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y) 257 x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39) 258 x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34) 259 x = "doesn't \"shrink\" does it" 260 y = 'doesn\'t "shrink" does it' 261 self.assertTrue(len(x) == 24 and x == y) 262 x = "does \"shrink\" doesn't it" 263 y = 'does "shrink" doesn\'t it' 264 self.assertTrue(len(x) == 24 and x == y) 265 x = """ 266The "quick" 267brown fox 268jumps over 269the 'lazy' dog. 270""" 271 y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n' 272 self.assertEqual(x, y) 273 y = ''' 274The "quick" 275brown fox 276jumps over 277the 'lazy' dog. 278''' 279 self.assertEqual(x, y) 280 y = "\n\ 281The \"quick\"\n\ 282brown fox\n\ 283jumps over\n\ 284the 'lazy' dog.\n\ 285" 286 self.assertEqual(x, y) 287 y = '\n\ 288The \"quick\"\n\ 289brown fox\n\ 290jumps over\n\ 291the \'lazy\' dog.\n\ 292' 293 self.assertEqual(x, y) 294 295 def test_ellipsis(self): 296 x = ... 297 self.assertTrue(x is Ellipsis) 298 self.assertRaises(SyntaxError, eval, ".. .") 299 300 def test_eof_error(self): 301 samples = ("def foo(", "\ndef foo(", "def foo(\n") 302 for s in samples: 303 with self.assertRaises(SyntaxError) as cm: 304 compile(s, "<test>", "exec") 305 self.assertIn("was never closed", str(cm.exception)) 306 307var_annot_global: int # a global annotated is necessary for test_var_annot 308 309# custom namespace for testing __annotations__ 310 311class CNS: 312 def __init__(self): 313 self._dct = {} 314 def __setitem__(self, item, value): 315 self._dct[item.lower()] = value 316 def __getitem__(self, item): 317 return self._dct[item] 318 319 320class GrammarTests(unittest.TestCase): 321 322 from test.support import check_syntax_error 323 from test.support.warnings_helper import check_syntax_warning 324 from test.support.warnings_helper import check_no_warnings 325 326 # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE 327 # XXX can't test in a script -- this rule is only used when interactive 328 329 # file_input: (NEWLINE | stmt)* ENDMARKER 330 # Being tested as this very moment this very module 331 332 # expr_input: testlist NEWLINE 333 # XXX Hard to test -- used only in calls to input() 334 335 def test_eval_input(self): 336 # testlist ENDMARKER 337 x = eval('1, 0 or 1') 338 339 def test_var_annot_basics(self): 340 # all these should be allowed 341 var1: int = 5 342 var2: [int, str] 343 my_lst = [42] 344 def one(): 345 return 1 346 int.new_attr: int 347 [list][0]: type 348 my_lst[one()-1]: int = 5 349 self.assertEqual(my_lst, [5]) 350 351 def test_var_annot_syntax_errors(self): 352 # parser pass 353 check_syntax_error(self, "def f: int") 354 check_syntax_error(self, "x: int: str") 355 check_syntax_error(self, "def f():\n" 356 " nonlocal x: int\n") 357 check_syntax_error(self, "def f():\n" 358 " global x: int\n") 359 check_syntax_error(self, "x: int = y = 1") 360 check_syntax_error(self, "z = w: int = 1") 361 check_syntax_error(self, "x: int = y: int = 1") 362 # AST pass 363 check_syntax_error(self, "[x, 0]: int\n") 364 check_syntax_error(self, "f(): int\n") 365 check_syntax_error(self, "(x,): int") 366 check_syntax_error(self, "def f():\n" 367 " (x, y): int = (1, 2)\n") 368 # symtable pass 369 check_syntax_error(self, "def f():\n" 370 " x: int\n" 371 " global x\n") 372 check_syntax_error(self, "def f():\n" 373 " global x\n" 374 " x: int\n") 375 check_syntax_error(self, "def f():\n" 376 " x: int\n" 377 " nonlocal x\n") 378 check_syntax_error(self, "def f():\n" 379 " nonlocal x\n" 380 " x: int\n") 381 382 def test_var_annot_basic_semantics(self): 383 # execution order 384 with self.assertRaises(ZeroDivisionError): 385 no_name[does_not_exist]: no_name_again = 1/0 386 with self.assertRaises(NameError): 387 no_name[does_not_exist]: 1/0 = 0 388 global var_annot_global 389 390 # function semantics 391 def f(): 392 st: str = "Hello" 393 a.b: int = (1, 2) 394 return st 395 self.assertEqual(f.__annotations__, {}) 396 def f_OK(): 397 x: 1/0 398 f_OK() 399 def fbad(): 400 x: int 401 print(x) 402 with self.assertRaises(UnboundLocalError): 403 fbad() 404 def f2bad(): 405 (no_such_global): int 406 print(no_such_global) 407 try: 408 f2bad() 409 except Exception as e: 410 self.assertIs(type(e), NameError) 411 412 # class semantics 413 class C: 414 __foo: int 415 s: str = "attr" 416 z = 2 417 def __init__(self, x): 418 self.x: int = x 419 self.assertEqual(C.__annotations__, {'_C__foo': int, 's': str}) 420 with self.assertRaises(NameError): 421 class CBad: 422 no_such_name_defined.attr: int = 0 423 with self.assertRaises(NameError): 424 class Cbad2(C): 425 x: int 426 x.y: list = [] 427 428 def test_annotations_inheritance(self): 429 # Check that annotations are not inherited by derived classes 430 class A: 431 attr: int 432 class B(A): 433 pass 434 class C(A): 435 attr: str 436 class D: 437 attr2: int 438 class E(A, D): 439 pass 440 class F(C, A): 441 pass 442 self.assertEqual(A.__annotations__, {"attr": int}) 443 self.assertEqual(B.__annotations__, {}) 444 self.assertEqual(C.__annotations__, {"attr" : str}) 445 self.assertEqual(D.__annotations__, {"attr2" : int}) 446 self.assertEqual(E.__annotations__, {}) 447 self.assertEqual(F.__annotations__, {}) 448 449 450 def test_var_annot_metaclass_semantics(self): 451 class CMeta(type): 452 @classmethod 453 def __prepare__(metacls, name, bases, **kwds): 454 return {'__annotations__': CNS()} 455 class CC(metaclass=CMeta): 456 XX: 'ANNOT' 457 self.assertEqual(CC.__annotations__['xx'], 'ANNOT') 458 459 def test_var_annot_module_semantics(self): 460 self.assertEqual(test.__annotations__, {}) 461 self.assertEqual(ann_module.__annotations__, 462 {1: 2, 'x': int, 'y': str, 'f': typing.Tuple[int, int], 'u': int | float}) 463 self.assertEqual(ann_module.M.__annotations__, 464 {'123': 123, 'o': type}) 465 self.assertEqual(ann_module2.__annotations__, {}) 466 467 def test_var_annot_in_module(self): 468 # check that functions fail the same way when executed 469 # outside of module where they were defined 470 ann_module3 = import_helper.import_fresh_module("test.typinganndata.ann_module3") 471 with self.assertRaises(NameError): 472 ann_module3.f_bad_ann() 473 with self.assertRaises(NameError): 474 ann_module3.g_bad_ann() 475 with self.assertRaises(NameError): 476 ann_module3.D_bad_ann(5) 477 478 def test_var_annot_simple_exec(self): 479 gns = {}; lns= {} 480 exec("'docstring'\n" 481 "__annotations__[1] = 2\n" 482 "x: int = 5\n", gns, lns) 483 self.assertEqual(lns["__annotations__"], {1: 2, 'x': int}) 484 with self.assertRaises(KeyError): 485 gns['__annotations__'] 486 487 def test_var_annot_custom_maps(self): 488 # tests with custom locals() and __annotations__ 489 ns = {'__annotations__': CNS()} 490 exec('X: int; Z: str = "Z"; (w): complex = 1j', ns) 491 self.assertEqual(ns['__annotations__']['x'], int) 492 self.assertEqual(ns['__annotations__']['z'], str) 493 with self.assertRaises(KeyError): 494 ns['__annotations__']['w'] 495 nonloc_ns = {} 496 class CNS2: 497 def __init__(self): 498 self._dct = {} 499 def __setitem__(self, item, value): 500 nonlocal nonloc_ns 501 self._dct[item] = value 502 nonloc_ns[item] = value 503 def __getitem__(self, item): 504 return self._dct[item] 505 exec('x: int = 1', {}, CNS2()) 506 self.assertEqual(nonloc_ns['__annotations__']['x'], int) 507 508 def test_var_annot_refleak(self): 509 # complex case: custom locals plus custom __annotations__ 510 # this was causing refleak 511 cns = CNS() 512 nonloc_ns = {'__annotations__': cns} 513 class CNS2: 514 def __init__(self): 515 self._dct = {'__annotations__': cns} 516 def __setitem__(self, item, value): 517 nonlocal nonloc_ns 518 self._dct[item] = value 519 nonloc_ns[item] = value 520 def __getitem__(self, item): 521 return self._dct[item] 522 exec('X: str', {}, CNS2()) 523 self.assertEqual(nonloc_ns['__annotations__']['x'], str) 524 525 def test_var_annot_rhs(self): 526 ns = {} 527 exec('x: tuple = 1, 2', ns) 528 self.assertEqual(ns['x'], (1, 2)) 529 stmt = ('def f():\n' 530 ' x: int = yield') 531 exec(stmt, ns) 532 self.assertEqual(list(ns['f']()), [None]) 533 534 ns = {"a": 1, 'b': (2, 3, 4), "c":5, "Tuple": typing.Tuple} 535 exec('x: Tuple[int, ...] = a,*b,c', ns) 536 self.assertEqual(ns['x'], (1, 2, 3, 4, 5)) 537 538 def test_funcdef(self): 539 ### [decorators] 'def' NAME parameters ['->' test] ':' suite 540 ### decorator: '@' namedexpr_test NEWLINE 541 ### decorators: decorator+ 542 ### parameters: '(' [typedargslist] ')' 543 ### typedargslist: ((tfpdef ['=' test] ',')* 544 ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef) 545 ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [',']) 546 ### tfpdef: NAME [':' test] 547 ### varargslist: ((vfpdef ['=' test] ',')* 548 ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef) 549 ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [',']) 550 ### vfpdef: NAME 551 def f1(): pass 552 f1() 553 f1(*()) 554 f1(*(), **{}) 555 def f2(one_argument): pass 556 def f3(two, arguments): pass 557 self.assertEqual(f2.__code__.co_varnames, ('one_argument',)) 558 self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments')) 559 def a1(one_arg,): pass 560 def a2(two, args,): pass 561 def v0(*rest): pass 562 def v1(a, *rest): pass 563 def v2(a, b, *rest): pass 564 565 f1() 566 f2(1) 567 f2(1,) 568 f3(1, 2) 569 f3(1, 2,) 570 v0() 571 v0(1) 572 v0(1,) 573 v0(1,2) 574 v0(1,2,3,4,5,6,7,8,9,0) 575 v1(1) 576 v1(1,) 577 v1(1,2) 578 v1(1,2,3) 579 v1(1,2,3,4,5,6,7,8,9,0) 580 v2(1,2) 581 v2(1,2,3) 582 v2(1,2,3,4) 583 v2(1,2,3,4,5,6,7,8,9,0) 584 585 def d01(a=1): pass 586 d01() 587 d01(1) 588 d01(*(1,)) 589 d01(*[] or [2]) 590 d01(*() or (), *{} and (), **() or {}) 591 d01(**{'a':2}) 592 d01(**{'a':2} or {}) 593 def d11(a, b=1): pass 594 d11(1) 595 d11(1, 2) 596 d11(1, **{'b':2}) 597 def d21(a, b, c=1): pass 598 d21(1, 2) 599 d21(1, 2, 3) 600 d21(*(1, 2, 3)) 601 d21(1, *(2, 3)) 602 d21(1, 2, *(3,)) 603 d21(1, 2, **{'c':3}) 604 def d02(a=1, b=2): pass 605 d02() 606 d02(1) 607 d02(1, 2) 608 d02(*(1, 2)) 609 d02(1, *(2,)) 610 d02(1, **{'b':2}) 611 d02(**{'a': 1, 'b': 2}) 612 def d12(a, b=1, c=2): pass 613 d12(1) 614 d12(1, 2) 615 d12(1, 2, 3) 616 def d22(a, b, c=1, d=2): pass 617 d22(1, 2) 618 d22(1, 2, 3) 619 d22(1, 2, 3, 4) 620 def d01v(a=1, *rest): pass 621 d01v() 622 d01v(1) 623 d01v(1, 2) 624 d01v(*(1, 2, 3, 4)) 625 d01v(*(1,)) 626 d01v(**{'a':2}) 627 def d11v(a, b=1, *rest): pass 628 d11v(1) 629 d11v(1, 2) 630 d11v(1, 2, 3) 631 def d21v(a, b, c=1, *rest): pass 632 d21v(1, 2) 633 d21v(1, 2, 3) 634 d21v(1, 2, 3, 4) 635 d21v(*(1, 2, 3, 4)) 636 d21v(1, 2, **{'c': 3}) 637 def d02v(a=1, b=2, *rest): pass 638 d02v() 639 d02v(1) 640 d02v(1, 2) 641 d02v(1, 2, 3) 642 d02v(1, *(2, 3, 4)) 643 d02v(**{'a': 1, 'b': 2}) 644 def d12v(a, b=1, c=2, *rest): pass 645 d12v(1) 646 d12v(1, 2) 647 d12v(1, 2, 3) 648 d12v(1, 2, 3, 4) 649 d12v(*(1, 2, 3, 4)) 650 d12v(1, 2, *(3, 4, 5)) 651 d12v(1, *(2,), **{'c': 3}) 652 def d22v(a, b, c=1, d=2, *rest): pass 653 d22v(1, 2) 654 d22v(1, 2, 3) 655 d22v(1, 2, 3, 4) 656 d22v(1, 2, 3, 4, 5) 657 d22v(*(1, 2, 3, 4)) 658 d22v(1, 2, *(3, 4, 5)) 659 d22v(1, *(2, 3), **{'d': 4}) 660 661 # keyword argument type tests 662 with warnings.catch_warnings(): 663 warnings.simplefilter('ignore', BytesWarning) 664 try: 665 str('x', **{b'foo':1 }) 666 except TypeError: 667 pass 668 else: 669 self.fail('Bytes should not work as keyword argument names') 670 # keyword only argument tests 671 def pos0key1(*, key): return key 672 pos0key1(key=100) 673 def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2 674 pos2key2(1, 2, k1=100) 675 pos2key2(1, 2, k1=100, k2=200) 676 pos2key2(1, 2, k2=100, k1=200) 677 def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg 678 pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200) 679 pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100) 680 681 self.assertRaises(SyntaxError, eval, "def f(*): pass") 682 self.assertRaises(SyntaxError, eval, "def f(*,): pass") 683 self.assertRaises(SyntaxError, eval, "def f(*, **kwds): pass") 684 685 # keyword arguments after *arglist 686 def f(*args, **kwargs): 687 return args, kwargs 688 self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4), 689 {'x':2, 'y':5})) 690 self.assertEqual(f(1, *(2,3), 4), ((1, 2, 3, 4), {})) 691 self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)") 692 self.assertEqual(f(**{'eggs':'scrambled', 'spam':'fried'}), 693 ((), {'eggs':'scrambled', 'spam':'fried'})) 694 self.assertEqual(f(spam='fried', **{'eggs':'scrambled'}), 695 ((), {'eggs':'scrambled', 'spam':'fried'})) 696 697 # Check ast errors in *args and *kwargs 698 check_syntax_error(self, "f(*g(1=2))") 699 check_syntax_error(self, "f(**g(1=2))") 700 701 # argument annotation tests 702 def f(x) -> list: pass 703 self.assertEqual(f.__annotations__, {'return': list}) 704 def f(x: int): pass 705 self.assertEqual(f.__annotations__, {'x': int}) 706 def f(x: int, /): pass 707 self.assertEqual(f.__annotations__, {'x': int}) 708 def f(x: int = 34, /): pass 709 self.assertEqual(f.__annotations__, {'x': int}) 710 def f(*x: str): pass 711 self.assertEqual(f.__annotations__, {'x': str}) 712 def f(**x: float): pass 713 self.assertEqual(f.__annotations__, {'x': float}) 714 def f(x, y: 1+2): pass 715 self.assertEqual(f.__annotations__, {'y': 3}) 716 def f(x, y: 1+2, /): pass 717 self.assertEqual(f.__annotations__, {'y': 3}) 718 def f(a, b: 1, c: 2, d): pass 719 self.assertEqual(f.__annotations__, {'b': 1, 'c': 2}) 720 def f(a, b: 1, /, c: 2, d): pass 721 self.assertEqual(f.__annotations__, {'b': 1, 'c': 2}) 722 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6): pass 723 self.assertEqual(f.__annotations__, 724 {'b': 1, 'c': 2, 'e': 3, 'g': 6}) 725 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6, h: 7, i=8, j: 9 = 10, 726 **k: 11) -> 12: pass 727 self.assertEqual(f.__annotations__, 728 {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9, 729 'k': 11, 'return': 12}) 730 def f(a, b: 1, c: 2, d, e: 3 = 4, f: int = 5, /, *g: 6, h: 7, i=8, j: 9 = 10, 731 **k: 11) -> 12: pass 732 self.assertEqual(f.__annotations__, 733 {'b': 1, 'c': 2, 'e': 3, 'f': int, 'g': 6, 'h': 7, 'j': 9, 734 'k': 11, 'return': 12}) 735 # Check for issue #20625 -- annotations mangling 736 class Spam: 737 def f(self, *, __kw: 1): 738 pass 739 class Ham(Spam): pass 740 self.assertEqual(Spam.f.__annotations__, {'_Spam__kw': 1}) 741 self.assertEqual(Ham.f.__annotations__, {'_Spam__kw': 1}) 742 # Check for SF Bug #1697248 - mixing decorators and a return annotation 743 def null(x): return x 744 @null 745 def f(x) -> list: pass 746 self.assertEqual(f.__annotations__, {'return': list}) 747 748 # Test expressions as decorators (PEP 614): 749 @False or null 750 def f(x): pass 751 @d := null 752 def f(x): pass 753 @lambda f: null(f) 754 def f(x): pass 755 @[..., null, ...][1] 756 def f(x): pass 757 @null(null)(null) 758 def f(x): pass 759 @[null][0].__call__.__call__ 760 def f(x): pass 761 762 # test closures with a variety of opargs 763 closure = 1 764 def f(): return closure 765 def f(x=1): return closure 766 def f(*, k=1): return closure 767 def f() -> int: return closure 768 769 # Check trailing commas are permitted in funcdef argument list 770 def f(a,): pass 771 def f(*args,): pass 772 def f(**kwds,): pass 773 def f(a, *args,): pass 774 def f(a, **kwds,): pass 775 def f(*args, b,): pass 776 def f(*, b,): pass 777 def f(*args, **kwds,): pass 778 def f(a, *args, b,): pass 779 def f(a, *, b,): pass 780 def f(a, *args, **kwds,): pass 781 def f(*args, b, **kwds,): pass 782 def f(*, b, **kwds,): pass 783 def f(a, *args, b, **kwds,): pass 784 def f(a, *, b, **kwds,): pass 785 786 def test_lambdef(self): 787 ### lambdef: 'lambda' [varargslist] ':' test 788 l1 = lambda : 0 789 self.assertEqual(l1(), 0) 790 l2 = lambda : a[d] # XXX just testing the expression 791 l3 = lambda : [2 < x for x in [-1, 3, 0]] 792 self.assertEqual(l3(), [0, 1, 0]) 793 l4 = lambda x = lambda y = lambda z=1 : z : y() : x() 794 self.assertEqual(l4(), 1) 795 l5 = lambda x, y, z=2: x + y + z 796 self.assertEqual(l5(1, 2), 5) 797 self.assertEqual(l5(1, 2, 3), 6) 798 check_syntax_error(self, "lambda x: x = 2") 799 check_syntax_error(self, "lambda (None,): None") 800 l6 = lambda x, y, *, k=20: x+y+k 801 self.assertEqual(l6(1,2), 1+2+20) 802 self.assertEqual(l6(1,2,k=10), 1+2+10) 803 804 # check that trailing commas are permitted 805 l10 = lambda a,: 0 806 l11 = lambda *args,: 0 807 l12 = lambda **kwds,: 0 808 l13 = lambda a, *args,: 0 809 l14 = lambda a, **kwds,: 0 810 l15 = lambda *args, b,: 0 811 l16 = lambda *, b,: 0 812 l17 = lambda *args, **kwds,: 0 813 l18 = lambda a, *args, b,: 0 814 l19 = lambda a, *, b,: 0 815 l20 = lambda a, *args, **kwds,: 0 816 l21 = lambda *args, b, **kwds,: 0 817 l22 = lambda *, b, **kwds,: 0 818 l23 = lambda a, *args, b, **kwds,: 0 819 l24 = lambda a, *, b, **kwds,: 0 820 821 822 ### stmt: simple_stmt | compound_stmt 823 # Tested below 824 825 def test_simple_stmt(self): 826 ### simple_stmt: small_stmt (';' small_stmt)* [';'] 827 x = 1; pass; del x 828 def foo(): 829 # verify statements that end with semi-colons 830 x = 1; pass; del x; 831 foo() 832 833 ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt 834 # Tested below 835 836 def test_expr_stmt(self): 837 # (exprlist '=')* exprlist 838 1 839 1, 2, 3 840 x = 1 841 x = 1, 2, 3 842 x = y = z = 1, 2, 3 843 x, y, z = 1, 2, 3 844 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4) 845 846 check_syntax_error(self, "x + 1 = 1") 847 check_syntax_error(self, "a + 1 = b + 2") 848 849 # Check the heuristic for print & exec covers significant cases 850 # As well as placing some limits on false positives 851 def test_former_statements_refer_to_builtins(self): 852 keywords = "print", "exec" 853 # Cases where we want the custom error 854 cases = [ 855 "{} foo", 856 "{} {{1:foo}}", 857 "if 1: {} foo", 858 "if 1: {} {{1:foo}}", 859 "if 1:\n {} foo", 860 "if 1:\n {} {{1:foo}}", 861 ] 862 for keyword in keywords: 863 custom_msg = "call to '{}'".format(keyword) 864 for case in cases: 865 source = case.format(keyword) 866 with self.subTest(source=source): 867 with self.assertRaisesRegex(SyntaxError, custom_msg): 868 exec(source) 869 source = source.replace("foo", "(foo.)") 870 with self.subTest(source=source): 871 with self.assertRaisesRegex(SyntaxError, "invalid syntax"): 872 exec(source) 873 874 def test_del_stmt(self): 875 # 'del' exprlist 876 abc = [1,2,3] 877 x, y, z = abc 878 xyz = x, y, z 879 880 del abc 881 del x, y, (z, xyz) 882 883 x, y, z = "xyz" 884 del x 885 del y, 886 del (z) 887 del () 888 889 a, b, c, d, e, f, g = "abcdefg" 890 del a, (b, c), (d, (e, f)) 891 892 a, b, c, d, e, f, g = "abcdefg" 893 del a, [b, c], (d, [e, f]) 894 895 abcd = list("abcd") 896 del abcd[1:2] 897 898 compile("del a, (b[0].c, (d.e, f.g[1:2])), [h.i.j], ()", "<testcase>", "exec") 899 900 def test_pass_stmt(self): 901 # 'pass' 902 pass 903 904 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt 905 # Tested below 906 907 def test_break_stmt(self): 908 # 'break' 909 while 1: break 910 911 def test_continue_stmt(self): 912 # 'continue' 913 i = 1 914 while i: i = 0; continue 915 916 msg = "" 917 while not msg: 918 msg = "ok" 919 try: 920 continue 921 msg = "continue failed to continue inside try" 922 except: 923 msg = "continue inside try called except block" 924 if msg != "ok": 925 self.fail(msg) 926 927 msg = "" 928 while not msg: 929 msg = "finally block not called" 930 try: 931 continue 932 finally: 933 msg = "ok" 934 if msg != "ok": 935 self.fail(msg) 936 937 def test_break_continue_loop(self): 938 # This test warrants an explanation. It is a test specifically for SF bugs 939 # #463359 and #462937. The bug is that a 'break' statement executed or 940 # exception raised inside a try/except inside a loop, *after* a continue 941 # statement has been executed in that loop, will cause the wrong number of 942 # arguments to be popped off the stack and the instruction pointer reset to 943 # a very small number (usually 0.) Because of this, the following test 944 # *must* written as a function, and the tracking vars *must* be function 945 # arguments with default values. Otherwise, the test will loop and loop. 946 947 def test_inner(extra_burning_oil = 1, count=0): 948 big_hippo = 2 949 while big_hippo: 950 count += 1 951 try: 952 if extra_burning_oil and big_hippo == 1: 953 extra_burning_oil -= 1 954 break 955 big_hippo -= 1 956 continue 957 except: 958 raise 959 if count > 2 or big_hippo != 1: 960 self.fail("continue then break in try/except in loop broken!") 961 test_inner() 962 963 def test_return(self): 964 # 'return' [testlist_star_expr] 965 def g1(): return 966 def g2(): return 1 967 def g3(): 968 z = [2, 3] 969 return 1, *z 970 971 g1() 972 x = g2() 973 y = g3() 974 self.assertEqual(y, (1, 2, 3), "unparenthesized star expr return") 975 check_syntax_error(self, "class foo:return 1") 976 977 def test_break_in_finally(self): 978 count = 0 979 while count < 2: 980 count += 1 981 try: 982 pass 983 finally: 984 break 985 self.assertEqual(count, 1) 986 987 count = 0 988 while count < 2: 989 count += 1 990 try: 991 continue 992 finally: 993 break 994 self.assertEqual(count, 1) 995 996 count = 0 997 while count < 2: 998 count += 1 999 try: 1000 1/0 1001 finally: 1002 break 1003 self.assertEqual(count, 1) 1004 1005 for count in [0, 1]: 1006 self.assertEqual(count, 0) 1007 try: 1008 pass 1009 finally: 1010 break 1011 self.assertEqual(count, 0) 1012 1013 for count in [0, 1]: 1014 self.assertEqual(count, 0) 1015 try: 1016 continue 1017 finally: 1018 break 1019 self.assertEqual(count, 0) 1020 1021 for count in [0, 1]: 1022 self.assertEqual(count, 0) 1023 try: 1024 1/0 1025 finally: 1026 break 1027 self.assertEqual(count, 0) 1028 1029 def test_continue_in_finally(self): 1030 count = 0 1031 while count < 2: 1032 count += 1 1033 try: 1034 pass 1035 finally: 1036 continue 1037 break 1038 self.assertEqual(count, 2) 1039 1040 count = 0 1041 while count < 2: 1042 count += 1 1043 try: 1044 break 1045 finally: 1046 continue 1047 self.assertEqual(count, 2) 1048 1049 count = 0 1050 while count < 2: 1051 count += 1 1052 try: 1053 1/0 1054 finally: 1055 continue 1056 break 1057 self.assertEqual(count, 2) 1058 1059 for count in [0, 1]: 1060 try: 1061 pass 1062 finally: 1063 continue 1064 break 1065 self.assertEqual(count, 1) 1066 1067 for count in [0, 1]: 1068 try: 1069 break 1070 finally: 1071 continue 1072 self.assertEqual(count, 1) 1073 1074 for count in [0, 1]: 1075 try: 1076 1/0 1077 finally: 1078 continue 1079 break 1080 self.assertEqual(count, 1) 1081 1082 def test_return_in_finally(self): 1083 def g1(): 1084 try: 1085 pass 1086 finally: 1087 return 1 1088 self.assertEqual(g1(), 1) 1089 1090 def g2(): 1091 try: 1092 return 2 1093 finally: 1094 return 3 1095 self.assertEqual(g2(), 3) 1096 1097 def g3(): 1098 try: 1099 1/0 1100 finally: 1101 return 4 1102 self.assertEqual(g3(), 4) 1103 1104 def test_break_in_finally_after_return(self): 1105 # See issue #37830 1106 def g1(x): 1107 for count in [0, 1]: 1108 count2 = 0 1109 while count2 < 20: 1110 count2 += 10 1111 try: 1112 return count + count2 1113 finally: 1114 if x: 1115 break 1116 return 'end', count, count2 1117 self.assertEqual(g1(False), 10) 1118 self.assertEqual(g1(True), ('end', 1, 10)) 1119 1120 def g2(x): 1121 for count in [0, 1]: 1122 for count2 in [10, 20]: 1123 try: 1124 return count + count2 1125 finally: 1126 if x: 1127 break 1128 return 'end', count, count2 1129 self.assertEqual(g2(False), 10) 1130 self.assertEqual(g2(True), ('end', 1, 10)) 1131 1132 def test_continue_in_finally_after_return(self): 1133 # See issue #37830 1134 def g1(x): 1135 count = 0 1136 while count < 100: 1137 count += 1 1138 try: 1139 return count 1140 finally: 1141 if x: 1142 continue 1143 return 'end', count 1144 self.assertEqual(g1(False), 1) 1145 self.assertEqual(g1(True), ('end', 100)) 1146 1147 def g2(x): 1148 for count in [0, 1]: 1149 try: 1150 return count 1151 finally: 1152 if x: 1153 continue 1154 return 'end', count 1155 self.assertEqual(g2(False), 0) 1156 self.assertEqual(g2(True), ('end', 1)) 1157 1158 def test_yield(self): 1159 # Allowed as standalone statement 1160 def g(): yield 1 1161 def g(): yield from () 1162 # Allowed as RHS of assignment 1163 def g(): x = yield 1 1164 def g(): x = yield from () 1165 # Ordinary yield accepts implicit tuples 1166 def g(): yield 1, 1 1167 def g(): x = yield 1, 1 1168 # 'yield from' does not 1169 check_syntax_error(self, "def g(): yield from (), 1") 1170 check_syntax_error(self, "def g(): x = yield from (), 1") 1171 # Requires parentheses as subexpression 1172 def g(): 1, (yield 1) 1173 def g(): 1, (yield from ()) 1174 check_syntax_error(self, "def g(): 1, yield 1") 1175 check_syntax_error(self, "def g(): 1, yield from ()") 1176 # Requires parentheses as call argument 1177 def g(): f((yield 1)) 1178 def g(): f((yield 1), 1) 1179 def g(): f((yield from ())) 1180 def g(): f((yield from ()), 1) 1181 # Do not require parenthesis for tuple unpacking 1182 def g(): rest = 4, 5, 6; yield 1, 2, 3, *rest 1183 self.assertEqual(list(g()), [(1, 2, 3, 4, 5, 6)]) 1184 check_syntax_error(self, "def g(): f(yield 1)") 1185 check_syntax_error(self, "def g(): f(yield 1, 1)") 1186 check_syntax_error(self, "def g(): f(yield from ())") 1187 check_syntax_error(self, "def g(): f(yield from (), 1)") 1188 # Not allowed at top level 1189 check_syntax_error(self, "yield") 1190 check_syntax_error(self, "yield from") 1191 # Not allowed at class scope 1192 check_syntax_error(self, "class foo:yield 1") 1193 check_syntax_error(self, "class foo:yield from ()") 1194 # Check annotation refleak on SyntaxError 1195 check_syntax_error(self, "def g(a:(yield)): pass") 1196 1197 def test_yield_in_comprehensions(self): 1198 # Check yield in comprehensions 1199 def g(): [x for x in [(yield 1)]] 1200 def g(): [x for x in [(yield from ())]] 1201 1202 check = self.check_syntax_error 1203 check("def g(): [(yield x) for x in ()]", 1204 "'yield' inside list comprehension") 1205 check("def g(): [x for x in () if not (yield x)]", 1206 "'yield' inside list comprehension") 1207 check("def g(): [y for x in () for y in [(yield x)]]", 1208 "'yield' inside list comprehension") 1209 check("def g(): {(yield x) for x in ()}", 1210 "'yield' inside set comprehension") 1211 check("def g(): {(yield x): x for x in ()}", 1212 "'yield' inside dict comprehension") 1213 check("def g(): {x: (yield x) for x in ()}", 1214 "'yield' inside dict comprehension") 1215 check("def g(): ((yield x) for x in ())", 1216 "'yield' inside generator expression") 1217 check("def g(): [(yield from x) for x in ()]", 1218 "'yield' inside list comprehension") 1219 check("class C: [(yield x) for x in ()]", 1220 "'yield' inside list comprehension") 1221 check("[(yield x) for x in ()]", 1222 "'yield' inside list comprehension") 1223 1224 def test_raise(self): 1225 # 'raise' test [',' test] 1226 try: raise RuntimeError('just testing') 1227 except RuntimeError: pass 1228 try: raise KeyboardInterrupt 1229 except KeyboardInterrupt: pass 1230 1231 def test_import(self): 1232 # 'import' dotted_as_names 1233 import sys 1234 import time, sys 1235 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names) 1236 from time import time 1237 from time import (time) 1238 # not testable inside a function, but already done at top of the module 1239 # from sys import * 1240 from sys import path, argv 1241 from sys import (path, argv) 1242 from sys import (path, argv,) 1243 1244 def test_global(self): 1245 # 'global' NAME (',' NAME)* 1246 global a 1247 global a, b 1248 global one, two, three, four, five, six, seven, eight, nine, ten 1249 1250 def test_nonlocal(self): 1251 # 'nonlocal' NAME (',' NAME)* 1252 x = 0 1253 y = 0 1254 def f(): 1255 nonlocal x 1256 nonlocal x, y 1257 1258 def test_assert(self): 1259 # assertTruestmt: 'assert' test [',' test] 1260 assert 1 1261 assert 1, 1 1262 assert lambda x:x 1263 assert 1, lambda x:x+1 1264 1265 try: 1266 assert True 1267 except AssertionError as e: 1268 self.fail("'assert True' should not have raised an AssertionError") 1269 1270 try: 1271 assert True, 'this should always pass' 1272 except AssertionError as e: 1273 self.fail("'assert True, msg' should not have " 1274 "raised an AssertionError") 1275 1276 # these tests fail if python is run with -O, so check __debug__ 1277 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False") 1278 def test_assert_failures(self): 1279 try: 1280 assert 0, "msg" 1281 except AssertionError as e: 1282 self.assertEqual(e.args[0], "msg") 1283 else: 1284 self.fail("AssertionError not raised by assert 0") 1285 1286 try: 1287 assert False 1288 except AssertionError as e: 1289 self.assertEqual(len(e.args), 0) 1290 else: 1291 self.fail("AssertionError not raised by 'assert False'") 1292 1293 def test_assert_syntax_warnings(self): 1294 # Ensure that we warn users if they provide a non-zero length tuple as 1295 # the assertion test. 1296 self.check_syntax_warning('assert(x, "msg")', 1297 'assertion is always true') 1298 self.check_syntax_warning('assert(False, "msg")', 1299 'assertion is always true') 1300 self.check_syntax_warning('assert(False,)', 1301 'assertion is always true') 1302 1303 with self.check_no_warnings(category=SyntaxWarning): 1304 compile('assert x, "msg"', '<testcase>', 'exec') 1305 compile('assert False, "msg"', '<testcase>', 'exec') 1306 1307 def test_assert_warning_promotes_to_syntax_error(self): 1308 # If SyntaxWarning is configured to be an error, it actually raises a 1309 # SyntaxError. 1310 # https://bugs.python.org/issue35029 1311 with warnings.catch_warnings(): 1312 warnings.simplefilter('error', SyntaxWarning) 1313 try: 1314 compile('assert x, "msg" ', '<testcase>', 'exec') 1315 except SyntaxError: 1316 self.fail('SyntaxError incorrectly raised for \'assert x, "msg"\'') 1317 with self.assertRaises(SyntaxError): 1318 compile('assert(x, "msg")', '<testcase>', 'exec') 1319 with self.assertRaises(SyntaxError): 1320 compile('assert(False, "msg")', '<testcase>', 'exec') 1321 with self.assertRaises(SyntaxError): 1322 compile('assert(False,)', '<testcase>', 'exec') 1323 1324 1325 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef 1326 # Tested below 1327 1328 def test_if(self): 1329 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] 1330 if 1: pass 1331 if 1: pass 1332 else: pass 1333 if 0: pass 1334 elif 0: pass 1335 if 0: pass 1336 elif 0: pass 1337 elif 0: pass 1338 elif 0: pass 1339 else: pass 1340 1341 def test_while(self): 1342 # 'while' test ':' suite ['else' ':' suite] 1343 while 0: pass 1344 while 0: pass 1345 else: pass 1346 1347 # Issue1920: "while 0" is optimized away, 1348 # ensure that the "else" clause is still present. 1349 x = 0 1350 while 0: 1351 x = 1 1352 else: 1353 x = 2 1354 self.assertEqual(x, 2) 1355 1356 def test_for(self): 1357 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] 1358 for i in 1, 2, 3: pass 1359 for i, j, k in (): pass 1360 else: pass 1361 class Squares: 1362 def __init__(self, max): 1363 self.max = max 1364 self.sofar = [] 1365 def __len__(self): return len(self.sofar) 1366 def __getitem__(self, i): 1367 if not 0 <= i < self.max: raise IndexError 1368 n = len(self.sofar) 1369 while n <= i: 1370 self.sofar.append(n*n) 1371 n = n+1 1372 return self.sofar[i] 1373 n = 0 1374 for x in Squares(10): n = n+x 1375 if n != 285: 1376 self.fail('for over growing sequence') 1377 1378 result = [] 1379 for x, in [(1,), (2,), (3,)]: 1380 result.append(x) 1381 self.assertEqual(result, [1, 2, 3]) 1382 1383 result = [] 1384 a = b = c = [1, 2, 3] 1385 for x in *a, *b, *c: 1386 result.append(x) 1387 self.assertEqual(result, 3 * a) 1388 1389 def test_try(self): 1390 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite] 1391 ### | 'try' ':' suite 'finally' ':' suite 1392 ### except_clause: 'except' [expr ['as' NAME]] 1393 try: 1394 1/0 1395 except ZeroDivisionError: 1396 pass 1397 else: 1398 pass 1399 try: 1/0 1400 except EOFError: pass 1401 except TypeError as msg: pass 1402 except: pass 1403 else: pass 1404 try: 1/0 1405 except (EOFError, TypeError, ZeroDivisionError): pass 1406 try: 1/0 1407 except (EOFError, TypeError, ZeroDivisionError) as msg: pass 1408 try: pass 1409 finally: pass 1410 with self.assertRaises(SyntaxError): 1411 compile("try:\n pass\nexcept Exception as a.b:\n pass", "?", "exec") 1412 compile("try:\n pass\nexcept Exception as a[b]:\n pass", "?", "exec") 1413 1414 def test_try_star(self): 1415 ### try_stmt: 'try': suite (except_star_clause : suite) + ['else' ':' suite] 1416 ### except_star_clause: 'except*' expr ['as' NAME] 1417 try: 1418 1/0 1419 except* ZeroDivisionError: 1420 pass 1421 else: 1422 pass 1423 try: 1/0 1424 except* EOFError: pass 1425 except* ZeroDivisionError as msg: pass 1426 else: pass 1427 try: 1/0 1428 except* (EOFError, TypeError, ZeroDivisionError): pass 1429 try: 1/0 1430 except* (EOFError, TypeError, ZeroDivisionError) as msg: pass 1431 try: pass 1432 finally: pass 1433 with self.assertRaises(SyntaxError): 1434 compile("try:\n pass\nexcept* Exception as a.b:\n pass", "?", "exec") 1435 compile("try:\n pass\nexcept* Exception as a[b]:\n pass", "?", "exec") 1436 compile("try:\n pass\nexcept*:\n pass", "?", "exec") 1437 1438 def test_suite(self): 1439 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT 1440 if 1: pass 1441 if 1: 1442 pass 1443 if 1: 1444 # 1445 # 1446 # 1447 pass 1448 pass 1449 # 1450 pass 1451 # 1452 1453 def test_test(self): 1454 ### and_test ('or' and_test)* 1455 ### and_test: not_test ('and' not_test)* 1456 ### not_test: 'not' not_test | comparison 1457 if not 1: pass 1458 if 1 and 1: pass 1459 if 1 or 1: pass 1460 if not not not 1: pass 1461 if not 1 and 1 and 1: pass 1462 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass 1463 1464 def test_comparison(self): 1465 ### comparison: expr (comp_op expr)* 1466 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not' 1467 if 1: pass 1468 x = (1 == 1) 1469 if 1 == 1: pass 1470 if 1 != 1: pass 1471 if 1 < 1: pass 1472 if 1 > 1: pass 1473 if 1 <= 1: pass 1474 if 1 >= 1: pass 1475 if x is x: pass 1476 if x is not x: pass 1477 if 1 in (): pass 1478 if 1 not in (): pass 1479 if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in x is x is not x: pass 1480 1481 def test_comparison_is_literal(self): 1482 def check(test, msg): 1483 self.check_syntax_warning(test, msg) 1484 1485 check('x is 1', '"is" with \'int\' literal') 1486 check('x is "thing"', '"is" with \'str\' literal') 1487 check('1 is x', '"is" with \'int\' literal') 1488 check('x is y is 1', '"is" with \'int\' literal') 1489 check('x is not 1', '"is not" with \'int\' literal') 1490 check('x is not (1, 2)', '"is not" with \'tuple\' literal') 1491 check('(1, 2) is not x', '"is not" with \'tuple\' literal') 1492 1493 check('None is 1', '"is" with \'int\' literal') 1494 check('1 is None', '"is" with \'int\' literal') 1495 1496 check('x == 3 is y', '"is" with \'int\' literal') 1497 check('x == "thing" is y', '"is" with \'str\' literal') 1498 1499 with warnings.catch_warnings(): 1500 warnings.simplefilter('error', SyntaxWarning) 1501 compile('x is None', '<testcase>', 'exec') 1502 compile('x is False', '<testcase>', 'exec') 1503 compile('x is True', '<testcase>', 'exec') 1504 compile('x is ...', '<testcase>', 'exec') 1505 compile('None is x', '<testcase>', 'exec') 1506 compile('False is x', '<testcase>', 'exec') 1507 compile('True is x', '<testcase>', 'exec') 1508 compile('... is x', '<testcase>', 'exec') 1509 1510 def test_warn_missed_comma(self): 1511 def check(test): 1512 self.check_syntax_warning(test, msg) 1513 1514 msg=r'is not callable; perhaps you missed a comma\?' 1515 check('[(1, 2) (3, 4)]') 1516 check('[(x, y) (3, 4)]') 1517 check('[[1, 2] (3, 4)]') 1518 check('[{1, 2} (3, 4)]') 1519 check('[{1: 2} (3, 4)]') 1520 check('[[i for i in range(5)] (3, 4)]') 1521 check('[{i for i in range(5)} (3, 4)]') 1522 check('[(i for i in range(5)) (3, 4)]') 1523 check('[{i: i for i in range(5)} (3, 4)]') 1524 check('[f"{x}" (3, 4)]') 1525 check('[f"x={x}" (3, 4)]') 1526 check('["abc" (3, 4)]') 1527 check('[b"abc" (3, 4)]') 1528 check('[123 (3, 4)]') 1529 check('[12.3 (3, 4)]') 1530 check('[12.3j (3, 4)]') 1531 check('[None (3, 4)]') 1532 check('[True (3, 4)]') 1533 check('[... (3, 4)]') 1534 1535 msg=r'is not subscriptable; perhaps you missed a comma\?' 1536 check('[{1, 2} [i, j]]') 1537 check('[{i for i in range(5)} [i, j]]') 1538 check('[(i for i in range(5)) [i, j]]') 1539 check('[(lambda x, y: x) [i, j]]') 1540 check('[123 [i, j]]') 1541 check('[12.3 [i, j]]') 1542 check('[12.3j [i, j]]') 1543 check('[None [i, j]]') 1544 check('[True [i, j]]') 1545 check('[... [i, j]]') 1546 1547 msg=r'indices must be integers or slices, not tuple; perhaps you missed a comma\?' 1548 check('[(1, 2) [i, j]]') 1549 check('[(x, y) [i, j]]') 1550 check('[[1, 2] [i, j]]') 1551 check('[[i for i in range(5)] [i, j]]') 1552 check('[f"{x}" [i, j]]') 1553 check('[f"x={x}" [i, j]]') 1554 check('["abc" [i, j]]') 1555 check('[b"abc" [i, j]]') 1556 1557 msg=r'indices must be integers or slices, not tuple;' 1558 check('[[1, 2] [3, 4]]') 1559 msg=r'indices must be integers or slices, not list;' 1560 check('[[1, 2] [[3, 4]]]') 1561 check('[[1, 2] [[i for i in range(5)]]]') 1562 msg=r'indices must be integers or slices, not set;' 1563 check('[[1, 2] [{3, 4}]]') 1564 check('[[1, 2] [{i for i in range(5)}]]') 1565 msg=r'indices must be integers or slices, not dict;' 1566 check('[[1, 2] [{3: 4}]]') 1567 check('[[1, 2] [{i: i for i in range(5)}]]') 1568 msg=r'indices must be integers or slices, not generator;' 1569 check('[[1, 2] [(i for i in range(5))]]') 1570 msg=r'indices must be integers or slices, not function;' 1571 check('[[1, 2] [(lambda x, y: x)]]') 1572 msg=r'indices must be integers or slices, not str;' 1573 check('[[1, 2] [f"{x}"]]') 1574 check('[[1, 2] [f"x={x}"]]') 1575 check('[[1, 2] ["abc"]]') 1576 msg=r'indices must be integers or slices, not' 1577 check('[[1, 2] [b"abc"]]') 1578 check('[[1, 2] [12.3]]') 1579 check('[[1, 2] [12.3j]]') 1580 check('[[1, 2] [None]]') 1581 check('[[1, 2] [...]]') 1582 1583 with warnings.catch_warnings(): 1584 warnings.simplefilter('error', SyntaxWarning) 1585 compile('[(lambda x, y: x) (3, 4)]', '<testcase>', 'exec') 1586 compile('[[1, 2] [i]]', '<testcase>', 'exec') 1587 compile('[[1, 2] [0]]', '<testcase>', 'exec') 1588 compile('[[1, 2] [True]]', '<testcase>', 'exec') 1589 compile('[[1, 2] [1:2]]', '<testcase>', 'exec') 1590 compile('[{(1, 2): 3} [i, j]]', '<testcase>', 'exec') 1591 1592 def test_binary_mask_ops(self): 1593 x = 1 & 1 1594 x = 1 ^ 1 1595 x = 1 | 1 1596 1597 def test_shift_ops(self): 1598 x = 1 << 1 1599 x = 1 >> 1 1600 x = 1 << 1 >> 1 1601 1602 def test_additive_ops(self): 1603 x = 1 1604 x = 1 + 1 1605 x = 1 - 1 - 1 1606 x = 1 - 1 + 1 - 1 + 1 1607 1608 def test_multiplicative_ops(self): 1609 x = 1 * 1 1610 x = 1 / 1 1611 x = 1 % 1 1612 x = 1 / 1 * 1 % 1 1613 1614 def test_unary_ops(self): 1615 x = +1 1616 x = -1 1617 x = ~1 1618 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1 1619 x = -1*1/1 + 1*1 - ---1*1 1620 1621 def test_selectors(self): 1622 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME 1623 ### subscript: expr | [expr] ':' [expr] 1624 1625 import sys, time 1626 c = sys.path[0] 1627 x = time.time() 1628 x = sys.modules['time'].time() 1629 a = '01234' 1630 c = a[0] 1631 c = a[-1] 1632 s = a[0:5] 1633 s = a[:5] 1634 s = a[0:] 1635 s = a[:] 1636 s = a[-5:] 1637 s = a[:-1] 1638 s = a[-4:-3] 1639 # A rough test of SF bug 1333982. https://bugs.python.org/issue1333982 1640 # The testing here is fairly incomplete. 1641 # Test cases should include: commas with 1 and 2 colons 1642 d = {} 1643 d[1] = 1 1644 d[1,] = 2 1645 d[1,2] = 3 1646 d[1,2,3] = 4 1647 L = list(d) 1648 L.sort(key=lambda x: (type(x).__name__, x)) 1649 self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]') 1650 1651 def test_atoms(self): 1652 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING 1653 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [',']) 1654 1655 x = (1) 1656 x = (1 or 2 or 3) 1657 x = (1 or 2 or 3, 2, 3) 1658 1659 x = [] 1660 x = [1] 1661 x = [1 or 2 or 3] 1662 x = [1 or 2 or 3, 2, 3] 1663 x = [] 1664 1665 x = {} 1666 x = {'one': 1} 1667 x = {'one': 1,} 1668 x = {'one' or 'two': 1 or 2} 1669 x = {'one': 1, 'two': 2} 1670 x = {'one': 1, 'two': 2,} 1671 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} 1672 1673 x = {'one'} 1674 x = {'one', 1,} 1675 x = {'one', 'two', 'three'} 1676 x = {2, 3, 4,} 1677 1678 x = x 1679 x = 'x' 1680 x = 123 1681 1682 ### exprlist: expr (',' expr)* [','] 1683 ### testlist: test (',' test)* [','] 1684 # These have been exercised enough above 1685 1686 def test_classdef(self): 1687 # 'class' NAME ['(' [testlist] ')'] ':' suite 1688 class B: pass 1689 class B2(): pass 1690 class C1(B): pass 1691 class C2(B): pass 1692 class D(C1, C2, B): pass 1693 class C: 1694 def meth1(self): pass 1695 def meth2(self, arg): pass 1696 def meth3(self, a1, a2): pass 1697 1698 # decorator: '@' namedexpr_test NEWLINE 1699 # decorators: decorator+ 1700 # decorated: decorators (classdef | funcdef) 1701 def class_decorator(x): return x 1702 @class_decorator 1703 class G: pass 1704 1705 # Test expressions as decorators (PEP 614): 1706 @False or class_decorator 1707 class H: pass 1708 @d := class_decorator 1709 class I: pass 1710 @lambda c: class_decorator(c) 1711 class J: pass 1712 @[..., class_decorator, ...][1] 1713 class K: pass 1714 @class_decorator(class_decorator)(class_decorator) 1715 class L: pass 1716 @[class_decorator][0].__call__.__call__ 1717 class M: pass 1718 1719 def test_dictcomps(self): 1720 # dictorsetmaker: ( (test ':' test (comp_for | 1721 # (',' test ':' test)* [','])) | 1722 # (test (comp_for | (',' test)* [','])) ) 1723 nums = [1, 2, 3] 1724 self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4}) 1725 1726 def test_listcomps(self): 1727 # list comprehension tests 1728 nums = [1, 2, 3, 4, 5] 1729 strs = ["Apple", "Banana", "Coconut"] 1730 spcs = [" Apple", " Banana ", "Coco nut "] 1731 1732 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut']) 1733 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15]) 1734 self.assertEqual([x for x in nums if x > 2], [3, 4, 5]) 1735 self.assertEqual([(i, s) for i in nums for s in strs], 1736 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'), 1737 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'), 1738 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'), 1739 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'), 1740 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')]) 1741 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]], 1742 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'), 1743 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'), 1744 (5, 'Banana'), (5, 'Coconut')]) 1745 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)], 1746 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]]) 1747 1748 def test_in_func(l): 1749 return [0 < x < 3 for x in l if x > 2] 1750 1751 self.assertEqual(test_in_func(nums), [False, False, False]) 1752 1753 def test_nested_front(): 1754 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]], 1755 [[1, 2], [3, 4], [5, 6]]) 1756 1757 test_nested_front() 1758 1759 check_syntax_error(self, "[i, s for i in nums for s in strs]") 1760 check_syntax_error(self, "[x if y]") 1761 1762 suppliers = [ 1763 (1, "Boeing"), 1764 (2, "Ford"), 1765 (3, "Macdonalds") 1766 ] 1767 1768 parts = [ 1769 (10, "Airliner"), 1770 (20, "Engine"), 1771 (30, "Cheeseburger") 1772 ] 1773 1774 suppart = [ 1775 (1, 10), (1, 20), (2, 20), (3, 30) 1776 ] 1777 1778 x = [ 1779 (sname, pname) 1780 for (sno, sname) in suppliers 1781 for (pno, pname) in parts 1782 for (sp_sno, sp_pno) in suppart 1783 if sno == sp_sno and pno == sp_pno 1784 ] 1785 1786 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'), 1787 ('Macdonalds', 'Cheeseburger')]) 1788 1789 def test_genexps(self): 1790 # generator expression tests 1791 g = ([x for x in range(10)] for x in range(1)) 1792 self.assertEqual(next(g), [x for x in range(10)]) 1793 try: 1794 next(g) 1795 self.fail('should produce StopIteration exception') 1796 except StopIteration: 1797 pass 1798 1799 a = 1 1800 try: 1801 g = (a for d in a) 1802 next(g) 1803 self.fail('should produce TypeError') 1804 except TypeError: 1805 pass 1806 1807 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd']) 1808 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy']) 1809 1810 a = [x for x in range(10)] 1811 b = (x for x in (y for y in a)) 1812 self.assertEqual(sum(b), sum([x for x in range(10)])) 1813 1814 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)])) 1815 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2])) 1816 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)])) 1817 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)])) 1818 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)])) 1819 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)])) 1820 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0) 1821 check_syntax_error(self, "foo(x for x in range(10), 100)") 1822 check_syntax_error(self, "foo(100, x for x in range(10))") 1823 1824 def test_comprehension_specials(self): 1825 # test for outmost iterable precomputation 1826 x = 10; g = (i for i in range(x)); x = 5 1827 self.assertEqual(len(list(g)), 10) 1828 1829 # This should hold, since we're only precomputing outmost iterable. 1830 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x)) 1831 x = 5; t = True; 1832 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g)) 1833 1834 # Grammar allows multiple adjacent 'if's in listcomps and genexps, 1835 # even though it's silly. Make sure it works (ifelse broke this.) 1836 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7]) 1837 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7]) 1838 1839 # verify unpacking single element tuples in listcomp/genexp. 1840 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6]) 1841 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9]) 1842 1843 def test_with_statement(self): 1844 class manager(object): 1845 def __enter__(self): 1846 return (1, 2) 1847 def __exit__(self, *args): 1848 pass 1849 1850 with manager(): 1851 pass 1852 with manager() as x: 1853 pass 1854 with manager() as (x, y): 1855 pass 1856 with manager(), manager(): 1857 pass 1858 with manager() as x, manager() as y: 1859 pass 1860 with manager() as x, manager(): 1861 pass 1862 1863 with ( 1864 manager() 1865 ): 1866 pass 1867 1868 with ( 1869 manager() as x 1870 ): 1871 pass 1872 1873 with ( 1874 manager() as (x, y), 1875 manager() as z, 1876 ): 1877 pass 1878 1879 with ( 1880 manager(), 1881 manager() 1882 ): 1883 pass 1884 1885 with ( 1886 manager() as x, 1887 manager() as y 1888 ): 1889 pass 1890 1891 with ( 1892 manager() as x, 1893 manager() 1894 ): 1895 pass 1896 1897 with ( 1898 manager() as x, 1899 manager() as y, 1900 manager() as z, 1901 ): 1902 pass 1903 1904 with ( 1905 manager() as x, 1906 manager() as y, 1907 manager(), 1908 ): 1909 pass 1910 1911 def test_if_else_expr(self): 1912 # Test ifelse expressions in various cases 1913 def _checkeval(msg, ret): 1914 "helper to check that evaluation of expressions is done correctly" 1915 print(msg) 1916 return ret 1917 1918 # the next line is not allowed anymore 1919 #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True]) 1920 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True]) 1921 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]) 1922 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5) 1923 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5) 1924 self.assertEqual((5 and 6 if 0 else 1), 1) 1925 self.assertEqual(((5 and 6) if 0 else 1), 1) 1926 self.assertEqual((5 and (6 if 1 else 1)), 6) 1927 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3) 1928 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1) 1929 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5) 1930 self.assertEqual((not 5 if 1 else 1), False) 1931 self.assertEqual((not 5 if 0 else 1), 1) 1932 self.assertEqual((6 + 1 if 1 else 2), 7) 1933 self.assertEqual((6 - 1 if 1 else 2), 5) 1934 self.assertEqual((6 * 2 if 1 else 4), 12) 1935 self.assertEqual((6 / 2 if 1 else 3), 3) 1936 self.assertEqual((6 < 4 if 0 else 2), 2) 1937 1938 def test_paren_evaluation(self): 1939 self.assertEqual(16 // (4 // 2), 8) 1940 self.assertEqual((16 // 4) // 2, 2) 1941 self.assertEqual(16 // 4 // 2, 2) 1942 x = 2 1943 y = 3 1944 self.assertTrue(False is (x is y)) 1945 self.assertFalse((False is x) is y) 1946 self.assertFalse(False is x is y) 1947 1948 def test_matrix_mul(self): 1949 # This is not intended to be a comprehensive test, rather just to be few 1950 # samples of the @ operator in test_grammar.py. 1951 class M: 1952 def __matmul__(self, o): 1953 return 4 1954 def __imatmul__(self, o): 1955 self.other = o 1956 return self 1957 m = M() 1958 self.assertEqual(m @ m, 4) 1959 m @= 42 1960 self.assertEqual(m.other, 42) 1961 1962 def test_async_await(self): 1963 async def test(): 1964 def sum(): 1965 pass 1966 if 1: 1967 await someobj() 1968 1969 self.assertEqual(test.__name__, 'test') 1970 self.assertTrue(bool(test.__code__.co_flags & inspect.CO_COROUTINE)) 1971 1972 def decorator(func): 1973 setattr(func, '_marked', True) 1974 return func 1975 1976 @decorator 1977 async def test2(): 1978 return 22 1979 self.assertTrue(test2._marked) 1980 self.assertEqual(test2.__name__, 'test2') 1981 self.assertTrue(bool(test2.__code__.co_flags & inspect.CO_COROUTINE)) 1982 1983 def test_async_for(self): 1984 class Done(Exception): pass 1985 1986 class AIter: 1987 def __aiter__(self): 1988 return self 1989 async def __anext__(self): 1990 raise StopAsyncIteration 1991 1992 async def foo(): 1993 async for i in AIter(): 1994 pass 1995 async for i, j in AIter(): 1996 pass 1997 async for i in AIter(): 1998 pass 1999 else: 2000 pass 2001 raise Done 2002 2003 with self.assertRaises(Done): 2004 foo().send(None) 2005 2006 def test_async_with(self): 2007 class Done(Exception): pass 2008 2009 class manager: 2010 async def __aenter__(self): 2011 return (1, 2) 2012 async def __aexit__(self, *exc): 2013 return False 2014 2015 async def foo(): 2016 async with manager(): 2017 pass 2018 async with manager() as x: 2019 pass 2020 async with manager() as (x, y): 2021 pass 2022 async with manager(), manager(): 2023 pass 2024 async with manager() as x, manager() as y: 2025 pass 2026 async with manager() as x, manager(): 2027 pass 2028 raise Done 2029 2030 with self.assertRaises(Done): 2031 foo().send(None) 2032 2033 2034if __name__ == '__main__': 2035 unittest.main() 2036