blob: 09ccde7002d8aa1019bce449b413d9b0f142ae57 [file] [log] [blame]
Guido van Rossum3bead091992-01-27 17:00:37 +00001# Python test set -- part 1, grammar.
2# This just tests whether the parser accepts them all.
3
Guido van Rossumf0253f22002-08-29 14:57:26 +00004# 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
9# regrtest.py.
10
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000011from test.test_support import TestFailed, verify, vereq, check_syntax
Jeremy Hylton7d3dff22001-10-10 01:45:02 +000012import sys
Guido van Rossum3bead091992-01-27 17:00:37 +000013
14print '1. Parser'
15
16print '1.1 Tokens'
17
18print '1.1.1 Backslashes'
19
20# Backslash means line continuation:
21x = 1 \
22+ 1
Fred Drake132dce22000-12-12 23:11:42 +000023if x != 2: raise TestFailed, 'backslash for line continuation'
Guido van Rossum3bead091992-01-27 17:00:37 +000024
25# Backslash does not means continuation in comments :\
26x = 0
Fred Drake132dce22000-12-12 23:11:42 +000027if x != 0: raise TestFailed, 'backslash ending comment'
Guido van Rossum3bead091992-01-27 17:00:37 +000028
29print '1.1.2 Numeric literals'
30
31print '1.1.2.1 Plain integers'
Fred Drake132dce22000-12-12 23:11:42 +000032if 0xff != 255: raise TestFailed, 'hex int'
33if 0377 != 255: raise TestFailed, 'octal int'
Guido van Rossumdd8cb441993-12-29 15:33:08 +000034if 2147483647 != 017777777777: raise TestFailed, 'large positive int'
35try:
Fred Drake004d5e62000-10-23 17:22:08 +000036 from sys import maxint
Guido van Rossumdd8cb441993-12-29 15:33:08 +000037except ImportError:
Fred Drake004d5e62000-10-23 17:22:08 +000038 maxint = 2147483647
Guido van Rossumdd8cb441993-12-29 15:33:08 +000039if maxint == 2147483647:
Guido van Rossum66b12592003-02-12 16:57:47 +000040 # The following test will start to fail in Python 2.4;
41 # change the 020000000000 to -020000000000
Guido van Rossum6c9e1302003-11-29 23:52:13 +000042 if -2147483647-1 != -020000000000: raise TestFailed, 'max negative int'
Fred Drake004d5e62000-10-23 17:22:08 +000043 # XXX -2147483648
Guido van Rossum6c9e1302003-11-29 23:52:13 +000044 if 037777777777 < 0: raise TestFailed, 'large oct'
45 if 0xffffffff < 0: raise TestFailed, 'large hex'
Fred Drake004d5e62000-10-23 17:22:08 +000046 for s in '2147483648', '040000000000', '0x100000000':
47 try:
48 x = eval(s)
49 except OverflowError:
Walter Dörwald70a6b492004-02-12 17:35:32 +000050 print "OverflowError on huge integer literal " + repr(s)
Guido van Rossumdd8cb441993-12-29 15:33:08 +000051elif eval('maxint == 9223372036854775807'):
Guido van Rossum6c9e1302003-11-29 23:52:13 +000052 if eval('-9223372036854775807-1 != -01000000000000000000000'):
Fred Drake004d5e62000-10-23 17:22:08 +000053 raise TestFailed, 'max negative int'
Guido van Rossum6c9e1302003-11-29 23:52:13 +000054 if eval('01777777777777777777777') < 0: raise TestFailed, 'large oct'
55 if eval('0xffffffffffffffff') < 0: raise TestFailed, 'large hex'
Fred Drake004d5e62000-10-23 17:22:08 +000056 for s in '9223372036854775808', '02000000000000000000000', \
57 '0x10000000000000000':
58 try:
59 x = eval(s)
60 except OverflowError:
Walter Dörwald70a6b492004-02-12 17:35:32 +000061 print "OverflowError on huge integer literal " + repr(s)
Guido van Rossumdd8cb441993-12-29 15:33:08 +000062else:
Fred Drake004d5e62000-10-23 17:22:08 +000063 print 'Weird maxint value', maxint
Guido van Rossum3bead091992-01-27 17:00:37 +000064
65print '1.1.2.2 Long integers'
66x = 0L
67x = 0l
68x = 0xffffffffffffffffL
69x = 0xffffffffffffffffl
70x = 077777777777777777L
71x = 077777777777777777l
72x = 123456789012345678901234567890L
73x = 123456789012345678901234567890l
74
75print '1.1.2.3 Floating point'
76x = 3.14
77x = 314.
78x = 0.314
79# XXX x = 000.314
80x = .314
81x = 3e14
82x = 3E14
83x = 3e-14
84x = 3e+14
85x = 3.e14
86x = .3e14
87x = 3.1e4
88
Guido van Rossumb31c7f71993-11-11 10:31:23 +000089print '1.1.3 String literals'
90
Marc-André Lemburg36619082001-01-17 19:11:13 +000091x = ''; y = ""; verify(len(x) == 0 and x == y)
92x = '\''; y = "'"; verify(len(x) == 1 and x == y and ord(x) == 39)
93x = '"'; y = "\""; verify(len(x) == 1 and x == y and ord(x) == 34)
Guido van Rossumb31c7f71993-11-11 10:31:23 +000094x = "doesn't \"shrink\" does it"
95y = 'doesn\'t "shrink" does it'
Marc-André Lemburg36619082001-01-17 19:11:13 +000096verify(len(x) == 24 and x == y)
Guido van Rossumb6775db1994-08-01 11:34:53 +000097x = "does \"shrink\" doesn't it"
98y = 'does "shrink" doesn\'t it'
Marc-André Lemburg36619082001-01-17 19:11:13 +000099verify(len(x) == 24 and x == y)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000100x = """
101The "quick"
102brown fox
103jumps over
104the 'lazy' dog.
105"""
106y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
Marc-André Lemburg36619082001-01-17 19:11:13 +0000107verify(x == y)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000108y = '''
109The "quick"
110brown fox
111jumps over
112the 'lazy' dog.
Marc-André Lemburg36619082001-01-17 19:11:13 +0000113'''; verify(x == y)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000114y = "\n\
115The \"quick\"\n\
116brown fox\n\
117jumps over\n\
118the 'lazy' dog.\n\
Marc-André Lemburg36619082001-01-17 19:11:13 +0000119"; verify(x == y)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000120y = '\n\
121The \"quick\"\n\
122brown fox\n\
123jumps over\n\
124the \'lazy\' dog.\n\
Marc-André Lemburg36619082001-01-17 19:11:13 +0000125'; verify(x == y)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000126
127
Guido van Rossum3bead091992-01-27 17:00:37 +0000128print '1.2 Grammar'
129
130print 'single_input' # NEWLINE | simple_stmt | compound_stmt NEWLINE
131# XXX can't test in a script -- this rule is only used when interactive
132
133print 'file_input' # (NEWLINE | stmt)* ENDMARKER
134# Being tested as this very moment this very module
135
136print 'expr_input' # testlist NEWLINE
137# XXX Hard to test -- used only in calls to input()
138
139print 'eval_input' # testlist ENDMARKER
140x = eval('1, 0 or 1')
141
142print 'funcdef'
143### 'def' NAME parameters ':' suite
144### parameters: '(' [varargslist] ')'
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000145### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME]
146### | ('**'|'*' '*') NAME)
Fred Drake004d5e62000-10-23 17:22:08 +0000147### | fpdef ['=' test] (',' fpdef ['=' test])* [',']
Guido van Rossum3bead091992-01-27 17:00:37 +0000148### fpdef: NAME | '(' fplist ')'
149### fplist: fpdef (',' fpdef)* [',']
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000150### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test)
Fred Drake004d5e62000-10-23 17:22:08 +0000151### argument: [test '='] test # Really [keyword '='] test
Guido van Rossum3bead091992-01-27 17:00:37 +0000152def f1(): pass
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000153f1()
154f1(*())
155f1(*(), **{})
Guido van Rossum3bead091992-01-27 17:00:37 +0000156def f2(one_argument): pass
157def f3(two, arguments): pass
158def f4(two, (compound, (argument, list))): pass
Jeremy Hylton92e9f292001-01-25 17:03:37 +0000159def f5((compound, first), two): pass
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160vereq(f2.func_code.co_varnames, ('one_argument',))
161vereq(f3.func_code.co_varnames, ('two', 'arguments'))
Jeremy Hylton7d3dff22001-10-10 01:45:02 +0000162if sys.platform.startswith('java'):
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163 vereq(f4.func_code.co_varnames,
Finn Bock4ab7adb2001-12-09 09:12:34 +0000164 ('two', '(compound, (argument, list))', 'compound', 'argument',
165 'list',))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000166 vereq(f5.func_code.co_varnames,
Jeremy Hylton7d3dff22001-10-10 01:45:02 +0000167 ('(compound, first)', 'two', 'compound', 'first'))
168else:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000169 vereq(f4.func_code.co_varnames,
170 ('two', '.1', 'compound', 'argument', 'list'))
171 vereq(f5.func_code.co_varnames,
172 ('.0', 'two', 'compound', 'first'))
Guido van Rossum3bead091992-01-27 17:00:37 +0000173def a1(one_arg,): pass
174def a2(two, args,): pass
175def v0(*rest): pass
176def v1(a, *rest): pass
177def v2(a, b, *rest): pass
Jeremy Hylton92e9f292001-01-25 17:03:37 +0000178def v3(a, (b, c), *rest): return a, b, c, rest
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179# ceval unpacks the formal arguments into the first argcount names;
180# thus, the names nested inside tuples must appear after these names.
Jeremy Hylton7d3dff22001-10-10 01:45:02 +0000181if sys.platform.startswith('java'):
182 verify(v3.func_code.co_varnames == ('a', '(b, c)', 'rest', 'b', 'c'))
183else:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000184 vereq(v3.func_code.co_varnames, ('a', '.1', 'rest', 'b', 'c'))
Jeremy Hylton92e9f292001-01-25 17:03:37 +0000185verify(v3(1, (2, 3), 4) == (1, 2, 3, (4,)))
Guido van Rossumb6775db1994-08-01 11:34:53 +0000186def d01(a=1): pass
187d01()
188d01(1)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000189d01(*(1,))
190d01(**{'a':2})
Guido van Rossumb6775db1994-08-01 11:34:53 +0000191def d11(a, b=1): pass
192d11(1)
193d11(1, 2)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000194d11(1, **{'b':2})
Guido van Rossumb6775db1994-08-01 11:34:53 +0000195def d21(a, b, c=1): pass
196d21(1, 2)
197d21(1, 2, 3)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000198d21(*(1, 2, 3))
199d21(1, *(2, 3))
200d21(1, 2, *(3,))
201d21(1, 2, **{'c':3})
Guido van Rossumb6775db1994-08-01 11:34:53 +0000202def d02(a=1, b=2): pass
203d02()
204d02(1)
205d02(1, 2)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000206d02(*(1, 2))
207d02(1, *(2,))
208d02(1, **{'b':2})
209d02(**{'a': 1, 'b': 2})
Guido van Rossumb6775db1994-08-01 11:34:53 +0000210def d12(a, b=1, c=2): pass
211d12(1)
212d12(1, 2)
213d12(1, 2, 3)
214def d22(a, b, c=1, d=2): pass
215d22(1, 2)
216d22(1, 2, 3)
217d22(1, 2, 3, 4)
218def d01v(a=1, *rest): pass
219d01v()
220d01v(1)
221d01v(1, 2)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000222d01v(*(1, 2, 3, 4))
223d01v(*(1,))
224d01v(**{'a':2})
Guido van Rossumb6775db1994-08-01 11:34:53 +0000225def d11v(a, b=1, *rest): pass
226d11v(1)
227d11v(1, 2)
228d11v(1, 2, 3)
229def d21v(a, b, c=1, *rest): pass
230d21v(1, 2)
231d21v(1, 2, 3)
232d21v(1, 2, 3, 4)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000233d21v(*(1, 2, 3, 4))
234d21v(1, 2, **{'c': 3})
Guido van Rossumb6775db1994-08-01 11:34:53 +0000235def d02v(a=1, b=2, *rest): pass
236d02v()
237d02v(1)
238d02v(1, 2)
239d02v(1, 2, 3)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000240d02v(1, *(2, 3, 4))
241d02v(**{'a': 1, 'b': 2})
Guido van Rossumb6775db1994-08-01 11:34:53 +0000242def d12v(a, b=1, c=2, *rest): pass
243d12v(1)
244d12v(1, 2)
245d12v(1, 2, 3)
246d12v(1, 2, 3, 4)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000247d12v(*(1, 2, 3, 4))
248d12v(1, 2, *(3, 4, 5))
249d12v(1, *(2,), **{'c': 3})
Guido van Rossumb6775db1994-08-01 11:34:53 +0000250def d22v(a, b, c=1, d=2, *rest): pass
251d22v(1, 2)
252d22v(1, 2, 3)
253d22v(1, 2, 3, 4)
254d22v(1, 2, 3, 4, 5)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000255d22v(*(1, 2, 3, 4))
256d22v(1, 2, *(3, 4, 5))
257d22v(1, *(2, 3), **{'d': 4})
Neal Norwitz33b730e2006-03-27 08:58:23 +0000258def d31v((x)): pass
259d31v(1)
260def d32v((x,)): pass
261d32v((1,))
Guido van Rossum3bead091992-01-27 17:00:37 +0000262
Sean Reifscheider4af861c2008-03-20 17:39:31 +0000263# Check ast errors in *args and *kwargs
264check_syntax("f(*g(1=2))")
265check_syntax("f(**g(1=2))")
266
Jeremy Hylton619eea62001-01-25 20:12:27 +0000267### lambdef: 'lambda' [varargslist] ':' test
268print 'lambdef'
269l1 = lambda : 0
270verify(l1() == 0)
271l2 = lambda : a[d] # XXX just testing the expression
272l3 = lambda : [2 < x for x in [-1, 3, 0L]]
273verify(l3() == [0, 1, 0])
274l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
275verify(l4() == 1)
276l5 = lambda x, y, z=2: x + y + z
277verify(l5(1, 2) == 5)
278verify(l5(1, 2, 3) == 6)
279check_syntax("lambda x: x = 2")
Georg Brandld297f1a2008-06-15 19:53:12 +0000280check_syntax("lambda (None,): None")
Jeremy Hylton619eea62001-01-25 20:12:27 +0000281
Guido van Rossum3bead091992-01-27 17:00:37 +0000282### stmt: simple_stmt | compound_stmt
283# Tested below
284
285### simple_stmt: small_stmt (';' small_stmt)* [';']
286print 'simple_stmt'
287x = 1; pass; del x
Neal Norwitzf8d403d2005-12-11 20:12:40 +0000288def foo():
289 # verify statments that end with semi-colons
290 x = 1; pass; del x;
291foo()
Guido van Rossum3bead091992-01-27 17:00:37 +0000292
Guido van Rossumb3b09c91993-10-22 14:24:22 +0000293### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt
Guido van Rossum3bead091992-01-27 17:00:37 +0000294# Tested below
295
296print 'expr_stmt' # (exprlist '=')* exprlist
2971
2981, 2, 3
299x = 1
300x = 1, 2, 3
301x = y = z = 1, 2, 3
302x, y, z = 1, 2, 3
303abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
304# NB these variables are deleted below
305
Jeremy Hylton47793992001-02-19 15:35:26 +0000306check_syntax("x + 1 = 1")
307check_syntax("a + 1 = b + 2")
308
Guido van Rossum3bead091992-01-27 17:00:37 +0000309print 'print_stmt' # 'print' (test ',')* [test]
310print 1, 2, 3
311print 1, 2, 3,
312print
313print 0 or 1, 0 or 1,
314print 0 or 1
315
Barry Warsawefc92ee2000-08-21 15:46:50 +0000316print 'extended print_stmt' # 'print' '>>' test ','
317import sys
318print >> sys.stdout, 1, 2, 3
319print >> sys.stdout, 1, 2, 3,
320print >> sys.stdout
321print >> sys.stdout, 0 or 1, 0 or 1,
322print >> sys.stdout, 0 or 1
323
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000324# test printing to an instance
Barry Warsaw9182b452000-08-29 04:57:10 +0000325class Gulp:
Fred Drake004d5e62000-10-23 17:22:08 +0000326 def write(self, msg): pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000327
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000328gulp = Gulp()
329print >> gulp, 1, 2, 3
330print >> gulp, 1, 2, 3,
331print >> gulp
332print >> gulp, 0 or 1, 0 or 1,
333print >> gulp, 0 or 1
334
335# test print >> None
Barry Warsaw9182b452000-08-29 04:57:10 +0000336def driver():
Fred Drake004d5e62000-10-23 17:22:08 +0000337 oldstdout = sys.stdout
338 sys.stdout = Gulp()
339 try:
340 tellme(Gulp())
341 tellme()
342 finally:
343 sys.stdout = oldstdout
Barry Warsaw9182b452000-08-29 04:57:10 +0000344
345# we should see this once
346def tellme(file=sys.stdout):
Fred Drake004d5e62000-10-23 17:22:08 +0000347 print >> file, 'hello world'
Barry Warsaw9182b452000-08-29 04:57:10 +0000348
349driver()
350
351# we should not see this at all
352def tellme(file=None):
Fred Drake004d5e62000-10-23 17:22:08 +0000353 print >> file, 'goodbye universe'
Barry Warsaw9182b452000-08-29 04:57:10 +0000354
355driver()
356
Barry Warsawefc92ee2000-08-21 15:46:50 +0000357# syntax errors
Barry Warsawefc92ee2000-08-21 15:46:50 +0000358check_syntax('print ,')
359check_syntax('print >> x,')
360
Guido van Rossum3bead091992-01-27 17:00:37 +0000361print 'del_stmt' # 'del' exprlist
362del abc
363del x, y, (z, xyz)
364
365print 'pass_stmt' # 'pass'
366pass
367
368print 'flow_stmt' # break_stmt | continue_stmt | return_stmt | raise_stmt
369# Tested below
370
371print 'break_stmt' # 'break'
372while 1: break
373
374print 'continue_stmt' # 'continue'
375i = 1
376while i: i = 0; continue
377
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000378msg = ""
379while not msg:
380 msg = "continue + try/except ok"
381 try:
382 continue
383 msg = "continue failed to continue inside try"
384 except:
385 msg = "continue inside try called except block"
386print msg
387
388msg = ""
389while not msg:
390 msg = "finally block not called"
391 try:
392 continue
393 finally:
394 msg = "continue + try/finally ok"
395print msg
Tim Peters10fb3862001-02-09 20:17:14 +0000396
Thomas Wouters80d373c2001-09-26 12:43:39 +0000397
398# This test warrants an explanation. It is a test specifically for SF bugs
399# #463359 and #462937. The bug is that a 'break' statement executed or
400# exception raised inside a try/except inside a loop, *after* a continue
401# statement has been executed in that loop, will cause the wrong number of
402# arguments to be popped off the stack and the instruction pointer reset to
403# a very small number (usually 0.) Because of this, the following test
404# *must* written as a function, and the tracking vars *must* be function
405# arguments with default values. Otherwise, the test will loop and loop.
406
407print "testing continue and break in try/except in loop"
408def test_break_continue_loop(extra_burning_oil = 1, count=0):
409 big_hippo = 2
410 while big_hippo:
411 count += 1
412 try:
413 if extra_burning_oil and big_hippo == 1:
414 extra_burning_oil -= 1
415 break
416 big_hippo -= 1
417 continue
418 except:
419 raise
420 if count > 2 or big_hippo <> 1:
421 print "continue then break in try/except in loop broken!"
422test_break_continue_loop()
423
Guido van Rossum3bead091992-01-27 17:00:37 +0000424print 'return_stmt' # 'return' [testlist]
425def g1(): return
426def g2(): return 1
427g1()
428x = g2()
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000429check_syntax("class foo:return 1")
430
431print 'yield_stmt'
432check_syntax("class foo:yield 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000433
434print 'raise_stmt' # 'raise' test [',' test]
435try: raise RuntimeError, 'just testing'
436except RuntimeError: pass
437try: raise KeyboardInterrupt
438except KeyboardInterrupt: pass
439
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000440print 'import_name' # 'import' dotted_as_names
Guido van Rossum3bead091992-01-27 17:00:37 +0000441import sys
Guido van Rossum51b1c1c1995-03-04 22:30:54 +0000442import time, sys
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000443print 'import_from' # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000444from time import time
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000445from time import (time)
Guido van Rossum3bead091992-01-27 17:00:37 +0000446from sys import *
Guido van Rossum51b1c1c1995-03-04 22:30:54 +0000447from sys import path, argv
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000448from sys import (path, argv)
449from sys import (path, argv,)
Guido van Rossum3bead091992-01-27 17:00:37 +0000450
451print 'global_stmt' # 'global' NAME (',' NAME)*
452def f():
Fred Drake004d5e62000-10-23 17:22:08 +0000453 global a
454 global a, b
455 global one, two, three, four, five, six, seven, eight, nine, ten
Guido van Rossum3bead091992-01-27 17:00:37 +0000456
Guido van Rossumb3b09c91993-10-22 14:24:22 +0000457print 'exec_stmt' # 'exec' expr ['in' expr [',' expr]]
458def f():
Fred Drake004d5e62000-10-23 17:22:08 +0000459 z = None
460 del z
461 exec 'z=1+1\n'
Fred Drake132dce22000-12-12 23:11:42 +0000462 if z != 2: raise TestFailed, 'exec \'z=1+1\'\\n'
Fred Drake004d5e62000-10-23 17:22:08 +0000463 del z
464 exec 'z=1+1'
Fred Drake132dce22000-12-12 23:11:42 +0000465 if z != 2: raise TestFailed, 'exec \'z=1+1\''
Fred Drake004d5e62000-10-23 17:22:08 +0000466 z = None
467 del z
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000468 import types
469 if hasattr(types, "UnicodeType"):
470 exec r"""if 1:
Fred Drake004d5e62000-10-23 17:22:08 +0000471 exec u'z=1+1\n'
Fred Drake132dce22000-12-12 23:11:42 +0000472 if z != 2: raise TestFailed, 'exec u\'z=1+1\'\\n'
Fred Drake004d5e62000-10-23 17:22:08 +0000473 del z
474 exec u'z=1+1'
Fred Drake132dce22000-12-12 23:11:42 +0000475 if z != 2: raise TestFailed, 'exec u\'z=1+1\''
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000476"""
Guido van Rossumb3b09c91993-10-22 14:24:22 +0000477f()
478g = {}
479exec 'z = 1' in g
Guido van Rossum1f976121995-01-10 10:34:21 +0000480if g.has_key('__builtins__'): del g['__builtins__']
Fred Drake132dce22000-12-12 23:11:42 +0000481if g != {'z': 1}: raise TestFailed, 'exec \'z = 1\' in g'
Guido van Rossumb3b09c91993-10-22 14:24:22 +0000482g = {}
483l = {}
Jeremy Hylton2922ea82001-02-28 23:49:19 +0000484
485import warnings
486warnings.filterwarnings("ignore", "global statement", module="<string>")
Guido van Rossumb3b09c91993-10-22 14:24:22 +0000487exec 'global a; a = 1; b = 2' in g, l
Guido van Rossum1f976121995-01-10 10:34:21 +0000488if g.has_key('__builtins__'): del g['__builtins__']
489if l.has_key('__builtins__'): del l['__builtins__']
Jeremy Hyltone1bb5f92001-01-19 03:26:33 +0000490if (g, l) != ({'a':1}, {'b':2}): raise TestFailed, 'exec ... in g (%s), l (%s)' %(g,l)
Guido van Rossumb3b09c91993-10-22 14:24:22 +0000491
492
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000493print "assert_stmt" # assert_stmt: 'assert' test [',' test]
494assert 1
495assert 1, 1
496assert lambda x:x
497assert 1, lambda x:x+1
498
Guido van Rossum3bead091992-01-27 17:00:37 +0000499### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
500# Tested below
501
502print 'if_stmt' # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
503if 1: pass
504if 1: pass
505else: pass
506if 0: pass
507elif 0: pass
508if 0: pass
509elif 0: pass
510elif 0: pass
511elif 0: pass
512else: pass
513
514print 'while_stmt' # 'while' test ':' suite ['else' ':' suite]
515while 0: pass
516while 0: pass
517else: pass
518
Amaury Forgeot d'Arcf1a71782008-01-24 23:42:08 +0000519# Issue1920: "while 0" is optimized away,
520# ensure that the "else" clause is still present.
521x = 0
522while 0:
523 x = 1
524else:
525 x = 2
526assert x == 2
527
Guido van Rossum3bead091992-01-27 17:00:37 +0000528print 'for_stmt' # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
Guido van Rossum3bead091992-01-27 17:00:37 +0000529for i in 1, 2, 3: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000530for i, j, k in (): pass
531else: pass
Guido van Rossumb6775db1994-08-01 11:34:53 +0000532class Squares:
Fred Drake004d5e62000-10-23 17:22:08 +0000533 def __init__(self, max):
534 self.max = max
535 self.sofar = []
536 def __len__(self): return len(self.sofar)
537 def __getitem__(self, i):
538 if not 0 <= i < self.max: raise IndexError
539 n = len(self.sofar)
540 while n <= i:
541 self.sofar.append(n*n)
542 n = n+1
543 return self.sofar[i]
Guido van Rossumb6775db1994-08-01 11:34:53 +0000544n = 0
545for x in Squares(10): n = n+x
546if n != 285: raise TestFailed, 'for over growing sequence'
Guido van Rossum3bead091992-01-27 17:00:37 +0000547
Neal Norwitzedef2be2006-07-12 05:26:17 +0000548result = []
549for x, in [(1,), (2,), (3,)]:
550 result.append(x)
551vereq(result, [1, 2, 3])
552
Guido van Rossumb6775db1994-08-01 11:34:53 +0000553print 'try_stmt'
554### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
555### | 'try' ':' suite 'finally' ':' suite
Guido van Rossum3bead091992-01-27 17:00:37 +0000556### except_clause: 'except' [expr [',' expr]]
Guido van Rossum85f18201992-11-27 22:53:50 +0000557try:
Fred Drake004d5e62000-10-23 17:22:08 +0000558 1/0
Guido van Rossum85f18201992-11-27 22:53:50 +0000559except ZeroDivisionError:
Fred Drake004d5e62000-10-23 17:22:08 +0000560 pass
Guido van Rossumb6775db1994-08-01 11:34:53 +0000561else:
Fred Drake004d5e62000-10-23 17:22:08 +0000562 pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000563try: 1/0
564except EOFError: pass
565except TypeError, msg: pass
566except RuntimeError, msg: pass
567except: pass
Guido van Rossumb6775db1994-08-01 11:34:53 +0000568else: pass
Guido van Rossum85f18201992-11-27 22:53:50 +0000569try: 1/0
570except (EOFError, TypeError, ZeroDivisionError): pass
571try: 1/0
572except (EOFError, TypeError, ZeroDivisionError), msg: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000573try: pass
574finally: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000575
576print 'suite' # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
577if 1: pass
578if 1:
Fred Drake004d5e62000-10-23 17:22:08 +0000579 pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000580if 1:
Fred Drake004d5e62000-10-23 17:22:08 +0000581 #
582 #
583 #
584 pass
585 pass
586 #
587 pass
588 #
Guido van Rossum3bead091992-01-27 17:00:37 +0000589
590print 'test'
591### and_test ('or' and_test)*
592### and_test: not_test ('and' not_test)*
593### not_test: 'not' not_test | comparison
594if not 1: pass
595if 1 and 1: pass
596if 1 or 1: pass
597if not not not 1: pass
598if not 1 and 1 and 1: pass
599if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
600
601print 'comparison'
602### comparison: expr (comp_op expr)*
603### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
604if 1: pass
605x = (1 == 1)
606if 1 == 1: pass
607if 1 != 1: pass
608if 1 <> 1: pass
609if 1 < 1: pass
610if 1 > 1: pass
611if 1 <= 1: pass
612if 1 >= 1: pass
613if 1 is 1: pass
614if 1 is not 1: pass
615if 1 in (): pass
616if 1 not in (): pass
Guido van Rossum85f18201992-11-27 22:53:50 +0000617if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000618
619print 'binary mask ops'
620x = 1 & 1
621x = 1 ^ 1
622x = 1 | 1
623
624print 'shift ops'
625x = 1 << 1
626x = 1 >> 1
627x = 1 << 1 >> 1
628
629print 'additive ops'
630x = 1
631x = 1 + 1
632x = 1 - 1 - 1
633x = 1 - 1 + 1 - 1 + 1
634
635print 'multiplicative ops'
636x = 1 * 1
637x = 1 / 1
638x = 1 % 1
639x = 1 / 1 * 1 % 1
640
641print 'unary ops'
642x = +1
643x = -1
644x = ~1
645x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
646x = -1*1/1 + 1*1 - ---1*1
647
648print 'selectors'
649### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
650### subscript: expr | [expr] ':' [expr]
Guido van Rossum85f18201992-11-27 22:53:50 +0000651f1()
652f2(1)
653f2(1,)
654f3(1, 2)
655f3(1, 2,)
656f4(1, (2, (3, 4)))
657v0()
658v0(1)
659v0(1,)
660v0(1,2)
661v0(1,2,3,4,5,6,7,8,9,0)
662v1(1)
663v1(1,)
664v1(1,2)
665v1(1,2,3)
666v1(1,2,3,4,5,6,7,8,9,0)
667v2(1,2)
668v2(1,2,3)
669v2(1,2,3,4)
670v2(1,2,3,4,5,6,7,8,9,0)
671v3(1,(2,3))
672v3(1,(2,3),4)
673v3(1,(2,3),4,5,6,7,8,9,0)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000674print
Guido van Rossum3bead091992-01-27 17:00:37 +0000675import sys, time
676c = sys.path[0]
677x = time.time()
678x = sys.modules['time'].time()
679a = '01234'
680c = a[0]
681c = a[-1]
682s = a[0:5]
683s = a[:5]
684s = a[0:]
685s = a[:]
686s = a[-5:]
687s = a[:-1]
688s = a[-4:-3]
Neal Norwitz03bdedd2006-02-28 17:53:58 +0000689# A rough test of SF bug 1333982. http://python.org/sf/1333982
Jeremy Hylton7b03bad2006-02-28 17:46:23 +0000690# The testing here is fairly incomplete.
Neal Norwitz03bdedd2006-02-28 17:53:58 +0000691# Test cases should include: commas with 1 and 2 colons
Jeremy Hylton7b03bad2006-02-28 17:46:23 +0000692d = {}
693d[1] = 1
694d[1,] = 2
695d[1,2] = 3
696d[1,2,3] = 4
697L = list(d)
698L.sort()
699print L
700
Guido van Rossum3bead091992-01-27 17:00:37 +0000701
702print 'atoms'
703### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
704### dictmaker: test ':' test (',' test ':' test)* [',']
705
706x = (1)
707x = (1 or 2 or 3)
708x = (1 or 2 or 3, 2, 3)
709
710x = []
711x = [1]
712x = [1 or 2 or 3]
713x = [1 or 2 or 3, 2, 3]
714x = []
715
716x = {}
717x = {'one': 1}
718x = {'one': 1,}
719x = {'one' or 'two': 1 or 2}
720x = {'one': 1, 'two': 2}
721x = {'one': 1, 'two': 2,}
722x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
723
724x = `x`
725x = `1 or 2 or 3`
Neal Norwitza3ce6aa2006-11-04 19:32:54 +0000726x = `1,2`
Guido van Rossum3bead091992-01-27 17:00:37 +0000727x = x
728x = 'x'
729x = 123
730
731### exprlist: expr (',' expr)* [',']
732### testlist: test (',' test)* [',']
733# These have been exercised enough above
734
Brett Cannon4ebc7e32005-04-09 01:27:37 +0000735print 'classdef' # 'class' NAME ['(' [testlist] ')'] ':' suite
Guido van Rossum3bead091992-01-27 17:00:37 +0000736class B: pass
Brett Cannon4ebc7e32005-04-09 01:27:37 +0000737class B2(): pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000738class C1(B): pass
739class C2(B): pass
740class D(C1, C2, B): pass
741class C:
Fred Drake004d5e62000-10-23 17:22:08 +0000742 def meth1(self): pass
743 def meth2(self, arg): pass
744 def meth3(self, a1, a2): pass
Skip Montanaro803d6e52000-08-12 18:09:51 +0000745
746# list comprehension tests
747nums = [1, 2, 3, 4, 5]
748strs = ["Apple", "Banana", "Coconut"]
749spcs = [" Apple", " Banana ", "Coco nut "]
750
751print [s.strip() for s in spcs]
752print [3 * x for x in nums]
753print [x for x in nums if x > 2]
754print [(i, s) for i in nums for s in strs]
755print [(i, s) for i in nums for s in [f for f in strs if "n" in f]]
Tim Petersf545baa2003-06-15 23:26:30 +0000756print [(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)]
Jeremy Hylton578ceee2001-01-23 01:51:40 +0000757
758def test_in_func(l):
759 return [None < x < 3 for x in l if x > 2]
760
761print test_in_func(nums)
762
Jeremy Hyltone241e292001-03-19 20:42:11 +0000763def test_nested_front():
764 print [[y for y in [x, x + 1]] for x in [1,3,5]]
765
766test_nested_front()
767
Jeremy Hylton92e9f292001-01-25 17:03:37 +0000768check_syntax("[i, s for i in nums for s in strs]")
769check_syntax("[x if y]")
Skip Montanaro46dfa5f2000-08-22 02:43:07 +0000770
Skip Montanaro803d6e52000-08-12 18:09:51 +0000771suppliers = [
772 (1, "Boeing"),
773 (2, "Ford"),
774 (3, "Macdonalds")
775]
776
777parts = [
778 (10, "Airliner"),
779 (20, "Engine"),
780 (30, "Cheeseburger")
781]
782
783suppart = [
784 (1, 10), (1, 20), (2, 20), (3, 30)
785]
786
787print [
788 (sname, pname)
789 for (sno, sname) in suppliers
790 for (pno, pname) in parts
791 for (sp_sno, sp_pno) in suppart
792 if sno == sp_sno and pno == sp_pno
793]
Raymond Hettinger354433a2004-05-19 08:20:33 +0000794
795# generator expression tests
796g = ([x for x in range(10)] for x in range(1))
797verify(g.next() == [x for x in range(10)])
798try:
799 g.next()
800 raise TestFailed, 'should produce StopIteration exception'
801except StopIteration:
802 pass
803
804a = 1
805try:
806 g = (a for d in a)
807 g.next()
808 raise TestFailed, 'should produce TypeError'
809except TypeError:
810 pass
811
812verify(list((x, y) for x in 'abcd' for y in 'abcd') == [(x, y) for x in 'abcd' for y in 'abcd'])
813verify(list((x, y) for x in 'ab' for y in 'xy') == [(x, y) for x in 'ab' for y in 'xy'])
814
815a = [x for x in range(10)]
816b = (x for x in (y for y in a))
817verify(sum(b) == sum([x for x in range(10)]))
818
819verify(sum(x**2 for x in range(10)) == sum([x**2 for x in range(10)]))
820verify(sum(x*x for x in range(10) if x%2) == sum([x*x for x in range(10) if x%2]))
821verify(sum(x for x in (y for y in range(10))) == sum([x for x in range(10)]))
822verify(sum(x for x in (y for y in (z for z in range(10)))) == sum([x for x in range(10)]))
823verify(sum(x for x in [y for y in (z for z in range(10))]) == sum([x for x in range(10)]))
824verify(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)]))
825verify(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True) == 0)
826check_syntax("foo(x for x in range(10), 100)")
827check_syntax("foo(100, x for x in range(10))")
828
829# test for outmost iterable precomputation
830x = 10; g = (i for i in range(x)); x = 5
831verify(len(list(g)) == 10)
832
833# This should hold, since we're only precomputing outmost iterable.
834x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
835x = 5; t = True;
836verify([(i,j) for i in range(10) for j in range(5)] == list(g))
Thomas Woutersdca3b9c2006-02-27 00:24:13 +0000837
Thomas Woutersced6cdd2006-04-12 00:07:59 +0000838# Grammar allows multiple adjacent 'if's in listcomps and genexps,
839# even though it's silly. Make sure it works (ifelse broke this.)
840verify([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
841verify((x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
842
Neal Norwitz3b3aae02006-09-05 03:56:01 +0000843# Verify unpacking single element tuples in listcomp/genexp.
844vereq([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
845vereq(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
846
Thomas Woutersdca3b9c2006-02-27 00:24:13 +0000847# Test ifelse expressions in various cases
848def _checkeval(msg, ret):
849 "helper to check that evaluation of expressions is done correctly"
850 print x
851 return ret
852
853verify([ x() for x in lambda: True, lambda: False if x() ] == [True])
854verify([ x() for x in (lambda: True, lambda: False) if x() ] == [True])
855verify([ x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False) ] == [True])
856verify((5 if 1 else _checkeval("check 1", 0)) == 5)
857verify((_checkeval("check 2", 0) if 0 else 5) == 5)
858verify((5 and 6 if 0 else 1) == 1)
859verify(((5 and 6) if 0 else 1) == 1)
860verify((5 and (6 if 1 else 1)) == 6)
861verify((0 or _checkeval("check 3", 2) if 0 else 3) == 3)
862verify((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)) == 1)
863verify((0 or 5 if 1 else _checkeval("check 6", 3)) == 5)
864verify((not 5 if 1 else 1) == False)
865verify((not 5 if 0 else 1) == 1)
866verify((6 + 1 if 1 else 2) == 7)
867verify((6 - 1 if 1 else 2) == 5)
868verify((6 * 2 if 1 else 4) == 12)
869verify((6 / 2 if 1 else 3) == 3)
870verify((6 < 4 if 0 else 2) == 2)