blob: 711d636f0448253329ab12cf6aaf1baaf73795de [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):
Guido van Rossume2a383d2007-01-15 16:59:06 +000058 x = 0
59 x = 0
60 x = 0xffffffffffffffff
61 x = 0xffffffffffffffff
62 x = 077777777777777777
63 x = 077777777777777777
64 x = 123456789012345678901234567890
65 x = 123456789012345678901234567890
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)
Georg Brandldde00282007-03-18 19:01:53 +0000124 self.assertRaises(SyntaxError, eval, ".. .")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000125
126class GrammarTests(unittest.TestCase):
127
128 # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
129 # XXX can't test in a script -- this rule is only used when interactive
130
131 # file_input: (NEWLINE | stmt)* ENDMARKER
132 # Being tested as this very moment this very module
133
134 # expr_input: testlist NEWLINE
135 # XXX Hard to test -- used only in calls to input()
136
137 def testEvalInput(self):
138 # testlist ENDMARKER
139 x = eval('1, 0 or 1')
140
141 def testFuncdef(self):
Neal Norwitzc1505362006-12-28 06:47:50 +0000142 ### [decorators] 'def' NAME parameters ['->' test] ':' suite
143 ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
144 ### decorators: decorator+
145 ### parameters: '(' [typedargslist] ')'
146 ### typedargslist: ((tfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000147 ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000148 ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000149 ### tfpdef: NAME [':' test]
Neal Norwitzc1505362006-12-28 06:47:50 +0000150 ### varargslist: ((vfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000151 ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000152 ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000153 ### vfpdef: NAME
Thomas Wouters89f507f2006-12-13 04:49:30 +0000154 def f1(): pass
155 f1()
156 f1(*())
157 f1(*(), **{})
158 def f2(one_argument): pass
159 def f3(two, arguments): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000160 self.assertEquals(f2.__code__.co_varnames, ('one_argument',))
161 self.assertEquals(f3.__code__.co_varnames, ('two', 'arguments'))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000162 def a1(one_arg,): pass
163 def a2(two, args,): pass
164 def v0(*rest): pass
165 def v1(a, *rest): pass
166 def v2(a, b, *rest): pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000167
168 f1()
169 f2(1)
170 f2(1,)
171 f3(1, 2)
172 f3(1, 2,)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000173 v0()
174 v0(1)
175 v0(1,)
176 v0(1,2)
177 v0(1,2,3,4,5,6,7,8,9,0)
178 v1(1)
179 v1(1,)
180 v1(1,2)
181 v1(1,2,3)
182 v1(1,2,3,4,5,6,7,8,9,0)
183 v2(1,2)
184 v2(1,2,3)
185 v2(1,2,3,4)
186 v2(1,2,3,4,5,6,7,8,9,0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000187
Thomas Wouters89f507f2006-12-13 04:49:30 +0000188 def d01(a=1): pass
189 d01()
190 d01(1)
191 d01(*(1,))
192 d01(**{'a':2})
193 def d11(a, b=1): pass
194 d11(1)
195 d11(1, 2)
196 d11(1, **{'b':2})
197 def d21(a, b, c=1): pass
198 d21(1, 2)
199 d21(1, 2, 3)
200 d21(*(1, 2, 3))
201 d21(1, *(2, 3))
202 d21(1, 2, *(3,))
203 d21(1, 2, **{'c':3})
204 def d02(a=1, b=2): pass
205 d02()
206 d02(1)
207 d02(1, 2)
208 d02(*(1, 2))
209 d02(1, *(2,))
210 d02(1, **{'b':2})
211 d02(**{'a': 1, 'b': 2})
212 def d12(a, b=1, c=2): pass
213 d12(1)
214 d12(1, 2)
215 d12(1, 2, 3)
216 def d22(a, b, c=1, d=2): pass
217 d22(1, 2)
218 d22(1, 2, 3)
219 d22(1, 2, 3, 4)
220 def d01v(a=1, *rest): pass
221 d01v()
222 d01v(1)
223 d01v(1, 2)
224 d01v(*(1, 2, 3, 4))
225 d01v(*(1,))
226 d01v(**{'a':2})
227 def d11v(a, b=1, *rest): pass
228 d11v(1)
229 d11v(1, 2)
230 d11v(1, 2, 3)
231 def d21v(a, b, c=1, *rest): pass
232 d21v(1, 2)
233 d21v(1, 2, 3)
234 d21v(1, 2, 3, 4)
235 d21v(*(1, 2, 3, 4))
236 d21v(1, 2, **{'c': 3})
237 def d02v(a=1, b=2, *rest): pass
238 d02v()
239 d02v(1)
240 d02v(1, 2)
241 d02v(1, 2, 3)
242 d02v(1, *(2, 3, 4))
243 d02v(**{'a': 1, 'b': 2})
244 def d12v(a, b=1, c=2, *rest): pass
245 d12v(1)
246 d12v(1, 2)
247 d12v(1, 2, 3)
248 d12v(1, 2, 3, 4)
249 d12v(*(1, 2, 3, 4))
250 d12v(1, 2, *(3, 4, 5))
251 d12v(1, *(2,), **{'c': 3})
252 def d22v(a, b, c=1, d=2, *rest): pass
253 d22v(1, 2)
254 d22v(1, 2, 3)
255 d22v(1, 2, 3, 4)
256 d22v(1, 2, 3, 4, 5)
257 d22v(*(1, 2, 3, 4))
258 d22v(1, 2, *(3, 4, 5))
259 d22v(1, *(2, 3), **{'d': 4})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000260 # keyword only argument tests
261 def pos0key1(*, key): return key
262 pos0key1(key=100)
263 def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
264 pos2key2(1, 2, k1=100)
265 pos2key2(1, 2, k1=100, k2=200)
266 pos2key2(1, 2, k2=100, k1=200)
267 def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
268 pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
269 pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
270
Neal Norwitzc1505362006-12-28 06:47:50 +0000271 # argument annotation tests
272 def f(x) -> list: pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000273 self.assertEquals(f.__annotations__, {'return': list})
Neal Norwitzc1505362006-12-28 06:47:50 +0000274 def f(x:int): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000275 self.assertEquals(f.__annotations__, {'x': int})
Neal Norwitzc1505362006-12-28 06:47:50 +0000276 def f(*x:str): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000277 self.assertEquals(f.__annotations__, {'x': str})
Neal Norwitzc1505362006-12-28 06:47:50 +0000278 def f(**x:float): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000279 self.assertEquals(f.__annotations__, {'x': float})
Neal Norwitzc1505362006-12-28 06:47:50 +0000280 def f(x, y:1+2): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000281 self.assertEquals(f.__annotations__, {'y': 3})
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000282 def f(a, b:1, c:2, d): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000283 self.assertEquals(f.__annotations__, {'b': 1, 'c': 2})
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000284 def f(a, b:1, c:2, d, e:3=4, f=5, *g:6): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000285 self.assertEquals(f.__annotations__,
Neal Norwitzc1505362006-12-28 06:47:50 +0000286 {'b': 1, 'c': 2, 'e': 3, 'g': 6})
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000287 def f(a, b:1, c:2, d, e:3=4, f=5, *g:6, h:7, i=8, j:9=10,
Neal Norwitzc1505362006-12-28 06:47:50 +0000288 **k:11) -> 12: pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000289 self.assertEquals(f.__annotations__,
Neal Norwitzc1505362006-12-28 06:47:50 +0000290 {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
291 'k': 11, 'return': 12})
Nick Coghlan71011e22007-04-23 11:05:01 +0000292 # Check for SF Bug #1697248 - mixing decorators and a return annotation
293 def null(x): return x
294 @null
295 def f(x) -> list: pass
296 self.assertEquals(f.__annotations__, {'return': list})
297
Guido van Rossum0240b922007-02-26 21:23:50 +0000298 # test MAKE_CLOSURE with a variety of oparg's
299 closure = 1
300 def f(): return closure
301 def f(x=1): return closure
302 def f(*, k=1): return closure
303 def f() -> int: return closure
Neal Norwitzc1505362006-12-28 06:47:50 +0000304
Thomas Wouters89f507f2006-12-13 04:49:30 +0000305 def testLambdef(self):
306 ### lambdef: 'lambda' [varargslist] ':' test
307 l1 = lambda : 0
308 self.assertEquals(l1(), 0)
309 l2 = lambda : a[d] # XXX just testing the expression
Guido van Rossume2a383d2007-01-15 16:59:06 +0000310 l3 = lambda : [2 < x for x in [-1, 3, 0]]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000311 self.assertEquals(l3(), [0, 1, 0])
312 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
313 self.assertEquals(l4(), 1)
314 l5 = lambda x, y, z=2: x + y + z
315 self.assertEquals(l5(1, 2), 5)
316 self.assertEquals(l5(1, 2, 3), 6)
317 check_syntax_error(self, "lambda x: x = 2")
318 l6 = lambda x, y, *, k=20: x+y+k
319 self.assertEquals(l6(1,2), 1+2+20)
320 self.assertEquals(l6(1,2,k=10), 1+2+10)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000321
322
Thomas Wouters89f507f2006-12-13 04:49:30 +0000323 ### stmt: simple_stmt | compound_stmt
324 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000325
Thomas Wouters89f507f2006-12-13 04:49:30 +0000326 def testSimpleStmt(self):
327 ### simple_stmt: small_stmt (';' small_stmt)* [';']
328 x = 1; pass; del x
329 def foo():
330 # verify statments that end with semi-colons
331 x = 1; pass; del x;
332 foo()
Georg Brandl52318d62006-09-06 07:06:08 +0000333
Guido van Rossumd8faa362007-04-27 19:54:29 +0000334 ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
Thomas Wouters89f507f2006-12-13 04:49:30 +0000335 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000336
Thomas Wouters89f507f2006-12-13 04:49:30 +0000337 def testExprStmt(self):
338 # (exprlist '=')* exprlist
339 1
340 1, 2, 3
341 x = 1
342 x = 1, 2, 3
343 x = y = z = 1, 2, 3
344 x, y, z = 1, 2, 3
345 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000346
Thomas Wouters89f507f2006-12-13 04:49:30 +0000347 check_syntax_error(self, "x + 1 = 1")
348 check_syntax_error(self, "a + 1 = b + 2")
Guido van Rossum3bead091992-01-27 17:00:37 +0000349
Thomas Wouters89f507f2006-12-13 04:49:30 +0000350 def testDelStmt(self):
351 # 'del' exprlist
352 abc = [1,2,3]
353 x, y, z = abc
354 xyz = x, y, z
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000355
Thomas Wouters89f507f2006-12-13 04:49:30 +0000356 del abc
357 del x, y, (z, xyz)
Barry Warsaw9182b452000-08-29 04:57:10 +0000358
Thomas Wouters89f507f2006-12-13 04:49:30 +0000359 def testPassStmt(self):
360 # 'pass'
361 pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000362
Thomas Wouters89f507f2006-12-13 04:49:30 +0000363 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
364 # Tested below
Barry Warsaw9182b452000-08-29 04:57:10 +0000365
Thomas Wouters89f507f2006-12-13 04:49:30 +0000366 def testBreakStmt(self):
367 # 'break'
368 while 1: break
Barry Warsaw9182b452000-08-29 04:57:10 +0000369
Thomas Wouters89f507f2006-12-13 04:49:30 +0000370 def testContinueStmt(self):
371 # 'continue'
372 i = 1
373 while i: i = 0; continue
Barry Warsaw9182b452000-08-29 04:57:10 +0000374
Thomas Wouters89f507f2006-12-13 04:49:30 +0000375 msg = ""
376 while not msg:
377 msg = "ok"
378 try:
379 continue
380 msg = "continue failed to continue inside try"
381 except:
382 msg = "continue inside try called except block"
383 if msg != "ok":
384 self.fail(msg)
Barry Warsawefc92ee2000-08-21 15:46:50 +0000385
Thomas Wouters89f507f2006-12-13 04:49:30 +0000386 msg = ""
387 while not msg:
388 msg = "finally block not called"
389 try:
390 continue
391 finally:
392 msg = "ok"
393 if msg != "ok":
394 self.fail(msg)
Guido van Rossum3bead091992-01-27 17:00:37 +0000395
Thomas Wouters89f507f2006-12-13 04:49:30 +0000396 def test_break_continue_loop(self):
397 # This test warrants an explanation. It is a test specifically for SF bugs
398 # #463359 and #462937. The bug is that a 'break' statement executed or
399 # exception raised inside a try/except inside a loop, *after* a continue
400 # statement has been executed in that loop, will cause the wrong number of
401 # arguments to be popped off the stack and the instruction pointer reset to
402 # a very small number (usually 0.) Because of this, the following test
403 # *must* written as a function, and the tracking vars *must* be function
404 # arguments with default values. Otherwise, the test will loop and loop.
Guido van Rossum3bead091992-01-27 17:00:37 +0000405
Thomas Wouters89f507f2006-12-13 04:49:30 +0000406 def test_inner(extra_burning_oil = 1, count=0):
407 big_hippo = 2
408 while big_hippo:
409 count += 1
410 try:
411 if extra_burning_oil and big_hippo == 1:
412 extra_burning_oil -= 1
413 break
414 big_hippo -= 1
415 continue
416 except:
417 raise
418 if count > 2 or big_hippo != 1:
419 self.fail("continue then break in try/except in loop broken!")
420 test_inner()
Guido van Rossum3bead091992-01-27 17:00:37 +0000421
Thomas Wouters89f507f2006-12-13 04:49:30 +0000422 def testReturn(self):
423 # 'return' [testlist]
424 def g1(): return
425 def g2(): return 1
426 g1()
427 x = g2()
428 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000429
Thomas Wouters89f507f2006-12-13 04:49:30 +0000430 def testYield(self):
431 check_syntax_error(self, "class foo:yield 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000432
Thomas Wouters89f507f2006-12-13 04:49:30 +0000433 def testRaise(self):
434 # 'raise' test [',' test]
435 try: raise RuntimeError, 'just testing'
436 except RuntimeError: pass
437 try: raise KeyboardInterrupt
438 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000439
Thomas Wouters89f507f2006-12-13 04:49:30 +0000440 def testImport(self):
441 # 'import' dotted_as_names
442 import sys
443 import time, sys
444 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
445 from time import time
446 from time import (time)
447 # not testable inside a function, but already done at top of the module
448 # from sys import *
449 from sys import path, argv
450 from sys import (path, argv)
451 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +0000452
Thomas Wouters89f507f2006-12-13 04:49:30 +0000453 def testGlobal(self):
454 # 'global' NAME (',' NAME)*
455 global a
456 global a, b
457 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +0000458
Thomas Wouters89f507f2006-12-13 04:49:30 +0000459 def testAssert(self):
460 # assert_stmt: 'assert' test [',' test]
461 assert 1
462 assert 1, 1
463 assert lambda x:x
464 assert 1, lambda x:x+1
Thomas Wouters80d373c2001-09-26 12:43:39 +0000465 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000466 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +0000467 except AssertionError as e:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000468 self.assertEquals(e.args[0], "msg")
469 else:
470 if __debug__:
471 self.fail("AssertionError not raised by assert 0")
Thomas Wouters80d373c2001-09-26 12:43:39 +0000472
Thomas Wouters89f507f2006-12-13 04:49:30 +0000473 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
474 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000475
Thomas Wouters89f507f2006-12-13 04:49:30 +0000476 def testIf(self):
477 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
478 if 1: pass
479 if 1: pass
480 else: pass
481 if 0: pass
482 elif 0: pass
483 if 0: pass
484 elif 0: pass
485 elif 0: pass
486 elif 0: pass
487 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000488
Thomas Wouters89f507f2006-12-13 04:49:30 +0000489 def testWhile(self):
490 # 'while' test ':' suite ['else' ':' suite]
491 while 0: pass
492 while 0: pass
493 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000494
Thomas Wouters89f507f2006-12-13 04:49:30 +0000495 def testFor(self):
496 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
497 for i in 1, 2, 3: pass
498 for i, j, k in (): pass
499 else: pass
500 class Squares:
501 def __init__(self, max):
502 self.max = max
503 self.sofar = []
504 def __len__(self): return len(self.sofar)
505 def __getitem__(self, i):
506 if not 0 <= i < self.max: raise IndexError
507 n = len(self.sofar)
508 while n <= i:
509 self.sofar.append(n*n)
510 n = n+1
511 return self.sofar[i]
512 n = 0
513 for x in Squares(10): n = n+x
514 if n != 285:
515 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000516
Thomas Wouters89f507f2006-12-13 04:49:30 +0000517 result = []
518 for x, in [(1,), (2,), (3,)]:
519 result.append(x)
520 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000521
Thomas Wouters89f507f2006-12-13 04:49:30 +0000522 def testTry(self):
523 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
524 ### | 'try' ':' suite 'finally' ':' suite
Guido van Rossumb940e112007-01-10 16:19:56 +0000525 ### except_clause: 'except' [expr ['as' expr]]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000526 try:
527 1/0
528 except ZeroDivisionError:
529 pass
530 else:
531 pass
532 try: 1/0
533 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000534 except TypeError as msg: pass
535 except RuntimeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000536 except: pass
537 else: pass
538 try: 1/0
539 except (EOFError, TypeError, ZeroDivisionError): pass
540 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000541 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000542 try: pass
543 finally: pass
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000544
Thomas Wouters89f507f2006-12-13 04:49:30 +0000545 def testSuite(self):
546 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
547 if 1: pass
548 if 1:
549 pass
550 if 1:
551 #
552 #
553 #
554 pass
555 pass
556 #
557 pass
558 #
Guido van Rossum3bead091992-01-27 17:00:37 +0000559
Thomas Wouters89f507f2006-12-13 04:49:30 +0000560 def testTest(self):
561 ### and_test ('or' and_test)*
562 ### and_test: not_test ('and' not_test)*
563 ### not_test: 'not' not_test | comparison
564 if not 1: pass
565 if 1 and 1: pass
566 if 1 or 1: pass
567 if not not not 1: pass
568 if not 1 and 1 and 1: pass
569 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000570
Thomas Wouters89f507f2006-12-13 04:49:30 +0000571 def testComparison(self):
572 ### comparison: expr (comp_op expr)*
573 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
574 if 1: pass
575 x = (1 == 1)
576 if 1 == 1: pass
577 if 1 != 1: pass
578 if 1 < 1: pass
579 if 1 > 1: pass
580 if 1 <= 1: pass
581 if 1 >= 1: pass
582 if 1 is 1: pass
583 if 1 is not 1: pass
584 if 1 in (): pass
585 if 1 not in (): pass
586 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 +0000587
Thomas Wouters89f507f2006-12-13 04:49:30 +0000588 def testBinaryMaskOps(self):
589 x = 1 & 1
590 x = 1 ^ 1
591 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000592
Thomas Wouters89f507f2006-12-13 04:49:30 +0000593 def testShiftOps(self):
594 x = 1 << 1
595 x = 1 >> 1
596 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000597
Thomas Wouters89f507f2006-12-13 04:49:30 +0000598 def testAdditiveOps(self):
599 x = 1
600 x = 1 + 1
601 x = 1 - 1 - 1
602 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000603
Thomas Wouters89f507f2006-12-13 04:49:30 +0000604 def testMultiplicativeOps(self):
605 x = 1 * 1
606 x = 1 / 1
607 x = 1 % 1
608 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000609
Thomas Wouters89f507f2006-12-13 04:49:30 +0000610 def testUnaryOps(self):
611 x = +1
612 x = -1
613 x = ~1
614 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
615 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +0000616
Thomas Wouters89f507f2006-12-13 04:49:30 +0000617 def testSelectors(self):
618 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
619 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +0000620
Thomas Wouters89f507f2006-12-13 04:49:30 +0000621 import sys, time
622 c = sys.path[0]
623 x = time.time()
624 x = sys.modules['time'].time()
625 a = '01234'
626 c = a[0]
627 c = a[-1]
628 s = a[0:5]
629 s = a[:5]
630 s = a[0:]
631 s = a[:]
632 s = a[-5:]
633 s = a[:-1]
634 s = a[-4:-3]
635 # A rough test of SF bug 1333982. http://python.org/sf/1333982
636 # The testing here is fairly incomplete.
637 # Test cases should include: commas with 1 and 2 colons
638 d = {}
639 d[1] = 1
640 d[1,] = 2
641 d[1,2] = 3
642 d[1,2,3] = 4
643 L = list(d)
644 L.sort(key=lambda x: x if isinstance(x, tuple) else ())
645 self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +0000646
Thomas Wouters89f507f2006-12-13 04:49:30 +0000647 def testAtoms(self):
648 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
649 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +0000650
Thomas Wouters89f507f2006-12-13 04:49:30 +0000651 x = (1)
652 x = (1 or 2 or 3)
653 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +0000654
Thomas Wouters89f507f2006-12-13 04:49:30 +0000655 x = []
656 x = [1]
657 x = [1 or 2 or 3]
658 x = [1 or 2 or 3, 2, 3]
659 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +0000660
Thomas Wouters89f507f2006-12-13 04:49:30 +0000661 x = {}
662 x = {'one': 1}
663 x = {'one': 1,}
664 x = {'one' or 'two': 1 or 2}
665 x = {'one': 1, 'two': 2}
666 x = {'one': 1, 'two': 2,}
667 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +0000668
Thomas Wouters89f507f2006-12-13 04:49:30 +0000669 x = {'one'}
670 x = {'one', 1,}
671 x = {'one', 'two', 'three'}
672 x = {2, 3, 4,}
673
674 x = x
675 x = 'x'
676 x = 123
677
678 ### exprlist: expr (',' expr)* [',']
679 ### testlist: test (',' test)* [',']
680 # These have been exercised enough above
681
682 def testClassdef(self):
683 # 'class' NAME ['(' [testlist] ')'] ':' suite
684 class B: pass
685 class B2(): pass
686 class C1(B): pass
687 class C2(B): pass
688 class D(C1, C2, B): pass
689 class C:
690 def meth1(self): pass
691 def meth2(self, arg): pass
692 def meth3(self, a1, a2): pass
693
694 def testListcomps(self):
695 # list comprehension tests
696 nums = [1, 2, 3, 4, 5]
697 strs = ["Apple", "Banana", "Coconut"]
698 spcs = [" Apple", " Banana ", "Coco nut "]
699
700 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
701 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
702 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
703 self.assertEqual([(i, s) for i in nums for s in strs],
704 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
705 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
706 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
707 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
708 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
709 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
710 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
711 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
712 (5, 'Banana'), (5, 'Coconut')])
713 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
714 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
715
716 def test_in_func(l):
717 return [0 < x < 3 for x in l if x > 2]
718
719 self.assertEqual(test_in_func(nums), [False, False, False])
720
721 def test_nested_front():
722 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
723 [[1, 2], [3, 4], [5, 6]])
724
725 test_nested_front()
726
727 check_syntax_error(self, "[i, s for i in nums for s in strs]")
728 check_syntax_error(self, "[x if y]")
729
730 suppliers = [
731 (1, "Boeing"),
732 (2, "Ford"),
733 (3, "Macdonalds")
734 ]
735
736 parts = [
737 (10, "Airliner"),
738 (20, "Engine"),
739 (30, "Cheeseburger")
740 ]
741
742 suppart = [
743 (1, 10), (1, 20), (2, 20), (3, 30)
744 ]
745
746 x = [
747 (sname, pname)
748 for (sno, sname) in suppliers
749 for (pno, pname) in parts
750 for (sp_sno, sp_pno) in suppart
751 if sno == sp_sno and pno == sp_pno
752 ]
753
754 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
755 ('Macdonalds', 'Cheeseburger')])
756
757 def testGenexps(self):
758 # generator expression tests
759 g = ([x for x in range(10)] for x in range(1))
Georg Brandla18af4e2007-04-21 15:47:16 +0000760 self.assertEqual(next(g), [x for x in range(10)])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000761 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000762 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000763 self.fail('should produce StopIteration exception')
764 except StopIteration:
765 pass
766
767 a = 1
768 try:
769 g = (a for d in a)
Georg Brandla18af4e2007-04-21 15:47:16 +0000770 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000771 self.fail('should produce TypeError')
772 except TypeError:
773 pass
774
775 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
776 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
777
778 a = [x for x in range(10)]
779 b = (x for x in (y for y in a))
780 self.assertEqual(sum(b), sum([x for x in range(10)]))
781
782 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
783 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
784 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
785 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
786 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
787 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)]))
788 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
789 check_syntax_error(self, "foo(x for x in range(10), 100)")
790 check_syntax_error(self, "foo(100, x for x in range(10))")
791
792 def testComprehensionSpecials(self):
793 # test for outmost iterable precomputation
794 x = 10; g = (i for i in range(x)); x = 5
795 self.assertEqual(len(list(g)), 10)
796
797 # This should hold, since we're only precomputing outmost iterable.
798 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
799 x = 5; t = True;
800 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
801
802 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
803 # even though it's silly. Make sure it works (ifelse broke this.)
804 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
805 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
806
807 # verify unpacking single element tuples in listcomp/genexp.
808 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
809 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
810
811 def testIfElseExpr(self):
812 # Test ifelse expressions in various cases
813 def _checkeval(msg, ret):
814 "helper to check that evaluation of expressions is done correctly"
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000815 print(x)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000816 return ret
817
Nick Coghlan650f0d02007-04-15 12:05:43 +0000818 # the next line is not allowed anymore
819 #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000820 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
821 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])
822 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
823 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
824 self.assertEqual((5 and 6 if 0 else 1), 1)
825 self.assertEqual(((5 and 6) if 0 else 1), 1)
826 self.assertEqual((5 and (6 if 1 else 1)), 6)
827 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
828 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
829 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
830 self.assertEqual((not 5 if 1 else 1), False)
831 self.assertEqual((not 5 if 0 else 1), 1)
832 self.assertEqual((6 + 1 if 1 else 2), 7)
833 self.assertEqual((6 - 1 if 1 else 2), 5)
834 self.assertEqual((6 * 2 if 1 else 4), 12)
835 self.assertEqual((6 / 2 if 1 else 3), 3)
836 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +0000837
Guido van Rossum3bead091992-01-27 17:00:37 +0000838
Thomas Wouters89f507f2006-12-13 04:49:30 +0000839def test_main():
840 run_unittest(TokenTests, GrammarTests)
Guido van Rossum3bead091992-01-27 17:00:37 +0000841
Thomas Wouters89f507f2006-12-13 04:49:30 +0000842if __name__ == '__main__':
843 test_main()