blob: 1a1475628e5db3c67a0c5bb34a27af7cce5108ed [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)
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):
Neal Norwitzc1505362006-12-28 06:47:50 +0000141 ### [decorators] 'def' NAME parameters ['->' test] ':' suite
142 ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
143 ### decorators: decorator+
144 ### parameters: '(' [typedargslist] ')'
145 ### typedargslist: ((tfpdef ['=' test] ',')*
146 ### ('*' [tname] (',' tname ['=' test])* [',' '**' tname] | '**' tname)
147 ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
148 ### tname: NAME [':' test]
149 ### tfpdef: tname | '(' tfplist ')'
150 ### tfplist: tfpdef (',' tfpdef)* [',']
151 ### varargslist: ((vfpdef ['=' test] ',')*
152 ### ('*' [vname] (',' vname ['=' test])* [',' '**' vname] | '**' vname)
153 ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
154 ### vname: NAME
155 ### vfpdef: vname | '(' vfplist ')'
156 ### vfplist: vfpdef (',' vfpdef)* [',']
Thomas Wouters89f507f2006-12-13 04:49:30 +0000157 def f1(): pass
158 f1()
159 f1(*())
160 f1(*(), **{})
161 def f2(one_argument): pass
162 def f3(two, arguments): pass
163 def f4(two, (compound, (argument, list))): pass
164 def f5((compound, first), two): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000165 self.assertEquals(f2.__code__.co_varnames, ('one_argument',))
166 self.assertEquals(f3.__code__.co_varnames, ('two', 'arguments'))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000167 if sys.platform.startswith('java'):
Neal Norwitz221085d2007-02-25 20:55:47 +0000168 self.assertEquals(f4.__code__.co_varnames,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000169 ('two', '(compound, (argument, list))', 'compound', 'argument',
170 'list',))
Neal Norwitz221085d2007-02-25 20:55:47 +0000171 self.assertEquals(f5.__code__.co_varnames,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000172 ('(compound, first)', 'two', 'compound', 'first'))
173 else:
Neal Norwitz221085d2007-02-25 20:55:47 +0000174 self.assertEquals(f4.__code__.co_varnames,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000175 ('two', '.1', 'compound', 'argument', 'list'))
Neal Norwitz221085d2007-02-25 20:55:47 +0000176 self.assertEquals(f5.__code__.co_varnames,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000177 ('.0', 'two', 'compound', 'first'))
178 def a1(one_arg,): pass
179 def a2(two, args,): pass
180 def v0(*rest): pass
181 def v1(a, *rest): pass
182 def v2(a, b, *rest): pass
183 def v3(a, (b, c), *rest): return a, b, c, rest
184
185 f1()
186 f2(1)
187 f2(1,)
188 f3(1, 2)
189 f3(1, 2,)
190 f4(1, (2, (3, 4)))
191 v0()
192 v0(1)
193 v0(1,)
194 v0(1,2)
195 v0(1,2,3,4,5,6,7,8,9,0)
196 v1(1)
197 v1(1,)
198 v1(1,2)
199 v1(1,2,3)
200 v1(1,2,3,4,5,6,7,8,9,0)
201 v2(1,2)
202 v2(1,2,3)
203 v2(1,2,3,4)
204 v2(1,2,3,4,5,6,7,8,9,0)
205 v3(1,(2,3))
206 v3(1,(2,3),4)
207 v3(1,(2,3),4,5,6,7,8,9,0)
208
209 # ceval unpacks the formal arguments into the first argcount names;
210 # thus, the names nested inside tuples must appear after these names.
211 if sys.platform.startswith('java'):
Neal Norwitz221085d2007-02-25 20:55:47 +0000212 self.assertEquals(v3.__code__.co_varnames, ('a', '(b, c)', 'rest', 'b', 'c'))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000213 else:
Neal Norwitz221085d2007-02-25 20:55:47 +0000214 self.assertEquals(v3.__code__.co_varnames, ('a', '.1', 'rest', 'b', 'c'))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000215 self.assertEquals(v3(1, (2, 3), 4), (1, 2, 3, (4,)))
216 def d01(a=1): pass
217 d01()
218 d01(1)
219 d01(*(1,))
220 d01(**{'a':2})
221 def d11(a, b=1): pass
222 d11(1)
223 d11(1, 2)
224 d11(1, **{'b':2})
225 def d21(a, b, c=1): pass
226 d21(1, 2)
227 d21(1, 2, 3)
228 d21(*(1, 2, 3))
229 d21(1, *(2, 3))
230 d21(1, 2, *(3,))
231 d21(1, 2, **{'c':3})
232 def d02(a=1, b=2): pass
233 d02()
234 d02(1)
235 d02(1, 2)
236 d02(*(1, 2))
237 d02(1, *(2,))
238 d02(1, **{'b':2})
239 d02(**{'a': 1, 'b': 2})
240 def d12(a, b=1, c=2): pass
241 d12(1)
242 d12(1, 2)
243 d12(1, 2, 3)
244 def d22(a, b, c=1, d=2): pass
245 d22(1, 2)
246 d22(1, 2, 3)
247 d22(1, 2, 3, 4)
248 def d01v(a=1, *rest): pass
249 d01v()
250 d01v(1)
251 d01v(1, 2)
252 d01v(*(1, 2, 3, 4))
253 d01v(*(1,))
254 d01v(**{'a':2})
255 def d11v(a, b=1, *rest): pass
256 d11v(1)
257 d11v(1, 2)
258 d11v(1, 2, 3)
259 def d21v(a, b, c=1, *rest): pass
260 d21v(1, 2)
261 d21v(1, 2, 3)
262 d21v(1, 2, 3, 4)
263 d21v(*(1, 2, 3, 4))
264 d21v(1, 2, **{'c': 3})
265 def d02v(a=1, b=2, *rest): pass
266 d02v()
267 d02v(1)
268 d02v(1, 2)
269 d02v(1, 2, 3)
270 d02v(1, *(2, 3, 4))
271 d02v(**{'a': 1, 'b': 2})
272 def d12v(a, b=1, c=2, *rest): pass
273 d12v(1)
274 d12v(1, 2)
275 d12v(1, 2, 3)
276 d12v(1, 2, 3, 4)
277 d12v(*(1, 2, 3, 4))
278 d12v(1, 2, *(3, 4, 5))
279 d12v(1, *(2,), **{'c': 3})
280 def d22v(a, b, c=1, d=2, *rest): pass
281 d22v(1, 2)
282 d22v(1, 2, 3)
283 d22v(1, 2, 3, 4)
284 d22v(1, 2, 3, 4, 5)
285 d22v(*(1, 2, 3, 4))
286 d22v(1, 2, *(3, 4, 5))
287 d22v(1, *(2, 3), **{'d': 4})
288 def d31v((x)): pass
289 d31v(1)
290 def d32v((x,)): pass
291 d32v((1,))
292 # keyword only argument tests
293 def pos0key1(*, key): return key
294 pos0key1(key=100)
295 def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
296 pos2key2(1, 2, k1=100)
297 pos2key2(1, 2, k1=100, k2=200)
298 pos2key2(1, 2, k2=100, k1=200)
299 def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
300 pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
301 pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
302
Neal Norwitzc1505362006-12-28 06:47:50 +0000303 # argument annotation tests
304 def f(x) -> list: pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000305 self.assertEquals(f.__annotations__, {'return': list})
Neal Norwitzc1505362006-12-28 06:47:50 +0000306 def f(x:int): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000307 self.assertEquals(f.__annotations__, {'x': int})
Neal Norwitzc1505362006-12-28 06:47:50 +0000308 def f(*x:str): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000309 self.assertEquals(f.__annotations__, {'x': str})
Neal Norwitzc1505362006-12-28 06:47:50 +0000310 def f(**x:float): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000311 self.assertEquals(f.__annotations__, {'x': float})
Neal Norwitzc1505362006-12-28 06:47:50 +0000312 def f(x, y:1+2): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000313 self.assertEquals(f.__annotations__, {'y': 3})
Neal Norwitzc1505362006-12-28 06:47:50 +0000314 def f(a, (b:1, c:2, d)): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000315 self.assertEquals(f.__annotations__, {'b': 1, 'c': 2})
Neal Norwitzc1505362006-12-28 06:47:50 +0000316 def f(a, (b:1, c:2, d), e:3=4, f=5, *g:6): pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000317 self.assertEquals(f.__annotations__,
Neal Norwitzc1505362006-12-28 06:47:50 +0000318 {'b': 1, 'c': 2, 'e': 3, 'g': 6})
319 def f(a, (b:1, c:2, d), e:3=4, f=5, *g:6, h:7, i=8, j:9=10,
320 **k:11) -> 12: pass
Neal Norwitz221085d2007-02-25 20:55:47 +0000321 self.assertEquals(f.__annotations__,
Neal Norwitzc1505362006-12-28 06:47:50 +0000322 {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
323 'k': 11, 'return': 12})
Guido van Rossum0240b922007-02-26 21:23:50 +0000324
325 # test MAKE_CLOSURE with a variety of oparg's
326 closure = 1
327 def f(): return closure
328 def f(x=1): return closure
329 def f(*, k=1): return closure
330 def f() -> int: return closure
Neal Norwitzc1505362006-12-28 06:47:50 +0000331
Thomas Wouters89f507f2006-12-13 04:49:30 +0000332 def testLambdef(self):
333 ### lambdef: 'lambda' [varargslist] ':' test
334 l1 = lambda : 0
335 self.assertEquals(l1(), 0)
336 l2 = lambda : a[d] # XXX just testing the expression
Guido van Rossume2a383d2007-01-15 16:59:06 +0000337 l3 = lambda : [2 < x for x in [-1, 3, 0]]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000338 self.assertEquals(l3(), [0, 1, 0])
339 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
340 self.assertEquals(l4(), 1)
341 l5 = lambda x, y, z=2: x + y + z
342 self.assertEquals(l5(1, 2), 5)
343 self.assertEquals(l5(1, 2, 3), 6)
344 check_syntax_error(self, "lambda x: x = 2")
345 l6 = lambda x, y, *, k=20: x+y+k
346 self.assertEquals(l6(1,2), 1+2+20)
347 self.assertEquals(l6(1,2,k=10), 1+2+10)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000348
349
Thomas Wouters89f507f2006-12-13 04:49:30 +0000350 ### stmt: simple_stmt | compound_stmt
351 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000352
Thomas Wouters89f507f2006-12-13 04:49:30 +0000353 def testSimpleStmt(self):
354 ### simple_stmt: small_stmt (';' small_stmt)* [';']
355 x = 1; pass; del x
356 def foo():
357 # verify statments that end with semi-colons
358 x = 1; pass; del x;
359 foo()
Georg Brandl52318d62006-09-06 07:06:08 +0000360
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000361 ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
Thomas Wouters89f507f2006-12-13 04:49:30 +0000362 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000363
Thomas Wouters89f507f2006-12-13 04:49:30 +0000364 def testExprStmt(self):
365 # (exprlist '=')* exprlist
366 1
367 1, 2, 3
368 x = 1
369 x = 1, 2, 3
370 x = y = z = 1, 2, 3
371 x, y, z = 1, 2, 3
372 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000373
Thomas Wouters89f507f2006-12-13 04:49:30 +0000374 check_syntax_error(self, "x + 1 = 1")
375 check_syntax_error(self, "a + 1 = b + 2")
Guido van Rossum3bead091992-01-27 17:00:37 +0000376
Thomas Wouters89f507f2006-12-13 04:49:30 +0000377 def testDelStmt(self):
378 # 'del' exprlist
379 abc = [1,2,3]
380 x, y, z = abc
381 xyz = x, y, z
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000382
Thomas Wouters89f507f2006-12-13 04:49:30 +0000383 del abc
384 del x, y, (z, xyz)
Barry Warsaw9182b452000-08-29 04:57:10 +0000385
Thomas Wouters89f507f2006-12-13 04:49:30 +0000386 def testPassStmt(self):
387 # 'pass'
388 pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000389
Thomas Wouters89f507f2006-12-13 04:49:30 +0000390 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
391 # Tested below
Barry Warsaw9182b452000-08-29 04:57:10 +0000392
Thomas Wouters89f507f2006-12-13 04:49:30 +0000393 def testBreakStmt(self):
394 # 'break'
395 while 1: break
Barry Warsaw9182b452000-08-29 04:57:10 +0000396
Thomas Wouters89f507f2006-12-13 04:49:30 +0000397 def testContinueStmt(self):
398 # 'continue'
399 i = 1
400 while i: i = 0; continue
Barry Warsaw9182b452000-08-29 04:57:10 +0000401
Thomas Wouters89f507f2006-12-13 04:49:30 +0000402 msg = ""
403 while not msg:
404 msg = "ok"
405 try:
406 continue
407 msg = "continue failed to continue inside try"
408 except:
409 msg = "continue inside try called except block"
410 if msg != "ok":
411 self.fail(msg)
Barry Warsawefc92ee2000-08-21 15:46:50 +0000412
Thomas Wouters89f507f2006-12-13 04:49:30 +0000413 msg = ""
414 while not msg:
415 msg = "finally block not called"
416 try:
417 continue
418 finally:
419 msg = "ok"
420 if msg != "ok":
421 self.fail(msg)
Guido van Rossum3bead091992-01-27 17:00:37 +0000422
Thomas Wouters89f507f2006-12-13 04:49:30 +0000423 def test_break_continue_loop(self):
424 # This test warrants an explanation. It is a test specifically for SF bugs
425 # #463359 and #462937. The bug is that a 'break' statement executed or
426 # exception raised inside a try/except inside a loop, *after* a continue
427 # statement has been executed in that loop, will cause the wrong number of
428 # arguments to be popped off the stack and the instruction pointer reset to
429 # a very small number (usually 0.) Because of this, the following test
430 # *must* written as a function, and the tracking vars *must* be function
431 # arguments with default values. Otherwise, the test will loop and loop.
Guido van Rossum3bead091992-01-27 17:00:37 +0000432
Thomas Wouters89f507f2006-12-13 04:49:30 +0000433 def test_inner(extra_burning_oil = 1, count=0):
434 big_hippo = 2
435 while big_hippo:
436 count += 1
437 try:
438 if extra_burning_oil and big_hippo == 1:
439 extra_burning_oil -= 1
440 break
441 big_hippo -= 1
442 continue
443 except:
444 raise
445 if count > 2 or big_hippo != 1:
446 self.fail("continue then break in try/except in loop broken!")
447 test_inner()
Guido van Rossum3bead091992-01-27 17:00:37 +0000448
Thomas Wouters89f507f2006-12-13 04:49:30 +0000449 def testReturn(self):
450 # 'return' [testlist]
451 def g1(): return
452 def g2(): return 1
453 g1()
454 x = g2()
455 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000456
Thomas Wouters89f507f2006-12-13 04:49:30 +0000457 def testYield(self):
458 check_syntax_error(self, "class foo:yield 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000459
Thomas Wouters89f507f2006-12-13 04:49:30 +0000460 def testRaise(self):
461 # 'raise' test [',' test]
462 try: raise RuntimeError, 'just testing'
463 except RuntimeError: pass
464 try: raise KeyboardInterrupt
465 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000466
Thomas Wouters89f507f2006-12-13 04:49:30 +0000467 def testImport(self):
468 # 'import' dotted_as_names
469 import sys
470 import time, sys
471 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
472 from time import time
473 from time import (time)
474 # not testable inside a function, but already done at top of the module
475 # from sys import *
476 from sys import path, argv
477 from sys import (path, argv)
478 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +0000479
Thomas Wouters89f507f2006-12-13 04:49:30 +0000480 def testGlobal(self):
481 # 'global' NAME (',' NAME)*
482 global a
483 global a, b
484 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +0000485
Thomas Wouters89f507f2006-12-13 04:49:30 +0000486 def testAssert(self):
487 # assert_stmt: 'assert' test [',' test]
488 assert 1
489 assert 1, 1
490 assert lambda x:x
491 assert 1, lambda x:x+1
Thomas Wouters80d373c2001-09-26 12:43:39 +0000492 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000493 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +0000494 except AssertionError as e:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000495 self.assertEquals(e.args[0], "msg")
496 else:
497 if __debug__:
498 self.fail("AssertionError not raised by assert 0")
Thomas Wouters80d373c2001-09-26 12:43:39 +0000499
Thomas Wouters89f507f2006-12-13 04:49:30 +0000500 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
501 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000502
Thomas Wouters89f507f2006-12-13 04:49:30 +0000503 def testIf(self):
504 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
505 if 1: pass
506 if 1: pass
507 else: pass
508 if 0: pass
509 elif 0: pass
510 if 0: pass
511 elif 0: pass
512 elif 0: pass
513 elif 0: pass
514 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000515
Thomas Wouters89f507f2006-12-13 04:49:30 +0000516 def testWhile(self):
517 # 'while' test ':' suite ['else' ':' suite]
518 while 0: pass
519 while 0: pass
520 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000521
Thomas Wouters89f507f2006-12-13 04:49:30 +0000522 def testFor(self):
523 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
524 for i in 1, 2, 3: pass
525 for i, j, k in (): pass
526 else: pass
527 class Squares:
528 def __init__(self, max):
529 self.max = max
530 self.sofar = []
531 def __len__(self): return len(self.sofar)
532 def __getitem__(self, i):
533 if not 0 <= i < self.max: raise IndexError
534 n = len(self.sofar)
535 while n <= i:
536 self.sofar.append(n*n)
537 n = n+1
538 return self.sofar[i]
539 n = 0
540 for x in Squares(10): n = n+x
541 if n != 285:
542 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000543
Thomas Wouters89f507f2006-12-13 04:49:30 +0000544 result = []
545 for x, in [(1,), (2,), (3,)]:
546 result.append(x)
547 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000548
Thomas Wouters89f507f2006-12-13 04:49:30 +0000549 def testTry(self):
550 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
551 ### | 'try' ':' suite 'finally' ':' suite
Guido van Rossumb940e112007-01-10 16:19:56 +0000552 ### except_clause: 'except' [expr ['as' expr]]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000553 try:
554 1/0
555 except ZeroDivisionError:
556 pass
557 else:
558 pass
559 try: 1/0
560 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000561 except TypeError as msg: pass
562 except RuntimeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000563 except: pass
564 else: pass
565 try: 1/0
566 except (EOFError, TypeError, ZeroDivisionError): pass
567 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000568 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000569 try: pass
570 finally: pass
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000571
Thomas Wouters89f507f2006-12-13 04:49:30 +0000572 def testSuite(self):
573 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
574 if 1: pass
575 if 1:
576 pass
577 if 1:
578 #
579 #
580 #
581 pass
582 pass
583 #
584 pass
585 #
Guido van Rossum3bead091992-01-27 17:00:37 +0000586
Thomas Wouters89f507f2006-12-13 04:49:30 +0000587 def testTest(self):
588 ### and_test ('or' and_test)*
589 ### and_test: not_test ('and' not_test)*
590 ### not_test: 'not' not_test | comparison
591 if not 1: pass
592 if 1 and 1: pass
593 if 1 or 1: pass
594 if not not not 1: pass
595 if not 1 and 1 and 1: pass
596 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000597
Thomas Wouters89f507f2006-12-13 04:49:30 +0000598 def testComparison(self):
599 ### comparison: expr (comp_op expr)*
600 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
601 if 1: pass
602 x = (1 == 1)
603 if 1 == 1: pass
604 if 1 != 1: pass
605 if 1 < 1: pass
606 if 1 > 1: pass
607 if 1 <= 1: pass
608 if 1 >= 1: pass
609 if 1 is 1: pass
610 if 1 is not 1: pass
611 if 1 in (): pass
612 if 1 not in (): pass
613 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 +0000614
Thomas Wouters89f507f2006-12-13 04:49:30 +0000615 def testBinaryMaskOps(self):
616 x = 1 & 1
617 x = 1 ^ 1
618 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000619
Thomas Wouters89f507f2006-12-13 04:49:30 +0000620 def testShiftOps(self):
621 x = 1 << 1
622 x = 1 >> 1
623 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000624
Thomas Wouters89f507f2006-12-13 04:49:30 +0000625 def testAdditiveOps(self):
626 x = 1
627 x = 1 + 1
628 x = 1 - 1 - 1
629 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000630
Thomas Wouters89f507f2006-12-13 04:49:30 +0000631 def testMultiplicativeOps(self):
632 x = 1 * 1
633 x = 1 / 1
634 x = 1 % 1
635 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000636
Thomas Wouters89f507f2006-12-13 04:49:30 +0000637 def testUnaryOps(self):
638 x = +1
639 x = -1
640 x = ~1
641 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
642 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +0000643
Thomas Wouters89f507f2006-12-13 04:49:30 +0000644 def testSelectors(self):
645 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
646 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +0000647
Thomas Wouters89f507f2006-12-13 04:49:30 +0000648 import sys, time
649 c = sys.path[0]
650 x = time.time()
651 x = sys.modules['time'].time()
652 a = '01234'
653 c = a[0]
654 c = a[-1]
655 s = a[0:5]
656 s = a[:5]
657 s = a[0:]
658 s = a[:]
659 s = a[-5:]
660 s = a[:-1]
661 s = a[-4:-3]
662 # A rough test of SF bug 1333982. http://python.org/sf/1333982
663 # The testing here is fairly incomplete.
664 # Test cases should include: commas with 1 and 2 colons
665 d = {}
666 d[1] = 1
667 d[1,] = 2
668 d[1,2] = 3
669 d[1,2,3] = 4
670 L = list(d)
671 L.sort(key=lambda x: x if isinstance(x, tuple) else ())
672 self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +0000673
Thomas Wouters89f507f2006-12-13 04:49:30 +0000674 def testAtoms(self):
675 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
676 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +0000677
Thomas Wouters89f507f2006-12-13 04:49:30 +0000678 x = (1)
679 x = (1 or 2 or 3)
680 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +0000681
Thomas Wouters89f507f2006-12-13 04:49:30 +0000682 x = []
683 x = [1]
684 x = [1 or 2 or 3]
685 x = [1 or 2 or 3, 2, 3]
686 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +0000687
Thomas Wouters89f507f2006-12-13 04:49:30 +0000688 x = {}
689 x = {'one': 1}
690 x = {'one': 1,}
691 x = {'one' or 'two': 1 or 2}
692 x = {'one': 1, 'two': 2}
693 x = {'one': 1, 'two': 2,}
694 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +0000695
Thomas Wouters89f507f2006-12-13 04:49:30 +0000696 x = {'one'}
697 x = {'one', 1,}
698 x = {'one', 'two', 'three'}
699 x = {2, 3, 4,}
700
701 x = x
702 x = 'x'
703 x = 123
704
705 ### exprlist: expr (',' expr)* [',']
706 ### testlist: test (',' test)* [',']
707 # These have been exercised enough above
708
709 def testClassdef(self):
710 # 'class' NAME ['(' [testlist] ')'] ':' suite
711 class B: pass
712 class B2(): pass
713 class C1(B): pass
714 class C2(B): pass
715 class D(C1, C2, B): pass
716 class C:
717 def meth1(self): pass
718 def meth2(self, arg): pass
719 def meth3(self, a1, a2): pass
720
721 def testListcomps(self):
722 # list comprehension tests
723 nums = [1, 2, 3, 4, 5]
724 strs = ["Apple", "Banana", "Coconut"]
725 spcs = [" Apple", " Banana ", "Coco nut "]
726
727 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
728 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
729 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
730 self.assertEqual([(i, s) for i in nums for s in strs],
731 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
732 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
733 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
734 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
735 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
736 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
737 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
738 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
739 (5, 'Banana'), (5, 'Coconut')])
740 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
741 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
742
743 def test_in_func(l):
744 return [0 < x < 3 for x in l if x > 2]
745
746 self.assertEqual(test_in_func(nums), [False, False, False])
747
748 def test_nested_front():
749 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
750 [[1, 2], [3, 4], [5, 6]])
751
752 test_nested_front()
753
754 check_syntax_error(self, "[i, s for i in nums for s in strs]")
755 check_syntax_error(self, "[x if y]")
756
757 suppliers = [
758 (1, "Boeing"),
759 (2, "Ford"),
760 (3, "Macdonalds")
761 ]
762
763 parts = [
764 (10, "Airliner"),
765 (20, "Engine"),
766 (30, "Cheeseburger")
767 ]
768
769 suppart = [
770 (1, 10), (1, 20), (2, 20), (3, 30)
771 ]
772
773 x = [
774 (sname, pname)
775 for (sno, sname) in suppliers
776 for (pno, pname) in parts
777 for (sp_sno, sp_pno) in suppart
778 if sno == sp_sno and pno == sp_pno
779 ]
780
781 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
782 ('Macdonalds', 'Cheeseburger')])
783
784 def testGenexps(self):
785 # generator expression tests
786 g = ([x for x in range(10)] for x in range(1))
787 self.assertEqual(g.next(), [x for x in range(10)])
788 try:
789 g.next()
790 self.fail('should produce StopIteration exception')
791 except StopIteration:
792 pass
793
794 a = 1
795 try:
796 g = (a for d in a)
797 g.next()
798 self.fail('should produce TypeError')
799 except TypeError:
800 pass
801
802 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
803 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
804
805 a = [x for x in range(10)]
806 b = (x for x in (y for y in a))
807 self.assertEqual(sum(b), sum([x for x in range(10)]))
808
809 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
810 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
811 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
812 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
813 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
814 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)]))
815 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
816 check_syntax_error(self, "foo(x for x in range(10), 100)")
817 check_syntax_error(self, "foo(100, x for x in range(10))")
818
819 def testComprehensionSpecials(self):
820 # test for outmost iterable precomputation
821 x = 10; g = (i for i in range(x)); x = 5
822 self.assertEqual(len(list(g)), 10)
823
824 # This should hold, since we're only precomputing outmost iterable.
825 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
826 x = 5; t = True;
827 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
828
829 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
830 # even though it's silly. Make sure it works (ifelse broke this.)
831 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
832 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
833
834 # verify unpacking single element tuples in listcomp/genexp.
835 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
836 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
837
838 def testIfElseExpr(self):
839 # Test ifelse expressions in various cases
840 def _checkeval(msg, ret):
841 "helper to check that evaluation of expressions is done correctly"
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000842 print(x)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000843 return ret
844
845 self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
846 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
847 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])
848 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
849 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
850 self.assertEqual((5 and 6 if 0 else 1), 1)
851 self.assertEqual(((5 and 6) if 0 else 1), 1)
852 self.assertEqual((5 and (6 if 1 else 1)), 6)
853 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
854 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
855 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
856 self.assertEqual((not 5 if 1 else 1), False)
857 self.assertEqual((not 5 if 0 else 1), 1)
858 self.assertEqual((6 + 1 if 1 else 2), 7)
859 self.assertEqual((6 - 1 if 1 else 2), 5)
860 self.assertEqual((6 * 2 if 1 else 4), 12)
861 self.assertEqual((6 / 2 if 1 else 3), 3)
862 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +0000863
Guido van Rossum3bead091992-01-27 17:00:37 +0000864
Thomas Wouters89f507f2006-12-13 04:49:30 +0000865def test_main():
866 run_unittest(TokenTests, GrammarTests)
Guido van Rossum3bead091992-01-27 17:00:37 +0000867
Thomas Wouters89f507f2006-12-13 04:49:30 +0000868if __name__ == '__main__':
869 test_main()