blob: 0d36a62bab216d901ad48ba7f9569158ff861430 [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):
58 x = 0L
59 x = 0l
60 x = 0xffffffffffffffffL
61 x = 0xffffffffffffffffl
62 x = 077777777777777777L
63 x = 077777777777777777l
64 x = 123456789012345678901234567890L
65 x = 123456789012345678901234567890l
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
165 self.assertEquals(f2.func_code.co_varnames, ('one_argument',))
166 self.assertEquals(f3.func_code.co_varnames, ('two', 'arguments'))
167 if sys.platform.startswith('java'):
168 self.assertEquals(f4.func_code.co_varnames,
169 ('two', '(compound, (argument, list))', 'compound', 'argument',
170 'list',))
171 self.assertEquals(f5.func_code.co_varnames,
172 ('(compound, first)', 'two', 'compound', 'first'))
173 else:
174 self.assertEquals(f4.func_code.co_varnames,
175 ('two', '.1', 'compound', 'argument', 'list'))
176 self.assertEquals(f5.func_code.co_varnames,
177 ('.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'):
212 self.assertEquals(v3.func_code.co_varnames, ('a', '(b, c)', 'rest', 'b', 'c'))
213 else:
214 self.assertEquals(v3.func_code.co_varnames, ('a', '.1', 'rest', 'b', 'c'))
215 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
305 self.assertEquals(f.func_annotations, {'return': list})
306 def f(x:int): pass
307 self.assertEquals(f.func_annotations, {'x': int})
308 def f(*x:str): pass
309 self.assertEquals(f.func_annotations, {'x': str})
310 def f(**x:float): pass
311 self.assertEquals(f.func_annotations, {'x': float})
312 def f(x, y:1+2): pass
313 self.assertEquals(f.func_annotations, {'y': 3})
314 def f(a, (b:1, c:2, d)): pass
315 self.assertEquals(f.func_annotations, {'b': 1, 'c': 2})
316 def f(a, (b:1, c:2, d), e:3=4, f=5, *g:6): pass
317 self.assertEquals(f.func_annotations,
318 {'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
321 self.assertEquals(f.func_annotations,
322 {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
323 'k': 11, 'return': 12})
324
Thomas Wouters89f507f2006-12-13 04:49:30 +0000325 def testLambdef(self):
326 ### lambdef: 'lambda' [varargslist] ':' test
327 l1 = lambda : 0
328 self.assertEquals(l1(), 0)
329 l2 = lambda : a[d] # XXX just testing the expression
330 l3 = lambda : [2 < x for x in [-1, 3, 0L]]
331 self.assertEquals(l3(), [0, 1, 0])
332 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
333 self.assertEquals(l4(), 1)
334 l5 = lambda x, y, z=2: x + y + z
335 self.assertEquals(l5(1, 2), 5)
336 self.assertEquals(l5(1, 2, 3), 6)
337 check_syntax_error(self, "lambda x: x = 2")
338 l6 = lambda x, y, *, k=20: x+y+k
339 self.assertEquals(l6(1,2), 1+2+20)
340 self.assertEquals(l6(1,2,k=10), 1+2+10)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000341
342
Thomas Wouters89f507f2006-12-13 04:49:30 +0000343 ### stmt: simple_stmt | compound_stmt
344 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000345
Thomas Wouters89f507f2006-12-13 04:49:30 +0000346 def testSimpleStmt(self):
347 ### simple_stmt: small_stmt (';' small_stmt)* [';']
348 x = 1; pass; del x
349 def foo():
350 # verify statments that end with semi-colons
351 x = 1; pass; del x;
352 foo()
Georg Brandl52318d62006-09-06 07:06:08 +0000353
Thomas Wouters89f507f2006-12-13 04:49:30 +0000354 ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
355 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000356
Thomas Wouters89f507f2006-12-13 04:49:30 +0000357 def testExprStmt(self):
358 # (exprlist '=')* exprlist
359 1
360 1, 2, 3
361 x = 1
362 x = 1, 2, 3
363 x = y = z = 1, 2, 3
364 x, y, z = 1, 2, 3
365 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000366
Thomas Wouters89f507f2006-12-13 04:49:30 +0000367 check_syntax_error(self, "x + 1 = 1")
368 check_syntax_error(self, "a + 1 = b + 2")
Guido van Rossum3bead091992-01-27 17:00:37 +0000369
Thomas Wouters89f507f2006-12-13 04:49:30 +0000370 def testPrintStmt(self):
371 # 'print' (test ',')* [test]
372 import StringIO
Guido van Rossum3bead091992-01-27 17:00:37 +0000373
Thomas Wouters89f507f2006-12-13 04:49:30 +0000374 # Can't test printing to real stdout without comparing output
375 # which is not available in unittest.
376 save_stdout = sys.stdout
377 sys.stdout = StringIO.StringIO()
Guido van Rossum3bead091992-01-27 17:00:37 +0000378
Thomas Wouters89f507f2006-12-13 04:49:30 +0000379 print 1, 2, 3
380 print 1, 2, 3,
381 print
382 print 0 or 1, 0 or 1,
383 print 0 or 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000384
Thomas Wouters89f507f2006-12-13 04:49:30 +0000385 # 'print' '>>' test ','
386 print >> sys.stdout, 1, 2, 3
387 print >> sys.stdout, 1, 2, 3,
388 print >> sys.stdout
389 print >> sys.stdout, 0 or 1, 0 or 1,
390 print >> sys.stdout, 0 or 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000391
Thomas Wouters89f507f2006-12-13 04:49:30 +0000392 # test printing to an instance
393 class Gulp:
394 def write(self, msg): pass
Jeremy Hylton619eea62001-01-25 20:12:27 +0000395
Thomas Wouters89f507f2006-12-13 04:49:30 +0000396 gulp = Gulp()
397 print >> gulp, 1, 2, 3
398 print >> gulp, 1, 2, 3,
399 print >> gulp
400 print >> gulp, 0 or 1, 0 or 1,
401 print >> gulp, 0 or 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000402
Thomas Wouters89f507f2006-12-13 04:49:30 +0000403 # test print >> None
404 def driver():
405 oldstdout = sys.stdout
406 sys.stdout = Gulp()
407 try:
408 tellme(Gulp())
409 tellme()
410 finally:
411 sys.stdout = oldstdout
Guido van Rossum3bead091992-01-27 17:00:37 +0000412
Thomas Wouters89f507f2006-12-13 04:49:30 +0000413 # we should see this once
414 def tellme(file=sys.stdout):
415 print >> file, 'hello world'
Guido van Rossum3bead091992-01-27 17:00:37 +0000416
Thomas Wouters89f507f2006-12-13 04:49:30 +0000417 driver()
Guido van Rossum3bead091992-01-27 17:00:37 +0000418
Thomas Wouters89f507f2006-12-13 04:49:30 +0000419 # we should not see this at all
420 def tellme(file=None):
421 print >> file, 'goodbye universe'
Jeremy Hylton47793992001-02-19 15:35:26 +0000422
Thomas Wouters89f507f2006-12-13 04:49:30 +0000423 driver()
Guido van Rossum3bead091992-01-27 17:00:37 +0000424
Thomas Wouters89f507f2006-12-13 04:49:30 +0000425 self.assertEqual(sys.stdout.getvalue(), '''\
4261 2 3
4271 2 3
4281 1 1
4291 2 3
4301 2 3
4311 1 1
432hello world
433''')
434 sys.stdout = save_stdout
Barry Warsawefc92ee2000-08-21 15:46:50 +0000435
Thomas Wouters89f507f2006-12-13 04:49:30 +0000436 # syntax errors
437 check_syntax_error(self, 'print ,')
438 check_syntax_error(self, 'print >> x,')
Barry Warsaw9182b452000-08-29 04:57:10 +0000439
Thomas Wouters89f507f2006-12-13 04:49:30 +0000440 def testDelStmt(self):
441 # 'del' exprlist
442 abc = [1,2,3]
443 x, y, z = abc
444 xyz = x, y, z
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000445
Thomas Wouters89f507f2006-12-13 04:49:30 +0000446 del abc
447 del x, y, (z, xyz)
Barry Warsaw9182b452000-08-29 04:57:10 +0000448
Thomas Wouters89f507f2006-12-13 04:49:30 +0000449 def testPassStmt(self):
450 # 'pass'
451 pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000452
Thomas Wouters89f507f2006-12-13 04:49:30 +0000453 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
454 # Tested below
Barry Warsaw9182b452000-08-29 04:57:10 +0000455
Thomas Wouters89f507f2006-12-13 04:49:30 +0000456 def testBreakStmt(self):
457 # 'break'
458 while 1: break
Barry Warsaw9182b452000-08-29 04:57:10 +0000459
Thomas Wouters89f507f2006-12-13 04:49:30 +0000460 def testContinueStmt(self):
461 # 'continue'
462 i = 1
463 while i: i = 0; continue
Barry Warsaw9182b452000-08-29 04:57:10 +0000464
Thomas Wouters89f507f2006-12-13 04:49:30 +0000465 msg = ""
466 while not msg:
467 msg = "ok"
468 try:
469 continue
470 msg = "continue failed to continue inside try"
471 except:
472 msg = "continue inside try called except block"
473 if msg != "ok":
474 self.fail(msg)
Barry Warsawefc92ee2000-08-21 15:46:50 +0000475
Thomas Wouters89f507f2006-12-13 04:49:30 +0000476 msg = ""
477 while not msg:
478 msg = "finally block not called"
479 try:
480 continue
481 finally:
482 msg = "ok"
483 if msg != "ok":
484 self.fail(msg)
Guido van Rossum3bead091992-01-27 17:00:37 +0000485
Thomas Wouters89f507f2006-12-13 04:49:30 +0000486 def test_break_continue_loop(self):
487 # This test warrants an explanation. It is a test specifically for SF bugs
488 # #463359 and #462937. The bug is that a 'break' statement executed or
489 # exception raised inside a try/except inside a loop, *after* a continue
490 # statement has been executed in that loop, will cause the wrong number of
491 # arguments to be popped off the stack and the instruction pointer reset to
492 # a very small number (usually 0.) Because of this, the following test
493 # *must* written as a function, and the tracking vars *must* be function
494 # arguments with default values. Otherwise, the test will loop and loop.
Guido van Rossum3bead091992-01-27 17:00:37 +0000495
Thomas Wouters89f507f2006-12-13 04:49:30 +0000496 def test_inner(extra_burning_oil = 1, count=0):
497 big_hippo = 2
498 while big_hippo:
499 count += 1
500 try:
501 if extra_burning_oil and big_hippo == 1:
502 extra_burning_oil -= 1
503 break
504 big_hippo -= 1
505 continue
506 except:
507 raise
508 if count > 2 or big_hippo != 1:
509 self.fail("continue then break in try/except in loop broken!")
510 test_inner()
Guido van Rossum3bead091992-01-27 17:00:37 +0000511
Thomas Wouters89f507f2006-12-13 04:49:30 +0000512 def testReturn(self):
513 # 'return' [testlist]
514 def g1(): return
515 def g2(): return 1
516 g1()
517 x = g2()
518 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000519
Thomas Wouters89f507f2006-12-13 04:49:30 +0000520 def testYield(self):
521 check_syntax_error(self, "class foo:yield 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000522
Thomas Wouters89f507f2006-12-13 04:49:30 +0000523 def testRaise(self):
524 # 'raise' test [',' test]
525 try: raise RuntimeError, 'just testing'
526 except RuntimeError: pass
527 try: raise KeyboardInterrupt
528 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000529
Thomas Wouters89f507f2006-12-13 04:49:30 +0000530 def testImport(self):
531 # 'import' dotted_as_names
532 import sys
533 import time, sys
534 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
535 from time import time
536 from time import (time)
537 # not testable inside a function, but already done at top of the module
538 # from sys import *
539 from sys import path, argv
540 from sys import (path, argv)
541 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +0000542
Thomas Wouters89f507f2006-12-13 04:49:30 +0000543 def testGlobal(self):
544 # 'global' NAME (',' NAME)*
545 global a
546 global a, b
547 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +0000548
Thomas Wouters89f507f2006-12-13 04:49:30 +0000549 def testAssert(self):
550 # assert_stmt: 'assert' test [',' test]
551 assert 1
552 assert 1, 1
553 assert lambda x:x
554 assert 1, lambda x:x+1
Thomas Wouters80d373c2001-09-26 12:43:39 +0000555 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000556 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +0000557 except AssertionError as e:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000558 self.assertEquals(e.args[0], "msg")
559 else:
560 if __debug__:
561 self.fail("AssertionError not raised by assert 0")
Thomas Wouters80d373c2001-09-26 12:43:39 +0000562
Thomas Wouters89f507f2006-12-13 04:49:30 +0000563 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
564 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000565
Thomas Wouters89f507f2006-12-13 04:49:30 +0000566 def testIf(self):
567 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
568 if 1: pass
569 if 1: pass
570 else: pass
571 if 0: pass
572 elif 0: pass
573 if 0: pass
574 elif 0: pass
575 elif 0: pass
576 elif 0: pass
577 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000578
Thomas Wouters89f507f2006-12-13 04:49:30 +0000579 def testWhile(self):
580 # 'while' test ':' suite ['else' ':' suite]
581 while 0: pass
582 while 0: pass
583 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000584
Thomas Wouters89f507f2006-12-13 04:49:30 +0000585 def testFor(self):
586 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
587 for i in 1, 2, 3: pass
588 for i, j, k in (): pass
589 else: pass
590 class Squares:
591 def __init__(self, max):
592 self.max = max
593 self.sofar = []
594 def __len__(self): return len(self.sofar)
595 def __getitem__(self, i):
596 if not 0 <= i < self.max: raise IndexError
597 n = len(self.sofar)
598 while n <= i:
599 self.sofar.append(n*n)
600 n = n+1
601 return self.sofar[i]
602 n = 0
603 for x in Squares(10): n = n+x
604 if n != 285:
605 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000606
Thomas Wouters89f507f2006-12-13 04:49:30 +0000607 result = []
608 for x, in [(1,), (2,), (3,)]:
609 result.append(x)
610 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000611
Thomas Wouters89f507f2006-12-13 04:49:30 +0000612 def testTry(self):
613 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
614 ### | 'try' ':' suite 'finally' ':' suite
Guido van Rossumb940e112007-01-10 16:19:56 +0000615 ### except_clause: 'except' [expr ['as' expr]]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000616 try:
617 1/0
618 except ZeroDivisionError:
619 pass
620 else:
621 pass
622 try: 1/0
623 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000624 except TypeError as msg: pass
625 except RuntimeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000626 except: pass
627 else: pass
628 try: 1/0
629 except (EOFError, TypeError, ZeroDivisionError): pass
630 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000631 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000632 try: pass
633 finally: pass
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000634
Thomas Wouters89f507f2006-12-13 04:49:30 +0000635 def testSuite(self):
636 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
637 if 1: pass
638 if 1:
639 pass
640 if 1:
641 #
642 #
643 #
644 pass
645 pass
646 #
647 pass
648 #
Guido van Rossum3bead091992-01-27 17:00:37 +0000649
Thomas Wouters89f507f2006-12-13 04:49:30 +0000650 def testTest(self):
651 ### and_test ('or' and_test)*
652 ### and_test: not_test ('and' not_test)*
653 ### not_test: 'not' not_test | comparison
654 if not 1: pass
655 if 1 and 1: pass
656 if 1 or 1: pass
657 if not not not 1: pass
658 if not 1 and 1 and 1: pass
659 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000660
Thomas Wouters89f507f2006-12-13 04:49:30 +0000661 def testComparison(self):
662 ### comparison: expr (comp_op expr)*
663 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
664 if 1: pass
665 x = (1 == 1)
666 if 1 == 1: pass
667 if 1 != 1: pass
668 if 1 < 1: pass
669 if 1 > 1: pass
670 if 1 <= 1: pass
671 if 1 >= 1: pass
672 if 1 is 1: pass
673 if 1 is not 1: pass
674 if 1 in (): pass
675 if 1 not in (): pass
676 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 +0000677
Thomas Wouters89f507f2006-12-13 04:49:30 +0000678 def testBinaryMaskOps(self):
679 x = 1 & 1
680 x = 1 ^ 1
681 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000682
Thomas Wouters89f507f2006-12-13 04:49:30 +0000683 def testShiftOps(self):
684 x = 1 << 1
685 x = 1 >> 1
686 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000687
Thomas Wouters89f507f2006-12-13 04:49:30 +0000688 def testAdditiveOps(self):
689 x = 1
690 x = 1 + 1
691 x = 1 - 1 - 1
692 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000693
Thomas Wouters89f507f2006-12-13 04:49:30 +0000694 def testMultiplicativeOps(self):
695 x = 1 * 1
696 x = 1 / 1
697 x = 1 % 1
698 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000699
Thomas Wouters89f507f2006-12-13 04:49:30 +0000700 def testUnaryOps(self):
701 x = +1
702 x = -1
703 x = ~1
704 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
705 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +0000706
Thomas Wouters89f507f2006-12-13 04:49:30 +0000707 def testSelectors(self):
708 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
709 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +0000710
Thomas Wouters89f507f2006-12-13 04:49:30 +0000711 import sys, time
712 c = sys.path[0]
713 x = time.time()
714 x = sys.modules['time'].time()
715 a = '01234'
716 c = a[0]
717 c = a[-1]
718 s = a[0:5]
719 s = a[:5]
720 s = a[0:]
721 s = a[:]
722 s = a[-5:]
723 s = a[:-1]
724 s = a[-4:-3]
725 # A rough test of SF bug 1333982. http://python.org/sf/1333982
726 # The testing here is fairly incomplete.
727 # Test cases should include: commas with 1 and 2 colons
728 d = {}
729 d[1] = 1
730 d[1,] = 2
731 d[1,2] = 3
732 d[1,2,3] = 4
733 L = list(d)
734 L.sort(key=lambda x: x if isinstance(x, tuple) else ())
735 self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +0000736
Thomas Wouters89f507f2006-12-13 04:49:30 +0000737 def testAtoms(self):
738 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
739 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +0000740
Thomas Wouters89f507f2006-12-13 04:49:30 +0000741 x = (1)
742 x = (1 or 2 or 3)
743 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +0000744
Thomas Wouters89f507f2006-12-13 04:49:30 +0000745 x = []
746 x = [1]
747 x = [1 or 2 or 3]
748 x = [1 or 2 or 3, 2, 3]
749 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +0000750
Thomas Wouters89f507f2006-12-13 04:49:30 +0000751 x = {}
752 x = {'one': 1}
753 x = {'one': 1,}
754 x = {'one' or 'two': 1 or 2}
755 x = {'one': 1, 'two': 2}
756 x = {'one': 1, 'two': 2,}
757 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +0000758
Thomas Wouters89f507f2006-12-13 04:49:30 +0000759 x = {'one'}
760 x = {'one', 1,}
761 x = {'one', 'two', 'three'}
762 x = {2, 3, 4,}
763
764 x = x
765 x = 'x'
766 x = 123
767
768 ### exprlist: expr (',' expr)* [',']
769 ### testlist: test (',' test)* [',']
770 # These have been exercised enough above
771
772 def testClassdef(self):
773 # 'class' NAME ['(' [testlist] ')'] ':' suite
774 class B: pass
775 class B2(): pass
776 class C1(B): pass
777 class C2(B): pass
778 class D(C1, C2, B): pass
779 class C:
780 def meth1(self): pass
781 def meth2(self, arg): pass
782 def meth3(self, a1, a2): pass
783
784 def testListcomps(self):
785 # list comprehension tests
786 nums = [1, 2, 3, 4, 5]
787 strs = ["Apple", "Banana", "Coconut"]
788 spcs = [" Apple", " Banana ", "Coco nut "]
789
790 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
791 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
792 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
793 self.assertEqual([(i, s) for i in nums for s in strs],
794 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
795 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
796 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
797 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
798 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
799 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
800 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
801 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
802 (5, 'Banana'), (5, 'Coconut')])
803 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
804 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
805
806 def test_in_func(l):
807 return [0 < x < 3 for x in l if x > 2]
808
809 self.assertEqual(test_in_func(nums), [False, False, False])
810
811 def test_nested_front():
812 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
813 [[1, 2], [3, 4], [5, 6]])
814
815 test_nested_front()
816
817 check_syntax_error(self, "[i, s for i in nums for s in strs]")
818 check_syntax_error(self, "[x if y]")
819
820 suppliers = [
821 (1, "Boeing"),
822 (2, "Ford"),
823 (3, "Macdonalds")
824 ]
825
826 parts = [
827 (10, "Airliner"),
828 (20, "Engine"),
829 (30, "Cheeseburger")
830 ]
831
832 suppart = [
833 (1, 10), (1, 20), (2, 20), (3, 30)
834 ]
835
836 x = [
837 (sname, pname)
838 for (sno, sname) in suppliers
839 for (pno, pname) in parts
840 for (sp_sno, sp_pno) in suppart
841 if sno == sp_sno and pno == sp_pno
842 ]
843
844 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
845 ('Macdonalds', 'Cheeseburger')])
846
847 def testGenexps(self):
848 # generator expression tests
849 g = ([x for x in range(10)] for x in range(1))
850 self.assertEqual(g.next(), [x for x in range(10)])
851 try:
852 g.next()
853 self.fail('should produce StopIteration exception')
854 except StopIteration:
855 pass
856
857 a = 1
858 try:
859 g = (a for d in a)
860 g.next()
861 self.fail('should produce TypeError')
862 except TypeError:
863 pass
864
865 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
866 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
867
868 a = [x for x in range(10)]
869 b = (x for x in (y for y in a))
870 self.assertEqual(sum(b), sum([x for x in range(10)]))
871
872 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
873 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
874 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
875 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
876 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
877 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)]))
878 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
879 check_syntax_error(self, "foo(x for x in range(10), 100)")
880 check_syntax_error(self, "foo(100, x for x in range(10))")
881
882 def testComprehensionSpecials(self):
883 # test for outmost iterable precomputation
884 x = 10; g = (i for i in range(x)); x = 5
885 self.assertEqual(len(list(g)), 10)
886
887 # This should hold, since we're only precomputing outmost iterable.
888 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
889 x = 5; t = True;
890 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
891
892 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
893 # even though it's silly. Make sure it works (ifelse broke this.)
894 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
895 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
896
897 # verify unpacking single element tuples in listcomp/genexp.
898 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
899 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
900
901 def testIfElseExpr(self):
902 # Test ifelse expressions in various cases
903 def _checkeval(msg, ret):
904 "helper to check that evaluation of expressions is done correctly"
905 print x
906 return ret
907
908 self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
909 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
910 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])
911 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
912 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
913 self.assertEqual((5 and 6 if 0 else 1), 1)
914 self.assertEqual(((5 and 6) if 0 else 1), 1)
915 self.assertEqual((5 and (6 if 1 else 1)), 6)
916 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
917 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
918 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
919 self.assertEqual((not 5 if 1 else 1), False)
920 self.assertEqual((not 5 if 0 else 1), 1)
921 self.assertEqual((6 + 1 if 1 else 2), 7)
922 self.assertEqual((6 - 1 if 1 else 2), 5)
923 self.assertEqual((6 * 2 if 1 else 4), 12)
924 self.assertEqual((6 / 2 if 1 else 3), 3)
925 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +0000926
Guido van Rossum3bead091992-01-27 17:00:37 +0000927
Thomas Wouters89f507f2006-12-13 04:49:30 +0000928def test_main():
929 run_unittest(TokenTests, GrammarTests)
Guido van Rossum3bead091992-01-27 17:00:37 +0000930
Thomas Wouters89f507f2006-12-13 04:49:30 +0000931if __name__ == '__main__':
932 test_main()