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

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