blob: 96cf824dc26f2857374418ec1f70b0c93759cf34 [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})
Nick Coghlan71011e22007-04-23 11:05:01 +0000325 # Check for SF Bug #1697248 - mixing decorators and a return annotation
326 def null(x): return x
327 @null
328 def f(x) -> list: pass
329 self.assertEquals(f.__annotations__, {'return': list})
330
Guido van Rossum0240b922007-02-26 21:23:50 +0000331 # test MAKE_CLOSURE with a variety of oparg's
332 closure = 1
333 def f(): return closure
334 def f(x=1): return closure
335 def f(*, k=1): return closure
336 def f() -> int: return closure
Neal Norwitzc1505362006-12-28 06:47:50 +0000337
Thomas Wouters89f507f2006-12-13 04:49:30 +0000338 def testLambdef(self):
339 ### lambdef: 'lambda' [varargslist] ':' test
340 l1 = lambda : 0
341 self.assertEquals(l1(), 0)
342 l2 = lambda : a[d] # XXX just testing the expression
Guido van Rossume2a383d2007-01-15 16:59:06 +0000343 l3 = lambda : [2 < x for x in [-1, 3, 0]]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000344 self.assertEquals(l3(), [0, 1, 0])
345 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
346 self.assertEquals(l4(), 1)
347 l5 = lambda x, y, z=2: x + y + z
348 self.assertEquals(l5(1, 2), 5)
349 self.assertEquals(l5(1, 2, 3), 6)
350 check_syntax_error(self, "lambda x: x = 2")
351 l6 = lambda x, y, *, k=20: x+y+k
352 self.assertEquals(l6(1,2), 1+2+20)
353 self.assertEquals(l6(1,2,k=10), 1+2+10)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000354
355
Thomas Wouters89f507f2006-12-13 04:49:30 +0000356 ### stmt: simple_stmt | compound_stmt
357 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000358
Thomas Wouters89f507f2006-12-13 04:49:30 +0000359 def testSimpleStmt(self):
360 ### simple_stmt: small_stmt (';' small_stmt)* [';']
361 x = 1; pass; del x
362 def foo():
363 # verify statments that end with semi-colons
364 x = 1; pass; del x;
365 foo()
Georg Brandl52318d62006-09-06 07:06:08 +0000366
Guido van Rossumd8faa362007-04-27 19:54:29 +0000367 ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
Thomas Wouters89f507f2006-12-13 04:49:30 +0000368 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000369
Thomas Wouters89f507f2006-12-13 04:49:30 +0000370 def testExprStmt(self):
371 # (exprlist '=')* exprlist
372 1
373 1, 2, 3
374 x = 1
375 x = 1, 2, 3
376 x = y = z = 1, 2, 3
377 x, y, z = 1, 2, 3
378 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000379
Thomas Wouters89f507f2006-12-13 04:49:30 +0000380 check_syntax_error(self, "x + 1 = 1")
381 check_syntax_error(self, "a + 1 = b + 2")
Guido van Rossum3bead091992-01-27 17:00:37 +0000382
Thomas Wouters89f507f2006-12-13 04:49:30 +0000383 def testDelStmt(self):
384 # 'del' exprlist
385 abc = [1,2,3]
386 x, y, z = abc
387 xyz = x, y, z
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000388
Thomas Wouters89f507f2006-12-13 04:49:30 +0000389 del abc
390 del x, y, (z, xyz)
Barry Warsaw9182b452000-08-29 04:57:10 +0000391
Thomas Wouters89f507f2006-12-13 04:49:30 +0000392 def testPassStmt(self):
393 # 'pass'
394 pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000395
Thomas Wouters89f507f2006-12-13 04:49:30 +0000396 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
397 # Tested below
Barry Warsaw9182b452000-08-29 04:57:10 +0000398
Thomas Wouters89f507f2006-12-13 04:49:30 +0000399 def testBreakStmt(self):
400 # 'break'
401 while 1: break
Barry Warsaw9182b452000-08-29 04:57:10 +0000402
Thomas Wouters89f507f2006-12-13 04:49:30 +0000403 def testContinueStmt(self):
404 # 'continue'
405 i = 1
406 while i: i = 0; continue
Barry Warsaw9182b452000-08-29 04:57:10 +0000407
Thomas Wouters89f507f2006-12-13 04:49:30 +0000408 msg = ""
409 while not msg:
410 msg = "ok"
411 try:
412 continue
413 msg = "continue failed to continue inside try"
414 except:
415 msg = "continue inside try called except block"
416 if msg != "ok":
417 self.fail(msg)
Barry Warsawefc92ee2000-08-21 15:46:50 +0000418
Thomas Wouters89f507f2006-12-13 04:49:30 +0000419 msg = ""
420 while not msg:
421 msg = "finally block not called"
422 try:
423 continue
424 finally:
425 msg = "ok"
426 if msg != "ok":
427 self.fail(msg)
Guido van Rossum3bead091992-01-27 17:00:37 +0000428
Thomas Wouters89f507f2006-12-13 04:49:30 +0000429 def test_break_continue_loop(self):
430 # This test warrants an explanation. It is a test specifically for SF bugs
431 # #463359 and #462937. The bug is that a 'break' statement executed or
432 # exception raised inside a try/except inside a loop, *after* a continue
433 # statement has been executed in that loop, will cause the wrong number of
434 # arguments to be popped off the stack and the instruction pointer reset to
435 # a very small number (usually 0.) Because of this, the following test
436 # *must* written as a function, and the tracking vars *must* be function
437 # arguments with default values. Otherwise, the test will loop and loop.
Guido van Rossum3bead091992-01-27 17:00:37 +0000438
Thomas Wouters89f507f2006-12-13 04:49:30 +0000439 def test_inner(extra_burning_oil = 1, count=0):
440 big_hippo = 2
441 while big_hippo:
442 count += 1
443 try:
444 if extra_burning_oil and big_hippo == 1:
445 extra_burning_oil -= 1
446 break
447 big_hippo -= 1
448 continue
449 except:
450 raise
451 if count > 2 or big_hippo != 1:
452 self.fail("continue then break in try/except in loop broken!")
453 test_inner()
Guido van Rossum3bead091992-01-27 17:00:37 +0000454
Thomas Wouters89f507f2006-12-13 04:49:30 +0000455 def testReturn(self):
456 # 'return' [testlist]
457 def g1(): return
458 def g2(): return 1
459 g1()
460 x = g2()
461 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000462
Thomas Wouters89f507f2006-12-13 04:49:30 +0000463 def testYield(self):
464 check_syntax_error(self, "class foo:yield 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000465
Thomas Wouters89f507f2006-12-13 04:49:30 +0000466 def testRaise(self):
467 # 'raise' test [',' test]
468 try: raise RuntimeError, 'just testing'
469 except RuntimeError: pass
470 try: raise KeyboardInterrupt
471 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000472
Thomas Wouters89f507f2006-12-13 04:49:30 +0000473 def testImport(self):
474 # 'import' dotted_as_names
475 import sys
476 import time, sys
477 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
478 from time import time
479 from time import (time)
480 # not testable inside a function, but already done at top of the module
481 # from sys import *
482 from sys import path, argv
483 from sys import (path, argv)
484 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +0000485
Thomas Wouters89f507f2006-12-13 04:49:30 +0000486 def testGlobal(self):
487 # 'global' NAME (',' NAME)*
488 global a
489 global a, b
490 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +0000491
Thomas Wouters89f507f2006-12-13 04:49:30 +0000492 def testAssert(self):
493 # assert_stmt: 'assert' test [',' test]
494 assert 1
495 assert 1, 1
496 assert lambda x:x
497 assert 1, lambda x:x+1
Thomas Wouters80d373c2001-09-26 12:43:39 +0000498 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000499 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +0000500 except AssertionError as e:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000501 self.assertEquals(e.args[0], "msg")
502 else:
503 if __debug__:
504 self.fail("AssertionError not raised by assert 0")
Thomas Wouters80d373c2001-09-26 12:43:39 +0000505
Thomas Wouters89f507f2006-12-13 04:49:30 +0000506 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
507 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000508
Thomas Wouters89f507f2006-12-13 04:49:30 +0000509 def testIf(self):
510 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
511 if 1: pass
512 if 1: pass
513 else: pass
514 if 0: pass
515 elif 0: pass
516 if 0: pass
517 elif 0: pass
518 elif 0: pass
519 elif 0: pass
520 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000521
Thomas Wouters89f507f2006-12-13 04:49:30 +0000522 def testWhile(self):
523 # 'while' test ':' suite ['else' ':' suite]
524 while 0: pass
525 while 0: pass
526 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000527
Thomas Wouters89f507f2006-12-13 04:49:30 +0000528 def testFor(self):
529 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
530 for i in 1, 2, 3: pass
531 for i, j, k in (): pass
532 else: pass
533 class Squares:
534 def __init__(self, max):
535 self.max = max
536 self.sofar = []
537 def __len__(self): return len(self.sofar)
538 def __getitem__(self, i):
539 if not 0 <= i < self.max: raise IndexError
540 n = len(self.sofar)
541 while n <= i:
542 self.sofar.append(n*n)
543 n = n+1
544 return self.sofar[i]
545 n = 0
546 for x in Squares(10): n = n+x
547 if n != 285:
548 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000549
Thomas Wouters89f507f2006-12-13 04:49:30 +0000550 result = []
551 for x, in [(1,), (2,), (3,)]:
552 result.append(x)
553 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000554
Thomas Wouters89f507f2006-12-13 04:49:30 +0000555 def testTry(self):
556 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
557 ### | 'try' ':' suite 'finally' ':' suite
Guido van Rossumb940e112007-01-10 16:19:56 +0000558 ### except_clause: 'except' [expr ['as' expr]]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000559 try:
560 1/0
561 except ZeroDivisionError:
562 pass
563 else:
564 pass
565 try: 1/0
566 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000567 except TypeError as msg: pass
568 except RuntimeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000569 except: pass
570 else: pass
571 try: 1/0
572 except (EOFError, TypeError, ZeroDivisionError): pass
573 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000574 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000575 try: pass
576 finally: pass
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000577
Thomas Wouters89f507f2006-12-13 04:49:30 +0000578 def testSuite(self):
579 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
580 if 1: pass
581 if 1:
582 pass
583 if 1:
584 #
585 #
586 #
587 pass
588 pass
589 #
590 pass
591 #
Guido van Rossum3bead091992-01-27 17:00:37 +0000592
Thomas Wouters89f507f2006-12-13 04:49:30 +0000593 def testTest(self):
594 ### and_test ('or' and_test)*
595 ### and_test: not_test ('and' not_test)*
596 ### not_test: 'not' not_test | comparison
597 if not 1: pass
598 if 1 and 1: pass
599 if 1 or 1: pass
600 if not not not 1: pass
601 if not 1 and 1 and 1: pass
602 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000603
Thomas Wouters89f507f2006-12-13 04:49:30 +0000604 def testComparison(self):
605 ### comparison: expr (comp_op expr)*
606 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
607 if 1: pass
608 x = (1 == 1)
609 if 1 == 1: pass
610 if 1 != 1: pass
611 if 1 < 1: pass
612 if 1 > 1: pass
613 if 1 <= 1: pass
614 if 1 >= 1: pass
615 if 1 is 1: pass
616 if 1 is not 1: pass
617 if 1 in (): pass
618 if 1 not in (): pass
619 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 +0000620
Thomas Wouters89f507f2006-12-13 04:49:30 +0000621 def testBinaryMaskOps(self):
622 x = 1 & 1
623 x = 1 ^ 1
624 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000625
Thomas Wouters89f507f2006-12-13 04:49:30 +0000626 def testShiftOps(self):
627 x = 1 << 1
628 x = 1 >> 1
629 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000630
Thomas Wouters89f507f2006-12-13 04:49:30 +0000631 def testAdditiveOps(self):
632 x = 1
633 x = 1 + 1
634 x = 1 - 1 - 1
635 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000636
Thomas Wouters89f507f2006-12-13 04:49:30 +0000637 def testMultiplicativeOps(self):
638 x = 1 * 1
639 x = 1 / 1
640 x = 1 % 1
641 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000642
Thomas Wouters89f507f2006-12-13 04:49:30 +0000643 def testUnaryOps(self):
644 x = +1
645 x = -1
646 x = ~1
647 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
648 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +0000649
Thomas Wouters89f507f2006-12-13 04:49:30 +0000650 def testSelectors(self):
651 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
652 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +0000653
Thomas Wouters89f507f2006-12-13 04:49:30 +0000654 import sys, time
655 c = sys.path[0]
656 x = time.time()
657 x = sys.modules['time'].time()
658 a = '01234'
659 c = a[0]
660 c = a[-1]
661 s = a[0:5]
662 s = a[:5]
663 s = a[0:]
664 s = a[:]
665 s = a[-5:]
666 s = a[:-1]
667 s = a[-4:-3]
668 # A rough test of SF bug 1333982. http://python.org/sf/1333982
669 # The testing here is fairly incomplete.
670 # Test cases should include: commas with 1 and 2 colons
671 d = {}
672 d[1] = 1
673 d[1,] = 2
674 d[1,2] = 3
675 d[1,2,3] = 4
676 L = list(d)
677 L.sort(key=lambda x: x if isinstance(x, tuple) else ())
678 self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +0000679
Thomas Wouters89f507f2006-12-13 04:49:30 +0000680 def testAtoms(self):
681 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
682 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +0000683
Thomas Wouters89f507f2006-12-13 04:49:30 +0000684 x = (1)
685 x = (1 or 2 or 3)
686 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +0000687
Thomas Wouters89f507f2006-12-13 04:49:30 +0000688 x = []
689 x = [1]
690 x = [1 or 2 or 3]
691 x = [1 or 2 or 3, 2, 3]
692 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +0000693
Thomas Wouters89f507f2006-12-13 04:49:30 +0000694 x = {}
695 x = {'one': 1}
696 x = {'one': 1,}
697 x = {'one' or 'two': 1 or 2}
698 x = {'one': 1, 'two': 2}
699 x = {'one': 1, 'two': 2,}
700 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +0000701
Thomas Wouters89f507f2006-12-13 04:49:30 +0000702 x = {'one'}
703 x = {'one', 1,}
704 x = {'one', 'two', 'three'}
705 x = {2, 3, 4,}
706
707 x = x
708 x = 'x'
709 x = 123
710
711 ### exprlist: expr (',' expr)* [',']
712 ### testlist: test (',' test)* [',']
713 # These have been exercised enough above
714
715 def testClassdef(self):
716 # 'class' NAME ['(' [testlist] ')'] ':' suite
717 class B: pass
718 class B2(): pass
719 class C1(B): pass
720 class C2(B): pass
721 class D(C1, C2, B): pass
722 class C:
723 def meth1(self): pass
724 def meth2(self, arg): pass
725 def meth3(self, a1, a2): pass
726
727 def testListcomps(self):
728 # list comprehension tests
729 nums = [1, 2, 3, 4, 5]
730 strs = ["Apple", "Banana", "Coconut"]
731 spcs = [" Apple", " Banana ", "Coco nut "]
732
733 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
734 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
735 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
736 self.assertEqual([(i, s) for i in nums for s in strs],
737 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
738 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
739 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
740 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
741 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
742 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
743 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
744 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
745 (5, 'Banana'), (5, 'Coconut')])
746 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
747 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
748
749 def test_in_func(l):
750 return [0 < x < 3 for x in l if x > 2]
751
752 self.assertEqual(test_in_func(nums), [False, False, False])
753
754 def test_nested_front():
755 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
756 [[1, 2], [3, 4], [5, 6]])
757
758 test_nested_front()
759
760 check_syntax_error(self, "[i, s for i in nums for s in strs]")
761 check_syntax_error(self, "[x if y]")
762
763 suppliers = [
764 (1, "Boeing"),
765 (2, "Ford"),
766 (3, "Macdonalds")
767 ]
768
769 parts = [
770 (10, "Airliner"),
771 (20, "Engine"),
772 (30, "Cheeseburger")
773 ]
774
775 suppart = [
776 (1, 10), (1, 20), (2, 20), (3, 30)
777 ]
778
779 x = [
780 (sname, pname)
781 for (sno, sname) in suppliers
782 for (pno, pname) in parts
783 for (sp_sno, sp_pno) in suppart
784 if sno == sp_sno and pno == sp_pno
785 ]
786
787 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
788 ('Macdonalds', 'Cheeseburger')])
789
790 def testGenexps(self):
791 # generator expression tests
792 g = ([x for x in range(10)] for x in range(1))
Georg Brandla18af4e2007-04-21 15:47:16 +0000793 self.assertEqual(next(g), [x for x in range(10)])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000794 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000795 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000796 self.fail('should produce StopIteration exception')
797 except StopIteration:
798 pass
799
800 a = 1
801 try:
802 g = (a for d in a)
Georg Brandla18af4e2007-04-21 15:47:16 +0000803 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000804 self.fail('should produce TypeError')
805 except TypeError:
806 pass
807
808 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
809 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
810
811 a = [x for x in range(10)]
812 b = (x for x in (y for y in a))
813 self.assertEqual(sum(b), sum([x for x in range(10)]))
814
815 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
816 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
817 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
818 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
819 self.assertEqual(sum(x for x in [y for y in (z for z 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) if True)) if True), 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) if True) if False) if True), 0)
822 check_syntax_error(self, "foo(x for x in range(10), 100)")
823 check_syntax_error(self, "foo(100, x for x in range(10))")
824
825 def testComprehensionSpecials(self):
826 # test for outmost iterable precomputation
827 x = 10; g = (i for i in range(x)); x = 5
828 self.assertEqual(len(list(g)), 10)
829
830 # This should hold, since we're only precomputing outmost iterable.
831 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
832 x = 5; t = True;
833 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
834
835 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
836 # even though it's silly. Make sure it works (ifelse broke this.)
837 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
838 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
839
840 # verify unpacking single element tuples in listcomp/genexp.
841 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
842 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
843
844 def testIfElseExpr(self):
845 # Test ifelse expressions in various cases
846 def _checkeval(msg, ret):
847 "helper to check that evaluation of expressions is done correctly"
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000848 print(x)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000849 return ret
850
Nick Coghlan650f0d02007-04-15 12:05:43 +0000851 # the next line is not allowed anymore
852 #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000853 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
854 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])
855 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
856 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
857 self.assertEqual((5 and 6 if 0 else 1), 1)
858 self.assertEqual(((5 and 6) if 0 else 1), 1)
859 self.assertEqual((5 and (6 if 1 else 1)), 6)
860 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
861 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
862 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
863 self.assertEqual((not 5 if 1 else 1), False)
864 self.assertEqual((not 5 if 0 else 1), 1)
865 self.assertEqual((6 + 1 if 1 else 2), 7)
866 self.assertEqual((6 - 1 if 1 else 2), 5)
867 self.assertEqual((6 * 2 if 1 else 4), 12)
868 self.assertEqual((6 / 2 if 1 else 3), 3)
869 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +0000870
Guido van Rossum3bead091992-01-27 17:00:37 +0000871
Thomas Wouters89f507f2006-12-13 04:49:30 +0000872def test_main():
873 run_unittest(TokenTests, GrammarTests)
Guido van Rossum3bead091992-01-27 17:00:37 +0000874
Thomas Wouters89f507f2006-12-13 04:49:30 +0000875if __name__ == '__main__':
876 test_main()