Debian Codegraph @

Lib/test/test_grammar.py

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