# Python test set -- part 1, grammar.
# This just tests whether the parser accepts them all.
# NOTE: When you run this test as a script from the command line, you
# get warnings about certain hex/oct constants. Since those are
# issued by the parser, you can't suppress them by adding a
# filterwarnings() call to this module. Therefore, to shut up the
# regression test, the filterwarnings() call has been added to
from test
.test_support
import TestFailed
, verify
, check_syntax
print '1.1.1 Backslashes'
# Backslash means line continuation:
if x
!= 2: raise TestFailed
, 'backslash for line continuation'
# Backslash does not means continuation in comments :\
if x
!= 0: raise TestFailed
, 'backslash ending comment'
print '1.1.2 Numeric literals'
print '1.1.2.1 Plain integers'
if 0xff != 255: raise TestFailed
, 'hex int'
if 0377 != 255: raise TestFailed
, 'octal int'
if 2147483647 != 017777777777: raise TestFailed
, 'large positive int'
# The following test will start to fail in Python 2.4;
# change the 020000000000 to -020000000000
if -2147483647-1 != -020000000000: raise TestFailed
, 'max negative int'
if 037777777777 < 0: raise TestFailed
, 'large oct'
if 0xffffffff < 0: raise TestFailed
, 'large hex'
for s
in '2147483648', '040000000000', '0x100000000':
print "OverflowError on huge integer literal " + repr(s
)
elif eval('maxint == 9223372036854775807'):
if eval('-9223372036854775807-1 != -01000000000000000000000'):
raise TestFailed
, 'max negative int'
if eval('01777777777777777777777') < 0: raise TestFailed
, 'large oct'
if eval('0xffffffffffffffff') < 0: raise TestFailed
, 'large hex'
for s
in '9223372036854775808', '02000000000000000000000', \
print "OverflowError on huge integer literal " + repr(s
)
print 'Weird maxint value', maxint
print '1.1.2.2 Long integers'
x
= 123456789012345678901234567890L
x
= 123456789012345678901234567890l
print '1.1.2.3 Floating point'
print '1.1.3 String literals'
x
= ''; y
= ""; verify(len(x
) == 0 and x
== y
)
x
= '\''; y
= "'"; verify(len(x
) == 1 and x
== y
and ord(x
) == 39)
x
= '"'; y
= "\""; verify(len(x
) == 1 and x
== y
and ord(x
) == 34)
x
= "doesn't \"shrink\" does it"
y
= 'doesn\'t "shrink" does it'
verify(len(x
) == 24 and x
== y
)
x
= "does \"shrink\" doesn't it"
y
= 'does "shrink" doesn\'t it'
verify(len(x
) == 24 and x
== y
)
y
= '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
print 'single_input' # NEWLINE | simple_stmt | compound_stmt NEWLINE
# XXX can't test in a script -- this rule is only used when interactive
print 'file_input' # (NEWLINE | stmt)* ENDMARKER
# Being tested as this very moment this very module
print 'expr_input' # testlist NEWLINE
# XXX Hard to test -- used only in calls to input()
print 'eval_input' # testlist ENDMARKER
### 'def' NAME parameters ':' suite
### parameters: '(' [varargslist] ')'
### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME]
### | ('**'|'*' '*') NAME)
### | fpdef ['=' test] (',' fpdef ['=' test])* [',']
### fpdef: NAME | '(' fplist ')'
### fplist: fpdef (',' fpdef)* [',']
### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test)
### argument: [test '='] test # Really [keyword '='] test
def f2(one_argument
): pass
def f3(two
, arguments
): pass
def f4(two
, (compound
, (argument
, list))): pass
def f5((compound
, first
), two
): pass
verify(f2
.func_code
.co_varnames
== ('one_argument',))
verify(f3
.func_code
.co_varnames
== ('two', 'arguments'))
if sys
.platform
.startswith('java'):
verify(f4
.func_code
.co_varnames
==
('two', '(compound, (argument, list))', 'compound', 'argument',
verify(f5
.func_code
.co_varnames
==
('(compound, first)', 'two', 'compound', 'first'))
verify(f4
.func_code
.co_varnames
== ('two', '.2', 'compound',
verify(f5
.func_code
.co_varnames
== ('.0', 'two', 'compound', 'first'))
def v2(a
, b
, *rest
): pass
def v3(a
, (b
, c
), *rest
): return a
, b
, c
, rest
if sys
.platform
.startswith('java'):
verify(v3
.func_code
.co_varnames
== ('a', '(b, c)', 'rest', 'b', 'c'))
verify(v3
.func_code
.co_varnames
== ('a', '.2', 'rest', 'b', 'c'))
verify(v3(1, (2, 3), 4) == (1, 2, 3, (4,)))
def d12(a
, b
=1, c
=2): pass
def d22(a
, b
, c
=1, d
=2): pass
def d01v(a
=1, *rest
): pass
def d11v(a
, b
=1, *rest
): pass
def d21v(a
, b
, c
=1, *rest
): pass
def d02v(a
=1, b
=2, *rest
): pass
def d12v(a
, b
=1, c
=2, *rest
): pass
d12v(1, *(2,), **{'c': 3})
def d22v(a
, b
, c
=1, d
=2, *rest
): pass
d22v(1, *(2, 3), **{'d': 4})
### lambdef: 'lambda' [varargslist] ':' test
l2
= lambda : a
[d
] # XXX just testing the expression
l3
= lambda : [2 < x
for x
in [-1, 3, 0L]]
verify(l3() == [0, 1, 0])
l4
= lambda x
= lambda y
= lambda z
=1 : z
: y() : x()
l5
= lambda x
, y
, z
=2: x
+ y
+ z
check_syntax("lambda x: x = 2")
### stmt: simple_stmt | compound_stmt
### simple_stmt: small_stmt (';' small_stmt)* [';']
### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt
print 'expr_stmt' # (exprlist '=')* exprlist
abc
= a
, b
, c
= x
, y
, z
= xyz
= 1, 2, (3, 4)
# NB these variables are deleted below
check_syntax("x + 1 = 1")
check_syntax("a + 1 = b + 2")
print 'print_stmt' # 'print' (test ',')* [test]
print 'extended print_stmt' # 'print' '>>' test ','
print >> sys
.stdout
, 1, 2, 3
print >> sys
.stdout
, 1, 2, 3,
print >> sys
.stdout
, 0 or 1, 0 or 1,
print >> sys
.stdout
, 0 or 1
# test printing to an instance
def write(self
, msg
): pass
print >> gulp
, 0 or 1, 0 or 1,
# we should see this once
def tellme(file=sys
.stdout
):
print >> file, 'hello world'
# we should not see this at all
print >> file, 'goodbye universe'
check_syntax('print >> x,')
print 'del_stmt' # 'del' exprlist
print 'pass_stmt' # 'pass'
print 'flow_stmt' # break_stmt | continue_stmt | return_stmt | raise_stmt
print 'break_stmt' # 'break'
print 'continue_stmt' # 'continue'
msg
= "continue + try/except ok"
msg
= "continue failed to continue inside try"
msg
= "continue inside try called except block"
msg
= "finally block not called"
msg
= "continue + try/finally ok"
# This test warrants an explanation. It is a test specifically for SF bugs
# #463359 and #462937. The bug is that a 'break' statement executed or
# exception raised inside a try/except inside a loop, *after* a continue
# statement has been executed in that loop, will cause the wrong number of
# arguments to be popped off the stack and the instruction pointer reset to
# a very small number (usually 0.) Because of this, the following test
# *must* written as a function, and the tracking vars *must* be function
# arguments with default values. Otherwise, the test will loop and loop.
print "testing continue and break in try/except in loop"
def test_break_continue_loop(extra_burning_oil
= 1, count
=0):
if extra_burning_oil
and big_hippo
== 1:
if count
> 2 or big_hippo
<> 1:
print "continue then break in try/except in loop broken!"
test_break_continue_loop()
print 'return_stmt' # 'return' [testlist]
print 'raise_stmt' # 'raise' test [',' test]
try: raise RuntimeError, 'just testing'
except RuntimeError: pass
try: raise KeyboardInterrupt
except KeyboardInterrupt: pass
print 'import_name' # 'import' dotted_as_names
print 'import_from' # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
from sys
import path
, argv
from sys
import (path
, argv
)
from sys
import (path
, argv
,)
print 'global_stmt' # 'global' NAME (',' NAME)*
global one
, two
, three
, four
, five
, six
, seven
, eight
, nine
, ten
print 'exec_stmt' # 'exec' expr ['in' expr [',' expr]]
if z
!= 2: raise TestFailed
, 'exec \'z=1+1\'\\n'
if z
!= 2: raise TestFailed
, 'exec \'z=1+1\''
if hasattr(types
, "UnicodeType"):
if z != 2: raise TestFailed, 'exec u\'z=1+1\'\\n'
if z != 2: raise TestFailed, 'exec u\'z=1+1\''
if g
.has_key('__builtins__'): del g
['__builtins__']
if g
!= {'z': 1}: raise TestFailed
, 'exec \'z = 1\' in g'
warnings
.filterwarnings("ignore", "global statement", module
="<string>")
exec 'global a; a = 1; b = 2' in g
, l
if g
.has_key('__builtins__'): del g
['__builtins__']
if l
.has_key('__builtins__'): del l
['__builtins__']
if (g
, l
) != ({'a':1}, {'b':2}): raise TestFailed
, 'exec ... in g (%s), l (%s)' %(g
,l
)
print "assert_stmt" # assert_stmt: 'assert' test [',' test]
### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
print 'if_stmt' # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
print 'while_stmt' # 'while' test ':' suite ['else' ':' suite]
print 'for_stmt' # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
def __len__(self
): return len(self
.sofar
)
def __getitem__(self
, i
):
if not 0 <= i
< self
.max: raise IndexError
for x
in Squares(10): n
= n
+x
if n
!= 285: raise TestFailed
, 'for over growing sequence'
### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
### | 'try' ':' suite 'finally' ':' suite
### except_clause: 'except' [expr [',' expr]]
except ZeroDivisionError:
except TypeError, msg
: pass
except RuntimeError, msg
: pass
except (EOFError, TypeError, ZeroDivisionError): pass
except (EOFError, TypeError, ZeroDivisionError), msg
: pass
print 'suite' # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
### and_test ('or' and_test)*
### and_test: not_test ('and' not_test)*
### not_test: 'not' not_test | comparison
if not 1 and 1 and 1: pass
if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
### comparison: expr (comp_op expr)*
### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass
print 'multiplicative ops'
x
= ~
1 ^
1 & 1 |
1 & 1 ^
-1
x
= -1*1/1 + 1*1 - ---1*1
### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
### subscript: expr | [expr] ':' [expr]
v3(1,(2,3),4,5,6,7,8,9,0)
x
= sys
.modules
['time'].time()
### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
### dictmaker: test ':' test (',' test ':' test)* [',']
x
= {'one' or 'two': 1 or 2}
x
= {'one': 1, 'two': 2,}
x
= {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
### exprlist: expr (',' expr)* [',']
### testlist: test (',' test)* [',']
# These have been exercised enough above
print 'classdef' # 'class' NAME ['(' testlist ')'] ':' suite
def meth2(self
, arg
): pass
def meth3(self
, a1
, a2
): pass
# list comprehension tests
strs
= ["Apple", "Banana", "Coconut"]
spcs
= [" Apple", " Banana ", "Coco nut "]
print [s
.strip() for s
in spcs
]
print [3 * x
for x
in nums
]
print [x
for x
in nums
if x
> 2]
print [(i
, s
) for i
in nums
for s
in strs
]
print [(i
, s
) for i
in nums
for s
in [f
for f
in strs
if "n" in f
]]
print [(lambda a
:[a
**i
for i
in range(a
+1)])(j
) for j
in range(5)]
return [None < x
< 3 for x
in l
if x
> 2]
print [[y
for y
in [x
, x
+ 1]] for x
in [1,3,5]]
check_syntax("[i, s for i in nums for s in strs]")
(1, 10), (1, 20), (2, 20), (3, 30)
for (sno
, sname
) in suppliers
for (pno
, pname
) in parts
for (sp_sno
, sp_pno
) in suppart
if sno
== sp_sno
and pno
== sp_pno
# generator expression tests
g
= ([x
for x
in range(10)] for x
in range(1))
verify(g
.next() == [x
for x
in range(10)])
raise TestFailed
, 'should produce StopIteration exception'
raise TestFailed
, 'should produce TypeError'
verify(list((x
, y
) for x
in 'abcd' for y
in 'abcd') == [(x
, y
) for x
in 'abcd' for y
in 'abcd'])
verify(list((x
, y
) for x
in 'ab' for y
in 'xy') == [(x
, y
) for x
in 'ab' for y
in 'xy'])
a
= [x
for x
in range(10)]
b
= (x
for x
in (y
for y
in a
))
verify(sum(b
) == sum([x
for x
in range(10)]))
verify(sum(x
**2 for x
in range(10)) == sum([x
**2 for x
in range(10)]))
verify(sum(x
*x
for x
in range(10) if x
%2) == sum([x
*x
for x
in range(10) if x
%2]))
verify(sum(x
for x
in (y
for y
in range(10))) == sum([x
for x
in range(10)]))
verify(sum(x
for x
in (y
for y
in (z
for z
in range(10)))) == sum([x
for x
in range(10)]))
verify(sum(x
for x
in [y
for y
in (z
for z
in range(10))]) == sum([x
for x
in range(10)]))
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)]))
verify(sum(x
for x
in (y
for y
in (z
for z
in range(10) if True) if False) if True) == 0)
check_syntax("foo(x for x in range(10), 100)")
check_syntax("foo(100, x for x in range(10))")
# test for outmost iterable precomputation
x
= 10; g
= (i
for i
in range(x
)); x
= 5
verify(len(list(g
)) == 10)
# This should hold, since we're only precomputing outmost iterable.
x
= 10; t
= False; g
= ((i
,j
) for i
in range(x
) if t
for j
in range(x
))
verify([(i
,j
) for i
in range(10) for j
in range(5)] == list(g
))