ยปCore Development>Code coverage>Lib/test/test_grammar.py

Python code coverage for Lib/test/test_grammar.py

#countcontent
1n/a# Python test set -- part 1, grammar.
2n/a# This just tests whether the parser accepts them all.
3n/a
4n/afrom test.support import check_syntax_error
5n/aimport inspect
6n/aimport unittest
7n/aimport sys
8n/a# testing import *
9n/afrom sys import *
10n/a
11n/a# different import patterns to check that __annotations__ does not interfere
12n/a# with import machinery
13n/aimport test.ann_module as ann_module
14n/aimport typing
15n/afrom collections import ChainMap
16n/afrom test import ann_module2
17n/aimport test
18n/a
19n/a# These are shared with test_tokenize and other test modules.
20n/a#
21n/a# Note: since several test cases filter out floats by looking for "e" and ".",
22n/a# don't add hexadecimal literals that contain "e" or "E".
23n/aVALID_UNDERSCORE_LITERALS = [
24n/a '0_0_0',
25n/a '4_2',
26n/a '1_0000_0000',
27n/a '0b1001_0100',
28n/a '0xffff_ffff',
29n/a '0o5_7_7',
30n/a '1_00_00.5',
31n/a '1_00_00.5e5',
32n/a '1_00_00e5_1',
33n/a '1e1_0',
34n/a '.1_4',
35n/a '.1_4e1',
36n/a '0b_0',
37n/a '0x_f',
38n/a '0o_5',
39n/a '1_00_00j',
40n/a '1_00_00.5j',
41n/a '1_00_00e5_1j',
42n/a '.1_4j',
43n/a '(1_2.5+3_3j)',
44n/a '(.5_6j)',
45n/a]
46n/aINVALID_UNDERSCORE_LITERALS = [
47n/a # Trailing underscores:
48n/a '0_',
49n/a '42_',
50n/a '1.4j_',
51n/a '0x_',
52n/a '0b1_',
53n/a '0xf_',
54n/a '0o5_',
55n/a '0 if 1_Else 1',
56n/a # Underscores in the base selector:
57n/a '0_b0',
58n/a '0_xf',
59n/a '0_o5',
60n/a # Old-style octal, still disallowed:
61n/a '0_7',
62n/a '09_99',
63n/a # Multiple consecutive underscores:
64n/a '4_______2',
65n/a '0.1__4',
66n/a '0.1__4j',
67n/a '0b1001__0100',
68n/a '0xffff__ffff',
69n/a '0x___',
70n/a '0o5__77',
71n/a '1e1__0',
72n/a '1e1__0j',
73n/a # Underscore right before a dot:
74n/a '1_.4',
75n/a '1_.4j',
76n/a # Underscore right after a dot:
77n/a '1._4',
78n/a '1._4j',
79n/a '._5',
80n/a '._5j',
81n/a # Underscore right after a sign:
82n/a '1.0e+_1',
83n/a '1.0e+_1j',
84n/a # Underscore right before j:
85n/a '1.4_j',
86n/a '1.4e5_j',
87n/a # Underscore right before e:
88n/a '1_e1',
89n/a '1.4_e1',
90n/a '1.4_e1j',
91n/a # Underscore right after e:
92n/a '1e_1',
93n/a '1.4e_1',
94n/a '1.4e_1j',
95n/a # Complex cases with parens:
96n/a '(1+1.5_j_)',
97n/a '(1+1.5_j)',
98n/a]
99n/a
100n/a
101n/aclass TokenTests(unittest.TestCase):
102n/a
103n/a def test_backslash(self):
104n/a # Backslash means line continuation:
105n/a x = 1 \
106n/a + 1
107n/a self.assertEqual(x, 2, 'backslash for line continuation')
108n/a
109n/a # Backslash does not means continuation in comments :\
110n/a x = 0
111n/a self.assertEqual(x, 0, 'backslash ending comment')
112n/a
113n/a def test_plain_integers(self):
114n/a self.assertEqual(type(000), type(0))
115n/a self.assertEqual(0xff, 255)
116n/a self.assertEqual(0o377, 255)
117n/a self.assertEqual(2147483647, 0o17777777777)
118n/a self.assertEqual(0b1001, 9)
119n/a # "0x" is not a valid literal
120n/a self.assertRaises(SyntaxError, eval, "0x")
121n/a from sys import maxsize
122n/a if maxsize == 2147483647:
123n/a self.assertEqual(-2147483647-1, -0o20000000000)
124n/a # XXX -2147483648
125n/a self.assertTrue(0o37777777777 > 0)
126n/a self.assertTrue(0xffffffff > 0)
127n/a self.assertTrue(0b1111111111111111111111111111111 > 0)
128n/a for s in ('2147483648', '0o40000000000', '0x100000000',
129n/a '0b10000000000000000000000000000000'):
130n/a try:
131n/a x = eval(s)
132n/a except OverflowError:
133n/a self.fail("OverflowError on huge integer literal %r" % s)
134n/a elif maxsize == 9223372036854775807:
135n/a self.assertEqual(-9223372036854775807-1, -0o1000000000000000000000)
136n/a self.assertTrue(0o1777777777777777777777 > 0)
137n/a self.assertTrue(0xffffffffffffffff > 0)
138n/a self.assertTrue(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
139n/a for s in '9223372036854775808', '0o2000000000000000000000', \
140n/a '0x10000000000000000', \
141n/a '0b100000000000000000000000000000000000000000000000000000000000000':
142n/a try:
143n/a x = eval(s)
144n/a except OverflowError:
145n/a self.fail("OverflowError on huge integer literal %r" % s)
146n/a else:
147n/a self.fail('Weird maxsize value %r' % maxsize)
148n/a
149n/a def test_long_integers(self):
150n/a x = 0
151n/a x = 0xffffffffffffffff
152n/a x = 0Xffffffffffffffff
153n/a x = 0o77777777777777777
154n/a x = 0O77777777777777777
155n/a x = 123456789012345678901234567890
156n/a x = 0b100000000000000000000000000000000000000000000000000000000000000000000
157n/a x = 0B111111111111111111111111111111111111111111111111111111111111111111111
158n/a
159n/a def test_floats(self):
160n/a x = 3.14
161n/a x = 314.
162n/a x = 0.314
163n/a # XXX x = 000.314
164n/a x = .314
165n/a x = 3e14
166n/a x = 3E14
167n/a x = 3e-14
168n/a x = 3e+14
169n/a x = 3.e14
170n/a x = .3e14
171n/a x = 3.1e4
172n/a
173n/a def test_float_exponent_tokenization(self):
174n/a # See issue 21642.
175n/a self.assertEqual(1 if 1else 0, 1)
176n/a self.assertEqual(1 if 0else 0, 0)
177n/a self.assertRaises(SyntaxError, eval, "0 if 1Else 0")
178n/a
179n/a def test_underscore_literals(self):
180n/a for lit in VALID_UNDERSCORE_LITERALS:
181n/a self.assertEqual(eval(lit), eval(lit.replace('_', '')))
182n/a for lit in INVALID_UNDERSCORE_LITERALS:
183n/a self.assertRaises(SyntaxError, eval, lit)
184n/a # Sanity check: no literal begins with an underscore
185n/a self.assertRaises(NameError, eval, "_0")
186n/a
187n/a def test_string_literals(self):
188n/a x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y)
189n/a x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39)
190n/a x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34)
191n/a x = "doesn't \"shrink\" does it"
192n/a y = 'doesn\'t "shrink" does it'
193n/a self.assertTrue(len(x) == 24 and x == y)
194n/a x = "does \"shrink\" doesn't it"
195n/a y = 'does "shrink" doesn\'t it'
196n/a self.assertTrue(len(x) == 24 and x == y)
197n/a x = """
198n/aThe "quick"
199n/abrown fox
200n/ajumps over
201n/athe 'lazy' dog.
202n/a"""
203n/a y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
204n/a self.assertEqual(x, y)
205n/a y = '''
206n/aThe "quick"
207n/abrown fox
208n/ajumps over
209n/athe 'lazy' dog.
210n/a'''
211n/a self.assertEqual(x, y)
212n/a y = "\n\
213n/aThe \"quick\"\n\
214n/abrown fox\n\
215n/ajumps over\n\
216n/athe 'lazy' dog.\n\
217n/a"
218n/a self.assertEqual(x, y)
219n/a y = '\n\
220n/aThe \"quick\"\n\
221n/abrown fox\n\
222n/ajumps over\n\
223n/athe \'lazy\' dog.\n\
224n/a'
225n/a self.assertEqual(x, y)
226n/a
227n/a def test_ellipsis(self):
228n/a x = ...
229n/a self.assertTrue(x is Ellipsis)
230n/a self.assertRaises(SyntaxError, eval, ".. .")
231n/a
232n/a def test_eof_error(self):
233n/a samples = ("def foo(", "\ndef foo(", "def foo(\n")
234n/a for s in samples:
235n/a with self.assertRaises(SyntaxError) as cm:
236n/a compile(s, "<test>", "exec")
237n/a self.assertIn("unexpected EOF", str(cm.exception))
238n/a
239n/avar_annot_global: int # a global annotated is necessary for test_var_annot
240n/a
241n/a# custom namespace for testing __annotations__
242n/a
243n/aclass CNS:
244n/a def __init__(self):
245n/a self._dct = {}
246n/a def __setitem__(self, item, value):
247n/a self._dct[item.lower()] = value
248n/a def __getitem__(self, item):
249n/a return self._dct[item]
250n/a
251n/a
252n/aclass GrammarTests(unittest.TestCase):
253n/a
254n/a # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
255n/a # XXX can't test in a script -- this rule is only used when interactive
256n/a
257n/a # file_input: (NEWLINE | stmt)* ENDMARKER
258n/a # Being tested as this very moment this very module
259n/a
260n/a # expr_input: testlist NEWLINE
261n/a # XXX Hard to test -- used only in calls to input()
262n/a
263n/a def test_eval_input(self):
264n/a # testlist ENDMARKER
265n/a x = eval('1, 0 or 1')
266n/a
267n/a def test_var_annot_basics(self):
268n/a # all these should be allowed
269n/a var1: int = 5
270n/a var2: [int, str]
271n/a my_lst = [42]
272n/a def one():
273n/a return 1
274n/a int.new_attr: int
275n/a [list][0]: type
276n/a my_lst[one()-1]: int = 5
277n/a self.assertEqual(my_lst, [5])
278n/a
279n/a def test_var_annot_syntax_errors(self):
280n/a # parser pass
281n/a check_syntax_error(self, "def f: int")
282n/a check_syntax_error(self, "x: int: str")
283n/a check_syntax_error(self, "def f():\n"
284n/a " nonlocal x: int\n")
285n/a # AST pass
286n/a check_syntax_error(self, "[x, 0]: int\n")
287n/a check_syntax_error(self, "f(): int\n")
288n/a check_syntax_error(self, "(x,): int")
289n/a check_syntax_error(self, "def f():\n"
290n/a " (x, y): int = (1, 2)\n")
291n/a # symtable pass
292n/a check_syntax_error(self, "def f():\n"
293n/a " x: int\n"
294n/a " global x\n")
295n/a check_syntax_error(self, "def f():\n"
296n/a " global x\n"
297n/a " x: int\n")
298n/a
299n/a def test_var_annot_basic_semantics(self):
300n/a # execution order
301n/a with self.assertRaises(ZeroDivisionError):
302n/a no_name[does_not_exist]: no_name_again = 1/0
303n/a with self.assertRaises(NameError):
304n/a no_name[does_not_exist]: 1/0 = 0
305n/a global var_annot_global
306n/a
307n/a # function semantics
308n/a def f():
309n/a st: str = "Hello"
310n/a a.b: int = (1, 2)
311n/a return st
312n/a self.assertEqual(f.__annotations__, {})
313n/a def f_OK():
314n/a x: 1/0
315n/a f_OK()
316n/a def fbad():
317n/a x: int
318n/a print(x)
319n/a with self.assertRaises(UnboundLocalError):
320n/a fbad()
321n/a def f2bad():
322n/a (no_such_global): int
323n/a print(no_such_global)
324n/a try:
325n/a f2bad()
326n/a except Exception as e:
327n/a self.assertIs(type(e), NameError)
328n/a
329n/a # class semantics
330n/a class C:
331n/a __foo: int
332n/a s: str = "attr"
333n/a z = 2
334n/a def __init__(self, x):
335n/a self.x: int = x
336n/a self.assertEqual(C.__annotations__, {'_C__foo': int, 's': str})
337n/a with self.assertRaises(NameError):
338n/a class CBad:
339n/a no_such_name_defined.attr: int = 0
340n/a with self.assertRaises(NameError):
341n/a class Cbad2(C):
342n/a x: int
343n/a x.y: list = []
344n/a
345n/a def test_var_annot_metaclass_semantics(self):
346n/a class CMeta(type):
347n/a @classmethod
348n/a def __prepare__(metacls, name, bases, **kwds):
349n/a return {'__annotations__': CNS()}
350n/a class CC(metaclass=CMeta):
351n/a XX: 'ANNOT'
352n/a self.assertEqual(CC.__annotations__['xx'], 'ANNOT')
353n/a
354n/a def test_var_annot_module_semantics(self):
355n/a with self.assertRaises(AttributeError):
356n/a print(test.__annotations__)
357n/a self.assertEqual(ann_module.__annotations__,
358n/a {1: 2, 'x': int, 'y': str, 'f': typing.Tuple[int, int]})
359n/a self.assertEqual(ann_module.M.__annotations__,
360n/a {'123': 123, 'o': type})
361n/a self.assertEqual(ann_module2.__annotations__, {})
362n/a
363n/a def test_var_annot_in_module(self):
364n/a # check that functions fail the same way when executed
365n/a # outside of module where they were defined
366n/a from test.ann_module3 import f_bad_ann, g_bad_ann, D_bad_ann
367n/a with self.assertRaises(NameError):
368n/a f_bad_ann()
369n/a with self.assertRaises(NameError):
370n/a g_bad_ann()
371n/a with self.assertRaises(NameError):
372n/a D_bad_ann(5)
373n/a
374n/a def test_var_annot_simple_exec(self):
375n/a gns = {}; lns= {}
376n/a exec("'docstring'\n"
377n/a "__annotations__[1] = 2\n"
378n/a "x: int = 5\n", gns, lns)
379n/a self.assertEqual(lns["__annotations__"], {1: 2, 'x': int})
380n/a with self.assertRaises(KeyError):
381n/a gns['__annotations__']
382n/a
383n/a def test_var_annot_custom_maps(self):
384n/a # tests with custom locals() and __annotations__
385n/a ns = {'__annotations__': CNS()}
386n/a exec('X: int; Z: str = "Z"; (w): complex = 1j', ns)
387n/a self.assertEqual(ns['__annotations__']['x'], int)
388n/a self.assertEqual(ns['__annotations__']['z'], str)
389n/a with self.assertRaises(KeyError):
390n/a ns['__annotations__']['w']
391n/a nonloc_ns = {}
392n/a class CNS2:
393n/a def __init__(self):
394n/a self._dct = {}
395n/a def __setitem__(self, item, value):
396n/a nonlocal nonloc_ns
397n/a self._dct[item] = value
398n/a nonloc_ns[item] = value
399n/a def __getitem__(self, item):
400n/a return self._dct[item]
401n/a exec('x: int = 1', {}, CNS2())
402n/a self.assertEqual(nonloc_ns['__annotations__']['x'], int)
403n/a
404n/a def test_var_annot_refleak(self):
405n/a # complex case: custom locals plus custom __annotations__
406n/a # this was causing refleak
407n/a cns = CNS()
408n/a nonloc_ns = {'__annotations__': cns}
409n/a class CNS2:
410n/a def __init__(self):
411n/a self._dct = {'__annotations__': cns}
412n/a def __setitem__(self, item, value):
413n/a nonlocal nonloc_ns
414n/a self._dct[item] = value
415n/a nonloc_ns[item] = value
416n/a def __getitem__(self, item):
417n/a return self._dct[item]
418n/a exec('X: str', {}, CNS2())
419n/a self.assertEqual(nonloc_ns['__annotations__']['x'], str)
420n/a
421n/a def test_funcdef(self):
422n/a ### [decorators] 'def' NAME parameters ['->' test] ':' suite
423n/a ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
424n/a ### decorators: decorator+
425n/a ### parameters: '(' [typedargslist] ')'
426n/a ### typedargslist: ((tfpdef ['=' test] ',')*
427n/a ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
428n/a ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
429n/a ### tfpdef: NAME [':' test]
430n/a ### varargslist: ((vfpdef ['=' test] ',')*
431n/a ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
432n/a ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
433n/a ### vfpdef: NAME
434n/a def f1(): pass
435n/a f1()
436n/a f1(*())
437n/a f1(*(), **{})
438n/a def f2(one_argument): pass
439n/a def f3(two, arguments): pass
440n/a self.assertEqual(f2.__code__.co_varnames, ('one_argument',))
441n/a self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments'))
442n/a def a1(one_arg,): pass
443n/a def a2(two, args,): pass
444n/a def v0(*rest): pass
445n/a def v1(a, *rest): pass
446n/a def v2(a, b, *rest): pass
447n/a
448n/a f1()
449n/a f2(1)
450n/a f2(1,)
451n/a f3(1, 2)
452n/a f3(1, 2,)
453n/a v0()
454n/a v0(1)
455n/a v0(1,)
456n/a v0(1,2)
457n/a v0(1,2,3,4,5,6,7,8,9,0)
458n/a v1(1)
459n/a v1(1,)
460n/a v1(1,2)
461n/a v1(1,2,3)
462n/a v1(1,2,3,4,5,6,7,8,9,0)
463n/a v2(1,2)
464n/a v2(1,2,3)
465n/a v2(1,2,3,4)
466n/a v2(1,2,3,4,5,6,7,8,9,0)
467n/a
468n/a def d01(a=1): pass
469n/a d01()
470n/a d01(1)
471n/a d01(*(1,))
472n/a d01(*[] or [2])
473n/a d01(*() or (), *{} and (), **() or {})
474n/a d01(**{'a':2})
475n/a d01(**{'a':2} or {})
476n/a def d11(a, b=1): pass
477n/a d11(1)
478n/a d11(1, 2)
479n/a d11(1, **{'b':2})
480n/a def d21(a, b, c=1): pass
481n/a d21(1, 2)
482n/a d21(1, 2, 3)
483n/a d21(*(1, 2, 3))
484n/a d21(1, *(2, 3))
485n/a d21(1, 2, *(3,))
486n/a d21(1, 2, **{'c':3})
487n/a def d02(a=1, b=2): pass
488n/a d02()
489n/a d02(1)
490n/a d02(1, 2)
491n/a d02(*(1, 2))
492n/a d02(1, *(2,))
493n/a d02(1, **{'b':2})
494n/a d02(**{'a': 1, 'b': 2})
495n/a def d12(a, b=1, c=2): pass
496n/a d12(1)
497n/a d12(1, 2)
498n/a d12(1, 2, 3)
499n/a def d22(a, b, c=1, d=2): pass
500n/a d22(1, 2)
501n/a d22(1, 2, 3)
502n/a d22(1, 2, 3, 4)
503n/a def d01v(a=1, *rest): pass
504n/a d01v()
505n/a d01v(1)
506n/a d01v(1, 2)
507n/a d01v(*(1, 2, 3, 4))
508n/a d01v(*(1,))
509n/a d01v(**{'a':2})
510n/a def d11v(a, b=1, *rest): pass
511n/a d11v(1)
512n/a d11v(1, 2)
513n/a d11v(1, 2, 3)
514n/a def d21v(a, b, c=1, *rest): pass
515n/a d21v(1, 2)
516n/a d21v(1, 2, 3)
517n/a d21v(1, 2, 3, 4)
518n/a d21v(*(1, 2, 3, 4))
519n/a d21v(1, 2, **{'c': 3})
520n/a def d02v(a=1, b=2, *rest): pass
521n/a d02v()
522n/a d02v(1)
523n/a d02v(1, 2)
524n/a d02v(1, 2, 3)
525n/a d02v(1, *(2, 3, 4))
526n/a d02v(**{'a': 1, 'b': 2})
527n/a def d12v(a, b=1, c=2, *rest): pass
528n/a d12v(1)
529n/a d12v(1, 2)
530n/a d12v(1, 2, 3)
531n/a d12v(1, 2, 3, 4)
532n/a d12v(*(1, 2, 3, 4))
533n/a d12v(1, 2, *(3, 4, 5))
534n/a d12v(1, *(2,), **{'c': 3})
535n/a def d22v(a, b, c=1, d=2, *rest): pass
536n/a d22v(1, 2)
537n/a d22v(1, 2, 3)
538n/a d22v(1, 2, 3, 4)
539n/a d22v(1, 2, 3, 4, 5)
540n/a d22v(*(1, 2, 3, 4))
541n/a d22v(1, 2, *(3, 4, 5))
542n/a d22v(1, *(2, 3), **{'d': 4})
543n/a
544n/a # keyword argument type tests
545n/a try:
546n/a str('x', **{b'foo':1 })
547n/a except TypeError:
548n/a pass
549n/a else:
550n/a self.fail('Bytes should not work as keyword argument names')
551n/a # keyword only argument tests
552n/a def pos0key1(*, key): return key
553n/a pos0key1(key=100)
554n/a def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
555n/a pos2key2(1, 2, k1=100)
556n/a pos2key2(1, 2, k1=100, k2=200)
557n/a pos2key2(1, 2, k2=100, k1=200)
558n/a def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
559n/a pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
560n/a pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
561n/a
562n/a self.assertRaises(SyntaxError, eval, "def f(*): pass")
563n/a self.assertRaises(SyntaxError, eval, "def f(*,): pass")
564n/a self.assertRaises(SyntaxError, eval, "def f(*, **kwds): pass")
565n/a
566n/a # keyword arguments after *arglist
567n/a def f(*args, **kwargs):
568n/a return args, kwargs
569n/a self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
570n/a {'x':2, 'y':5}))
571n/a self.assertEqual(f(1, *(2,3), 4), ((1, 2, 3, 4), {}))
572n/a self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
573n/a self.assertEqual(f(**{'eggs':'scrambled', 'spam':'fried'}),
574n/a ((), {'eggs':'scrambled', 'spam':'fried'}))
575n/a self.assertEqual(f(spam='fried', **{'eggs':'scrambled'}),
576n/a ((), {'eggs':'scrambled', 'spam':'fried'}))
577n/a
578n/a # argument annotation tests
579n/a def f(x) -> list: pass
580n/a self.assertEqual(f.__annotations__, {'return': list})
581n/a def f(x: int): pass
582n/a self.assertEqual(f.__annotations__, {'x': int})
583n/a def f(*x: str): pass
584n/a self.assertEqual(f.__annotations__, {'x': str})
585n/a def f(**x: float): pass
586n/a self.assertEqual(f.__annotations__, {'x': float})
587n/a def f(x, y: 1+2): pass
588n/a self.assertEqual(f.__annotations__, {'y': 3})
589n/a def f(a, b: 1, c: 2, d): pass
590n/a self.assertEqual(f.__annotations__, {'b': 1, 'c': 2})
591n/a def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6): pass
592n/a self.assertEqual(f.__annotations__,
593n/a {'b': 1, 'c': 2, 'e': 3, 'g': 6})
594n/a def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6, h: 7, i=8, j: 9 = 10,
595n/a **k: 11) -> 12: pass
596n/a self.assertEqual(f.__annotations__,
597n/a {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
598n/a 'k': 11, 'return': 12})
599n/a # Check for issue #20625 -- annotations mangling
600n/a class Spam:
601n/a def f(self, *, __kw: 1):
602n/a pass
603n/a class Ham(Spam): pass
604n/a self.assertEqual(Spam.f.__annotations__, {'_Spam__kw': 1})
605n/a self.assertEqual(Ham.f.__annotations__, {'_Spam__kw': 1})
606n/a # Check for SF Bug #1697248 - mixing decorators and a return annotation
607n/a def null(x): return x
608n/a @null
609n/a def f(x) -> list: pass
610n/a self.assertEqual(f.__annotations__, {'return': list})
611n/a
612n/a # test closures with a variety of opargs
613n/a closure = 1
614n/a def f(): return closure
615n/a def f(x=1): return closure
616n/a def f(*, k=1): return closure
617n/a def f() -> int: return closure
618n/a
619n/a # Check ast errors in *args and *kwargs
620n/a check_syntax_error(self, "f(*g(1=2))")
621n/a check_syntax_error(self, "f(**g(1=2))")
622n/a
623n/a # Check trailing commas are permitted in funcdef argument list
624n/a def f(a,): pass
625n/a def f(*args,): pass
626n/a def f(**kwds,): pass
627n/a def f(a, *args,): pass
628n/a def f(a, **kwds,): pass
629n/a def f(*args, b,): pass
630n/a def f(*, b,): pass
631n/a def f(*args, **kwds,): pass
632n/a def f(a, *args, b,): pass
633n/a def f(a, *, b,): pass
634n/a def f(a, *args, **kwds,): pass
635n/a def f(*args, b, **kwds,): pass
636n/a def f(*, b, **kwds,): pass
637n/a def f(a, *args, b, **kwds,): pass
638n/a def f(a, *, b, **kwds,): pass
639n/a
640n/a def test_lambdef(self):
641n/a ### lambdef: 'lambda' [varargslist] ':' test
642n/a l1 = lambda : 0
643n/a self.assertEqual(l1(), 0)
644n/a l2 = lambda : a[d] # XXX just testing the expression
645n/a l3 = lambda : [2 < x for x in [-1, 3, 0]]
646n/a self.assertEqual(l3(), [0, 1, 0])
647n/a l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
648n/a self.assertEqual(l4(), 1)
649n/a l5 = lambda x, y, z=2: x + y + z
650n/a self.assertEqual(l5(1, 2), 5)
651n/a self.assertEqual(l5(1, 2, 3), 6)
652n/a check_syntax_error(self, "lambda x: x = 2")
653n/a check_syntax_error(self, "lambda (None,): None")
654n/a l6 = lambda x, y, *, k=20: x+y+k
655n/a self.assertEqual(l6(1,2), 1+2+20)
656n/a self.assertEqual(l6(1,2,k=10), 1+2+10)
657n/a
658n/a # check that trailing commas are permitted
659n/a l10 = lambda a,: 0
660n/a l11 = lambda *args,: 0
661n/a l12 = lambda **kwds,: 0
662n/a l13 = lambda a, *args,: 0
663n/a l14 = lambda a, **kwds,: 0
664n/a l15 = lambda *args, b,: 0
665n/a l16 = lambda *, b,: 0
666n/a l17 = lambda *args, **kwds,: 0
667n/a l18 = lambda a, *args, b,: 0
668n/a l19 = lambda a, *, b,: 0
669n/a l20 = lambda a, *args, **kwds,: 0
670n/a l21 = lambda *args, b, **kwds,: 0
671n/a l22 = lambda *, b, **kwds,: 0
672n/a l23 = lambda a, *args, b, **kwds,: 0
673n/a l24 = lambda a, *, b, **kwds,: 0
674n/a
675n/a
676n/a ### stmt: simple_stmt | compound_stmt
677n/a # Tested below
678n/a
679n/a def test_simple_stmt(self):
680n/a ### simple_stmt: small_stmt (';' small_stmt)* [';']
681n/a x = 1; pass; del x
682n/a def foo():
683n/a # verify statements that end with semi-colons
684n/a x = 1; pass; del x;
685n/a foo()
686n/a
687n/a ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
688n/a # Tested below
689n/a
690n/a def test_expr_stmt(self):
691n/a # (exprlist '=')* exprlist
692n/a 1
693n/a 1, 2, 3
694n/a x = 1
695n/a x = 1, 2, 3
696n/a x = y = z = 1, 2, 3
697n/a x, y, z = 1, 2, 3
698n/a abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
699n/a
700n/a check_syntax_error(self, "x + 1 = 1")
701n/a check_syntax_error(self, "a + 1 = b + 2")
702n/a
703n/a # Check the heuristic for print & exec covers significant cases
704n/a # As well as placing some limits on false positives
705n/a def test_former_statements_refer_to_builtins(self):
706n/a keywords = "print", "exec"
707n/a # Cases where we want the custom error
708n/a cases = [
709n/a "{} foo",
710n/a "{} {{1:foo}}",
711n/a "if 1: {} foo",
712n/a "if 1: {} {{1:foo}}",
713n/a "if 1:\n {} foo",
714n/a "if 1:\n {} {{1:foo}}",
715n/a ]
716n/a for keyword in keywords:
717n/a custom_msg = "call to '{}'".format(keyword)
718n/a for case in cases:
719n/a source = case.format(keyword)
720n/a with self.subTest(source=source):
721n/a with self.assertRaisesRegex(SyntaxError, custom_msg):
722n/a exec(source)
723n/a source = source.replace("foo", "(foo.)")
724n/a with self.subTest(source=source):
725n/a with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
726n/a exec(source)
727n/a
728n/a def test_del_stmt(self):
729n/a # 'del' exprlist
730n/a abc = [1,2,3]
731n/a x, y, z = abc
732n/a xyz = x, y, z
733n/a
734n/a del abc
735n/a del x, y, (z, xyz)
736n/a
737n/a def test_pass_stmt(self):
738n/a # 'pass'
739n/a pass
740n/a
741n/a # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
742n/a # Tested below
743n/a
744n/a def test_break_stmt(self):
745n/a # 'break'
746n/a while 1: break
747n/a
748n/a def test_continue_stmt(self):
749n/a # 'continue'
750n/a i = 1
751n/a while i: i = 0; continue
752n/a
753n/a msg = ""
754n/a while not msg:
755n/a msg = "ok"
756n/a try:
757n/a continue
758n/a msg = "continue failed to continue inside try"
759n/a except:
760n/a msg = "continue inside try called except block"
761n/a if msg != "ok":
762n/a self.fail(msg)
763n/a
764n/a msg = ""
765n/a while not msg:
766n/a msg = "finally block not called"
767n/a try:
768n/a continue
769n/a finally:
770n/a msg = "ok"
771n/a if msg != "ok":
772n/a self.fail(msg)
773n/a
774n/a def test_break_continue_loop(self):
775n/a # This test warrants an explanation. It is a test specifically for SF bugs
776n/a # #463359 and #462937. The bug is that a 'break' statement executed or
777n/a # exception raised inside a try/except inside a loop, *after* a continue
778n/a # statement has been executed in that loop, will cause the wrong number of
779n/a # arguments to be popped off the stack and the instruction pointer reset to
780n/a # a very small number (usually 0.) Because of this, the following test
781n/a # *must* written as a function, and the tracking vars *must* be function
782n/a # arguments with default values. Otherwise, the test will loop and loop.
783n/a
784n/a def test_inner(extra_burning_oil = 1, count=0):
785n/a big_hippo = 2
786n/a while big_hippo:
787n/a count += 1
788n/a try:
789n/a if extra_burning_oil and big_hippo == 1:
790n/a extra_burning_oil -= 1
791n/a break
792n/a big_hippo -= 1
793n/a continue
794n/a except:
795n/a raise
796n/a if count > 2 or big_hippo != 1:
797n/a self.fail("continue then break in try/except in loop broken!")
798n/a test_inner()
799n/a
800n/a def test_return(self):
801n/a # 'return' [testlist]
802n/a def g1(): return
803n/a def g2(): return 1
804n/a g1()
805n/a x = g2()
806n/a check_syntax_error(self, "class foo:return 1")
807n/a
808n/a def test_yield(self):
809n/a # Allowed as standalone statement
810n/a def g(): yield 1
811n/a def g(): yield from ()
812n/a # Allowed as RHS of assignment
813n/a def g(): x = yield 1
814n/a def g(): x = yield from ()
815n/a # Ordinary yield accepts implicit tuples
816n/a def g(): yield 1, 1
817n/a def g(): x = yield 1, 1
818n/a # 'yield from' does not
819n/a check_syntax_error(self, "def g(): yield from (), 1")
820n/a check_syntax_error(self, "def g(): x = yield from (), 1")
821n/a # Requires parentheses as subexpression
822n/a def g(): 1, (yield 1)
823n/a def g(): 1, (yield from ())
824n/a check_syntax_error(self, "def g(): 1, yield 1")
825n/a check_syntax_error(self, "def g(): 1, yield from ()")
826n/a # Requires parentheses as call argument
827n/a def g(): f((yield 1))
828n/a def g(): f((yield 1), 1)
829n/a def g(): f((yield from ()))
830n/a def g(): f((yield from ()), 1)
831n/a check_syntax_error(self, "def g(): f(yield 1)")
832n/a check_syntax_error(self, "def g(): f(yield 1, 1)")
833n/a check_syntax_error(self, "def g(): f(yield from ())")
834n/a check_syntax_error(self, "def g(): f(yield from (), 1)")
835n/a # Not allowed at top level
836n/a check_syntax_error(self, "yield")
837n/a check_syntax_error(self, "yield from")
838n/a # Not allowed at class scope
839n/a check_syntax_error(self, "class foo:yield 1")
840n/a check_syntax_error(self, "class foo:yield from ()")
841n/a # Check annotation refleak on SyntaxError
842n/a check_syntax_error(self, "def g(a:(yield)): pass")
843n/a
844n/a def test_raise(self):
845n/a # 'raise' test [',' test]
846n/a try: raise RuntimeError('just testing')
847n/a except RuntimeError: pass
848n/a try: raise KeyboardInterrupt
849n/a except KeyboardInterrupt: pass
850n/a
851n/a def test_import(self):
852n/a # 'import' dotted_as_names
853n/a import sys
854n/a import time, sys
855n/a # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
856n/a from time import time
857n/a from time import (time)
858n/a # not testable inside a function, but already done at top of the module
859n/a # from sys import *
860n/a from sys import path, argv
861n/a from sys import (path, argv)
862n/a from sys import (path, argv,)
863n/a
864n/a def test_global(self):
865n/a # 'global' NAME (',' NAME)*
866n/a global a
867n/a global a, b
868n/a global one, two, three, four, five, six, seven, eight, nine, ten
869n/a
870n/a def test_nonlocal(self):
871n/a # 'nonlocal' NAME (',' NAME)*
872n/a x = 0
873n/a y = 0
874n/a def f():
875n/a nonlocal x
876n/a nonlocal x, y
877n/a
878n/a def test_assert(self):
879n/a # assertTruestmt: 'assert' test [',' test]
880n/a assert 1
881n/a assert 1, 1
882n/a assert lambda x:x
883n/a assert 1, lambda x:x+1
884n/a
885n/a try:
886n/a assert True
887n/a except AssertionError as e:
888n/a self.fail("'assert True' should not have raised an AssertionError")
889n/a
890n/a try:
891n/a assert True, 'this should always pass'
892n/a except AssertionError as e:
893n/a self.fail("'assert True, msg' should not have "
894n/a "raised an AssertionError")
895n/a
896n/a # these tests fail if python is run with -O, so check __debug__
897n/a @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
898n/a def testAssert2(self):
899n/a try:
900n/a assert 0, "msg"
901n/a except AssertionError as e:
902n/a self.assertEqual(e.args[0], "msg")
903n/a else:
904n/a self.fail("AssertionError not raised by assert 0")
905n/a
906n/a try:
907n/a assert False
908n/a except AssertionError as e:
909n/a self.assertEqual(len(e.args), 0)
910n/a else:
911n/a self.fail("AssertionError not raised by 'assert False'")
912n/a
913n/a
914n/a ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
915n/a # Tested below
916n/a
917n/a def test_if(self):
918n/a # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
919n/a if 1: pass
920n/a if 1: pass
921n/a else: pass
922n/a if 0: pass
923n/a elif 0: pass
924n/a if 0: pass
925n/a elif 0: pass
926n/a elif 0: pass
927n/a elif 0: pass
928n/a else: pass
929n/a
930n/a def test_while(self):
931n/a # 'while' test ':' suite ['else' ':' suite]
932n/a while 0: pass
933n/a while 0: pass
934n/a else: pass
935n/a
936n/a # Issue1920: "while 0" is optimized away,
937n/a # ensure that the "else" clause is still present.
938n/a x = 0
939n/a while 0:
940n/a x = 1
941n/a else:
942n/a x = 2
943n/a self.assertEqual(x, 2)
944n/a
945n/a def test_for(self):
946n/a # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
947n/a for i in 1, 2, 3: pass
948n/a for i, j, k in (): pass
949n/a else: pass
950n/a class Squares:
951n/a def __init__(self, max):
952n/a self.max = max
953n/a self.sofar = []
954n/a def __len__(self): return len(self.sofar)
955n/a def __getitem__(self, i):
956n/a if not 0 <= i < self.max: raise IndexError
957n/a n = len(self.sofar)
958n/a while n <= i:
959n/a self.sofar.append(n*n)
960n/a n = n+1
961n/a return self.sofar[i]
962n/a n = 0
963n/a for x in Squares(10): n = n+x
964n/a if n != 285:
965n/a self.fail('for over growing sequence')
966n/a
967n/a result = []
968n/a for x, in [(1,), (2,), (3,)]:
969n/a result.append(x)
970n/a self.assertEqual(result, [1, 2, 3])
971n/a
972n/a def test_try(self):
973n/a ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
974n/a ### | 'try' ':' suite 'finally' ':' suite
975n/a ### except_clause: 'except' [expr ['as' expr]]
976n/a try:
977n/a 1/0
978n/a except ZeroDivisionError:
979n/a pass
980n/a else:
981n/a pass
982n/a try: 1/0
983n/a except EOFError: pass
984n/a except TypeError as msg: pass
985n/a except RuntimeError as msg: pass
986n/a except: pass
987n/a else: pass
988n/a try: 1/0
989n/a except (EOFError, TypeError, ZeroDivisionError): pass
990n/a try: 1/0
991n/a except (EOFError, TypeError, ZeroDivisionError) as msg: pass
992n/a try: pass
993n/a finally: pass
994n/a
995n/a def test_suite(self):
996n/a # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
997n/a if 1: pass
998n/a if 1:
999n/a pass
1000n/a if 1:
1001n/a #
1002n/a #
1003n/a #
1004n/a pass
1005n/a pass
1006n/a #
1007n/a pass
1008n/a #
1009n/a
1010n/a def test_test(self):
1011n/a ### and_test ('or' and_test)*
1012n/a ### and_test: not_test ('and' not_test)*
1013n/a ### not_test: 'not' not_test | comparison
1014n/a if not 1: pass
1015n/a if 1 and 1: pass
1016n/a if 1 or 1: pass
1017n/a if not not not 1: pass
1018n/a if not 1 and 1 and 1: pass
1019n/a if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
1020n/a
1021n/a def test_comparison(self):
1022n/a ### comparison: expr (comp_op expr)*
1023n/a ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
1024n/a if 1: pass
1025n/a x = (1 == 1)
1026n/a if 1 == 1: pass
1027n/a if 1 != 1: pass
1028n/a if 1 < 1: pass
1029n/a if 1 > 1: pass
1030n/a if 1 <= 1: pass
1031n/a if 1 >= 1: pass
1032n/a if 1 is 1: pass
1033n/a if 1 is not 1: pass
1034n/a if 1 in (): pass
1035n/a if 1 not in (): pass
1036n/a if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass
1037n/a
1038n/a def test_binary_mask_ops(self):
1039n/a x = 1 & 1
1040n/a x = 1 ^ 1
1041n/a x = 1 | 1
1042n/a
1043n/a def test_shift_ops(self):
1044n/a x = 1 << 1
1045n/a x = 1 >> 1
1046n/a x = 1 << 1 >> 1
1047n/a
1048n/a def test_additive_ops(self):
1049n/a x = 1
1050n/a x = 1 + 1
1051n/a x = 1 - 1 - 1
1052n/a x = 1 - 1 + 1 - 1 + 1
1053n/a
1054n/a def test_multiplicative_ops(self):
1055n/a x = 1 * 1
1056n/a x = 1 / 1
1057n/a x = 1 % 1
1058n/a x = 1 / 1 * 1 % 1
1059n/a
1060n/a def test_unary_ops(self):
1061n/a x = +1
1062n/a x = -1
1063n/a x = ~1
1064n/a x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
1065n/a x = -1*1/1 + 1*1 - ---1*1
1066n/a
1067n/a def test_selectors(self):
1068n/a ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
1069n/a ### subscript: expr | [expr] ':' [expr]
1070n/a
1071n/a import sys, time
1072n/a c = sys.path[0]
1073n/a x = time.time()
1074n/a x = sys.modules['time'].time()
1075n/a a = '01234'
1076n/a c = a[0]
1077n/a c = a[-1]
1078n/a s = a[0:5]
1079n/a s = a[:5]
1080n/a s = a[0:]
1081n/a s = a[:]
1082n/a s = a[-5:]
1083n/a s = a[:-1]
1084n/a s = a[-4:-3]
1085n/a # A rough test of SF bug 1333982. http://python.org/sf/1333982
1086n/a # The testing here is fairly incomplete.
1087n/a # Test cases should include: commas with 1 and 2 colons
1088n/a d = {}
1089n/a d[1] = 1
1090n/a d[1,] = 2
1091n/a d[1,2] = 3
1092n/a d[1,2,3] = 4
1093n/a L = list(d)
1094n/a L.sort(key=lambda x: x if isinstance(x, tuple) else ())
1095n/a self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
1096n/a
1097n/a def test_atoms(self):
1098n/a ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
1099n/a ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
1100n/a
1101n/a x = (1)
1102n/a x = (1 or 2 or 3)
1103n/a x = (1 or 2 or 3, 2, 3)
1104n/a
1105n/a x = []
1106n/a x = [1]
1107n/a x = [1 or 2 or 3]
1108n/a x = [1 or 2 or 3, 2, 3]
1109n/a x = []
1110n/a
1111n/a x = {}
1112n/a x = {'one': 1}
1113n/a x = {'one': 1,}
1114n/a x = {'one' or 'two': 1 or 2}
1115n/a x = {'one': 1, 'two': 2}
1116n/a x = {'one': 1, 'two': 2,}
1117n/a x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
1118n/a
1119n/a x = {'one'}
1120n/a x = {'one', 1,}
1121n/a x = {'one', 'two', 'three'}
1122n/a x = {2, 3, 4,}
1123n/a
1124n/a x = x
1125n/a x = 'x'
1126n/a x = 123
1127n/a
1128n/a ### exprlist: expr (',' expr)* [',']
1129n/a ### testlist: test (',' test)* [',']
1130n/a # These have been exercised enough above
1131n/a
1132n/a def test_classdef(self):
1133n/a # 'class' NAME ['(' [testlist] ')'] ':' suite
1134n/a class B: pass
1135n/a class B2(): pass
1136n/a class C1(B): pass
1137n/a class C2(B): pass
1138n/a class D(C1, C2, B): pass
1139n/a class C:
1140n/a def meth1(self): pass
1141n/a def meth2(self, arg): pass
1142n/a def meth3(self, a1, a2): pass
1143n/a
1144n/a # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
1145n/a # decorators: decorator+
1146n/a # decorated: decorators (classdef | funcdef)
1147n/a def class_decorator(x): return x
1148n/a @class_decorator
1149n/a class G: pass
1150n/a
1151n/a def test_dictcomps(self):
1152n/a # dictorsetmaker: ( (test ':' test (comp_for |
1153n/a # (',' test ':' test)* [','])) |
1154n/a # (test (comp_for | (',' test)* [','])) )
1155n/a nums = [1, 2, 3]
1156n/a self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
1157n/a
1158n/a def test_listcomps(self):
1159n/a # list comprehension tests
1160n/a nums = [1, 2, 3, 4, 5]
1161n/a strs = ["Apple", "Banana", "Coconut"]
1162n/a spcs = [" Apple", " Banana ", "Coco nut "]
1163n/a
1164n/a self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
1165n/a self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
1166n/a self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
1167n/a self.assertEqual([(i, s) for i in nums for s in strs],
1168n/a [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
1169n/a (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
1170n/a (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
1171n/a (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
1172n/a (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
1173n/a self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
1174n/a [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
1175n/a (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
1176n/a (5, 'Banana'), (5, 'Coconut')])
1177n/a self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
1178n/a [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
1179n/a
1180n/a def test_in_func(l):
1181n/a return [0 < x < 3 for x in l if x > 2]
1182n/a
1183n/a self.assertEqual(test_in_func(nums), [False, False, False])
1184n/a
1185n/a def test_nested_front():
1186n/a self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
1187n/a [[1, 2], [3, 4], [5, 6]])
1188n/a
1189n/a test_nested_front()
1190n/a
1191n/a check_syntax_error(self, "[i, s for i in nums for s in strs]")
1192n/a check_syntax_error(self, "[x if y]")
1193n/a
1194n/a suppliers = [
1195n/a (1, "Boeing"),
1196n/a (2, "Ford"),
1197n/a (3, "Macdonalds")
1198n/a ]
1199n/a
1200n/a parts = [
1201n/a (10, "Airliner"),
1202n/a (20, "Engine"),
1203n/a (30, "Cheeseburger")
1204n/a ]
1205n/a
1206n/a suppart = [
1207n/a (1, 10), (1, 20), (2, 20), (3, 30)
1208n/a ]
1209n/a
1210n/a x = [
1211n/a (sname, pname)
1212n/a for (sno, sname) in suppliers
1213n/a for (pno, pname) in parts
1214n/a for (sp_sno, sp_pno) in suppart
1215n/a if sno == sp_sno and pno == sp_pno
1216n/a ]
1217n/a
1218n/a self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
1219n/a ('Macdonalds', 'Cheeseburger')])
1220n/a
1221n/a def test_genexps(self):
1222n/a # generator expression tests
1223n/a g = ([x for x in range(10)] for x in range(1))
1224n/a self.assertEqual(next(g), [x for x in range(10)])
1225n/a try:
1226n/a next(g)
1227n/a self.fail('should produce StopIteration exception')
1228n/a except StopIteration:
1229n/a pass
1230n/a
1231n/a a = 1
1232n/a try:
1233n/a g = (a for d in a)
1234n/a next(g)
1235n/a self.fail('should produce TypeError')
1236n/a except TypeError:
1237n/a pass
1238n/a
1239n/a self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
1240n/a self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
1241n/a
1242n/a a = [x for x in range(10)]
1243n/a b = (x for x in (y for y in a))
1244n/a self.assertEqual(sum(b), sum([x for x in range(10)]))
1245n/a
1246n/a self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
1247n/a self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
1248n/a self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
1249n/a self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
1250n/a self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
1251n/a 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)]))
1252n/a self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
1253n/a check_syntax_error(self, "foo(x for x in range(10), 100)")
1254n/a check_syntax_error(self, "foo(100, x for x in range(10))")
1255n/a
1256n/a def test_comprehension_specials(self):
1257n/a # test for outmost iterable precomputation
1258n/a x = 10; g = (i for i in range(x)); x = 5
1259n/a self.assertEqual(len(list(g)), 10)
1260n/a
1261n/a # This should hold, since we're only precomputing outmost iterable.
1262n/a x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
1263n/a x = 5; t = True;
1264n/a self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
1265n/a
1266n/a # Grammar allows multiple adjacent 'if's in listcomps and genexps,
1267n/a # even though it's silly. Make sure it works (ifelse broke this.)
1268n/a self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
1269n/a self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
1270n/a
1271n/a # verify unpacking single element tuples in listcomp/genexp.
1272n/a self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
1273n/a self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
1274n/a
1275n/a def test_with_statement(self):
1276n/a class manager(object):
1277n/a def __enter__(self):
1278n/a return (1, 2)
1279n/a def __exit__(self, *args):
1280n/a pass
1281n/a
1282n/a with manager():
1283n/a pass
1284n/a with manager() as x:
1285n/a pass
1286n/a with manager() as (x, y):
1287n/a pass
1288n/a with manager(), manager():
1289n/a pass
1290n/a with manager() as x, manager() as y:
1291n/a pass
1292n/a with manager() as x, manager():
1293n/a pass
1294n/a
1295n/a def test_if_else_expr(self):
1296n/a # Test ifelse expressions in various cases
1297n/a def _checkeval(msg, ret):
1298n/a "helper to check that evaluation of expressions is done correctly"
1299n/a print(msg)
1300n/a return ret
1301n/a
1302n/a # the next line is not allowed anymore
1303n/a #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
1304n/a self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
1305n/a 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])
1306n/a self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
1307n/a self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
1308n/a self.assertEqual((5 and 6 if 0 else 1), 1)
1309n/a self.assertEqual(((5 and 6) if 0 else 1), 1)
1310n/a self.assertEqual((5 and (6 if 1 else 1)), 6)
1311n/a self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
1312n/a self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
1313n/a self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
1314n/a self.assertEqual((not 5 if 1 else 1), False)
1315n/a self.assertEqual((not 5 if 0 else 1), 1)
1316n/a self.assertEqual((6 + 1 if 1 else 2), 7)
1317n/a self.assertEqual((6 - 1 if 1 else 2), 5)
1318n/a self.assertEqual((6 * 2 if 1 else 4), 12)
1319n/a self.assertEqual((6 / 2 if 1 else 3), 3)
1320n/a self.assertEqual((6 < 4 if 0 else 2), 2)
1321n/a
1322n/a def test_paren_evaluation(self):
1323n/a self.assertEqual(16 // (4 // 2), 8)
1324n/a self.assertEqual((16 // 4) // 2, 2)
1325n/a self.assertEqual(16 // 4 // 2, 2)
1326n/a self.assertTrue(False is (2 is 3))
1327n/a self.assertFalse((False is 2) is 3)
1328n/a self.assertFalse(False is 2 is 3)
1329n/a
1330n/a def test_matrix_mul(self):
1331n/a # This is not intended to be a comprehensive test, rather just to be few
1332n/a # samples of the @ operator in test_grammar.py.
1333n/a class M:
1334n/a def __matmul__(self, o):
1335n/a return 4
1336n/a def __imatmul__(self, o):
1337n/a self.other = o
1338n/a return self
1339n/a m = M()
1340n/a self.assertEqual(m @ m, 4)
1341n/a m @= 42
1342n/a self.assertEqual(m.other, 42)
1343n/a
1344n/a def test_async_await(self):
1345n/a async def test():
1346n/a def sum():
1347n/a pass
1348n/a if 1:
1349n/a await someobj()
1350n/a
1351n/a self.assertEqual(test.__name__, 'test')
1352n/a self.assertTrue(bool(test.__code__.co_flags & inspect.CO_COROUTINE))
1353n/a
1354n/a def decorator(func):
1355n/a setattr(func, '_marked', True)
1356n/a return func
1357n/a
1358n/a @decorator
1359n/a async def test2():
1360n/a return 22
1361n/a self.assertTrue(test2._marked)
1362n/a self.assertEqual(test2.__name__, 'test2')
1363n/a self.assertTrue(bool(test2.__code__.co_flags & inspect.CO_COROUTINE))
1364n/a
1365n/a def test_async_for(self):
1366n/a class Done(Exception): pass
1367n/a
1368n/a class AIter:
1369n/a def __aiter__(self):
1370n/a return self
1371n/a async def __anext__(self):
1372n/a raise StopAsyncIteration
1373n/a
1374n/a async def foo():
1375n/a async for i in AIter():
1376n/a pass
1377n/a async for i, j in AIter():
1378n/a pass
1379n/a async for i in AIter():
1380n/a pass
1381n/a else:
1382n/a pass
1383n/a raise Done
1384n/a
1385n/a with self.assertRaises(Done):
1386n/a foo().send(None)
1387n/a
1388n/a def test_async_with(self):
1389n/a class Done(Exception): pass
1390n/a
1391n/a class manager:
1392n/a async def __aenter__(self):
1393n/a return (1, 2)
1394n/a async def __aexit__(self, *exc):
1395n/a return False
1396n/a
1397n/a async def foo():
1398n/a async with manager():
1399n/a pass
1400n/a async with manager() as x:
1401n/a pass
1402n/a async with manager() as (x, y):
1403n/a pass
1404n/a async with manager(), manager():
1405n/a pass
1406n/a async with manager() as x, manager() as y:
1407n/a pass
1408n/a async with manager() as x, manager():
1409n/a pass
1410n/a raise Done
1411n/a
1412n/a with self.assertRaises(Done):
1413n/a foo().send(None)
1414n/a
1415n/a
1416n/aif __name__ == '__main__':
1417n/a unittest.main()