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