blob: e0d5b745d646082fad722d33fce762ae6014edaa [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
Barry Warsaw408b6d32002-07-30 23:27:12 +000011from test.test_support import TestFailed, verify, 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
160verify(f2.func_code.co_varnames == ('one_argument',))
161verify(f3.func_code.co_varnames == ('two', 'arguments'))
Jeremy Hylton7d3dff22001-10-10 01:45:02 +0000162if sys.platform.startswith('java'):
163 verify(f4.func_code.co_varnames ==
Finn Bock4ab7adb2001-12-09 09:12:34 +0000164 ('two', '(compound, (argument, list))', 'compound', 'argument',
165 'list',))
Jeremy Hylton7d3dff22001-10-10 01:45:02 +0000166 verify(f5.func_code.co_varnames ==
167 ('(compound, first)', 'two', 'compound', 'first'))
168else:
169 verify(f4.func_code.co_varnames == ('two', '.2', 'compound',
170 'argument', 'list'))
171 verify(f5.func_code.co_varnames == ('.0', 'two', 'compound', 'first'))
Guido van Rossum3bead091992-01-27 17:00:37 +0000172def a1(one_arg,): pass
173def a2(two, args,): pass
174def v0(*rest): pass
175def v1(a, *rest): pass
176def v2(a, b, *rest): pass
Jeremy Hylton92e9f292001-01-25 17:03:37 +0000177def v3(a, (b, c), *rest): return a, b, c, rest
Jeremy Hylton7d3dff22001-10-10 01:45:02 +0000178if sys.platform.startswith('java'):
179 verify(v3.func_code.co_varnames == ('a', '(b, c)', 'rest', 'b', 'c'))
180else:
181 verify(v3.func_code.co_varnames == ('a', '.2', 'rest', 'b', 'c'))
Jeremy Hylton92e9f292001-01-25 17:03:37 +0000182verify(v3(1, (2, 3), 4) == (1, 2, 3, (4,)))
Guido van Rossumb6775db1994-08-01 11:34:53 +0000183def d01(a=1): pass
184d01()
185d01(1)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000186d01(*(1,))
187d01(**{'a':2})
Guido van Rossumb6775db1994-08-01 11:34:53 +0000188def d11(a, b=1): pass
189d11(1)
190d11(1, 2)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000191d11(1, **{'b':2})
Guido van Rossumb6775db1994-08-01 11:34:53 +0000192def d21(a, b, c=1): pass
193d21(1, 2)
194d21(1, 2, 3)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000195d21(*(1, 2, 3))
196d21(1, *(2, 3))
197d21(1, 2, *(3,))
198d21(1, 2, **{'c':3})
Guido van Rossumb6775db1994-08-01 11:34:53 +0000199def d02(a=1, b=2): pass
200d02()
201d02(1)
202d02(1, 2)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000203d02(*(1, 2))
204d02(1, *(2,))
205d02(1, **{'b':2})
206d02(**{'a': 1, 'b': 2})
Guido van Rossumb6775db1994-08-01 11:34:53 +0000207def d12(a, b=1, c=2): pass
208d12(1)
209d12(1, 2)
210d12(1, 2, 3)
211def d22(a, b, c=1, d=2): pass
212d22(1, 2)
213d22(1, 2, 3)
214d22(1, 2, 3, 4)
215def d01v(a=1, *rest): pass
216d01v()
217d01v(1)
218d01v(1, 2)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000219d01v(*(1, 2, 3, 4))
220d01v(*(1,))
221d01v(**{'a':2})
Guido van Rossumb6775db1994-08-01 11:34:53 +0000222def d11v(a, b=1, *rest): pass
223d11v(1)
224d11v(1, 2)
225d11v(1, 2, 3)
226def d21v(a, b, c=1, *rest): pass
227d21v(1, 2)
228d21v(1, 2, 3)
229d21v(1, 2, 3, 4)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000230d21v(*(1, 2, 3, 4))
231d21v(1, 2, **{'c': 3})
Guido van Rossumb6775db1994-08-01 11:34:53 +0000232def d02v(a=1, b=2, *rest): pass
233d02v()
234d02v(1)
235d02v(1, 2)
236d02v(1, 2, 3)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000237d02v(1, *(2, 3, 4))
238d02v(**{'a': 1, 'b': 2})
Guido van Rossumb6775db1994-08-01 11:34:53 +0000239def d12v(a, b=1, c=2, *rest): pass
240d12v(1)
241d12v(1, 2)
242d12v(1, 2, 3)
243d12v(1, 2, 3, 4)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000244d12v(*(1, 2, 3, 4))
245d12v(1, 2, *(3, 4, 5))
246d12v(1, *(2,), **{'c': 3})
Guido van Rossumb6775db1994-08-01 11:34:53 +0000247def d22v(a, b, c=1, d=2, *rest): pass
248d22v(1, 2)
249d22v(1, 2, 3)
250d22v(1, 2, 3, 4)
251d22v(1, 2, 3, 4, 5)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000252d22v(*(1, 2, 3, 4))
253d22v(1, 2, *(3, 4, 5))
254d22v(1, *(2, 3), **{'d': 4})
Guido van Rossum3bead091992-01-27 17:00:37 +0000255
Jeremy Hylton619eea62001-01-25 20:12:27 +0000256### lambdef: 'lambda' [varargslist] ':' test
257print 'lambdef'
258l1 = lambda : 0
259verify(l1() == 0)
260l2 = lambda : a[d] # XXX just testing the expression
261l3 = lambda : [2 < x for x in [-1, 3, 0L]]
262verify(l3() == [0, 1, 0])
263l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
264verify(l4() == 1)
265l5 = lambda x, y, z=2: x + y + z
266verify(l5(1, 2) == 5)
267verify(l5(1, 2, 3) == 6)
268check_syntax("lambda x: x = 2")
269
Guido van Rossum3bead091992-01-27 17:00:37 +0000270### stmt: simple_stmt | compound_stmt
271# Tested below
272
273### simple_stmt: small_stmt (';' small_stmt)* [';']
274print 'simple_stmt'
275x = 1; pass; del x
276
Guido van Rossumb3b09c91993-10-22 14:24:22 +0000277### 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 +0000278# Tested below
279
280print 'expr_stmt' # (exprlist '=')* exprlist
2811
2821, 2, 3
283x = 1
284x = 1, 2, 3
285x = y = z = 1, 2, 3
286x, y, z = 1, 2, 3
287abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
288# NB these variables are deleted below
289
Jeremy Hylton47793992001-02-19 15:35:26 +0000290check_syntax("x + 1 = 1")
291check_syntax("a + 1 = b + 2")
292
Guido van Rossum3bead091992-01-27 17:00:37 +0000293print 'print_stmt' # 'print' (test ',')* [test]
294print 1, 2, 3
295print 1, 2, 3,
296print
297print 0 or 1, 0 or 1,
298print 0 or 1
299
Barry Warsawefc92ee2000-08-21 15:46:50 +0000300print 'extended print_stmt' # 'print' '>>' test ','
301import sys
302print >> sys.stdout, 1, 2, 3
303print >> sys.stdout, 1, 2, 3,
304print >> sys.stdout
305print >> sys.stdout, 0 or 1, 0 or 1,
306print >> sys.stdout, 0 or 1
307
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000308# test printing to an instance
Barry Warsaw9182b452000-08-29 04:57:10 +0000309class Gulp:
Fred Drake004d5e62000-10-23 17:22:08 +0000310 def write(self, msg): pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000311
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000312gulp = Gulp()
313print >> gulp, 1, 2, 3
314print >> gulp, 1, 2, 3,
315print >> gulp
316print >> gulp, 0 or 1, 0 or 1,
317print >> gulp, 0 or 1
318
319# test print >> None
Barry Warsaw9182b452000-08-29 04:57:10 +0000320def driver():
Fred Drake004d5e62000-10-23 17:22:08 +0000321 oldstdout = sys.stdout
322 sys.stdout = Gulp()
323 try:
324 tellme(Gulp())
325 tellme()
326 finally:
327 sys.stdout = oldstdout
Barry Warsaw9182b452000-08-29 04:57:10 +0000328
329# we should see this once
330def tellme(file=sys.stdout):
Fred Drake004d5e62000-10-23 17:22:08 +0000331 print >> file, 'hello world'
Barry Warsaw9182b452000-08-29 04:57:10 +0000332
333driver()
334
335# we should not see this at all
336def tellme(file=None):
Fred Drake004d5e62000-10-23 17:22:08 +0000337 print >> file, 'goodbye universe'
Barry Warsaw9182b452000-08-29 04:57:10 +0000338
339driver()
340
Barry Warsawefc92ee2000-08-21 15:46:50 +0000341# syntax errors
Barry Warsawefc92ee2000-08-21 15:46:50 +0000342check_syntax('print ,')
343check_syntax('print >> x,')
344
Guido van Rossum3bead091992-01-27 17:00:37 +0000345print 'del_stmt' # 'del' exprlist
346del abc
347del x, y, (z, xyz)
348
349print 'pass_stmt' # 'pass'
350pass
351
352print 'flow_stmt' # break_stmt | continue_stmt | return_stmt | raise_stmt
353# Tested below
354
355print 'break_stmt' # 'break'
356while 1: break
357
358print 'continue_stmt' # 'continue'
359i = 1
360while i: i = 0; continue
361
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000362msg = ""
363while not msg:
364 msg = "continue + try/except ok"
365 try:
366 continue
367 msg = "continue failed to continue inside try"
368 except:
369 msg = "continue inside try called except block"
370print msg
371
372msg = ""
373while not msg:
374 msg = "finally block not called"
375 try:
376 continue
377 finally:
378 msg = "continue + try/finally ok"
379print msg
Tim Peters10fb3862001-02-09 20:17:14 +0000380
Thomas Wouters80d373c2001-09-26 12:43:39 +0000381
382# This test warrants an explanation. It is a test specifically for SF bugs
383# #463359 and #462937. The bug is that a 'break' statement executed or
384# exception raised inside a try/except inside a loop, *after* a continue
385# statement has been executed in that loop, will cause the wrong number of
386# arguments to be popped off the stack and the instruction pointer reset to
387# a very small number (usually 0.) Because of this, the following test
388# *must* written as a function, and the tracking vars *must* be function
389# arguments with default values. Otherwise, the test will loop and loop.
390
391print "testing continue and break in try/except in loop"
392def test_break_continue_loop(extra_burning_oil = 1, count=0):
393 big_hippo = 2
394 while big_hippo:
395 count += 1
396 try:
397 if extra_burning_oil and big_hippo == 1:
398 extra_burning_oil -= 1
399 break
400 big_hippo -= 1
401 continue
402 except:
403 raise
404 if count > 2 or big_hippo <> 1:
405 print "continue then break in try/except in loop broken!"
406test_break_continue_loop()
407
Guido van Rossum3bead091992-01-27 17:00:37 +0000408print 'return_stmt' # 'return' [testlist]
409def g1(): return
410def g2(): return 1
411g1()
412x = g2()
413
414print 'raise_stmt' # 'raise' test [',' test]
415try: raise RuntimeError, 'just testing'
416except RuntimeError: pass
417try: raise KeyboardInterrupt
418except KeyboardInterrupt: pass
419
420print 'import_stmt' # 'import' NAME (',' NAME)* | 'from' NAME 'import' ('*' | NAME (',' NAME)*)
Guido van Rossum3bead091992-01-27 17:00:37 +0000421import sys
Guido van Rossum51b1c1c1995-03-04 22:30:54 +0000422import time, sys
Guido van Rossumb6775db1994-08-01 11:34:53 +0000423from time import time
Guido van Rossum3bead091992-01-27 17:00:37 +0000424from sys import *
Guido van Rossum51b1c1c1995-03-04 22:30:54 +0000425from sys import path, argv
Guido van Rossum3bead091992-01-27 17:00:37 +0000426
427print 'global_stmt' # 'global' NAME (',' NAME)*
428def f():
Fred Drake004d5e62000-10-23 17:22:08 +0000429 global a
430 global a, b
431 global one, two, three, four, five, six, seven, eight, nine, ten
Guido van Rossum3bead091992-01-27 17:00:37 +0000432
Guido van Rossumb3b09c91993-10-22 14:24:22 +0000433print 'exec_stmt' # 'exec' expr ['in' expr [',' expr]]
434def f():
Fred Drake004d5e62000-10-23 17:22:08 +0000435 z = None
436 del z
437 exec 'z=1+1\n'
Fred Drake132dce22000-12-12 23:11:42 +0000438 if z != 2: raise TestFailed, 'exec \'z=1+1\'\\n'
Fred Drake004d5e62000-10-23 17:22:08 +0000439 del z
440 exec 'z=1+1'
Fred Drake132dce22000-12-12 23:11:42 +0000441 if z != 2: raise TestFailed, 'exec \'z=1+1\''
Fred Drake004d5e62000-10-23 17:22:08 +0000442 z = None
443 del z
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000444 import types
445 if hasattr(types, "UnicodeType"):
446 exec r"""if 1:
Fred Drake004d5e62000-10-23 17:22:08 +0000447 exec u'z=1+1\n'
Fred Drake132dce22000-12-12 23:11:42 +0000448 if z != 2: raise TestFailed, 'exec u\'z=1+1\'\\n'
Fred Drake004d5e62000-10-23 17:22:08 +0000449 del z
450 exec u'z=1+1'
Fred Drake132dce22000-12-12 23:11:42 +0000451 if z != 2: raise TestFailed, 'exec u\'z=1+1\''
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000452"""
Guido van Rossumb3b09c91993-10-22 14:24:22 +0000453f()
454g = {}
455exec 'z = 1' in g
Guido van Rossum1f976121995-01-10 10:34:21 +0000456if g.has_key('__builtins__'): del g['__builtins__']
Fred Drake132dce22000-12-12 23:11:42 +0000457if g != {'z': 1}: raise TestFailed, 'exec \'z = 1\' in g'
Guido van Rossumb3b09c91993-10-22 14:24:22 +0000458g = {}
459l = {}
Jeremy Hylton2922ea82001-02-28 23:49:19 +0000460
461import warnings
462warnings.filterwarnings("ignore", "global statement", module="<string>")
Guido van Rossumb3b09c91993-10-22 14:24:22 +0000463exec 'global a; a = 1; b = 2' in g, l
Guido van Rossum1f976121995-01-10 10:34:21 +0000464if g.has_key('__builtins__'): del g['__builtins__']
465if l.has_key('__builtins__'): del l['__builtins__']
Jeremy Hyltone1bb5f92001-01-19 03:26:33 +0000466if (g, l) != ({'a':1}, {'b':2}): raise TestFailed, 'exec ... in g (%s), l (%s)' %(g,l)
Guido van Rossumb3b09c91993-10-22 14:24:22 +0000467
468
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000469print "assert_stmt" # assert_stmt: 'assert' test [',' test]
470assert 1
471assert 1, 1
472assert lambda x:x
473assert 1, lambda x:x+1
474
Guido van Rossum3bead091992-01-27 17:00:37 +0000475### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
476# Tested below
477
478print 'if_stmt' # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
479if 1: pass
480if 1: pass
481else: pass
482if 0: pass
483elif 0: pass
484if 0: pass
485elif 0: pass
486elif 0: pass
487elif 0: pass
488else: pass
489
490print 'while_stmt' # 'while' test ':' suite ['else' ':' suite]
491while 0: pass
492while 0: pass
493else: pass
494
495print 'for_stmt' # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
Guido van Rossum3bead091992-01-27 17:00:37 +0000496for i in 1, 2, 3: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000497for i, j, k in (): pass
498else: pass
Guido van Rossumb6775db1994-08-01 11:34:53 +0000499class Squares:
Fred Drake004d5e62000-10-23 17:22:08 +0000500 def __init__(self, max):
501 self.max = max
502 self.sofar = []
503 def __len__(self): return len(self.sofar)
504 def __getitem__(self, i):
505 if not 0 <= i < self.max: raise IndexError
506 n = len(self.sofar)
507 while n <= i:
508 self.sofar.append(n*n)
509 n = n+1
510 return self.sofar[i]
Guido van Rossumb6775db1994-08-01 11:34:53 +0000511n = 0
512for x in Squares(10): n = n+x
513if n != 285: raise TestFailed, 'for over growing sequence'
Guido van Rossum3bead091992-01-27 17:00:37 +0000514
Guido van Rossumb6775db1994-08-01 11:34:53 +0000515print 'try_stmt'
516### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
517### | 'try' ':' suite 'finally' ':' suite
Guido van Rossum3bead091992-01-27 17:00:37 +0000518### except_clause: 'except' [expr [',' expr]]
Guido van Rossum85f18201992-11-27 22:53:50 +0000519try:
Fred Drake004d5e62000-10-23 17:22:08 +0000520 1/0
Guido van Rossum85f18201992-11-27 22:53:50 +0000521except ZeroDivisionError:
Fred Drake004d5e62000-10-23 17:22:08 +0000522 pass
Guido van Rossumb6775db1994-08-01 11:34:53 +0000523else:
Fred Drake004d5e62000-10-23 17:22:08 +0000524 pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000525try: 1/0
526except EOFError: pass
527except TypeError, msg: pass
528except RuntimeError, msg: pass
529except: pass
Guido van Rossumb6775db1994-08-01 11:34:53 +0000530else: pass
Guido van Rossum85f18201992-11-27 22:53:50 +0000531try: 1/0
532except (EOFError, TypeError, ZeroDivisionError): pass
533try: 1/0
534except (EOFError, TypeError, ZeroDivisionError), msg: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000535try: pass
536finally: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000537
538print 'suite' # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
539if 1: pass
540if 1:
Fred Drake004d5e62000-10-23 17:22:08 +0000541 pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000542if 1:
Fred Drake004d5e62000-10-23 17:22:08 +0000543 #
544 #
545 #
546 pass
547 pass
548 #
549 pass
550 #
Guido van Rossum3bead091992-01-27 17:00:37 +0000551
552print 'test'
553### and_test ('or' and_test)*
554### and_test: not_test ('and' not_test)*
555### not_test: 'not' not_test | comparison
556if not 1: pass
557if 1 and 1: pass
558if 1 or 1: pass
559if not not not 1: pass
560if not 1 and 1 and 1: pass
561if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
562
563print 'comparison'
564### comparison: expr (comp_op expr)*
565### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
566if 1: pass
567x = (1 == 1)
568if 1 == 1: pass
569if 1 != 1: pass
570if 1 <> 1: pass
571if 1 < 1: pass
572if 1 > 1: pass
573if 1 <= 1: pass
574if 1 >= 1: pass
575if 1 is 1: pass
576if 1 is not 1: pass
577if 1 in (): pass
578if 1 not in (): pass
Guido van Rossum85f18201992-11-27 22:53:50 +0000579if 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 +0000580
581print 'binary mask ops'
582x = 1 & 1
583x = 1 ^ 1
584x = 1 | 1
585
586print 'shift ops'
587x = 1 << 1
588x = 1 >> 1
589x = 1 << 1 >> 1
590
591print 'additive ops'
592x = 1
593x = 1 + 1
594x = 1 - 1 - 1
595x = 1 - 1 + 1 - 1 + 1
596
597print 'multiplicative ops'
598x = 1 * 1
599x = 1 / 1
600x = 1 % 1
601x = 1 / 1 * 1 % 1
602
603print 'unary ops'
604x = +1
605x = -1
606x = ~1
607x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
608x = -1*1/1 + 1*1 - ---1*1
609
610print 'selectors'
611### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
612### subscript: expr | [expr] ':' [expr]
Guido van Rossum85f18201992-11-27 22:53:50 +0000613f1()
614f2(1)
615f2(1,)
616f3(1, 2)
617f3(1, 2,)
618f4(1, (2, (3, 4)))
619v0()
620v0(1)
621v0(1,)
622v0(1,2)
623v0(1,2,3,4,5,6,7,8,9,0)
624v1(1)
625v1(1,)
626v1(1,2)
627v1(1,2,3)
628v1(1,2,3,4,5,6,7,8,9,0)
629v2(1,2)
630v2(1,2,3)
631v2(1,2,3,4)
632v2(1,2,3,4,5,6,7,8,9,0)
633v3(1,(2,3))
634v3(1,(2,3),4)
635v3(1,(2,3),4,5,6,7,8,9,0)
Jeremy Hyltonaed0d8d2000-03-28 23:51:17 +0000636print
Guido van Rossum3bead091992-01-27 17:00:37 +0000637import sys, time
638c = sys.path[0]
639x = time.time()
640x = sys.modules['time'].time()
641a = '01234'
642c = a[0]
643c = a[-1]
644s = a[0:5]
645s = a[:5]
646s = a[0:]
647s = a[:]
648s = a[-5:]
649s = a[:-1]
650s = a[-4:-3]
651
652print 'atoms'
653### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
654### dictmaker: test ':' test (',' test ':' test)* [',']
655
656x = (1)
657x = (1 or 2 or 3)
658x = (1 or 2 or 3, 2, 3)
659
660x = []
661x = [1]
662x = [1 or 2 or 3]
663x = [1 or 2 or 3, 2, 3]
664x = []
665
666x = {}
667x = {'one': 1}
668x = {'one': 1,}
669x = {'one' or 'two': 1 or 2}
670x = {'one': 1, 'two': 2}
671x = {'one': 1, 'two': 2,}
672x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
673
674x = `x`
675x = `1 or 2 or 3`
676x = x
677x = 'x'
678x = 123
679
680### exprlist: expr (',' expr)* [',']
681### testlist: test (',' test)* [',']
682# These have been exercised enough above
683
Guido van Rossum85f18201992-11-27 22:53:50 +0000684print 'classdef' # 'class' NAME ['(' testlist ')'] ':' suite
Guido van Rossum3bead091992-01-27 17:00:37 +0000685class B: pass
686class C1(B): pass
687class C2(B): pass
688class D(C1, C2, B): pass
689class C:
Fred Drake004d5e62000-10-23 17:22:08 +0000690 def meth1(self): pass
691 def meth2(self, arg): pass
692 def meth3(self, a1, a2): pass
Skip Montanaro803d6e52000-08-12 18:09:51 +0000693
694# list comprehension tests
695nums = [1, 2, 3, 4, 5]
696strs = ["Apple", "Banana", "Coconut"]
697spcs = [" Apple", " Banana ", "Coco nut "]
698
699print [s.strip() for s in spcs]
700print [3 * x for x in nums]
701print [x for x in nums if x > 2]
702print [(i, s) for i in nums for s in strs]
703print [(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 +0000704print [(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)]
Jeremy Hylton578ceee2001-01-23 01:51:40 +0000705
706def test_in_func(l):
707 return [None < x < 3 for x in l if x > 2]
708
709print test_in_func(nums)
710
Jeremy Hyltone241e292001-03-19 20:42:11 +0000711def test_nested_front():
712 print [[y for y in [x, x + 1]] for x in [1,3,5]]
713
714test_nested_front()
715
Jeremy Hylton92e9f292001-01-25 17:03:37 +0000716check_syntax("[i, s for i in nums for s in strs]")
717check_syntax("[x if y]")
Skip Montanaro46dfa5f2000-08-22 02:43:07 +0000718
Skip Montanaro803d6e52000-08-12 18:09:51 +0000719suppliers = [
720 (1, "Boeing"),
721 (2, "Ford"),
722 (3, "Macdonalds")
723]
724
725parts = [
726 (10, "Airliner"),
727 (20, "Engine"),
728 (30, "Cheeseburger")
729]
730
731suppart = [
732 (1, 10), (1, 20), (2, 20), (3, 30)
733]
734
735print [
736 (sname, pname)
737 for (sno, sname) in suppliers
738 for (pno, pname) in parts
739 for (sp_sno, sp_pno) in suppart
740 if sno == sp_sno and pno == sp_pno
741]
Raymond Hettinger354433a2004-05-19 08:20:33 +0000742
743# generator expression tests
744g = ([x for x in range(10)] for x in range(1))
745verify(g.next() == [x for x in range(10)])
746try:
747 g.next()
748 raise TestFailed, 'should produce StopIteration exception'
749except StopIteration:
750 pass
751
752a = 1
753try:
754 g = (a for d in a)
755 g.next()
756 raise TestFailed, 'should produce TypeError'
757except TypeError:
758 pass
759
760verify(list((x, y) for x in 'abcd' for y in 'abcd') == [(x, y) for x in 'abcd' for y in 'abcd'])
761verify(list((x, y) for x in 'ab' for y in 'xy') == [(x, y) for x in 'ab' for y in 'xy'])
762
763a = [x for x in range(10)]
764b = (x for x in (y for y in a))
765verify(sum(b) == sum([x for x in range(10)]))
766
767verify(sum(x**2 for x in range(10)) == sum([x**2 for x in range(10)]))
768verify(sum(x*x for x in range(10) if x%2) == sum([x*x for x in range(10) if x%2]))
769verify(sum(x for x in (y for y in range(10))) == sum([x for x in range(10)]))
770verify(sum(x for x in (y for y in (z for z in range(10)))) == sum([x for x in range(10)]))
771verify(sum(x for x in [y for y in (z for z in range(10))]) == sum([x for x in range(10)]))
772verify(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)]))
773verify(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True) == 0)
774check_syntax("foo(x for x in range(10), 100)")
775check_syntax("foo(100, x for x in range(10))")
776
777# test for outmost iterable precomputation
778x = 10; g = (i for i in range(x)); x = 5
779verify(len(list(g)) == 10)
780
781# This should hold, since we're only precomputing outmost iterable.
782x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
783x = 5; t = True;
784verify([(i,j) for i in range(10) for j in range(5)] == list(g))