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 TestFailed
, verify
, vereq
, check_syntax
18 print '1.1.1 Backslashes'
20 # Backslash means line continuation:
23 if x
!= 2: raise TestFailed
, 'backslash for line continuation'
25 # Backslash does not means continuation in comments :\
27 if x
!= 0: raise TestFailed
, 'backslash ending comment'
29 print '1.1.2 Numeric literals'
31 print '1.1.2.1 Plain integers'
32 if 0xff != 255: raise TestFailed
, 'hex int'
33 if 0377 != 255: raise TestFailed
, 'octal int'
34 if 2147483647 != 017777777777: raise TestFailed
, 'large positive int'
36 from sys
import maxint
39 if maxint
== 2147483647:
40 # The following test will start to fail in Python 2.4;
41 # change the 020000000000 to -020000000000
42 if -2147483647-1 != -020000000000: raise TestFailed
, 'max negative int'
44 if 037777777777 < 0: raise TestFailed
, 'large oct'
45 if 0xffffffff < 0: raise TestFailed
, 'large hex'
46 for s
in '2147483648', '040000000000', '0x100000000':
50 print "OverflowError on huge integer literal " + repr(s
)
51 elif eval('maxint == 9223372036854775807'):
52 if eval('-9223372036854775807-1 != -01000000000000000000000'):
53 raise TestFailed
, 'max negative int'
54 if eval('01777777777777777777777') < 0: raise TestFailed
, 'large oct'
55 if eval('0xffffffffffffffff') < 0: raise TestFailed
, 'large hex'
56 for s
in '9223372036854775808', '02000000000000000000000', \
57 '0x10000000000000000':
61 print "OverflowError on huge integer literal " + repr(s
)
63 print 'Weird maxint value', maxint
65 print '1.1.2.2 Long integers'
68 x
= 0xffffffffffffffffL
69 x
= 0xffffffffffffffffl
70 x
= 077777777777777777L
71 x
= 077777777777777777l
72 x
= 123456789012345678901234567890L
73 x
= 123456789012345678901234567890l
75 print '1.1.2.3 Floating point'
89 print '1.1.3 String literals'
91 x
= ''; y
= ""; verify(len(x
) == 0 and x
== y
)
92 x
= '\''; y
= "'"; verify(len(x
) == 1 and x
== y
and ord(x
) == 39)
93 x
= '"'; y
= "\""; verify(len(x
) == 1 and x
== y
and ord(x
) == 34)
94 x
= "doesn't \"shrink\" does it"
95 y
= 'doesn\'t "shrink" does it'
96 verify(len(x
) == 24 and x
== y
)
97 x
= "does \"shrink\" doesn't it"
98 y
= 'does "shrink" doesn\'t it'
99 verify(len(x
) == 24 and x
== y
)
106 y
= '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
130 print 'single_input' # NEWLINE | simple_stmt | compound_stmt NEWLINE
131 # XXX can't test in a script -- this rule is only used when interactive
133 print 'file_input' # (NEWLINE | stmt)* ENDMARKER
134 # Being tested as this very moment this very module
136 print 'expr_input' # testlist NEWLINE
137 # XXX Hard to test -- used only in calls to input()
139 print 'eval_input' # testlist ENDMARKER
140 x
= eval('1, 0 or 1')
143 ### 'def' NAME parameters ':' suite
144 ### parameters: '(' [varargslist] ')'
145 ### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME]
146 ### | ('**'|'*' '*') NAME)
147 ### | fpdef ['=' test] (',' fpdef ['=' test])* [',']
148 ### fpdef: NAME | '(' fplist ')'
149 ### fplist: fpdef (',' fpdef)* [',']
150 ### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test)
151 ### argument: [test '='] test # Really [keyword '='] test
156 def f2(one_argument
): pass
157 def f3(two
, arguments
): pass
158 def f4(two
, (compound
, (argument
, list))): pass
159 def f5((compound
, first
), two
): pass
160 vereq(f2
.func_code
.co_varnames
, ('one_argument',))
161 vereq(f3
.func_code
.co_varnames
, ('two', 'arguments'))
162 if sys
.platform
.startswith('java'):
163 vereq(f4
.func_code
.co_varnames
,
164 ('two', '(compound, (argument, list))', 'compound', 'argument',
166 vereq(f5
.func_code
.co_varnames
,
167 ('(compound, first)', 'two', 'compound', 'first'))
169 vereq(f4
.func_code
.co_varnames
,
170 ('two', '.1', 'compound', 'argument', 'list'))
171 vereq(f5
.func_code
.co_varnames
,
172 ('.0', 'two', 'compound', 'first'))
173 def a1(one_arg
,): pass
174 def a2(two
, args
,): pass
176 def v1(a
, *rest
): pass
177 def v2(a
, b
, *rest
): pass
178 def v3(a
, (b
, c
), *rest
): return a
, b
, c
, rest
179 # ceval unpacks the formal arguments into the first argcount names;
180 # thus, the names nested inside tuples must appear after these names.
181 if sys
.platform
.startswith('java'):
182 verify(v3
.func_code
.co_varnames
== ('a', '(b, c)', 'rest', 'b', 'c'))
184 vereq(v3
.func_code
.co_varnames
, ('a', '.1', 'rest', 'b', 'c'))
185 verify(v3(1, (2, 3), 4) == (1, 2, 3, (4,)))
191 def d11(a
, b
=1): pass
195 def d21(a
, b
, c
=1): pass
202 def d02(a
=1, b
=2): pass
209 d02(**{'a': 1, 'b': 2})
210 def d12(a
, b
=1, c
=2): pass
214 def d22(a
, b
, c
=1, d
=2): pass
218 def d01v(a
=1, *rest
): pass
225 def d11v(a
, b
=1, *rest
): pass
229 def d21v(a
, b
, c
=1, *rest
): pass
234 d21v(1, 2, **{'c': 3})
235 def d02v(a
=1, b
=2, *rest
): pass
241 d02v(**{'a': 1, 'b': 2})
242 def d12v(a
, b
=1, c
=2, *rest
): pass
248 d12v(1, 2, *(3, 4, 5))
249 d12v(1, *(2,), **{'c': 3})
250 def d22v(a
, b
, c
=1, d
=2, *rest
): pass
256 d22v(1, 2, *(3, 4, 5))
257 d22v(1, *(2, 3), **{'d': 4})
259 ### lambdef: 'lambda' [varargslist] ':' test
263 l2
= lambda : a
[d
] # XXX just testing the expression
264 l3
= lambda : [2 < x
for x
in [-1, 3, 0L]]
265 verify(l3() == [0, 1, 0])
266 l4
= lambda x
= lambda y
= lambda z
=1 : z
: y() : x()
268 l5
= lambda x
, y
, z
=2: x
+ y
+ z
269 verify(l5(1, 2) == 5)
270 verify(l5(1, 2, 3) == 6)
271 check_syntax("lambda x: x = 2")
273 ### stmt: simple_stmt | compound_stmt
276 ### simple_stmt: small_stmt (';' small_stmt)* [';']
280 # verify statments that end with semi-colons
284 ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt
287 print 'expr_stmt' # (exprlist '=')* exprlist
294 abc
= a
, b
, c
= x
, y
, z
= xyz
= 1, 2, (3, 4)
295 # NB these variables are deleted below
297 check_syntax("x + 1 = 1")
298 check_syntax("a + 1 = b + 2")
300 print 'print_stmt' # 'print' (test ',')* [test]
304 print 0 or 1, 0 or 1,
307 print 'extended print_stmt' # 'print' '>>' test ','
309 print >> sys
.stdout
, 1, 2, 3
310 print >> sys
.stdout
, 1, 2, 3,
312 print >> sys
.stdout
, 0 or 1, 0 or 1,
313 print >> sys
.stdout
, 0 or 1
315 # test printing to an instance
317 def write(self
, msg
): pass
320 print >> gulp
, 1, 2, 3
321 print >> gulp
, 1, 2, 3,
323 print >> gulp
, 0 or 1, 0 or 1,
324 print >> gulp
, 0 or 1
328 oldstdout
= sys
.stdout
334 sys
.stdout
= oldstdout
336 # we should see this once
337 def tellme(file=sys
.stdout
):
338 print >> file, 'hello world'
342 # we should not see this at all
343 def tellme(file=None):
344 print >> file, 'goodbye universe'
349 check_syntax('print ,')
350 check_syntax('print >> x,')
352 print 'del_stmt' # 'del' exprlist
356 print 'pass_stmt' # 'pass'
359 print 'flow_stmt' # break_stmt | continue_stmt | return_stmt | raise_stmt
362 print 'break_stmt' # 'break'
365 print 'continue_stmt' # 'continue'
367 while i
: i
= 0; continue
371 msg
= "continue + try/except ok"
374 msg
= "continue failed to continue inside try"
376 msg
= "continue inside try called except block"
381 msg
= "finally block not called"
385 msg
= "continue + try/finally ok"
389 # This test warrants an explanation. It is a test specifically for SF bugs
390 # #463359 and #462937. The bug is that a 'break' statement executed or
391 # exception raised inside a try/except inside a loop, *after* a continue
392 # statement has been executed in that loop, will cause the wrong number of
393 # arguments to be popped off the stack and the instruction pointer reset to
394 # a very small number (usually 0.) Because of this, the following test
395 # *must* written as a function, and the tracking vars *must* be function
396 # arguments with default values. Otherwise, the test will loop and loop.
398 print "testing continue and break in try/except in loop"
399 def test_break_continue_loop(extra_burning_oil
= 1, count
=0):
404 if extra_burning_oil
and big_hippo
== 1:
405 extra_burning_oil
-= 1
411 if count
> 2 or big_hippo
<> 1:
412 print "continue then break in try/except in loop broken!"
413 test_break_continue_loop()
415 print 'return_stmt' # 'return' [testlist]
420 check_syntax("class foo:return 1")
423 check_syntax("class foo:yield 1")
425 print 'raise_stmt' # 'raise' test [',' test]
426 try: raise RuntimeError, 'just testing'
427 except RuntimeError: pass
428 try: raise KeyboardInterrupt
429 except KeyboardInterrupt: pass
431 print 'import_name' # 'import' dotted_as_names
434 print 'import_from' # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
435 from time
import time
436 from time
import (time
)
438 from sys
import path
, argv
439 from sys
import (path
, argv
)
440 from sys
import (path
, argv
,)
442 print 'global_stmt' # 'global' NAME (',' NAME)*
446 global one
, two
, three
, four
, five
, six
, seven
, eight
, nine
, ten
448 print 'exec_stmt' # 'exec' expr ['in' expr [',' expr]]
453 if z
!= 2: raise TestFailed
, 'exec \'z=1+1\'\\n'
456 if z
!= 2: raise TestFailed
, 'exec \'z=1+1\''
460 if hasattr(types
, "UnicodeType"):
463 if z != 2: raise TestFailed, 'exec u\'z=1+1\'\\n'
466 if z != 2: raise TestFailed, 'exec u\'z=1+1\''
471 if g
.has_key('__builtins__'): del g
['__builtins__']
472 if g
!= {'z': 1}: raise TestFailed
, 'exec \'z = 1\' in g'
477 warnings
.filterwarnings("ignore", "global statement", module
="<string>")
478 exec 'global a; a = 1; b = 2' in g
, l
479 if g
.has_key('__builtins__'): del g
['__builtins__']
480 if l
.has_key('__builtins__'): del l
['__builtins__']
481 if (g
, l
) != ({'a':1}, {'b':2}): raise TestFailed
, 'exec ... in g (%s), l (%s)' %(g
,l
)
484 print "assert_stmt" # assert_stmt: 'assert' test [',' test]
488 assert 1, lambda x
:x
+1
490 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
493 print 'if_stmt' # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
505 print 'while_stmt' # 'while' test ':' suite ['else' ':' suite]
510 print 'for_stmt' # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
511 for i
in 1, 2, 3: pass
512 for i
, j
, k
in (): pass
515 def __init__(self
, max):
518 def __len__(self
): return len(self
.sofar
)
519 def __getitem__(self
, i
):
520 if not 0 <= i
< self
.max: raise IndexError
523 self
.sofar
.append(n
*n
)
527 for x
in Squares(10): n
= n
+x
528 if n
!= 285: raise TestFailed
, 'for over growing sequence'
531 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
532 ### | 'try' ':' suite 'finally' ':' suite
533 ### except_clause: 'except' [expr [',' expr]]
536 except ZeroDivisionError:
541 except EOFError: pass
542 except TypeError, msg
: pass
543 except RuntimeError, msg
: pass
547 except (EOFError, TypeError, ZeroDivisionError): pass
549 except (EOFError, TypeError, ZeroDivisionError), msg
: pass
553 print 'suite' # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
568 ### and_test ('or' and_test)*
569 ### and_test: not_test ('and' not_test)*
570 ### not_test: 'not' not_test | comparison
574 if not not not 1: pass
575 if not 1 and 1 and 1: pass
576 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
579 ### comparison: expr (comp_op expr)*
580 ### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
594 if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass
596 print 'binary mask ops'
610 x
= 1 - 1 + 1 - 1 + 1
612 print 'multiplicative ops'
622 x
= ~
1 ^
1 & 1 |
1 & 1 ^
-1
623 x
= -1*1/1 + 1*1 - ---1*1
626 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
627 ### subscript: expr | [expr] ':' [expr]
638 v0(1,2,3,4,5,6,7,8,9,0)
643 v1(1,2,3,4,5,6,7,8,9,0)
647 v2(1,2,3,4,5,6,7,8,9,0)
650 v3(1,(2,3),4,5,6,7,8,9,0)
655 x
= sys
.modules
['time'].time()
666 # A rough test of SF bug 1333982. http://python.org/sf/1333982
667 # The testing here is fairly incomplete.
668 # Test cases should include: commas with 1 and 2 colons
680 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
681 ### dictmaker: test ':' test (',' test ':' test)* [',']
685 x
= (1 or 2 or 3, 2, 3)
690 x
= [1 or 2 or 3, 2, 3]
696 x
= {'one' or 'two': 1 or 2}
697 x
= {'one': 1, 'two': 2}
698 x
= {'one': 1, 'two': 2,}
699 x
= {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
707 ### exprlist: expr (',' expr)* [',']
708 ### testlist: test (',' test)* [',']
709 # These have been exercised enough above
711 print 'classdef' # 'class' NAME ['(' [testlist] ')'] ':' suite
716 class D(C1
, C2
, B
): pass
718 def meth1(self
): pass
719 def meth2(self
, arg
): pass
720 def meth3(self
, a1
, a2
): pass
722 # list comprehension tests
723 nums
= [1, 2, 3, 4, 5]
724 strs
= ["Apple", "Banana", "Coconut"]
725 spcs
= [" Apple", " Banana ", "Coco nut "]
727 print [s
.strip() for s
in spcs
]
728 print [3 * x
for x
in nums
]
729 print [x
for x
in nums
if x
> 2]
730 print [(i
, s
) for i
in nums
for s
in strs
]
731 print [(i
, s
) for i
in nums
for s
in [f
for f
in strs
if "n" in f
]]
732 print [(lambda a
:[a
**i
for i
in range(a
+1)])(j
) for j
in range(5)]
735 return [None < x
< 3 for x
in l
if x
> 2]
737 print test_in_func(nums
)
739 def test_nested_front():
740 print [[y
for y
in [x
, x
+ 1]] for x
in [1,3,5]]
744 check_syntax("[i, s for i in nums for s in strs]")
745 check_syntax("[x if y]")
760 (1, 10), (1, 20), (2, 20), (3, 30)
765 for (sno
, sname
) in suppliers
766 for (pno
, pname
) in parts
767 for (sp_sno
, sp_pno
) in suppart
768 if sno
== sp_sno
and pno
== sp_pno
771 # generator expression tests
772 g
= ([x
for x
in range(10)] for x
in range(1))
773 verify(g
.next() == [x
for x
in range(10)])
776 raise TestFailed
, 'should produce StopIteration exception'
777 except StopIteration:
784 raise TestFailed
, 'should produce TypeError'
788 verify(list((x
, y
) for x
in 'abcd' for y
in 'abcd') == [(x
, y
) for x
in 'abcd' for y
in 'abcd'])
789 verify(list((x
, y
) for x
in 'ab' for y
in 'xy') == [(x
, y
) for x
in 'ab' for y
in 'xy'])
791 a
= [x
for x
in range(10)]
792 b
= (x
for x
in (y
for y
in a
))
793 verify(sum(b
) == sum([x
for x
in range(10)]))
795 verify(sum(x
**2 for x
in range(10)) == sum([x
**2 for x
in range(10)]))
796 verify(sum(x
*x
for x
in range(10) if x
%2) == sum([x
*x
for x
in range(10) if x
%2]))
797 verify(sum(x
for x
in (y
for y
in range(10))) == sum([x
for x
in range(10)]))
798 verify(sum(x
for x
in (y
for y
in (z
for z
in range(10)))) == sum([x
for x
in range(10)]))
799 verify(sum(x
for x
in [y
for y
in (z
for z
in range(10))]) == sum([x
for x
in range(10)]))
800 verify(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)]))
801 verify(sum(x
for x
in (y
for y
in (z
for z
in range(10) if True) if False) if True) == 0)
802 check_syntax("foo(x for x in range(10), 100)")
803 check_syntax("foo(100, x for x in range(10))")
805 # test for outmost iterable precomputation
806 x
= 10; g
= (i
for i
in range(x
)); x
= 5
807 verify(len(list(g
)) == 10)
809 # This should hold, since we're only precomputing outmost iterable.
810 x
= 10; t
= False; g
= ((i
,j
) for i
in range(x
) if t
for j
in range(x
))
812 verify([(i
,j
) for i
in range(10) for j
in range(5)] == list(g
))
814 # Test ifelse expressions in various cases
815 def _checkeval(msg
, ret
):
816 "helper to check that evaluation of expressions is done correctly"
820 verify([ x() for x
in lambda: True, lambda: False if x() ] == [True])
821 verify([ x() for x
in (lambda: True, lambda: False) if x() ] == [True])
822 verify([ x(False) for x
in (lambda x
: False if x
else True, lambda x
: True if x
else False) if x(False) ] == [True])
823 verify((5 if 1 else _checkeval("check 1", 0)) == 5)
824 verify((_checkeval("check 2", 0) if 0 else 5) == 5)
825 verify((5 and 6 if 0 else 1) == 1)
826 verify(((5 and 6) if 0 else 1) == 1)
827 verify((5 and (6 if 1 else 1)) == 6)
828 verify((0 or _checkeval("check 3", 2) if 0 else 3) == 3)
829 verify((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)) == 1)
830 verify((0 or 5 if 1 else _checkeval("check 6", 3)) == 5)
831 verify((not 5 if 1 else 1) == False)
832 verify((not 5 if 0 else 1) == 1)
833 verify((6 + 1 if 1 else 2) == 7)
834 verify((6 - 1 if 1 else 2) == 5)
835 verify((6 * 2 if 1 else 4) == 12)
836 verify((6 / 2 if 1 else 3) == 3)
837 verify((6 < 4 if 0 else 2) == 2)