ยปCore Development>Code coverage>Lib/lib2to3/tests/data/py3_test_grammar.py

Python code coverage for Lib/lib2to3/tests/data/py3_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/a# NOTE: When you run this test as a script from the command line, you
5n/a# get warnings about certain hex/oct constants. Since those are
6n/a# issued by the parser, you can't suppress them by adding a
7n/a# filterwarnings() call to this module. Therefore, to shut up the
8n/a# regression test, the filterwarnings() call has been added to
9n/a# regrtest.py.
10n/a
11n/afrom test.support import run_unittest, check_syntax_error
12n/aimport unittest
13n/aimport sys
14n/a# testing import *
15n/afrom sys import *
16n/a
17n/aclass TokenTests(unittest.TestCase):
18n/a
19n/a def testBackslash(self):
20n/a # Backslash means line continuation:
21n/a x = 1 \
22n/a + 1
23n/a self.assertEquals(x, 2, 'backslash for line continuation')
24n/a
25n/a # Backslash does not means continuation in comments :\
26n/a x = 0
27n/a self.assertEquals(x, 0, 'backslash ending comment')
28n/a
29n/a def testPlainIntegers(self):
30n/a self.assertEquals(type(000), type(0))
31n/a self.assertEquals(0xff, 255)
32n/a self.assertEquals(0o377, 255)
33n/a self.assertEquals(2147483647, 0o17777777777)
34n/a self.assertEquals(0b1001, 9)
35n/a # "0x" is not a valid literal
36n/a self.assertRaises(SyntaxError, eval, "0x")
37n/a from sys import maxsize
38n/a if maxsize == 2147483647:
39n/a self.assertEquals(-2147483647-1, -0o20000000000)
40n/a # XXX -2147483648
41n/a self.assert_(0o37777777777 > 0)
42n/a self.assert_(0xffffffff > 0)
43n/a self.assert_(0b1111111111111111111111111111111 > 0)
44n/a for s in ('2147483648', '0o40000000000', '0x100000000',
45n/a '0b10000000000000000000000000000000'):
46n/a try:
47n/a x = eval(s)
48n/a except OverflowError:
49n/a self.fail("OverflowError on huge integer literal %r" % s)
50n/a elif maxsize == 9223372036854775807:
51n/a self.assertEquals(-9223372036854775807-1, -0o1000000000000000000000)
52n/a self.assert_(0o1777777777777777777777 > 0)
53n/a self.assert_(0xffffffffffffffff > 0)
54n/a self.assert_(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
55n/a for s in '9223372036854775808', '0o2000000000000000000000', \
56n/a '0x10000000000000000', \
57n/a '0b100000000000000000000000000000000000000000000000000000000000000':
58n/a try:
59n/a x = eval(s)
60n/a except OverflowError:
61n/a self.fail("OverflowError on huge integer literal %r" % s)
62n/a else:
63n/a self.fail('Weird maxsize value %r' % maxsize)
64n/a
65n/a def testLongIntegers(self):
66n/a x = 0
67n/a x = 0xffffffffffffffff
68n/a x = 0Xffffffffffffffff
69n/a x = 0o77777777777777777
70n/a x = 0O77777777777777777
71n/a x = 123456789012345678901234567890
72n/a x = 0b100000000000000000000000000000000000000000000000000000000000000000000
73n/a x = 0B111111111111111111111111111111111111111111111111111111111111111111111
74n/a
75n/a def testFloats(self):
76n/a x = 3.14
77n/a x = 314.
78n/a x = 0.314
79n/a # XXX x = 000.314
80n/a x = .314
81n/a x = 3e14
82n/a x = 3E14
83n/a x = 3e-14
84n/a x = 3e+14
85n/a x = 3.e14
86n/a x = .3e14
87n/a x = 3.1e4
88n/a
89n/a def testStringLiterals(self):
90n/a x = ''; y = ""; self.assert_(len(x) == 0 and x == y)
91n/a x = '\''; y = "'"; self.assert_(len(x) == 1 and x == y and ord(x) == 39)
92n/a x = '"'; y = "\""; self.assert_(len(x) == 1 and x == y and ord(x) == 34)
93n/a x = "doesn't \"shrink\" does it"
94n/a y = 'doesn\'t "shrink" does it'
95n/a self.assert_(len(x) == 24 and x == y)
96n/a x = "does \"shrink\" doesn't it"
97n/a y = 'does "shrink" doesn\'t it'
98n/a self.assert_(len(x) == 24 and x == y)
99n/a x = """
100n/aThe "quick"
101n/abrown fox
102n/ajumps over
103n/athe 'lazy' dog.
104n/a"""
105n/a y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
106n/a self.assertEquals(x, y)
107n/a y = '''
108n/aThe "quick"
109n/abrown fox
110n/ajumps over
111n/athe 'lazy' dog.
112n/a'''
113n/a self.assertEquals(x, y)
114n/a y = "\n\
115n/aThe \"quick\"\n\
116n/abrown fox\n\
117n/ajumps over\n\
118n/athe 'lazy' dog.\n\
119n/a"
120n/a self.assertEquals(x, y)
121n/a y = '\n\
122n/aThe \"quick\"\n\
123n/abrown fox\n\
124n/ajumps over\n\
125n/athe \'lazy\' dog.\n\
126n/a'
127n/a self.assertEquals(x, y)
128n/a
129n/a def testEllipsis(self):
130n/a x = ...
131n/a self.assert_(x is Ellipsis)
132n/a self.assertRaises(SyntaxError, eval, ".. .")
133n/a
134n/aclass GrammarTests(unittest.TestCase):
135n/a
136n/a # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
137n/a # XXX can't test in a script -- this rule is only used when interactive
138n/a
139n/a # file_input: (NEWLINE | stmt)* ENDMARKER
140n/a # Being tested as this very moment this very module
141n/a
142n/a # expr_input: testlist NEWLINE
143n/a # XXX Hard to test -- used only in calls to input()
144n/a
145n/a def testEvalInput(self):
146n/a # testlist ENDMARKER
147n/a x = eval('1, 0 or 1')
148n/a
149n/a def testFuncdef(self):
150n/a ### [decorators] 'def' NAME parameters ['->' test] ':' suite
151n/a ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
152n/a ### decorators: decorator+
153n/a ### parameters: '(' [typedargslist] ')'
154n/a ### typedargslist: ((tfpdef ['=' test] ',')*
155n/a ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
156n/a ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
157n/a ### tfpdef: NAME [':' test]
158n/a ### varargslist: ((vfpdef ['=' test] ',')*
159n/a ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
160n/a ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
161n/a ### vfpdef: NAME
162n/a def f1(): pass
163n/a f1()
164n/a f1(*())
165n/a f1(*(), **{})
166n/a def f2(one_argument): pass
167n/a def f3(two, arguments): pass
168n/a self.assertEquals(f2.__code__.co_varnames, ('one_argument',))
169n/a self.assertEquals(f3.__code__.co_varnames, ('two', 'arguments'))
170n/a def a1(one_arg,): pass
171n/a def a2(two, args,): pass
172n/a def v0(*rest): pass
173n/a def v1(a, *rest): pass
174n/a def v2(a, b, *rest): pass
175n/a
176n/a f1()
177n/a f2(1)
178n/a f2(1,)
179n/a f3(1, 2)
180n/a f3(1, 2,)
181n/a v0()
182n/a v0(1)
183n/a v0(1,)
184n/a v0(1,2)
185n/a v0(1,2,3,4,5,6,7,8,9,0)
186n/a v1(1)
187n/a v1(1,)
188n/a v1(1,2)
189n/a v1(1,2,3)
190n/a v1(1,2,3,4,5,6,7,8,9,0)
191n/a v2(1,2)
192n/a v2(1,2,3)
193n/a v2(1,2,3,4)
194n/a v2(1,2,3,4,5,6,7,8,9,0)
195n/a
196n/a def d01(a=1): pass
197n/a d01()
198n/a d01(1)
199n/a d01(*(1,))
200n/a d01(**{'a':2})
201n/a def d11(a, b=1): pass
202n/a d11(1)
203n/a d11(1, 2)
204n/a d11(1, **{'b':2})
205n/a def d21(a, b, c=1): pass
206n/a d21(1, 2)
207n/a d21(1, 2, 3)
208n/a d21(*(1, 2, 3))
209n/a d21(1, *(2, 3))
210n/a d21(1, 2, *(3,))
211n/a d21(1, 2, **{'c':3})
212n/a def d02(a=1, b=2): pass
213n/a d02()
214n/a d02(1)
215n/a d02(1, 2)
216n/a d02(*(1, 2))
217n/a d02(1, *(2,))
218n/a d02(1, **{'b':2})
219n/a d02(**{'a': 1, 'b': 2})
220n/a def d12(a, b=1, c=2): pass
221n/a d12(1)
222n/a d12(1, 2)
223n/a d12(1, 2, 3)
224n/a def d22(a, b, c=1, d=2): pass
225n/a d22(1, 2)
226n/a d22(1, 2, 3)
227n/a d22(1, 2, 3, 4)
228n/a def d01v(a=1, *rest): pass
229n/a d01v()
230n/a d01v(1)
231n/a d01v(1, 2)
232n/a d01v(*(1, 2, 3, 4))
233n/a d01v(*(1,))
234n/a d01v(**{'a':2})
235n/a def d11v(a, b=1, *rest): pass
236n/a d11v(1)
237n/a d11v(1, 2)
238n/a d11v(1, 2, 3)
239n/a def d21v(a, b, c=1, *rest): pass
240n/a d21v(1, 2)
241n/a d21v(1, 2, 3)
242n/a d21v(1, 2, 3, 4)
243n/a d21v(*(1, 2, 3, 4))
244n/a d21v(1, 2, **{'c': 3})
245n/a def d02v(a=1, b=2, *rest): pass
246n/a d02v()
247n/a d02v(1)
248n/a d02v(1, 2)
249n/a d02v(1, 2, 3)
250n/a d02v(1, *(2, 3, 4))
251n/a d02v(**{'a': 1, 'b': 2})
252n/a def d12v(a, b=1, c=2, *rest): pass
253n/a d12v(1)
254n/a d12v(1, 2)
255n/a d12v(1, 2, 3)
256n/a d12v(1, 2, 3, 4)
257n/a d12v(*(1, 2, 3, 4))
258n/a d12v(1, 2, *(3, 4, 5))
259n/a d12v(1, *(2,), **{'c': 3})
260n/a def d22v(a, b, c=1, d=2, *rest): pass
261n/a d22v(1, 2)
262n/a d22v(1, 2, 3)
263n/a d22v(1, 2, 3, 4)
264n/a d22v(1, 2, 3, 4, 5)
265n/a d22v(*(1, 2, 3, 4))
266n/a d22v(1, 2, *(3, 4, 5))
267n/a d22v(1, *(2, 3), **{'d': 4})
268n/a
269n/a # keyword argument type tests
270n/a try:
271n/a str('x', **{b'foo':1 })
272n/a except TypeError:
273n/a pass
274n/a else:
275n/a self.fail('Bytes should not work as keyword argument names')
276n/a # keyword only argument tests
277n/a def pos0key1(*, key): return key
278n/a pos0key1(key=100)
279n/a def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
280n/a pos2key2(1, 2, k1=100)
281n/a pos2key2(1, 2, k1=100, k2=200)
282n/a pos2key2(1, 2, k2=100, k1=200)
283n/a def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
284n/a pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
285n/a pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
286n/a
287n/a # keyword arguments after *arglist
288n/a def f(*args, **kwargs):
289n/a return args, kwargs
290n/a self.assertEquals(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
291n/a {'x':2, 'y':5}))
292n/a self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)")
293n/a self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
294n/a
295n/a # argument annotation tests
296n/a def f(x) -> list: pass
297n/a self.assertEquals(f.__annotations__, {'return': list})
298n/a def f(x:int): pass
299n/a self.assertEquals(f.__annotations__, {'x': int})
300n/a def f(*x:str): pass
301n/a self.assertEquals(f.__annotations__, {'x': str})
302n/a def f(**x:float): pass
303n/a self.assertEquals(f.__annotations__, {'x': float})
304n/a def f(x, y:1+2): pass
305n/a self.assertEquals(f.__annotations__, {'y': 3})
306n/a def f(a, b:1, c:2, d): pass
307n/a self.assertEquals(f.__annotations__, {'b': 1, 'c': 2})
308n/a def f(a, b:1, c:2, d, e:3=4, f=5, *g:6): pass
309n/a self.assertEquals(f.__annotations__,
310n/a {'b': 1, 'c': 2, 'e': 3, 'g': 6})
311n/a def f(a, b:1, c:2, d, e:3=4, f=5, *g:6, h:7, i=8, j:9=10,
312n/a **k:11) -> 12: pass
313n/a self.assertEquals(f.__annotations__,
314n/a {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
315n/a 'k': 11, 'return': 12})
316n/a # Check for SF Bug #1697248 - mixing decorators and a return annotation
317n/a def null(x): return x
318n/a @null
319n/a def f(x) -> list: pass
320n/a self.assertEquals(f.__annotations__, {'return': list})
321n/a
322n/a # test closures with a variety of oparg's
323n/a closure = 1
324n/a def f(): return closure
325n/a def f(x=1): return closure
326n/a def f(*, k=1): return closure
327n/a def f() -> int: return closure
328n/a
329n/a # Check ast errors in *args and *kwargs
330n/a check_syntax_error(self, "f(*g(1=2))")
331n/a check_syntax_error(self, "f(**g(1=2))")
332n/a
333n/a def testLambdef(self):
334n/a ### lambdef: 'lambda' [varargslist] ':' test
335n/a l1 = lambda : 0
336n/a self.assertEquals(l1(), 0)
337n/a l2 = lambda : a[d] # XXX just testing the expression
338n/a l3 = lambda : [2 < x for x in [-1, 3, 0]]
339n/a self.assertEquals(l3(), [0, 1, 0])
340n/a l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
341n/a self.assertEquals(l4(), 1)
342n/a l5 = lambda x, y, z=2: x + y + z
343n/a self.assertEquals(l5(1, 2), 5)
344n/a self.assertEquals(l5(1, 2, 3), 6)
345n/a check_syntax_error(self, "lambda x: x = 2")
346n/a check_syntax_error(self, "lambda (None,): None")
347n/a l6 = lambda x, y, *, k=20: x+y+k
348n/a self.assertEquals(l6(1,2), 1+2+20)
349n/a self.assertEquals(l6(1,2,k=10), 1+2+10)
350n/a
351n/a
352n/a ### stmt: simple_stmt | compound_stmt
353n/a # Tested below
354n/a
355n/a def testSimpleStmt(self):
356n/a ### simple_stmt: small_stmt (';' small_stmt)* [';']
357n/a x = 1; pass; del x
358n/a def foo():
359n/a # verify statements that end with semi-colons
360n/a x = 1; pass; del x;
361n/a foo()
362n/a
363n/a ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
364n/a # Tested below
365n/a
366n/a def testExprStmt(self):
367n/a # (exprlist '=')* exprlist
368n/a 1
369n/a 1, 2, 3
370n/a x = 1
371n/a x = 1, 2, 3
372n/a x = y = z = 1, 2, 3
373n/a x, y, z = 1, 2, 3
374n/a abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
375n/a
376n/a check_syntax_error(self, "x + 1 = 1")
377n/a check_syntax_error(self, "a + 1 = b + 2")
378n/a
379n/a def testDelStmt(self):
380n/a # 'del' exprlist
381n/a abc = [1,2,3]
382n/a x, y, z = abc
383n/a xyz = x, y, z
384n/a
385n/a del abc
386n/a del x, y, (z, xyz)
387n/a
388n/a def testPassStmt(self):
389n/a # 'pass'
390n/a pass
391n/a
392n/a # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
393n/a # Tested below
394n/a
395n/a def testBreakStmt(self):
396n/a # 'break'
397n/a while 1: break
398n/a
399n/a def testContinueStmt(self):
400n/a # 'continue'
401n/a i = 1
402n/a while i: i = 0; continue
403n/a
404n/a msg = ""
405n/a while not msg:
406n/a msg = "ok"
407n/a try:
408n/a continue
409n/a msg = "continue failed to continue inside try"
410n/a except:
411n/a msg = "continue inside try called except block"
412n/a if msg != "ok":
413n/a self.fail(msg)
414n/a
415n/a msg = ""
416n/a while not msg:
417n/a msg = "finally block not called"
418n/a try:
419n/a continue
420n/a finally:
421n/a msg = "ok"
422n/a if msg != "ok":
423n/a self.fail(msg)
424n/a
425n/a def test_break_continue_loop(self):
426n/a # This test warrants an explanation. It is a test specifically for SF bugs
427n/a # #463359 and #462937. The bug is that a 'break' statement executed or
428n/a # exception raised inside a try/except inside a loop, *after* a continue
429n/a # statement has been executed in that loop, will cause the wrong number of
430n/a # arguments to be popped off the stack and the instruction pointer reset to
431n/a # a very small number (usually 0.) Because of this, the following test
432n/a # *must* written as a function, and the tracking vars *must* be function
433n/a # arguments with default values. Otherwise, the test will loop and loop.
434n/a
435n/a def test_inner(extra_burning_oil = 1, count=0):
436n/a big_hippo = 2
437n/a while big_hippo:
438n/a count += 1
439n/a try:
440n/a if extra_burning_oil and big_hippo == 1:
441n/a extra_burning_oil -= 1
442n/a break
443n/a big_hippo -= 1
444n/a continue
445n/a except:
446n/a raise
447n/a if count > 2 or big_hippo != 1:
448n/a self.fail("continue then break in try/except in loop broken!")
449n/a test_inner()
450n/a
451n/a def testReturn(self):
452n/a # 'return' [testlist]
453n/a def g1(): return
454n/a def g2(): return 1
455n/a g1()
456n/a x = g2()
457n/a check_syntax_error(self, "class foo:return 1")
458n/a
459n/a def testYield(self):
460n/a check_syntax_error(self, "class foo:yield 1")
461n/a
462n/a def testRaise(self):
463n/a # 'raise' test [',' test]
464n/a try: raise RuntimeError('just testing')
465n/a except RuntimeError: pass
466n/a try: raise KeyboardInterrupt
467n/a except KeyboardInterrupt: pass
468n/a
469n/a def testImport(self):
470n/a # 'import' dotted_as_names
471n/a import sys
472n/a import time, sys
473n/a # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
474n/a from time import time
475n/a from time import (time)
476n/a # not testable inside a function, but already done at top of the module
477n/a # from sys import *
478n/a from sys import path, argv
479n/a from sys import (path, argv)
480n/a from sys import (path, argv,)
481n/a
482n/a def testGlobal(self):
483n/a # 'global' NAME (',' NAME)*
484n/a global a
485n/a global a, b
486n/a global one, two, three, four, five, six, seven, eight, nine, ten
487n/a
488n/a def testNonlocal(self):
489n/a # 'nonlocal' NAME (',' NAME)*
490n/a x = 0
491n/a y = 0
492n/a def f():
493n/a nonlocal x
494n/a nonlocal x, y
495n/a
496n/a def testAssert(self):
497n/a # assert_stmt: 'assert' test [',' test]
498n/a assert 1
499n/a assert 1, 1
500n/a assert lambda x:x
501n/a assert 1, lambda x:x+1
502n/a try:
503n/a assert 0, "msg"
504n/a except AssertionError as e:
505n/a self.assertEquals(e.args[0], "msg")
506n/a else:
507n/a if __debug__:
508n/a self.fail("AssertionError not raised by assert 0")
509n/a
510n/a ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
511n/a # Tested below
512n/a
513n/a def testIf(self):
514n/a # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
515n/a if 1: pass
516n/a if 1: pass
517n/a else: pass
518n/a if 0: pass
519n/a elif 0: pass
520n/a if 0: pass
521n/a elif 0: pass
522n/a elif 0: pass
523n/a elif 0: pass
524n/a else: pass
525n/a
526n/a def testWhile(self):
527n/a # 'while' test ':' suite ['else' ':' suite]
528n/a while 0: pass
529n/a while 0: pass
530n/a else: pass
531n/a
532n/a # Issue1920: "while 0" is optimized away,
533n/a # ensure that the "else" clause is still present.
534n/a x = 0
535n/a while 0:
536n/a x = 1
537n/a else:
538n/a x = 2
539n/a self.assertEquals(x, 2)
540n/a
541n/a def testFor(self):
542n/a # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
543n/a for i in 1, 2, 3: pass
544n/a for i, j, k in (): pass
545n/a else: pass
546n/a class Squares:
547n/a def __init__(self, max):
548n/a self.max = max
549n/a self.sofar = []
550n/a def __len__(self): return len(self.sofar)
551n/a def __getitem__(self, i):
552n/a if not 0 <= i < self.max: raise IndexError
553n/a n = len(self.sofar)
554n/a while n <= i:
555n/a self.sofar.append(n*n)
556n/a n = n+1
557n/a return self.sofar[i]
558n/a n = 0
559n/a for x in Squares(10): n = n+x
560n/a if n != 285:
561n/a self.fail('for over growing sequence')
562n/a
563n/a result = []
564n/a for x, in [(1,), (2,), (3,)]:
565n/a result.append(x)
566n/a self.assertEqual(result, [1, 2, 3])
567n/a
568n/a def testTry(self):
569n/a ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
570n/a ### | 'try' ':' suite 'finally' ':' suite
571n/a ### except_clause: 'except' [expr ['as' expr]]
572n/a try:
573n/a 1/0
574n/a except ZeroDivisionError:
575n/a pass
576n/a else:
577n/a pass
578n/a try: 1/0
579n/a except EOFError: pass
580n/a except TypeError as msg: pass
581n/a except RuntimeError as msg: pass
582n/a except: pass
583n/a else: pass
584n/a try: 1/0
585n/a except (EOFError, TypeError, ZeroDivisionError): pass
586n/a try: 1/0
587n/a except (EOFError, TypeError, ZeroDivisionError) as msg: pass
588n/a try: pass
589n/a finally: pass
590n/a
591n/a def testSuite(self):
592n/a # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
593n/a if 1: pass
594n/a if 1:
595n/a pass
596n/a if 1:
597n/a #
598n/a #
599n/a #
600n/a pass
601n/a pass
602n/a #
603n/a pass
604n/a #
605n/a
606n/a def testTest(self):
607n/a ### and_test ('or' and_test)*
608n/a ### and_test: not_test ('and' not_test)*
609n/a ### not_test: 'not' not_test | comparison
610n/a if not 1: pass
611n/a if 1 and 1: pass
612n/a if 1 or 1: pass
613n/a if not not not 1: pass
614n/a if not 1 and 1 and 1: pass
615n/a if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
616n/a
617n/a def testComparison(self):
618n/a ### comparison: expr (comp_op expr)*
619n/a ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
620n/a if 1: pass
621n/a x = (1 == 1)
622n/a if 1 == 1: pass
623n/a if 1 != 1: pass
624n/a if 1 < 1: pass
625n/a if 1 > 1: pass
626n/a if 1 <= 1: pass
627n/a if 1 >= 1: pass
628n/a if 1 is 1: pass
629n/a if 1 is not 1: pass
630n/a if 1 in (): pass
631n/a if 1 not in (): pass
632n/a if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass
633n/a
634n/a def testBinaryMaskOps(self):
635n/a x = 1 & 1
636n/a x = 1 ^ 1
637n/a x = 1 | 1
638n/a
639n/a def testShiftOps(self):
640n/a x = 1 << 1
641n/a x = 1 >> 1
642n/a x = 1 << 1 >> 1
643n/a
644n/a def testAdditiveOps(self):
645n/a x = 1
646n/a x = 1 + 1
647n/a x = 1 - 1 - 1
648n/a x = 1 - 1 + 1 - 1 + 1
649n/a
650n/a def testMultiplicativeOps(self):
651n/a x = 1 * 1
652n/a x = 1 / 1
653n/a x = 1 % 1
654n/a x = 1 / 1 * 1 % 1
655n/a
656n/a def testUnaryOps(self):
657n/a x = +1
658n/a x = -1
659n/a x = ~1
660n/a x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
661n/a x = -1*1/1 + 1*1 - ---1*1
662n/a
663n/a def testSelectors(self):
664n/a ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
665n/a ### subscript: expr | [expr] ':' [expr]
666n/a
667n/a import sys, time
668n/a c = sys.path[0]
669n/a x = time.time()
670n/a x = sys.modules['time'].time()
671n/a a = '01234'
672n/a c = a[0]
673n/a c = a[-1]
674n/a s = a[0:5]
675n/a s = a[:5]
676n/a s = a[0:]
677n/a s = a[:]
678n/a s = a[-5:]
679n/a s = a[:-1]
680n/a s = a[-4:-3]
681n/a # A rough test of SF bug 1333982. http://python.org/sf/1333982
682n/a # The testing here is fairly incomplete.
683n/a # Test cases should include: commas with 1 and 2 colons
684n/a d = {}
685n/a d[1] = 1
686n/a d[1,] = 2
687n/a d[1,2] = 3
688n/a d[1,2,3] = 4
689n/a L = list(d)
690n/a L.sort(key=lambda x: x if isinstance(x, tuple) else ())
691n/a self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
692n/a
693n/a def testAtoms(self):
694n/a ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
695n/a ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
696n/a
697n/a x = (1)
698n/a x = (1 or 2 or 3)
699n/a x = (1 or 2 or 3, 2, 3)
700n/a
701n/a x = []
702n/a x = [1]
703n/a x = [1 or 2 or 3]
704n/a x = [1 or 2 or 3, 2, 3]
705n/a x = []
706n/a
707n/a x = {}
708n/a x = {'one': 1}
709n/a x = {'one': 1,}
710n/a x = {'one' or 'two': 1 or 2}
711n/a x = {'one': 1, 'two': 2}
712n/a x = {'one': 1, 'two': 2,}
713n/a x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
714n/a
715n/a x = {'one'}
716n/a x = {'one', 1,}
717n/a x = {'one', 'two', 'three'}
718n/a x = {2, 3, 4,}
719n/a
720n/a x = x
721n/a x = 'x'
722n/a x = 123
723n/a
724n/a ### exprlist: expr (',' expr)* [',']
725n/a ### testlist: test (',' test)* [',']
726n/a # These have been exercised enough above
727n/a
728n/a def testClassdef(self):
729n/a # 'class' NAME ['(' [testlist] ')'] ':' suite
730n/a class B: pass
731n/a class B2(): pass
732n/a class C1(B): pass
733n/a class C2(B): pass
734n/a class D(C1, C2, B): pass
735n/a class C:
736n/a def meth1(self): pass
737n/a def meth2(self, arg): pass
738n/a def meth3(self, a1, a2): pass
739n/a
740n/a # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
741n/a # decorators: decorator+
742n/a # decorated: decorators (classdef | funcdef)
743n/a def class_decorator(x): return x
744n/a @class_decorator
745n/a class G: pass
746n/a
747n/a def testDictcomps(self):
748n/a # dictorsetmaker: ( (test ':' test (comp_for |
749n/a # (',' test ':' test)* [','])) |
750n/a # (test (comp_for | (',' test)* [','])) )
751n/a nums = [1, 2, 3]
752n/a self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
753n/a
754n/a def testListcomps(self):
755n/a # list comprehension tests
756n/a nums = [1, 2, 3, 4, 5]
757n/a strs = ["Apple", "Banana", "Coconut"]
758n/a spcs = [" Apple", " Banana ", "Coco nut "]
759n/a
760n/a self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
761n/a self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
762n/a self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
763n/a self.assertEqual([(i, s) for i in nums for s in strs],
764n/a [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
765n/a (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
766n/a (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
767n/a (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
768n/a (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
769n/a self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
770n/a [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
771n/a (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
772n/a (5, 'Banana'), (5, 'Coconut')])
773n/a self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
774n/a [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
775n/a
776n/a def test_in_func(l):
777n/a return [0 < x < 3 for x in l if x > 2]
778n/a
779n/a self.assertEqual(test_in_func(nums), [False, False, False])
780n/a
781n/a def test_nested_front():
782n/a self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
783n/a [[1, 2], [3, 4], [5, 6]])
784n/a
785n/a test_nested_front()
786n/a
787n/a check_syntax_error(self, "[i, s for i in nums for s in strs]")
788n/a check_syntax_error(self, "[x if y]")
789n/a
790n/a suppliers = [
791n/a (1, "Boeing"),
792n/a (2, "Ford"),
793n/a (3, "Macdonalds")
794n/a ]
795n/a
796n/a parts = [
797n/a (10, "Airliner"),
798n/a (20, "Engine"),
799n/a (30, "Cheeseburger")
800n/a ]
801n/a
802n/a suppart = [
803n/a (1, 10), (1, 20), (2, 20), (3, 30)
804n/a ]
805n/a
806n/a x = [
807n/a (sname, pname)
808n/a for (sno, sname) in suppliers
809n/a for (pno, pname) in parts
810n/a for (sp_sno, sp_pno) in suppart
811n/a if sno == sp_sno and pno == sp_pno
812n/a ]
813n/a
814n/a self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
815n/a ('Macdonalds', 'Cheeseburger')])
816n/a
817n/a def testGenexps(self):
818n/a # generator expression tests
819n/a g = ([x for x in range(10)] for x in range(1))
820n/a self.assertEqual(next(g), [x for x in range(10)])
821n/a try:
822n/a next(g)
823n/a self.fail('should produce StopIteration exception')
824n/a except StopIteration:
825n/a pass
826n/a
827n/a a = 1
828n/a try:
829n/a g = (a for d in a)
830n/a next(g)
831n/a self.fail('should produce TypeError')
832n/a except TypeError:
833n/a pass
834n/a
835n/a self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
836n/a self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
837n/a
838n/a a = [x for x in range(10)]
839n/a b = (x for x in (y for y in a))
840n/a self.assertEqual(sum(b), sum([x for x in range(10)]))
841n/a
842n/a self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
843n/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]))
844n/a self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
845n/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)]))
846n/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)]))
847n/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)]))
848n/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)
849n/a check_syntax_error(self, "foo(x for x in range(10), 100)")
850n/a check_syntax_error(self, "foo(100, x for x in range(10))")
851n/a
852n/a def testComprehensionSpecials(self):
853n/a # test for outmost iterable precomputation
854n/a x = 10; g = (i for i in range(x)); x = 5
855n/a self.assertEqual(len(list(g)), 10)
856n/a
857n/a # This should hold, since we're only precomputing outmost iterable.
858n/a x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
859n/a x = 5; t = True;
860n/a self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
861n/a
862n/a # Grammar allows multiple adjacent 'if's in listcomps and genexps,
863n/a # even though it's silly. Make sure it works (ifelse broke this.)
864n/a self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
865n/a self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
866n/a
867n/a # verify unpacking single element tuples in listcomp/genexp.
868n/a self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
869n/a self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
870n/a
871n/a def test_with_statement(self):
872n/a class manager(object):
873n/a def __enter__(self):
874n/a return (1, 2)
875n/a def __exit__(self, *args):
876n/a pass
877n/a
878n/a with manager():
879n/a pass
880n/a with manager() as x:
881n/a pass
882n/a with manager() as (x, y):
883n/a pass
884n/a with manager(), manager():
885n/a pass
886n/a with manager() as x, manager() as y:
887n/a pass
888n/a with manager() as x, manager():
889n/a pass
890n/a
891n/a def testIfElseExpr(self):
892n/a # Test ifelse expressions in various cases
893n/a def _checkeval(msg, ret):
894n/a "helper to check that evaluation of expressions is done correctly"
895n/a print(x)
896n/a return ret
897n/a
898n/a # the next line is not allowed anymore
899n/a #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
900n/a self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
901n/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])
902n/a self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
903n/a self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
904n/a self.assertEqual((5 and 6 if 0 else 1), 1)
905n/a self.assertEqual(((5 and 6) if 0 else 1), 1)
906n/a self.assertEqual((5 and (6 if 1 else 1)), 6)
907n/a self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
908n/a self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
909n/a self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
910n/a self.assertEqual((not 5 if 1 else 1), False)
911n/a self.assertEqual((not 5 if 0 else 1), 1)
912n/a self.assertEqual((6 + 1 if 1 else 2), 7)
913n/a self.assertEqual((6 - 1 if 1 else 2), 5)
914n/a self.assertEqual((6 * 2 if 1 else 4), 12)
915n/a self.assertEqual((6 / 2 if 1 else 3), 3)
916n/a self.assertEqual((6 < 4 if 0 else 2), 2)
917n/a
918n/a
919n/adef test_main():
920n/a run_unittest(TokenTests, GrammarTests)
921n/a
922n/aif __name__ == '__main__':
923n/a test_main()