blob: f4a04788b08ade13f9e23e8dd262380b89f7ecdd [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
Thomas Wouters89f507f2006-12-13 04:49:30 +000011from test.test_support import run_unittest, check_syntax_error
12import unittest
Jeremy Hylton7d3dff22001-10-10 01:45:02 +000013import sys
Thomas Wouters89f507f2006-12-13 04:49:30 +000014# testing import *
15from sys import *
Guido van Rossum3bead091992-01-27 17:00:37 +000016
Thomas Wouters89f507f2006-12-13 04:49:30 +000017class TokenTests(unittest.TestCase):
Guido van Rossum3bead091992-01-27 17:00:37 +000018
Thomas Wouters89f507f2006-12-13 04:49:30 +000019 def testBackslash(self):
20 # Backslash means line continuation:
21 x = 1 \
22 + 1
23 self.assertEquals(x, 2, 'backslash for line continuation')
Guido van Rossum3bead091992-01-27 17:00:37 +000024
Thomas Wouters89f507f2006-12-13 04:49:30 +000025 # Backslash does not means continuation in comments :\
26 x = 0
27 self.assertEquals(x, 0, 'backslash ending comment')
Guido van Rossum3bead091992-01-27 17:00:37 +000028
Thomas Wouters89f507f2006-12-13 04:49:30 +000029 def testPlainIntegers(self):
30 self.assertEquals(0xff, 255)
31 self.assertEquals(0377, 255)
32 self.assertEquals(2147483647, 017777777777)
33 from sys import maxint
34 if maxint == 2147483647:
35 self.assertEquals(-2147483647-1, -020000000000)
36 # XXX -2147483648
37 self.assert_(037777777777 > 0)
38 self.assert_(0xffffffff > 0)
39 for s in '2147483648', '040000000000', '0x100000000':
40 try:
41 x = eval(s)
42 except OverflowError:
43 self.fail("OverflowError on huge integer literal %r" % s)
44 elif maxint == 9223372036854775807:
45 self.assertEquals(-9223372036854775807-1, -01000000000000000000000)
46 self.assert_(01777777777777777777777 > 0)
47 self.assert_(0xffffffffffffffff > 0)
48 for s in '9223372036854775808', '02000000000000000000000', \
49 '0x10000000000000000':
50 try:
51 x = eval(s)
52 except OverflowError:
53 self.fail("OverflowError on huge integer literal %r" % s)
54 else:
55 self.fail('Weird maxint value %r' % maxint)
Guido van Rossum3bead091992-01-27 17:00:37 +000056
Thomas Wouters89f507f2006-12-13 04:49:30 +000057 def testLongIntegers(self):
58 x = 0L
59 x = 0l
60 x = 0xffffffffffffffffL
61 x = 0xffffffffffffffffl
62 x = 077777777777777777L
63 x = 077777777777777777l
64 x = 123456789012345678901234567890L
65 x = 123456789012345678901234567890l
Guido van Rossum3bead091992-01-27 17:00:37 +000066
Thomas Wouters89f507f2006-12-13 04:49:30 +000067 def testFloats(self):
68 x = 3.14
69 x = 314.
70 x = 0.314
71 # XXX x = 000.314
72 x = .314
73 x = 3e14
74 x = 3E14
75 x = 3e-14
76 x = 3e+14
77 x = 3.e14
78 x = .3e14
79 x = 3.1e4
Guido van Rossum3bead091992-01-27 17:00:37 +000080
Thomas Wouters89f507f2006-12-13 04:49:30 +000081 def testStringLiterals(self):
82 x = ''; y = ""; self.assert_(len(x) == 0 and x == y)
83 x = '\''; y = "'"; self.assert_(len(x) == 1 and x == y and ord(x) == 39)
84 x = '"'; y = "\""; self.assert_(len(x) == 1 and x == y and ord(x) == 34)
85 x = "doesn't \"shrink\" does it"
86 y = 'doesn\'t "shrink" does it'
87 self.assert_(len(x) == 24 and x == y)
88 x = "does \"shrink\" doesn't it"
89 y = 'does "shrink" doesn\'t it'
90 self.assert_(len(x) == 24 and x == y)
91 x = """
Guido van Rossumb6775db1994-08-01 11:34:53 +000092The "quick"
93brown fox
94jumps over
95the 'lazy' dog.
96"""
Thomas Wouters89f507f2006-12-13 04:49:30 +000097 y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
98 self.assertEquals(x, y)
99 y = '''
Guido van Rossumb6775db1994-08-01 11:34:53 +0000100The "quick"
101brown fox
102jumps over
103the 'lazy' dog.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000104'''
105 self.assertEquals(x, y)
106 y = "\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000107The \"quick\"\n\
108brown fox\n\
109jumps over\n\
110the 'lazy' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000111"
112 self.assertEquals(x, y)
113 y = '\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000114The \"quick\"\n\
115brown fox\n\
116jumps over\n\
117the \'lazy\' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000118'
119 self.assertEquals(x, y)
120
121 def testEllipsis(self):
122 x = ...
123 self.assert_(x is Ellipsis)
124
125class GrammarTests(unittest.TestCase):
126
127 # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
128 # XXX can't test in a script -- this rule is only used when interactive
129
130 # file_input: (NEWLINE | stmt)* ENDMARKER
131 # Being tested as this very moment this very module
132
133 # expr_input: testlist NEWLINE
134 # XXX Hard to test -- used only in calls to input()
135
136 def testEvalInput(self):
137 # testlist ENDMARKER
138 x = eval('1, 0 or 1')
139
140 def testFuncdef(self):
141 ### 'def' NAME parameters ':' suite
142 ### parameters: '(' [varargslist] ')'
143 ### varargslist: (fpdef ['=' test] ',')*
144 ### ('*' (NAME|',' fpdef ['=' test]) [',' ('**'|'*' '*') NAME]
145 ### | ('**'|'*' '*') NAME)
146 ### | fpdef ['=' test] (',' fpdef ['=' test])* [',']
147 ### fpdef: NAME | '(' fplist ')'
148 ### fplist: fpdef (',' fpdef)* [',']
149 ### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test)
150 ### argument: [test '='] test # Really [keyword '='] test
151 def f1(): pass
152 f1()
153 f1(*())
154 f1(*(), **{})
155 def f2(one_argument): pass
156 def f3(two, arguments): pass
157 def f4(two, (compound, (argument, list))): pass
158 def f5((compound, first), two): pass
159 self.assertEquals(f2.func_code.co_varnames, ('one_argument',))
160 self.assertEquals(f3.func_code.co_varnames, ('two', 'arguments'))
161 if sys.platform.startswith('java'):
162 self.assertEquals(f4.func_code.co_varnames,
163 ('two', '(compound, (argument, list))', 'compound', 'argument',
164 'list',))
165 self.assertEquals(f5.func_code.co_varnames,
166 ('(compound, first)', 'two', 'compound', 'first'))
167 else:
168 self.assertEquals(f4.func_code.co_varnames,
169 ('two', '.1', 'compound', 'argument', 'list'))
170 self.assertEquals(f5.func_code.co_varnames,
171 ('.0', 'two', 'compound', 'first'))
172 def a1(one_arg,): pass
173 def a2(two, args,): pass
174 def v0(*rest): pass
175 def v1(a, *rest): pass
176 def v2(a, b, *rest): pass
177 def v3(a, (b, c), *rest): return a, b, c, rest
178
179 f1()
180 f2(1)
181 f2(1,)
182 f3(1, 2)
183 f3(1, 2,)
184 f4(1, (2, (3, 4)))
185 v0()
186 v0(1)
187 v0(1,)
188 v0(1,2)
189 v0(1,2,3,4,5,6,7,8,9,0)
190 v1(1)
191 v1(1,)
192 v1(1,2)
193 v1(1,2,3)
194 v1(1,2,3,4,5,6,7,8,9,0)
195 v2(1,2)
196 v2(1,2,3)
197 v2(1,2,3,4)
198 v2(1,2,3,4,5,6,7,8,9,0)
199 v3(1,(2,3))
200 v3(1,(2,3),4)
201 v3(1,(2,3),4,5,6,7,8,9,0)
202
203 # ceval unpacks the formal arguments into the first argcount names;
204 # thus, the names nested inside tuples must appear after these names.
205 if sys.platform.startswith('java'):
206 self.assertEquals(v3.func_code.co_varnames, ('a', '(b, c)', 'rest', 'b', 'c'))
207 else:
208 self.assertEquals(v3.func_code.co_varnames, ('a', '.1', 'rest', 'b', 'c'))
209 self.assertEquals(v3(1, (2, 3), 4), (1, 2, 3, (4,)))
210 def d01(a=1): pass
211 d01()
212 d01(1)
213 d01(*(1,))
214 d01(**{'a':2})
215 def d11(a, b=1): pass
216 d11(1)
217 d11(1, 2)
218 d11(1, **{'b':2})
219 def d21(a, b, c=1): pass
220 d21(1, 2)
221 d21(1, 2, 3)
222 d21(*(1, 2, 3))
223 d21(1, *(2, 3))
224 d21(1, 2, *(3,))
225 d21(1, 2, **{'c':3})
226 def d02(a=1, b=2): pass
227 d02()
228 d02(1)
229 d02(1, 2)
230 d02(*(1, 2))
231 d02(1, *(2,))
232 d02(1, **{'b':2})
233 d02(**{'a': 1, 'b': 2})
234 def d12(a, b=1, c=2): pass
235 d12(1)
236 d12(1, 2)
237 d12(1, 2, 3)
238 def d22(a, b, c=1, d=2): pass
239 d22(1, 2)
240 d22(1, 2, 3)
241 d22(1, 2, 3, 4)
242 def d01v(a=1, *rest): pass
243 d01v()
244 d01v(1)
245 d01v(1, 2)
246 d01v(*(1, 2, 3, 4))
247 d01v(*(1,))
248 d01v(**{'a':2})
249 def d11v(a, b=1, *rest): pass
250 d11v(1)
251 d11v(1, 2)
252 d11v(1, 2, 3)
253 def d21v(a, b, c=1, *rest): pass
254 d21v(1, 2)
255 d21v(1, 2, 3)
256 d21v(1, 2, 3, 4)
257 d21v(*(1, 2, 3, 4))
258 d21v(1, 2, **{'c': 3})
259 def d02v(a=1, b=2, *rest): pass
260 d02v()
261 d02v(1)
262 d02v(1, 2)
263 d02v(1, 2, 3)
264 d02v(1, *(2, 3, 4))
265 d02v(**{'a': 1, 'b': 2})
266 def d12v(a, b=1, c=2, *rest): pass
267 d12v(1)
268 d12v(1, 2)
269 d12v(1, 2, 3)
270 d12v(1, 2, 3, 4)
271 d12v(*(1, 2, 3, 4))
272 d12v(1, 2, *(3, 4, 5))
273 d12v(1, *(2,), **{'c': 3})
274 def d22v(a, b, c=1, d=2, *rest): pass
275 d22v(1, 2)
276 d22v(1, 2, 3)
277 d22v(1, 2, 3, 4)
278 d22v(1, 2, 3, 4, 5)
279 d22v(*(1, 2, 3, 4))
280 d22v(1, 2, *(3, 4, 5))
281 d22v(1, *(2, 3), **{'d': 4})
282 def d31v((x)): pass
283 d31v(1)
284 def d32v((x,)): pass
285 d32v((1,))
286 # keyword only argument tests
287 def pos0key1(*, key): return key
288 pos0key1(key=100)
289 def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
290 pos2key2(1, 2, k1=100)
291 pos2key2(1, 2, k1=100, k2=200)
292 pos2key2(1, 2, k2=100, k1=200)
293 def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
294 pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
295 pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
296
297 def testLambdef(self):
298 ### lambdef: 'lambda' [varargslist] ':' test
299 l1 = lambda : 0
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 l6 = lambda x, y, *, k=20: x+y+k
311 self.assertEquals(l6(1,2), 1+2+20)
312 self.assertEquals(l6(1,2,k=10), 1+2+10)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000313
314
Thomas Wouters89f507f2006-12-13 04:49:30 +0000315 ### stmt: simple_stmt | compound_stmt
316 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000317
Thomas Wouters89f507f2006-12-13 04:49:30 +0000318 def testSimpleStmt(self):
319 ### simple_stmt: small_stmt (';' small_stmt)* [';']
320 x = 1; pass; del x
321 def foo():
322 # verify statments that end with semi-colons
323 x = 1; pass; del x;
324 foo()
Georg Brandl52318d62006-09-06 07:06:08 +0000325
Thomas Wouters89f507f2006-12-13 04:49:30 +0000326 ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
327 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000328
Thomas Wouters89f507f2006-12-13 04:49:30 +0000329 def testExprStmt(self):
330 # (exprlist '=')* exprlist
331 1
332 1, 2, 3
333 x = 1
334 x = 1, 2, 3
335 x = y = z = 1, 2, 3
336 x, y, z = 1, 2, 3
337 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000338
Thomas Wouters89f507f2006-12-13 04:49:30 +0000339 check_syntax_error(self, "x + 1 = 1")
340 check_syntax_error(self, "a + 1 = b + 2")
Guido van Rossum3bead091992-01-27 17:00:37 +0000341
Thomas Wouters89f507f2006-12-13 04:49:30 +0000342 def testPrintStmt(self):
343 # 'print' (test ',')* [test]
344 import StringIO
Guido van Rossum3bead091992-01-27 17:00:37 +0000345
Thomas Wouters89f507f2006-12-13 04:49:30 +0000346 # Can't test printing to real stdout without comparing output
347 # which is not available in unittest.
348 save_stdout = sys.stdout
349 sys.stdout = StringIO.StringIO()
Guido van Rossum3bead091992-01-27 17:00:37 +0000350
Thomas Wouters89f507f2006-12-13 04:49:30 +0000351 print 1, 2, 3
352 print 1, 2, 3,
353 print
354 print 0 or 1, 0 or 1,
355 print 0 or 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000356
Thomas Wouters89f507f2006-12-13 04:49:30 +0000357 # 'print' '>>' test ','
358 print >> sys.stdout, 1, 2, 3
359 print >> sys.stdout, 1, 2, 3,
360 print >> sys.stdout
361 print >> sys.stdout, 0 or 1, 0 or 1,
362 print >> sys.stdout, 0 or 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000363
Thomas Wouters89f507f2006-12-13 04:49:30 +0000364 # test printing to an instance
365 class Gulp:
366 def write(self, msg): pass
Jeremy Hylton619eea62001-01-25 20:12:27 +0000367
Thomas Wouters89f507f2006-12-13 04:49:30 +0000368 gulp = Gulp()
369 print >> gulp, 1, 2, 3
370 print >> gulp, 1, 2, 3,
371 print >> gulp
372 print >> gulp, 0 or 1, 0 or 1,
373 print >> gulp, 0 or 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000374
Thomas Wouters89f507f2006-12-13 04:49:30 +0000375 # test print >> None
376 def driver():
377 oldstdout = sys.stdout
378 sys.stdout = Gulp()
379 try:
380 tellme(Gulp())
381 tellme()
382 finally:
383 sys.stdout = oldstdout
Guido van Rossum3bead091992-01-27 17:00:37 +0000384
Thomas Wouters89f507f2006-12-13 04:49:30 +0000385 # we should see this once
386 def tellme(file=sys.stdout):
387 print >> file, 'hello world'
Guido van Rossum3bead091992-01-27 17:00:37 +0000388
Thomas Wouters89f507f2006-12-13 04:49:30 +0000389 driver()
Guido van Rossum3bead091992-01-27 17:00:37 +0000390
Thomas Wouters89f507f2006-12-13 04:49:30 +0000391 # we should not see this at all
392 def tellme(file=None):
393 print >> file, 'goodbye universe'
Jeremy Hylton47793992001-02-19 15:35:26 +0000394
Thomas Wouters89f507f2006-12-13 04:49:30 +0000395 driver()
Guido van Rossum3bead091992-01-27 17:00:37 +0000396
Thomas Wouters89f507f2006-12-13 04:49:30 +0000397 self.assertEqual(sys.stdout.getvalue(), '''\
3981 2 3
3991 2 3
4001 1 1
4011 2 3
4021 2 3
4031 1 1
404hello world
405''')
406 sys.stdout = save_stdout
Barry Warsawefc92ee2000-08-21 15:46:50 +0000407
Thomas Wouters89f507f2006-12-13 04:49:30 +0000408 # syntax errors
409 check_syntax_error(self, 'print ,')
410 check_syntax_error(self, 'print >> x,')
Barry Warsaw9182b452000-08-29 04:57:10 +0000411
Thomas Wouters89f507f2006-12-13 04:49:30 +0000412 def testDelStmt(self):
413 # 'del' exprlist
414 abc = [1,2,3]
415 x, y, z = abc
416 xyz = x, y, z
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000417
Thomas Wouters89f507f2006-12-13 04:49:30 +0000418 del abc
419 del x, y, (z, xyz)
Barry Warsaw9182b452000-08-29 04:57:10 +0000420
Thomas Wouters89f507f2006-12-13 04:49:30 +0000421 def testPassStmt(self):
422 # 'pass'
423 pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000424
Thomas Wouters89f507f2006-12-13 04:49:30 +0000425 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
426 # Tested below
Barry Warsaw9182b452000-08-29 04:57:10 +0000427
Thomas Wouters89f507f2006-12-13 04:49:30 +0000428 def testBreakStmt(self):
429 # 'break'
430 while 1: break
Barry Warsaw9182b452000-08-29 04:57:10 +0000431
Thomas Wouters89f507f2006-12-13 04:49:30 +0000432 def testContinueStmt(self):
433 # 'continue'
434 i = 1
435 while i: i = 0; continue
Barry Warsaw9182b452000-08-29 04:57:10 +0000436
Thomas Wouters89f507f2006-12-13 04:49:30 +0000437 msg = ""
438 while not msg:
439 msg = "ok"
440 try:
441 continue
442 msg = "continue failed to continue inside try"
443 except:
444 msg = "continue inside try called except block"
445 if msg != "ok":
446 self.fail(msg)
Barry Warsawefc92ee2000-08-21 15:46:50 +0000447
Thomas Wouters89f507f2006-12-13 04:49:30 +0000448 msg = ""
449 while not msg:
450 msg = "finally block not called"
451 try:
452 continue
453 finally:
454 msg = "ok"
455 if msg != "ok":
456 self.fail(msg)
Guido van Rossum3bead091992-01-27 17:00:37 +0000457
Thomas Wouters89f507f2006-12-13 04:49:30 +0000458 def test_break_continue_loop(self):
459 # This test warrants an explanation. It is a test specifically for SF bugs
460 # #463359 and #462937. The bug is that a 'break' statement executed or
461 # exception raised inside a try/except inside a loop, *after* a continue
462 # statement has been executed in that loop, will cause the wrong number of
463 # arguments to be popped off the stack and the instruction pointer reset to
464 # a very small number (usually 0.) Because of this, the following test
465 # *must* written as a function, and the tracking vars *must* be function
466 # arguments with default values. Otherwise, the test will loop and loop.
Guido van Rossum3bead091992-01-27 17:00:37 +0000467
Thomas Wouters89f507f2006-12-13 04:49:30 +0000468 def test_inner(extra_burning_oil = 1, count=0):
469 big_hippo = 2
470 while big_hippo:
471 count += 1
472 try:
473 if extra_burning_oil and big_hippo == 1:
474 extra_burning_oil -= 1
475 break
476 big_hippo -= 1
477 continue
478 except:
479 raise
480 if count > 2 or big_hippo != 1:
481 self.fail("continue then break in try/except in loop broken!")
482 test_inner()
Guido van Rossum3bead091992-01-27 17:00:37 +0000483
Thomas Wouters89f507f2006-12-13 04:49:30 +0000484 def testReturn(self):
485 # 'return' [testlist]
486 def g1(): return
487 def g2(): return 1
488 g1()
489 x = g2()
490 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000491
Thomas Wouters89f507f2006-12-13 04:49:30 +0000492 def testYield(self):
493 check_syntax_error(self, "class foo:yield 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000494
Thomas Wouters89f507f2006-12-13 04:49:30 +0000495 def testRaise(self):
496 # 'raise' test [',' test]
497 try: raise RuntimeError, 'just testing'
498 except RuntimeError: pass
499 try: raise KeyboardInterrupt
500 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000501
Thomas Wouters89f507f2006-12-13 04:49:30 +0000502 def testImport(self):
503 # 'import' dotted_as_names
504 import sys
505 import time, sys
506 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
507 from time import time
508 from time import (time)
509 # not testable inside a function, but already done at top of the module
510 # from sys import *
511 from sys import path, argv
512 from sys import (path, argv)
513 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +0000514
Thomas Wouters89f507f2006-12-13 04:49:30 +0000515 def testGlobal(self):
516 # 'global' NAME (',' NAME)*
517 global a
518 global a, b
519 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +0000520
Thomas Wouters89f507f2006-12-13 04:49:30 +0000521 def testAssert(self):
522 # assert_stmt: 'assert' test [',' test]
523 assert 1
524 assert 1, 1
525 assert lambda x:x
526 assert 1, lambda x:x+1
Thomas Wouters80d373c2001-09-26 12:43:39 +0000527 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000528 assert 0, "msg"
529 except AssertionError, e:
530 self.assertEquals(e.args[0], "msg")
531 else:
532 if __debug__:
533 self.fail("AssertionError not raised by assert 0")
Thomas Wouters80d373c2001-09-26 12:43:39 +0000534
Thomas Wouters89f507f2006-12-13 04:49:30 +0000535 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
536 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000537
Thomas Wouters89f507f2006-12-13 04:49:30 +0000538 def testIf(self):
539 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
540 if 1: pass
541 if 1: pass
542 else: pass
543 if 0: pass
544 elif 0: pass
545 if 0: pass
546 elif 0: pass
547 elif 0: pass
548 elif 0: pass
549 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000550
Thomas Wouters89f507f2006-12-13 04:49:30 +0000551 def testWhile(self):
552 # 'while' test ':' suite ['else' ':' suite]
553 while 0: pass
554 while 0: pass
555 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000556
Thomas Wouters89f507f2006-12-13 04:49:30 +0000557 def testFor(self):
558 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
559 for i in 1, 2, 3: pass
560 for i, j, k in (): pass
561 else: pass
562 class Squares:
563 def __init__(self, max):
564 self.max = max
565 self.sofar = []
566 def __len__(self): return len(self.sofar)
567 def __getitem__(self, i):
568 if not 0 <= i < self.max: raise IndexError
569 n = len(self.sofar)
570 while n <= i:
571 self.sofar.append(n*n)
572 n = n+1
573 return self.sofar[i]
574 n = 0
575 for x in Squares(10): n = n+x
576 if n != 285:
577 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000578
Thomas Wouters89f507f2006-12-13 04:49:30 +0000579 result = []
580 for x, in [(1,), (2,), (3,)]:
581 result.append(x)
582 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000583
Thomas Wouters89f507f2006-12-13 04:49:30 +0000584 def testTry(self):
585 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
586 ### | 'try' ':' suite 'finally' ':' suite
587 ### except_clause: 'except' [expr [',' expr]]
588 try:
589 1/0
590 except ZeroDivisionError:
591 pass
592 else:
593 pass
594 try: 1/0
595 except EOFError: pass
596 except TypeError, msg: pass
597 except RuntimeError, msg: pass
598 except: pass
599 else: pass
600 try: 1/0
601 except (EOFError, TypeError, ZeroDivisionError): pass
602 try: 1/0
603 except (EOFError, TypeError, ZeroDivisionError), msg: pass
604 try: pass
605 finally: pass
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000606
Thomas Wouters89f507f2006-12-13 04:49:30 +0000607 def testSuite(self):
608 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
609 if 1: pass
610 if 1:
611 pass
612 if 1:
613 #
614 #
615 #
616 pass
617 pass
618 #
619 pass
620 #
Guido van Rossum3bead091992-01-27 17:00:37 +0000621
Thomas Wouters89f507f2006-12-13 04:49:30 +0000622 def testTest(self):
623 ### and_test ('or' and_test)*
624 ### and_test: not_test ('and' not_test)*
625 ### not_test: 'not' not_test | comparison
626 if not 1: pass
627 if 1 and 1: pass
628 if 1 or 1: pass
629 if not not not 1: pass
630 if not 1 and 1 and 1: pass
631 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000632
Thomas Wouters89f507f2006-12-13 04:49:30 +0000633 def testComparison(self):
634 ### comparison: expr (comp_op expr)*
635 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
636 if 1: pass
637 x = (1 == 1)
638 if 1 == 1: pass
639 if 1 != 1: pass
640 if 1 < 1: pass
641 if 1 > 1: pass
642 if 1 <= 1: pass
643 if 1 >= 1: pass
644 if 1 is 1: pass
645 if 1 is not 1: pass
646 if 1 in (): pass
647 if 1 not in (): pass
648 if 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 +0000649
Thomas Wouters89f507f2006-12-13 04:49:30 +0000650 def testBinaryMaskOps(self):
651 x = 1 & 1
652 x = 1 ^ 1
653 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000654
Thomas Wouters89f507f2006-12-13 04:49:30 +0000655 def testShiftOps(self):
656 x = 1 << 1
657 x = 1 >> 1
658 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000659
Thomas Wouters89f507f2006-12-13 04:49:30 +0000660 def testAdditiveOps(self):
661 x = 1
662 x = 1 + 1
663 x = 1 - 1 - 1
664 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000665
Thomas Wouters89f507f2006-12-13 04:49:30 +0000666 def testMultiplicativeOps(self):
667 x = 1 * 1
668 x = 1 / 1
669 x = 1 % 1
670 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000671
Thomas Wouters89f507f2006-12-13 04:49:30 +0000672 def testUnaryOps(self):
673 x = +1
674 x = -1
675 x = ~1
676 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
677 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +0000678
Thomas Wouters89f507f2006-12-13 04:49:30 +0000679 def testSelectors(self):
680 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
681 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +0000682
Thomas Wouters89f507f2006-12-13 04:49:30 +0000683 import sys, time
684 c = sys.path[0]
685 x = time.time()
686 x = sys.modules['time'].time()
687 a = '01234'
688 c = a[0]
689 c = a[-1]
690 s = a[0:5]
691 s = a[:5]
692 s = a[0:]
693 s = a[:]
694 s = a[-5:]
695 s = a[:-1]
696 s = a[-4:-3]
697 # A rough test of SF bug 1333982. http://python.org/sf/1333982
698 # The testing here is fairly incomplete.
699 # Test cases should include: commas with 1 and 2 colons
700 d = {}
701 d[1] = 1
702 d[1,] = 2
703 d[1,2] = 3
704 d[1,2,3] = 4
705 L = list(d)
706 L.sort(key=lambda x: x if isinstance(x, tuple) else ())
707 self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +0000708
Thomas Wouters89f507f2006-12-13 04:49:30 +0000709 def testAtoms(self):
710 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
711 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +0000712
Thomas Wouters89f507f2006-12-13 04:49:30 +0000713 x = (1)
714 x = (1 or 2 or 3)
715 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +0000716
Thomas Wouters89f507f2006-12-13 04:49:30 +0000717 x = []
718 x = [1]
719 x = [1 or 2 or 3]
720 x = [1 or 2 or 3, 2, 3]
721 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +0000722
Thomas Wouters89f507f2006-12-13 04:49:30 +0000723 x = {}
724 x = {'one': 1}
725 x = {'one': 1,}
726 x = {'one' or 'two': 1 or 2}
727 x = {'one': 1, 'two': 2}
728 x = {'one': 1, 'two': 2,}
729 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +0000730
Thomas Wouters89f507f2006-12-13 04:49:30 +0000731 x = {'one'}
732 x = {'one', 1,}
733 x = {'one', 'two', 'three'}
734 x = {2, 3, 4,}
735
736 x = x
737 x = 'x'
738 x = 123
739
740 ### exprlist: expr (',' expr)* [',']
741 ### testlist: test (',' test)* [',']
742 # These have been exercised enough above
743
744 def testClassdef(self):
745 # 'class' NAME ['(' [testlist] ')'] ':' suite
746 class B: pass
747 class B2(): pass
748 class C1(B): pass
749 class C2(B): pass
750 class D(C1, C2, B): pass
751 class C:
752 def meth1(self): pass
753 def meth2(self, arg): pass
754 def meth3(self, a1, a2): pass
755
756 def testListcomps(self):
757 # list comprehension tests
758 nums = [1, 2, 3, 4, 5]
759 strs = ["Apple", "Banana", "Coconut"]
760 spcs = [" Apple", " Banana ", "Coco nut "]
761
762 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
763 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
764 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
765 self.assertEqual([(i, s) for i in nums for s in strs],
766 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
767 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
768 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
769 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
770 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
771 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
772 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
773 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
774 (5, 'Banana'), (5, 'Coconut')])
775 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
776 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
777
778 def test_in_func(l):
779 return [0 < x < 3 for x in l if x > 2]
780
781 self.assertEqual(test_in_func(nums), [False, False, False])
782
783 def test_nested_front():
784 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
785 [[1, 2], [3, 4], [5, 6]])
786
787 test_nested_front()
788
789 check_syntax_error(self, "[i, s for i in nums for s in strs]")
790 check_syntax_error(self, "[x if y]")
791
792 suppliers = [
793 (1, "Boeing"),
794 (2, "Ford"),
795 (3, "Macdonalds")
796 ]
797
798 parts = [
799 (10, "Airliner"),
800 (20, "Engine"),
801 (30, "Cheeseburger")
802 ]
803
804 suppart = [
805 (1, 10), (1, 20), (2, 20), (3, 30)
806 ]
807
808 x = [
809 (sname, pname)
810 for (sno, sname) in suppliers
811 for (pno, pname) in parts
812 for (sp_sno, sp_pno) in suppart
813 if sno == sp_sno and pno == sp_pno
814 ]
815
816 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
817 ('Macdonalds', 'Cheeseburger')])
818
819 def testGenexps(self):
820 # generator expression tests
821 g = ([x for x in range(10)] for x in range(1))
822 self.assertEqual(g.next(), [x for x in range(10)])
823 try:
824 g.next()
825 self.fail('should produce StopIteration exception')
826 except StopIteration:
827 pass
828
829 a = 1
830 try:
831 g = (a for d in a)
832 g.next()
833 self.fail('should produce TypeError')
834 except TypeError:
835 pass
836
837 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
838 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
839
840 a = [x for x in range(10)]
841 b = (x for x in (y for y in a))
842 self.assertEqual(sum(b), sum([x for x in range(10)]))
843
844 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
845 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
846 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
847 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
848 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
849 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)]))
850 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
851 check_syntax_error(self, "foo(x for x in range(10), 100)")
852 check_syntax_error(self, "foo(100, x for x in range(10))")
853
854 def testComprehensionSpecials(self):
855 # test for outmost iterable precomputation
856 x = 10; g = (i for i in range(x)); x = 5
857 self.assertEqual(len(list(g)), 10)
858
859 # This should hold, since we're only precomputing outmost iterable.
860 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
861 x = 5; t = True;
862 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
863
864 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
865 # even though it's silly. Make sure it works (ifelse broke this.)
866 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
867 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
868
869 # verify unpacking single element tuples in listcomp/genexp.
870 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
871 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
872
873 def testIfElseExpr(self):
874 # Test ifelse expressions in various cases
875 def _checkeval(msg, ret):
876 "helper to check that evaluation of expressions is done correctly"
877 print x
878 return ret
879
880 self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
881 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
882 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])
883 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
884 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
885 self.assertEqual((5 and 6 if 0 else 1), 1)
886 self.assertEqual(((5 and 6) if 0 else 1), 1)
887 self.assertEqual((5 and (6 if 1 else 1)), 6)
888 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
889 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
890 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
891 self.assertEqual((not 5 if 1 else 1), False)
892 self.assertEqual((not 5 if 0 else 1), 1)
893 self.assertEqual((6 + 1 if 1 else 2), 7)
894 self.assertEqual((6 - 1 if 1 else 2), 5)
895 self.assertEqual((6 * 2 if 1 else 4), 12)
896 self.assertEqual((6 / 2 if 1 else 3), 3)
897 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +0000898
Guido van Rossum3bead091992-01-27 17:00:37 +0000899
Thomas Wouters89f507f2006-12-13 04:49:30 +0000900def test_main():
901 run_unittest(TokenTests, GrammarTests)
Guido van Rossum3bead091992-01-27 17:00:37 +0000902
Thomas Wouters89f507f2006-12-13 04:49:30 +0000903if __name__ == '__main__':
904 test_main()