1 # Python test set -- part 1, grammar.
2 # This just tests whether the parser accepts them all.
4 # NOTE: When you run this test as a script from the command line, you
5 # get warnings about certain hex/oct constants. Since those are
6 # issued by the parser, you can't suppress them by adding a
7 # filterwarnings() call to this module. Therefore, to shut up the
8 # regression test, the filterwarnings() call has been added to
11 from test
.test_support
import run_unittest
, check_syntax_error
17 class TokenTests(unittest
.TestCase
):
19 def testBackslash(self
):
20 # Backslash means line continuation:
23 self
.assertEquals(x
, 2, 'backslash for line continuation')
25 # Backslash does not means continuation in comments :\
27 self
.assertEquals(x
, 0, 'backslash ending comment')
29 def testPlainIntegers(self
):
30 self
.assertEquals(0xff, 255)
31 self
.assertEquals(0377, 255)
32 self
.assertEquals(2147483647, 017777777777)
33 # "0x" is not a valid literal
34 self
.assertRaises(SyntaxError, eval, "0x")
35 from sys
import maxint
36 if maxint
== 2147483647:
37 self
.assertEquals(-2147483647-1, -020000000000)
39 self
.assertTrue(037777777777 > 0)
40 self
.assertTrue(0xffffffff > 0)
41 for s
in '2147483648', '040000000000', '0x100000000':
45 self
.fail("OverflowError on huge integer literal %r" % s
)
46 elif maxint
== 9223372036854775807:
47 self
.assertEquals(-9223372036854775807-1, -01000000000000000000000)
48 self
.assertTrue(01777777777777777777777 > 0)
49 self
.assertTrue(0xffffffffffffffff > 0)
50 for s
in '9223372036854775808', '02000000000000000000000', \
51 '0x10000000000000000':
55 self
.fail("OverflowError on huge integer literal %r" % s
)
57 self
.fail('Weird maxint value %r' % maxint
)
59 def testLongIntegers(self
):
62 x
= 0xffffffffffffffffL
63 x
= 0xffffffffffffffffl
64 x
= 077777777777777777L
65 x
= 077777777777777777l
66 x
= 123456789012345678901234567890L
67 x
= 123456789012345678901234567890l
83 def testStringLiterals(self
):
84 x
= ''; y
= ""; self
.assertTrue(len(x
) == 0 and x
== y
)
85 x
= '\''; y
= "'"; self
.assertTrue(len(x
) == 1 and x
== y
and ord(x
) == 39)
86 x
= '"'; y
= "\""; self
.assertTrue(len(x
) == 1 and x
== y
and ord(x
) == 34)
87 x
= "doesn't \"shrink\" does it"
88 y
= 'doesn\'t "shrink" does it'
89 self
.assertTrue(len(x
) == 24 and x
== y
)
90 x
= "does \"shrink\" doesn't it"
91 y
= 'does "shrink" doesn\'t it'
92 self
.assertTrue(len(x
) == 24 and x
== y
)
99 y
= '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
100 self
.assertEquals(x
, y
)
107 self
.assertEquals(x
, y
)
114 self
.assertEquals(x
, y
)
121 self
.assertEquals(x
, y
)
124 class GrammarTests(unittest
.TestCase
):
126 # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
127 # XXX can't test in a script -- this rule is only used when interactive
129 # file_input: (NEWLINE | stmt)* ENDMARKER
130 # Being tested as this very moment this very module
132 # expr_input: testlist NEWLINE
133 # XXX Hard to test -- used only in calls to input()
135 def testEvalInput(self
):
137 x
= eval('1, 0 or 1')
139 def testFuncdef(self
):
140 ### 'def' NAME parameters ':' suite
141 ### parameters: '(' [varargslist] ')'
142 ### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME]
143 ### | ('**'|'*' '*') NAME)
144 ### | fpdef ['=' test] (',' fpdef ['=' test])* [',']
145 ### fpdef: NAME | '(' fplist ')'
146 ### fplist: fpdef (',' fpdef)* [',']
147 ### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test)
148 ### argument: [test '='] test # Really [keyword '='] test
153 def f2(one_argument
): pass
154 def f3(two
, arguments
): pass
155 def f4(two
, (compound
, (argument
, list))): pass
156 def f5((compound
, first
), two
): pass
157 self
.assertEquals(f2
.func_code
.co_varnames
, ('one_argument',))
158 self
.assertEquals(f3
.func_code
.co_varnames
, ('two', 'arguments'))
159 if sys
.platform
.startswith('java'):
160 self
.assertEquals(f4
.func_code
.co_varnames
,
161 ('two', '(compound, (argument, list))', 'compound', 'argument',
163 self
.assertEquals(f5
.func_code
.co_varnames
,
164 ('(compound, first)', 'two', 'compound', 'first'))
166 self
.assertEquals(f4
.func_code
.co_varnames
,
167 ('two', '.1', 'compound', 'argument', 'list'))
168 self
.assertEquals(f5
.func_code
.co_varnames
,
169 ('.0', 'two', 'compound', 'first'))
170 def a1(one_arg
,): pass
171 def a2(two
, args
,): pass
173 def v1(a
, *rest
): pass
174 def v2(a
, b
, *rest
): pass
175 def v3(a
, (b
, c
), *rest
): return a
, b
, c
, rest
187 v0(1,2,3,4,5,6,7,8,9,0)
192 v1(1,2,3,4,5,6,7,8,9,0)
196 v2(1,2,3,4,5,6,7,8,9,0)
199 v3(1,(2,3),4,5,6,7,8,9,0)
201 # ceval unpacks the formal arguments into the first argcount names;
202 # thus, the names nested inside tuples must appear after these names.
203 if sys
.platform
.startswith('java'):
204 self
.assertEquals(v3
.func_code
.co_varnames
, ('a', '(b, c)', 'rest', 'b', 'c'))
206 self
.assertEquals(v3
.func_code
.co_varnames
, ('a', '.1', 'rest', 'b', 'c'))
207 self
.assertEquals(v3(1, (2, 3), 4), (1, 2, 3, (4,)))
213 def d11(a
, b
=1): pass
217 def d21(a
, b
, c
=1): pass
224 def d02(a
=1, b
=2): pass
231 d02(**{'a': 1, 'b': 2})
232 def d12(a
, b
=1, c
=2): pass
236 def d22(a
, b
, c
=1, d
=2): pass
240 def d01v(a
=1, *rest
): pass
247 def d11v(a
, b
=1, *rest
): pass
251 def d21v(a
, b
, c
=1, *rest
): pass
256 d21v(1, 2, **{'c': 3})
257 def d02v(a
=1, b
=2, *rest
): pass
263 d02v(**{'a': 1, 'b': 2})
264 def d12v(a
, b
=1, c
=2, *rest
): pass
270 d12v(1, 2, *(3, 4, 5))
271 d12v(1, *(2,), **{'c': 3})
272 def d22v(a
, b
, c
=1, d
=2, *rest
): pass
278 d22v(1, 2, *(3, 4, 5))
279 d22v(1, *(2, 3), **{'d': 4})
285 # keyword arguments after *arglist
286 def f(*args
, **kwargs
):
288 self
.assertEquals(f(1, x
=2, *[3, 4], y
=5), ((1, 3, 4),
290 self
.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)")
291 self
.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
293 # Check ast errors in *args and *kwargs
294 check_syntax_error(self
, "f(*g(1=2))")
295 check_syntax_error(self
, "f(**g(1=2))")
297 def testLambdef(self
):
298 ### lambdef: 'lambda' [varargslist] ':' test
300 self
.assertEquals(l1(), 0)
301 l2
= lambda : a
[d
] # XXX just testing the expression
302 l3
= lambda : [2 < x
for x
in [-1, 3, 0L]]
303 self
.assertEquals(l3(), [0, 1, 0])
304 l4
= lambda x
= lambda y
= lambda z
=1 : z
: y() : x()
305 self
.assertEquals(l4(), 1)
306 l5
= lambda x
, y
, z
=2: x
+ y
+ z
307 self
.assertEquals(l5(1, 2), 5)
308 self
.assertEquals(l5(1, 2, 3), 6)
309 check_syntax_error(self
, "lambda x: x = 2")
310 check_syntax_error(self
, "lambda (None,): None")
312 ### stmt: simple_stmt | compound_stmt
315 def testSimpleStmt(self
):
316 ### simple_stmt: small_stmt (';' small_stmt)* [';']
319 # verify statments that end with semi-colons
323 ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt
326 def testExprStmt(self
):
327 # (exprlist '=')* exprlist
334 abc
= a
, b
, c
= x
, y
, z
= xyz
= 1, 2, (3, 4)
336 check_syntax_error(self
, "x + 1 = 1")
337 check_syntax_error(self
, "a + 1 = b + 2")
339 def testPrintStmt(self
):
340 # 'print' (test ',')* [test]
343 # Can't test printing to real stdout without comparing output
344 # which is not available in unittest.
345 save_stdout
= sys
.stdout
346 sys
.stdout
= StringIO
.StringIO()
351 print 0 or 1, 0 or 1,
354 # 'print' '>>' test ','
355 print >> sys
.stdout
, 1, 2, 3
356 print >> sys
.stdout
, 1, 2, 3,
358 print >> sys
.stdout
, 0 or 1, 0 or 1,
359 print >> sys
.stdout
, 0 or 1
361 # test printing to an instance
363 def write(self
, msg
): pass
366 print >> gulp
, 1, 2, 3
367 print >> gulp
, 1, 2, 3,
369 print >> gulp
, 0 or 1, 0 or 1,
370 print >> gulp
, 0 or 1
374 oldstdout
= sys
.stdout
380 sys
.stdout
= oldstdout
382 # we should see this once
383 def tellme(file=sys
.stdout
):
384 print >> file, 'hello world'
388 # we should not see this at all
389 def tellme(file=None):
390 print >> file, 'goodbye universe'
394 self
.assertEqual(sys
.stdout
.getvalue(), '''\
403 sys
.stdout
= save_stdout
406 check_syntax_error(self
, 'print ,')
407 check_syntax_error(self
, 'print >> x,')
409 def testDelStmt(self
):
418 def testPassStmt(self
):
422 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
425 def testBreakStmt(self
):
429 def testContinueStmt(self
):
432 while i
: i
= 0; continue
439 msg
= "continue failed to continue inside try"
441 msg
= "continue inside try called except block"
447 msg
= "finally block not called"
455 def test_break_continue_loop(self
):
456 # This test warrants an explanation. It is a test specifically for SF bugs
457 # #463359 and #462937. The bug is that a 'break' statement executed or
458 # exception raised inside a try/except inside a loop, *after* a continue
459 # statement has been executed in that loop, will cause the wrong number of
460 # arguments to be popped off the stack and the instruction pointer reset to
461 # a very small number (usually 0.) Because of this, the following test
462 # *must* written as a function, and the tracking vars *must* be function
463 # arguments with default values. Otherwise, the test will loop and loop.
465 def test_inner(extra_burning_oil
= 1, count
=0):
470 if extra_burning_oil
and big_hippo
== 1:
471 extra_burning_oil
-= 1
477 if count
> 2 or big_hippo
<> 1:
478 self
.fail("continue then break in try/except in loop broken!")
481 def testReturn(self
):
482 # 'return' [testlist]
487 check_syntax_error(self
, "class foo:return 1")
490 check_syntax_error(self
, "class foo:yield 1")
493 # 'raise' test [',' test]
494 try: raise RuntimeError, 'just testing'
495 except RuntimeError: pass
496 try: raise KeyboardInterrupt
497 except KeyboardInterrupt: pass
499 def testImport(self
):
500 # 'import' dotted_as_names
503 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
504 from time
import time
505 from time
import (time
)
506 # not testable inside a function, but already done at top of the module
508 from sys
import path
, argv
509 from sys
import (path
, argv
)
510 from sys
import (path
, argv
,)
512 def testGlobal(self
):
513 # 'global' NAME (',' NAME)*
516 global one
, two
, three
, four
, five
, six
, seven
, eight
, nine
, ten
519 # 'exec' expr ['in' expr [',' expr]]
523 if z
!= 2: self
.fail('exec \'z=1+1\'\\n')
526 if z
!= 2: self
.fail('exec \'z=1+1\'')
530 if hasattr(types
, "UnicodeType"):
533 if z != 2: self.fail('exec u\'z=1+1\'\\n')
536 if z != 2: self.fail('exec u\'z=1+1\'')"""
539 if g
.has_key('__builtins__'): del g
['__builtins__']
540 if g
!= {'z': 1}: self
.fail('exec \'z = 1\' in g')
545 warnings
.filterwarnings("ignore", "global statement", module
="<string>")
546 exec 'global a; a = 1; b = 2' in g
, l
547 if g
.has_key('__builtins__'): del g
['__builtins__']
548 if l
.has_key('__builtins__'): del l
['__builtins__']
549 if (g
, l
) != ({'a':1}, {'b':2}):
550 self
.fail('exec ... in g (%s), l (%s)' %(g
,l
))
552 def testAssert(self
):
553 # assertTruestmt: 'assert' test [',' test]
557 assert 1, lambda x
:x
+1
560 except AssertionError, e
:
561 self
.assertEquals(e
.args
[0], "msg")
564 self
.fail("AssertionError not raised by assert 0")
566 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
570 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
583 # 'while' test ':' suite ['else' ':' suite]
588 # Issue1920: "while 0" is optimized away,
589 # ensure that the "else" clause is still present.
595 self
.assertEquals(x
, 2)
598 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
599 for i
in 1, 2, 3: pass
600 for i
, j
, k
in (): pass
603 def __init__(self
, max):
606 def __len__(self
): return len(self
.sofar
)
607 def __getitem__(self
, i
):
608 if not 0 <= i
< self
.max: raise IndexError
611 self
.sofar
.append(n
*n
)
615 for x
in Squares(10): n
= n
+x
617 self
.fail('for over growing sequence')
620 for x
, in [(1,), (2,), (3,)]:
622 self
.assertEqual(result
, [1, 2, 3])
625 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
626 ### | 'try' ':' suite 'finally' ':' suite
627 ### except_clause: 'except' [expr [('as' | ',') expr]]
630 except ZeroDivisionError:
635 except EOFError: pass
636 except TypeError as msg
: pass
637 except RuntimeError, msg
: pass
641 except (EOFError, TypeError, ZeroDivisionError): pass
643 except (EOFError, TypeError, ZeroDivisionError), msg
: pass
648 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
663 ### and_test ('or' and_test)*
664 ### and_test: not_test ('and' not_test)*
665 ### not_test: 'not' not_test | comparison
669 if not not not 1: pass
670 if not 1 and 1 and 1: pass
671 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
673 def testComparison(self
):
674 ### comparison: expr (comp_op expr)*
675 ### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
689 if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass
691 def testBinaryMaskOps(self
):
696 def testShiftOps(self
):
701 def testAdditiveOps(self
):
705 x
= 1 - 1 + 1 - 1 + 1
707 def testMultiplicativeOps(self
):
713 def testUnaryOps(self
):
717 x
= ~
1 ^
1 & 1 |
1 & 1 ^
-1
718 x
= -1*1/1 + 1*1 - ---1*1
720 def testSelectors(self
):
721 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
722 ### subscript: expr | [expr] ':' [expr]
727 x
= sys
.modules
['time'].time()
738 # A rough test of SF bug 1333982. http://python.org/sf/1333982
739 # The testing here is fairly incomplete.
740 # Test cases should include: commas with 1 and 2 colons
748 self
.assertEquals(str(L
), '[1, (1,), (1, 2), (1, 2, 3)]')
751 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
752 ### dictorsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
756 x
= (1 or 2 or 3, 2, 3)
761 x
= [1 or 2 or 3, 2, 3]
767 x
= {'one' or 'two': 1 or 2}
768 x
= {'one': 1, 'two': 2}
769 x
= {'one': 1, 'two': 2,}
770 x
= {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
774 x
= {'one', 'two', 'three'}
779 self
.assertEqual(`
1,2`
, '(1, 2)')
785 ### exprlist: expr (',' expr)* [',']
786 ### testlist: test (',' test)* [',']
787 # These have been exercised enough above
789 def testClassdef(self
):
790 # 'class' NAME ['(' [testlist] ')'] ':' suite
795 class D(C1
, C2
, B
): pass
797 def meth1(self
): pass
798 def meth2(self
, arg
): pass
799 def meth3(self
, a1
, a2
): pass
800 # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
801 # decorators: decorator+
802 # decorated: decorators (classdef | funcdef)
803 def class_decorator(x
):
809 self
.assertEqual(G
.decorated
, True)
811 def testDictcomps(self
):
812 # dictorsetmaker: ( (test ':' test (comp_for |
813 # (',' test ':' test)* [','])) |
814 # (test (comp_for | (',' test)* [','])) )
816 self
.assertEqual({i
:i
+1 for i
in nums
}, {1: 2, 2: 3, 3: 4})
818 def testListcomps(self
):
819 # list comprehension tests
820 nums
= [1, 2, 3, 4, 5]
821 strs
= ["Apple", "Banana", "Coconut"]
822 spcs
= [" Apple", " Banana ", "Coco nut "]
824 self
.assertEqual([s
.strip() for s
in spcs
], ['Apple', 'Banana', 'Coco nut'])
825 self
.assertEqual([3 * x
for x
in nums
], [3, 6, 9, 12, 15])
826 self
.assertEqual([x
for x
in nums
if x
> 2], [3, 4, 5])
827 self
.assertEqual([(i
, s
) for i
in nums
for s
in strs
],
828 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
829 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
830 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
831 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
832 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
833 self
.assertEqual([(i
, s
) for i
in nums
for s
in [f
for f
in strs
if "n" in f
]],
834 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
835 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
836 (5, 'Banana'), (5, 'Coconut')])
837 self
.assertEqual([(lambda a
:[a
**i
for i
in range(a
+1)])(j
) for j
in range(5)],
838 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
841 return [None < x
< 3 for x
in l
if x
> 2]
843 self
.assertEqual(test_in_func(nums
), [False, False, False])
845 def test_nested_front():
846 self
.assertEqual([[y
for y
in [x
, x
+ 1]] for x
in [1,3,5]],
847 [[1, 2], [3, 4], [5, 6]])
851 check_syntax_error(self
, "[i, s for i in nums for s in strs]")
852 check_syntax_error(self
, "[x if y]")
867 (1, 10), (1, 20), (2, 20), (3, 30)
872 for (sno
, sname
) in suppliers
873 for (pno
, pname
) in parts
874 for (sp_sno
, sp_pno
) in suppart
875 if sno
== sp_sno
and pno
== sp_pno
878 self
.assertEqual(x
, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
879 ('Macdonalds', 'Cheeseburger')])
881 def testGenexps(self
):
882 # generator expression tests
883 g
= ([x
for x
in range(10)] for x
in range(1))
884 self
.assertEqual(g
.next(), [x
for x
in range(10)])
887 self
.fail('should produce StopIteration exception')
888 except StopIteration:
895 self
.fail('should produce TypeError')
899 self
.assertEqual(list((x
, y
) for x
in 'abcd' for y
in 'abcd'), [(x
, y
) for x
in 'abcd' for y
in 'abcd'])
900 self
.assertEqual(list((x
, y
) for x
in 'ab' for y
in 'xy'), [(x
, y
) for x
in 'ab' for y
in 'xy'])
902 a
= [x
for x
in range(10)]
903 b
= (x
for x
in (y
for y
in a
))
904 self
.assertEqual(sum(b
), sum([x
for x
in range(10)]))
906 self
.assertEqual(sum(x
**2 for x
in range(10)), sum([x
**2 for x
in range(10)]))
907 self
.assertEqual(sum(x
*x
for x
in range(10) if x
%2), sum([x
*x
for x
in range(10) if x
%2]))
908 self
.assertEqual(sum(x
for x
in (y
for y
in range(10))), sum([x
for x
in range(10)]))
909 self
.assertEqual(sum(x
for x
in (y
for y
in (z
for z
in range(10)))), sum([x
for x
in range(10)]))
910 self
.assertEqual(sum(x
for x
in [y
for y
in (z
for z
in range(10))]), sum([x
for x
in range(10)]))
911 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)]))
912 self
.assertEqual(sum(x
for x
in (y
for y
in (z
for z
in range(10) if True) if False) if True), 0)
913 check_syntax_error(self
, "foo(x for x in range(10), 100)")
914 check_syntax_error(self
, "foo(100, x for x in range(10))")
916 def testComprehensionSpecials(self
):
917 # test for outmost iterable precomputation
918 x
= 10; g
= (i
for i
in range(x
)); x
= 5
919 self
.assertEqual(len(list(g
)), 10)
921 # This should hold, since we're only precomputing outmost iterable.
922 x
= 10; t
= False; g
= ((i
,j
) for i
in range(x
) if t
for j
in range(x
))
924 self
.assertEqual([(i
,j
) for i
in range(10) for j
in range(5)], list(g
))
926 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
927 # even though it's silly. Make sure it works (ifelse broke this.)
928 self
.assertEqual([ x
for x
in range(10) if x
% 2 if x
% 3 ], [1, 5, 7])
929 self
.assertEqual(list(x
for x
in range(10) if x
% 2 if x
% 3), [1, 5, 7])
931 # verify unpacking single element tuples in listcomp/genexp.
932 self
.assertEqual([x
for x
, in [(4,), (5,), (6,)]], [4, 5, 6])
933 self
.assertEqual(list(x
for x
, in [(7,), (8,), (9,)]), [7, 8, 9])
935 def test_with_statement(self
):
936 class manager(object):
939 def __exit__(self
, *args
):
946 with
manager() as (x
, y
):
948 with
manager(), manager():
950 with
manager() as x
, manager() as y
:
952 with
manager() as x
, manager():
955 def testIfElseExpr(self
):
956 # Test ifelse expressions in various cases
957 def _checkeval(msg
, ret
):
958 "helper to check that evaluation of expressions is done correctly"
962 self
.assertEqual([ x() for x
in lambda: True, lambda: False if x() ], [True])
963 self
.assertEqual([ x() for x
in (lambda: True, lambda: False) if x() ], [True])
964 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])
965 self
.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
966 self
.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
967 self
.assertEqual((5 and 6 if 0 else 1), 1)
968 self
.assertEqual(((5 and 6) if 0 else 1), 1)
969 self
.assertEqual((5 and (6 if 1 else 1)), 6)
970 self
.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
971 self
.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
972 self
.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
973 self
.assertEqual((not 5 if 1 else 1), False)
974 self
.assertEqual((not 5 if 0 else 1), 1)
975 self
.assertEqual((6 + 1 if 1 else 2), 7)
976 self
.assertEqual((6 - 1 if 1 else 2), 5)
977 self
.assertEqual((6 * 2 if 1 else 4), 12)
978 self
.assertEqual((6 / 2 if 1 else 3), 3)
979 self
.assertEqual((6 < 4 if 0 else 2), 2)
981 def test_paren_evaluation(self
):
982 self
.assertEqual(16 // (4 // 2), 8)
983 self
.assertEqual((16 // 4) // 2, 2)
984 self
.assertEqual(16 // 4 // 2, 2)
985 self
.assertTrue(False is (2 is 3))
986 self
.assertFalse((False is 2) is 3)
987 self
.assertFalse(False is 2 is 3)
991 run_unittest(TokenTests
, GrammarTests
)
993 if __name__
== '__main__':