blob: 4c0eda53d3d8fe8cadddc355bc9275835322b329 [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):
Guido van Rossumcd16bf62007-06-13 18:07:49 +000030 self.assertEquals(type(000), type(0))
Thomas Wouters89f507f2006-12-13 04:49:30 +000031 self.assertEquals(0xff, 255)
Guido van Rossumcd16bf62007-06-13 18:07:49 +000032 self.assertEquals(0o377, 255)
33 self.assertEquals(2147483647, 0o17777777777)
34 self.assertEquals(0b1001, 9)
Georg Brandlfceab5a2008-01-19 20:08:23 +000035 # "0x" is not a valid literal
36 self.assertRaises(SyntaxError, eval, "0x")
Christian Heimesa37d4c62007-12-04 23:02:19 +000037 from sys import maxsize
38 if maxsize == 2147483647:
Guido van Rossumcd16bf62007-06-13 18:07:49 +000039 self.assertEquals(-2147483647-1, -0o20000000000)
Thomas Wouters89f507f2006-12-13 04:49:30 +000040 # XXX -2147483648
Guido van Rossumcd16bf62007-06-13 18:07:49 +000041 self.assert_(0o37777777777 > 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +000042 self.assert_(0xffffffff > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +000043 self.assert_(0b1111111111111111111111111111111 > 0)
44 for s in ('2147483648', '0o40000000000', '0x100000000',
45 '0b10000000000000000000000000000000'):
Thomas Wouters89f507f2006-12-13 04:49:30 +000046 try:
47 x = eval(s)
48 except OverflowError:
49 self.fail("OverflowError on huge integer literal %r" % s)
Christian Heimesa37d4c62007-12-04 23:02:19 +000050 elif maxsize == 9223372036854775807:
Guido van Rossumcd16bf62007-06-13 18:07:49 +000051 self.assertEquals(-9223372036854775807-1, -0o1000000000000000000000)
52 self.assert_(0o1777777777777777777777 > 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +000053 self.assert_(0xffffffffffffffff > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +000054 self.assert_(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
55 for s in '9223372036854775808', '0o2000000000000000000000', \
56 '0x10000000000000000', \
57 '0b100000000000000000000000000000000000000000000000000000000000000':
Thomas Wouters89f507f2006-12-13 04:49:30 +000058 try:
59 x = eval(s)
60 except OverflowError:
61 self.fail("OverflowError on huge integer literal %r" % s)
62 else:
Christian Heimesa37d4c62007-12-04 23:02:19 +000063 self.fail('Weird maxsize value %r' % maxsize)
Guido van Rossum3bead091992-01-27 17:00:37 +000064
Thomas Wouters89f507f2006-12-13 04:49:30 +000065 def testLongIntegers(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +000066 x = 0
Guido van Rossume2a383d2007-01-15 16:59:06 +000067 x = 0xffffffffffffffff
Guido van Rossumcd16bf62007-06-13 18:07:49 +000068 x = 0Xffffffffffffffff
69 x = 0o77777777777777777
70 x = 0O77777777777777777
Guido van Rossume2a383d2007-01-15 16:59:06 +000071 x = 123456789012345678901234567890
Guido van Rossumcd16bf62007-06-13 18:07:49 +000072 x = 0b100000000000000000000000000000000000000000000000000000000000000000000
73 x = 0B111111111111111111111111111111111111111111111111111111111111111111111
Guido van Rossum3bead091992-01-27 17:00:37 +000074
Thomas Wouters89f507f2006-12-13 04:49:30 +000075 def testFloats(self):
76 x = 3.14
77 x = 314.
78 x = 0.314
79 # XXX x = 000.314
80 x = .314
81 x = 3e14
82 x = 3E14
83 x = 3e-14
84 x = 3e+14
85 x = 3.e14
86 x = .3e14
87 x = 3.1e4
Guido van Rossum3bead091992-01-27 17:00:37 +000088
Thomas Wouters89f507f2006-12-13 04:49:30 +000089 def testStringLiterals(self):
90 x = ''; y = ""; self.assert_(len(x) == 0 and x == y)
91 x = '\''; y = "'"; self.assert_(len(x) == 1 and x == y and ord(x) == 39)
92 x = '"'; y = "\""; self.assert_(len(x) == 1 and x == y and ord(x) == 34)
93 x = "doesn't \"shrink\" does it"
94 y = 'doesn\'t "shrink" does it'
95 self.assert_(len(x) == 24 and x == y)
96 x = "does \"shrink\" doesn't it"
97 y = 'does "shrink" doesn\'t it'
98 self.assert_(len(x) == 24 and x == y)
99 x = """
Guido van Rossumb6775db1994-08-01 11:34:53 +0000100The "quick"
101brown fox
102jumps over
103the 'lazy' dog.
104"""
Thomas Wouters89f507f2006-12-13 04:49:30 +0000105 y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
106 self.assertEquals(x, y)
107 y = '''
Guido van Rossumb6775db1994-08-01 11:34:53 +0000108The "quick"
109brown fox
110jumps over
111the 'lazy' dog.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000112'''
113 self.assertEquals(x, y)
114 y = "\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000115The \"quick\"\n\
116brown fox\n\
117jumps over\n\
118the 'lazy' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000119"
120 self.assertEquals(x, y)
121 y = '\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000122The \"quick\"\n\
123brown fox\n\
124jumps over\n\
125the \'lazy\' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000126'
127 self.assertEquals(x, y)
128
129 def testEllipsis(self):
130 x = ...
131 self.assert_(x is Ellipsis)
Georg Brandldde00282007-03-18 19:01:53 +0000132 self.assertRaises(SyntaxError, eval, ".. .")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000133
134class GrammarTests(unittest.TestCase):
135
136 # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
137 # XXX can't test in a script -- this rule is only used when interactive
138
139 # file_input: (NEWLINE | stmt)* ENDMARKER
140 # Being tested as this very moment this very module
141
142 # expr_input: testlist NEWLINE
143 # XXX Hard to test -- used only in calls to input()
144
145 def testEvalInput(self):
146 # testlist ENDMARKER
147 x = eval('1, 0 or 1')
148
149 def testFuncdef(self):
Neal Norwitzc1505362006-12-28 06:47:50 +0000150 ### [decorators] 'def' NAME parameters ['->' test] ':' suite
151 ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
152 ### decorators: decorator+
153 ### parameters: '(' [typedargslist] ')'
154 ### typedargslist: ((tfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000155 ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000156 ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000157 ### tfpdef: NAME [':' test]
Neal Norwitzc1505362006-12-28 06:47:50 +0000158 ### varargslist: ((vfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000159 ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000160 ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000161 ### vfpdef: NAME
Thomas Wouters89f507f2006-12-13 04:49:30 +0000162 def f1(): pass
163 f1()
164 f1(*())
165 f1(*(), **{})
166 def f2(one_argument): pass
167 def f3(two, arguments): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000168 self.assertEquals(f2.__code__.co_varnames, ('one_argument',))
169 self.assertEquals(f3.__code__.co_varnames, ('two', 'arguments'))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000170 def a1(one_arg,): pass
171 def a2(two, args,): pass
172 def v0(*rest): pass
173 def v1(a, *rest): pass
174 def v2(a, b, *rest): pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000175
176 f1()
177 f2(1)
178 f2(1,)
179 f3(1, 2)
180 f3(1, 2,)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000181 v0()
182 v0(1)
183 v0(1,)
184 v0(1,2)
185 v0(1,2,3,4,5,6,7,8,9,0)
186 v1(1)
187 v1(1,)
188 v1(1,2)
189 v1(1,2,3)
190 v1(1,2,3,4,5,6,7,8,9,0)
191 v2(1,2)
192 v2(1,2,3)
193 v2(1,2,3,4)
194 v2(1,2,3,4,5,6,7,8,9,0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000195
Thomas Wouters89f507f2006-12-13 04:49:30 +0000196 def d01(a=1): pass
197 d01()
198 d01(1)
199 d01(*(1,))
200 d01(**{'a':2})
201 def d11(a, b=1): pass
202 d11(1)
203 d11(1, 2)
204 d11(1, **{'b':2})
205 def d21(a, b, c=1): pass
206 d21(1, 2)
207 d21(1, 2, 3)
208 d21(*(1, 2, 3))
209 d21(1, *(2, 3))
210 d21(1, 2, *(3,))
211 d21(1, 2, **{'c':3})
212 def d02(a=1, b=2): pass
213 d02()
214 d02(1)
215 d02(1, 2)
216 d02(*(1, 2))
217 d02(1, *(2,))
218 d02(1, **{'b':2})
219 d02(**{'a': 1, 'b': 2})
220 def d12(a, b=1, c=2): pass
221 d12(1)
222 d12(1, 2)
223 d12(1, 2, 3)
224 def d22(a, b, c=1, d=2): pass
225 d22(1, 2)
226 d22(1, 2, 3)
227 d22(1, 2, 3, 4)
228 def d01v(a=1, *rest): pass
229 d01v()
230 d01v(1)
231 d01v(1, 2)
232 d01v(*(1, 2, 3, 4))
233 d01v(*(1,))
234 d01v(**{'a':2})
235 def d11v(a, b=1, *rest): pass
236 d11v(1)
237 d11v(1, 2)
238 d11v(1, 2, 3)
239 def d21v(a, b, c=1, *rest): pass
240 d21v(1, 2)
241 d21v(1, 2, 3)
242 d21v(1, 2, 3, 4)
243 d21v(*(1, 2, 3, 4))
244 d21v(1, 2, **{'c': 3})
245 def d02v(a=1, b=2, *rest): pass
246 d02v()
247 d02v(1)
248 d02v(1, 2)
249 d02v(1, 2, 3)
250 d02v(1, *(2, 3, 4))
251 d02v(**{'a': 1, 'b': 2})
252 def d12v(a, b=1, c=2, *rest): pass
253 d12v(1)
254 d12v(1, 2)
255 d12v(1, 2, 3)
256 d12v(1, 2, 3, 4)
257 d12v(*(1, 2, 3, 4))
258 d12v(1, 2, *(3, 4, 5))
259 d12v(1, *(2,), **{'c': 3})
260 def d22v(a, b, c=1, d=2, *rest): pass
261 d22v(1, 2)
262 d22v(1, 2, 3)
263 d22v(1, 2, 3, 4)
264 d22v(1, 2, 3, 4, 5)
265 d22v(*(1, 2, 3, 4))
266 d22v(1, 2, *(3, 4, 5))
267 d22v(1, *(2, 3), **{'d': 4})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000268 # keyword only argument tests
269 def pos0key1(*, key): return key
270 pos0key1(key=100)
271 def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
272 pos2key2(1, 2, k1=100)
273 pos2key2(1, 2, k1=100, k2=200)
274 pos2key2(1, 2, k2=100, k1=200)
275 def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
276 pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
277 pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
278
Neal Norwitzc1505362006-12-28 06:47:50 +0000279 # argument annotation tests
280 def f(x) -> list: pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000281 self.assertEquals(f.__annotations__, {'return': list})
Neal Norwitzc1505362006-12-28 06:47:50 +0000282 def f(x:int): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000283 self.assertEquals(f.__annotations__, {'x': int})
Neal Norwitzc1505362006-12-28 06:47:50 +0000284 def f(*x:str): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000285 self.assertEquals(f.__annotations__, {'x': str})
Neal Norwitzc1505362006-12-28 06:47:50 +0000286 def f(**x:float): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000287 self.assertEquals(f.__annotations__, {'x': float})
Neal Norwitzc1505362006-12-28 06:47:50 +0000288 def f(x, y:1+2): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000289 self.assertEquals(f.__annotations__, {'y': 3})
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000290 def f(a, b:1, c:2, d): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000291 self.assertEquals(f.__annotations__, {'b': 1, 'c': 2})
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000292 def f(a, b:1, c:2, d, e:3=4, f=5, *g:6): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000293 self.assertEquals(f.__annotations__,
Neal Norwitzc1505362006-12-28 06:47:50 +0000294 {'b': 1, 'c': 2, 'e': 3, 'g': 6})
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000295 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 +0000296 **k:11) -> 12: pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000297 self.assertEquals(f.__annotations__,
Neal Norwitzc1505362006-12-28 06:47:50 +0000298 {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
299 'k': 11, 'return': 12})
Nick Coghlan71011e22007-04-23 11:05:01 +0000300 # Check for SF Bug #1697248 - mixing decorators and a return annotation
301 def null(x): return x
302 @null
303 def f(x) -> list: pass
304 self.assertEquals(f.__annotations__, {'return': list})
305
Guido van Rossum0240b922007-02-26 21:23:50 +0000306 # test MAKE_CLOSURE with a variety of oparg's
307 closure = 1
308 def f(): return closure
309 def f(x=1): return closure
310 def f(*, k=1): return closure
311 def f() -> int: return closure
Neal Norwitzc1505362006-12-28 06:47:50 +0000312
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000313 # Check ast errors in *args and *kwargs
314 check_syntax_error(self, "f(*g(1=2))")
315 check_syntax_error(self, "f(**g(1=2))")
316
Thomas Wouters89f507f2006-12-13 04:49:30 +0000317 def testLambdef(self):
318 ### lambdef: 'lambda' [varargslist] ':' test
319 l1 = lambda : 0
320 self.assertEquals(l1(), 0)
321 l2 = lambda : a[d] # XXX just testing the expression
Guido van Rossume2a383d2007-01-15 16:59:06 +0000322 l3 = lambda : [2 < x for x in [-1, 3, 0]]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000323 self.assertEquals(l3(), [0, 1, 0])
324 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
325 self.assertEquals(l4(), 1)
326 l5 = lambda x, y, z=2: x + y + z
327 self.assertEquals(l5(1, 2), 5)
328 self.assertEquals(l5(1, 2, 3), 6)
329 check_syntax_error(self, "lambda x: x = 2")
330 l6 = lambda x, y, *, k=20: x+y+k
331 self.assertEquals(l6(1,2), 1+2+20)
332 self.assertEquals(l6(1,2,k=10), 1+2+10)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000333
334
Thomas Wouters89f507f2006-12-13 04:49:30 +0000335 ### stmt: simple_stmt | compound_stmt
336 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000337
Thomas Wouters89f507f2006-12-13 04:49:30 +0000338 def testSimpleStmt(self):
339 ### simple_stmt: small_stmt (';' small_stmt)* [';']
340 x = 1; pass; del x
341 def foo():
342 # verify statments that end with semi-colons
343 x = 1; pass; del x;
344 foo()
Georg Brandl52318d62006-09-06 07:06:08 +0000345
Guido van Rossumd8faa362007-04-27 19:54:29 +0000346 ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
Thomas Wouters89f507f2006-12-13 04:49:30 +0000347 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000348
Thomas Wouters89f507f2006-12-13 04:49:30 +0000349 def testExprStmt(self):
350 # (exprlist '=')* exprlist
351 1
352 1, 2, 3
353 x = 1
354 x = 1, 2, 3
355 x = y = z = 1, 2, 3
356 x, y, z = 1, 2, 3
357 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000358
Thomas Wouters89f507f2006-12-13 04:49:30 +0000359 check_syntax_error(self, "x + 1 = 1")
360 check_syntax_error(self, "a + 1 = b + 2")
Guido van Rossum3bead091992-01-27 17:00:37 +0000361
Thomas Wouters89f507f2006-12-13 04:49:30 +0000362 def testDelStmt(self):
363 # 'del' exprlist
364 abc = [1,2,3]
365 x, y, z = abc
366 xyz = x, y, z
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000367
Thomas Wouters89f507f2006-12-13 04:49:30 +0000368 del abc
369 del x, y, (z, xyz)
Barry Warsaw9182b452000-08-29 04:57:10 +0000370
Thomas Wouters89f507f2006-12-13 04:49:30 +0000371 def testPassStmt(self):
372 # 'pass'
373 pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000374
Thomas Wouters89f507f2006-12-13 04:49:30 +0000375 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
376 # Tested below
Barry Warsaw9182b452000-08-29 04:57:10 +0000377
Thomas Wouters89f507f2006-12-13 04:49:30 +0000378 def testBreakStmt(self):
379 # 'break'
380 while 1: break
Barry Warsaw9182b452000-08-29 04:57:10 +0000381
Thomas Wouters89f507f2006-12-13 04:49:30 +0000382 def testContinueStmt(self):
383 # 'continue'
384 i = 1
385 while i: i = 0; continue
Barry Warsaw9182b452000-08-29 04:57:10 +0000386
Thomas Wouters89f507f2006-12-13 04:49:30 +0000387 msg = ""
388 while not msg:
389 msg = "ok"
390 try:
391 continue
392 msg = "continue failed to continue inside try"
393 except:
394 msg = "continue inside try called except block"
395 if msg != "ok":
396 self.fail(msg)
Barry Warsawefc92ee2000-08-21 15:46:50 +0000397
Thomas Wouters89f507f2006-12-13 04:49:30 +0000398 msg = ""
399 while not msg:
400 msg = "finally block not called"
401 try:
402 continue
403 finally:
404 msg = "ok"
405 if msg != "ok":
406 self.fail(msg)
Guido van Rossum3bead091992-01-27 17:00:37 +0000407
Thomas Wouters89f507f2006-12-13 04:49:30 +0000408 def test_break_continue_loop(self):
409 # This test warrants an explanation. It is a test specifically for SF bugs
410 # #463359 and #462937. The bug is that a 'break' statement executed or
411 # exception raised inside a try/except inside a loop, *after* a continue
412 # statement has been executed in that loop, will cause the wrong number of
413 # arguments to be popped off the stack and the instruction pointer reset to
414 # a very small number (usually 0.) Because of this, the following test
415 # *must* written as a function, and the tracking vars *must* be function
416 # arguments with default values. Otherwise, the test will loop and loop.
Guido van Rossum3bead091992-01-27 17:00:37 +0000417
Thomas Wouters89f507f2006-12-13 04:49:30 +0000418 def test_inner(extra_burning_oil = 1, count=0):
419 big_hippo = 2
420 while big_hippo:
421 count += 1
422 try:
423 if extra_burning_oil and big_hippo == 1:
424 extra_burning_oil -= 1
425 break
426 big_hippo -= 1
427 continue
428 except:
429 raise
430 if count > 2 or big_hippo != 1:
431 self.fail("continue then break in try/except in loop broken!")
432 test_inner()
Guido van Rossum3bead091992-01-27 17:00:37 +0000433
Thomas Wouters89f507f2006-12-13 04:49:30 +0000434 def testReturn(self):
435 # 'return' [testlist]
436 def g1(): return
437 def g2(): return 1
438 g1()
439 x = g2()
440 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000441
Thomas Wouters89f507f2006-12-13 04:49:30 +0000442 def testYield(self):
443 check_syntax_error(self, "class foo:yield 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000444
Thomas Wouters89f507f2006-12-13 04:49:30 +0000445 def testRaise(self):
446 # 'raise' test [',' test]
Collin Winter828f04a2007-08-31 00:04:24 +0000447 try: raise RuntimeError('just testing')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000448 except RuntimeError: pass
449 try: raise KeyboardInterrupt
450 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000451
Thomas Wouters89f507f2006-12-13 04:49:30 +0000452 def testImport(self):
453 # 'import' dotted_as_names
454 import sys
455 import time, sys
456 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
457 from time import time
458 from time import (time)
459 # not testable inside a function, but already done at top of the module
460 # from sys import *
461 from sys import path, argv
462 from sys import (path, argv)
463 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +0000464
Thomas Wouters89f507f2006-12-13 04:49:30 +0000465 def testGlobal(self):
466 # 'global' NAME (',' NAME)*
467 global a
468 global a, b
469 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +0000470
Thomas Wouters89f507f2006-12-13 04:49:30 +0000471 def testAssert(self):
472 # assert_stmt: 'assert' test [',' test]
473 assert 1
474 assert 1, 1
475 assert lambda x:x
476 assert 1, lambda x:x+1
Thomas Wouters80d373c2001-09-26 12:43:39 +0000477 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000478 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +0000479 except AssertionError as e:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000480 self.assertEquals(e.args[0], "msg")
481 else:
482 if __debug__:
483 self.fail("AssertionError not raised by assert 0")
Thomas Wouters80d373c2001-09-26 12:43:39 +0000484
Thomas Wouters89f507f2006-12-13 04:49:30 +0000485 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
486 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000487
Thomas Wouters89f507f2006-12-13 04:49:30 +0000488 def testIf(self):
489 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
490 if 1: pass
491 if 1: pass
492 else: pass
493 if 0: pass
494 elif 0: pass
495 if 0: pass
496 elif 0: pass
497 elif 0: pass
498 elif 0: pass
499 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000500
Thomas Wouters89f507f2006-12-13 04:49:30 +0000501 def testWhile(self):
502 # 'while' test ':' suite ['else' ':' suite]
503 while 0: pass
504 while 0: pass
505 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000506
Christian Heimes969fe572008-01-25 11:23:10 +0000507 # Issue1920: "while 0" is optimized away,
508 # ensure that the "else" clause is still present.
509 x = 0
510 while 0:
511 x = 1
512 else:
513 x = 2
514 self.assertEquals(x, 2)
515
Thomas Wouters89f507f2006-12-13 04:49:30 +0000516 def testFor(self):
517 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
518 for i in 1, 2, 3: pass
519 for i, j, k in (): pass
520 else: pass
521 class Squares:
522 def __init__(self, max):
523 self.max = max
524 self.sofar = []
525 def __len__(self): return len(self.sofar)
526 def __getitem__(self, i):
527 if not 0 <= i < self.max: raise IndexError
528 n = len(self.sofar)
529 while n <= i:
530 self.sofar.append(n*n)
531 n = n+1
532 return self.sofar[i]
533 n = 0
534 for x in Squares(10): n = n+x
535 if n != 285:
536 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000537
Thomas Wouters89f507f2006-12-13 04:49:30 +0000538 result = []
539 for x, in [(1,), (2,), (3,)]:
540 result.append(x)
541 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000542
Thomas Wouters89f507f2006-12-13 04:49:30 +0000543 def testTry(self):
544 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
545 ### | 'try' ':' suite 'finally' ':' suite
Guido van Rossumb940e112007-01-10 16:19:56 +0000546 ### except_clause: 'except' [expr ['as' expr]]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000547 try:
548 1/0
549 except ZeroDivisionError:
550 pass
551 else:
552 pass
553 try: 1/0
554 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000555 except TypeError as msg: pass
556 except RuntimeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000557 except: pass
558 else: pass
559 try: 1/0
560 except (EOFError, TypeError, ZeroDivisionError): pass
561 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000562 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000563 try: pass
564 finally: pass
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000565
Thomas Wouters89f507f2006-12-13 04:49:30 +0000566 def testSuite(self):
567 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
568 if 1: pass
569 if 1:
570 pass
571 if 1:
572 #
573 #
574 #
575 pass
576 pass
577 #
578 pass
579 #
Guido van Rossum3bead091992-01-27 17:00:37 +0000580
Thomas Wouters89f507f2006-12-13 04:49:30 +0000581 def testTest(self):
582 ### and_test ('or' and_test)*
583 ### and_test: not_test ('and' not_test)*
584 ### not_test: 'not' not_test | comparison
585 if not 1: pass
586 if 1 and 1: pass
587 if 1 or 1: pass
588 if not not not 1: pass
589 if not 1 and 1 and 1: pass
590 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000591
Thomas Wouters89f507f2006-12-13 04:49:30 +0000592 def testComparison(self):
593 ### comparison: expr (comp_op expr)*
594 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
595 if 1: pass
596 x = (1 == 1)
597 if 1 == 1: pass
598 if 1 != 1: pass
599 if 1 < 1: pass
600 if 1 > 1: pass
601 if 1 <= 1: pass
602 if 1 >= 1: pass
603 if 1 is 1: pass
604 if 1 is not 1: pass
605 if 1 in (): pass
606 if 1 not in (): pass
607 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 +0000608
Thomas Wouters89f507f2006-12-13 04:49:30 +0000609 def testBinaryMaskOps(self):
610 x = 1 & 1
611 x = 1 ^ 1
612 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000613
Thomas Wouters89f507f2006-12-13 04:49:30 +0000614 def testShiftOps(self):
615 x = 1 << 1
616 x = 1 >> 1
617 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000618
Thomas Wouters89f507f2006-12-13 04:49:30 +0000619 def testAdditiveOps(self):
620 x = 1
621 x = 1 + 1
622 x = 1 - 1 - 1
623 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000624
Thomas Wouters89f507f2006-12-13 04:49:30 +0000625 def testMultiplicativeOps(self):
626 x = 1 * 1
627 x = 1 / 1
628 x = 1 % 1
629 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000630
Thomas Wouters89f507f2006-12-13 04:49:30 +0000631 def testUnaryOps(self):
632 x = +1
633 x = -1
634 x = ~1
635 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
636 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +0000637
Thomas Wouters89f507f2006-12-13 04:49:30 +0000638 def testSelectors(self):
639 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
640 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +0000641
Thomas Wouters89f507f2006-12-13 04:49:30 +0000642 import sys, time
643 c = sys.path[0]
644 x = time.time()
645 x = sys.modules['time'].time()
646 a = '01234'
647 c = a[0]
648 c = a[-1]
649 s = a[0:5]
650 s = a[:5]
651 s = a[0:]
652 s = a[:]
653 s = a[-5:]
654 s = a[:-1]
655 s = a[-4:-3]
656 # A rough test of SF bug 1333982. http://python.org/sf/1333982
657 # The testing here is fairly incomplete.
658 # Test cases should include: commas with 1 and 2 colons
659 d = {}
660 d[1] = 1
661 d[1,] = 2
662 d[1,2] = 3
663 d[1,2,3] = 4
664 L = list(d)
665 L.sort(key=lambda x: x if isinstance(x, tuple) else ())
666 self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +0000667
Thomas Wouters89f507f2006-12-13 04:49:30 +0000668 def testAtoms(self):
669 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
670 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +0000671
Thomas Wouters89f507f2006-12-13 04:49:30 +0000672 x = (1)
673 x = (1 or 2 or 3)
674 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +0000675
Thomas Wouters89f507f2006-12-13 04:49:30 +0000676 x = []
677 x = [1]
678 x = [1 or 2 or 3]
679 x = [1 or 2 or 3, 2, 3]
680 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +0000681
Thomas Wouters89f507f2006-12-13 04:49:30 +0000682 x = {}
683 x = {'one': 1}
684 x = {'one': 1,}
685 x = {'one' or 'two': 1 or 2}
686 x = {'one': 1, 'two': 2}
687 x = {'one': 1, 'two': 2,}
688 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +0000689
Thomas Wouters89f507f2006-12-13 04:49:30 +0000690 x = {'one'}
691 x = {'one', 1,}
692 x = {'one', 'two', 'three'}
693 x = {2, 3, 4,}
694
695 x = x
696 x = 'x'
697 x = 123
698
699 ### exprlist: expr (',' expr)* [',']
700 ### testlist: test (',' test)* [',']
701 # These have been exercised enough above
702
703 def testClassdef(self):
704 # 'class' NAME ['(' [testlist] ')'] ':' suite
705 class B: pass
706 class B2(): pass
707 class C1(B): pass
708 class C2(B): pass
709 class D(C1, C2, B): pass
710 class C:
711 def meth1(self): pass
712 def meth2(self, arg): pass
713 def meth3(self, a1, a2): pass
714
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000715 # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
716 # decorators: decorator+
717 # decorated: decorators (classdef | funcdef)
718 def class_decorator(x): return x
719 @class_decorator
720 class G: pass
721
722 def testDictcomps(self):
723 # dictorsetmaker: ( (test ':' test (comp_for |
724 # (',' test ':' test)* [','])) |
725 # (test (comp_for | (',' test)* [','])) )
726 nums = [1, 2, 3]
727 self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
728
Thomas Wouters89f507f2006-12-13 04:49:30 +0000729 def testListcomps(self):
730 # list comprehension tests
731 nums = [1, 2, 3, 4, 5]
732 strs = ["Apple", "Banana", "Coconut"]
733 spcs = [" Apple", " Banana ", "Coco nut "]
734
735 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
736 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
737 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
738 self.assertEqual([(i, s) for i in nums for s in strs],
739 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
740 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
741 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
742 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
743 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
744 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
745 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
746 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
747 (5, 'Banana'), (5, 'Coconut')])
748 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
749 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
750
751 def test_in_func(l):
752 return [0 < x < 3 for x in l if x > 2]
753
754 self.assertEqual(test_in_func(nums), [False, False, False])
755
756 def test_nested_front():
757 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
758 [[1, 2], [3, 4], [5, 6]])
759
760 test_nested_front()
761
762 check_syntax_error(self, "[i, s for i in nums for s in strs]")
763 check_syntax_error(self, "[x if y]")
764
765 suppliers = [
766 (1, "Boeing"),
767 (2, "Ford"),
768 (3, "Macdonalds")
769 ]
770
771 parts = [
772 (10, "Airliner"),
773 (20, "Engine"),
774 (30, "Cheeseburger")
775 ]
776
777 suppart = [
778 (1, 10), (1, 20), (2, 20), (3, 30)
779 ]
780
781 x = [
782 (sname, pname)
783 for (sno, sname) in suppliers
784 for (pno, pname) in parts
785 for (sp_sno, sp_pno) in suppart
786 if sno == sp_sno and pno == sp_pno
787 ]
788
789 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
790 ('Macdonalds', 'Cheeseburger')])
791
792 def testGenexps(self):
793 # generator expression tests
794 g = ([x for x in range(10)] for x in range(1))
Georg Brandla18af4e2007-04-21 15:47:16 +0000795 self.assertEqual(next(g), [x for x in range(10)])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000796 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000797 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000798 self.fail('should produce StopIteration exception')
799 except StopIteration:
800 pass
801
802 a = 1
803 try:
804 g = (a for d in a)
Georg Brandla18af4e2007-04-21 15:47:16 +0000805 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000806 self.fail('should produce TypeError')
807 except TypeError:
808 pass
809
810 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
811 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
812
813 a = [x for x in range(10)]
814 b = (x for x in (y for y in a))
815 self.assertEqual(sum(b), sum([x for x in range(10)]))
816
817 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
818 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
819 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
820 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
821 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
822 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)]))
823 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
824 check_syntax_error(self, "foo(x for x in range(10), 100)")
825 check_syntax_error(self, "foo(100, x for x in range(10))")
826
827 def testComprehensionSpecials(self):
828 # test for outmost iterable precomputation
829 x = 10; g = (i for i in range(x)); x = 5
830 self.assertEqual(len(list(g)), 10)
831
832 # This should hold, since we're only precomputing outmost iterable.
833 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
834 x = 5; t = True;
835 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
836
837 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
838 # even though it's silly. Make sure it works (ifelse broke this.)
839 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
840 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
841
842 # verify unpacking single element tuples in listcomp/genexp.
843 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
844 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
845
846 def testIfElseExpr(self):
847 # Test ifelse expressions in various cases
848 def _checkeval(msg, ret):
849 "helper to check that evaluation of expressions is done correctly"
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000850 print(x)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000851 return ret
852
Nick Coghlan650f0d02007-04-15 12:05:43 +0000853 # the next line is not allowed anymore
854 #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000855 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
856 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])
857 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
858 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
859 self.assertEqual((5 and 6 if 0 else 1), 1)
860 self.assertEqual(((5 and 6) if 0 else 1), 1)
861 self.assertEqual((5 and (6 if 1 else 1)), 6)
862 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
863 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
864 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
865 self.assertEqual((not 5 if 1 else 1), False)
866 self.assertEqual((not 5 if 0 else 1), 1)
867 self.assertEqual((6 + 1 if 1 else 2), 7)
868 self.assertEqual((6 - 1 if 1 else 2), 5)
869 self.assertEqual((6 * 2 if 1 else 4), 12)
870 self.assertEqual((6 / 2 if 1 else 3), 3)
871 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +0000872
Guido van Rossum3bead091992-01-27 17:00:37 +0000873
Thomas Wouters89f507f2006-12-13 04:49:30 +0000874def test_main():
875 run_unittest(TokenTests, GrammarTests)
Guido van Rossum3bead091992-01-27 17:00:37 +0000876
Thomas Wouters89f507f2006-12-13 04:49:30 +0000877if __name__ == '__main__':
878 test_main()