blob: e2bb3eb9e630dbeed338ad5accb0397cdaf11222 [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
Georg Brandlc6fdec62006-10-28 13:10:17 +000011from test.test_support import run_unittest, check_syntax_error
12import unittest
Jeremy Hylton7d3dff22001-10-10 01:45:02 +000013import sys
Georg Brandlc6fdec62006-10-28 13:10:17 +000014# testing import *
15from sys import *
Guido van Rossum3bead091992-01-27 17:00:37 +000016
Georg Brandlc6fdec62006-10-28 13:10:17 +000017class TokenTests(unittest.TestCase):
Guido van Rossum3bead091992-01-27 17:00:37 +000018
Georg Brandlc6fdec62006-10-28 13:10:17 +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
Georg Brandlc6fdec62006-10-28 13:10:17 +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
Georg Brandlc6fdec62006-10-28 13:10:17 +000029 def testPlainIntegers(self):
30 self.assertEquals(0xff, 255)
31 self.assertEquals(0377, 255)
32 self.assertEquals(2147483647, 017777777777)
Georg Brandl14404b62008-01-19 19:27:05 +000033 # "0x" is not a valid literal
34 self.assertRaises(SyntaxError, eval, "0x")
Georg Brandlc6fdec62006-10-28 13:10:17 +000035 from sys import maxint
36 if maxint == 2147483647:
37 self.assertEquals(-2147483647-1, -020000000000)
38 # XXX -2147483648
39 self.assert_(037777777777 > 0)
40 self.assert_(0xffffffff > 0)
41 for s in '2147483648', '040000000000', '0x100000000':
42 try:
43 x = eval(s)
44 except OverflowError:
45 self.fail("OverflowError on huge integer literal %r" % s)
46 elif maxint == 9223372036854775807:
47 self.assertEquals(-9223372036854775807-1, -01000000000000000000000)
48 self.assert_(01777777777777777777777 > 0)
49 self.assert_(0xffffffffffffffff > 0)
50 for s in '9223372036854775808', '02000000000000000000000', \
51 '0x10000000000000000':
52 try:
53 x = eval(s)
54 except OverflowError:
55 self.fail("OverflowError on huge integer literal %r" % s)
56 else:
57 self.fail('Weird maxint value %r' % maxint)
Guido van Rossum3bead091992-01-27 17:00:37 +000058
Georg Brandlc6fdec62006-10-28 13:10:17 +000059 def testLongIntegers(self):
60 x = 0L
61 x = 0l
62 x = 0xffffffffffffffffL
63 x = 0xffffffffffffffffl
64 x = 077777777777777777L
65 x = 077777777777777777l
66 x = 123456789012345678901234567890L
67 x = 123456789012345678901234567890l
Guido van Rossum3bead091992-01-27 17:00:37 +000068
Georg Brandlc6fdec62006-10-28 13:10:17 +000069 def testFloats(self):
70 x = 3.14
71 x = 314.
72 x = 0.314
73 # XXX x = 000.314
74 x = .314
75 x = 3e14
76 x = 3E14
77 x = 3e-14
78 x = 3e+14
79 x = 3.e14
80 x = .3e14
81 x = 3.1e4
Guido van Rossum3bead091992-01-27 17:00:37 +000082
Georg Brandlc6fdec62006-10-28 13:10:17 +000083 def testStringLiterals(self):
84 x = ''; y = ""; self.assert_(len(x) == 0 and x == y)
85 x = '\''; y = "'"; self.assert_(len(x) == 1 and x == y and ord(x) == 39)
86 x = '"'; y = "\""; self.assert_(len(x) == 1 and x == y and ord(x) == 34)
87 x = "doesn't \"shrink\" does it"
88 y = 'doesn\'t "shrink" does it'
89 self.assert_(len(x) == 24 and x == y)
90 x = "does \"shrink\" doesn't it"
91 y = 'does "shrink" doesn\'t it'
92 self.assert_(len(x) == 24 and x == y)
93 x = """
Guido van Rossumb6775db1994-08-01 11:34:53 +000094The "quick"
95brown fox
96jumps over
97the 'lazy' dog.
98"""
Georg Brandlc6fdec62006-10-28 13:10:17 +000099 y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
100 self.assertEquals(x, y)
101 y = '''
Guido van Rossumb6775db1994-08-01 11:34:53 +0000102The "quick"
103brown fox
104jumps over
105the 'lazy' dog.
Georg Brandlc6fdec62006-10-28 13:10:17 +0000106'''
107 self.assertEquals(x, y)
108 y = "\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000109The \"quick\"\n\
110brown fox\n\
111jumps over\n\
112the 'lazy' dog.\n\
Georg Brandlc6fdec62006-10-28 13:10:17 +0000113"
114 self.assertEquals(x, y)
115 y = '\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000116The \"quick\"\n\
117brown fox\n\
118jumps over\n\
119the \'lazy\' dog.\n\
Georg Brandlc6fdec62006-10-28 13:10:17 +0000120'
121 self.assertEquals(x, y)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000122
123
Georg Brandlc6fdec62006-10-28 13:10:17 +0000124class GrammarTests(unittest.TestCase):
Guido van Rossum3bead091992-01-27 17:00:37 +0000125
Georg Brandlc6fdec62006-10-28 13:10:17 +0000126 # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
127 # XXX can't test in a script -- this rule is only used when interactive
Tim Petersabd8a332006-11-03 02:32:46 +0000128
Georg Brandlc6fdec62006-10-28 13:10:17 +0000129 # file_input: (NEWLINE | stmt)* ENDMARKER
130 # Being tested as this very moment this very module
Tim Petersabd8a332006-11-03 02:32:46 +0000131
Georg Brandlc6fdec62006-10-28 13:10:17 +0000132 # expr_input: testlist NEWLINE
133 # XXX Hard to test -- used only in calls to input()
Guido van Rossum3bead091992-01-27 17:00:37 +0000134
Georg Brandlc6fdec62006-10-28 13:10:17 +0000135 def testEvalInput(self):
136 # testlist ENDMARKER
137 x = eval('1, 0 or 1')
Guido van Rossum3bead091992-01-27 17:00:37 +0000138
Georg Brandlc6fdec62006-10-28 13:10:17 +0000139 def testFuncdef(self):
140 ### 'def' NAME parameters ':' suite
141 ### parameters: '(' [varargslist] ')'
142 ### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME]
143 ### | ('**'|'*' '*') NAME)
144 ### | fpdef ['=' test] (',' fpdef ['=' test])* [',']
145 ### fpdef: NAME | '(' fplist ')'
146 ### fplist: fpdef (',' fpdef)* [',']
147 ### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test)
148 ### argument: [test '='] test # Really [keyword '='] test
149 def f1(): pass
150 f1()
151 f1(*())
152 f1(*(), **{})
153 def f2(one_argument): pass
154 def f3(two, arguments): pass
155 def f4(two, (compound, (argument, list))): pass
156 def f5((compound, first), two): pass
157 self.assertEquals(f2.func_code.co_varnames, ('one_argument',))
158 self.assertEquals(f3.func_code.co_varnames, ('two', 'arguments'))
159 if sys.platform.startswith('java'):
160 self.assertEquals(f4.func_code.co_varnames,
161 ('two', '(compound, (argument, list))', 'compound', 'argument',
162 'list',))
163 self.assertEquals(f5.func_code.co_varnames,
164 ('(compound, first)', 'two', 'compound', 'first'))
165 else:
166 self.assertEquals(f4.func_code.co_varnames,
167 ('two', '.1', 'compound', 'argument', 'list'))
168 self.assertEquals(f5.func_code.co_varnames,
169 ('.0', 'two', 'compound', 'first'))
170 def a1(one_arg,): pass
171 def a2(two, args,): pass
172 def v0(*rest): pass
173 def v1(a, *rest): pass
174 def v2(a, b, *rest): pass
175 def v3(a, (b, c), *rest): return a, b, c, rest
Guido van Rossum3bead091992-01-27 17:00:37 +0000176
Georg Brandlc6fdec62006-10-28 13:10:17 +0000177 f1()
178 f2(1)
179 f2(1,)
180 f3(1, 2)
181 f3(1, 2,)
182 f4(1, (2, (3, 4)))
183 v0()
184 v0(1)
185 v0(1,)
186 v0(1,2)
187 v0(1,2,3,4,5,6,7,8,9,0)
188 v1(1)
189 v1(1,)
190 v1(1,2)
191 v1(1,2,3)
192 v1(1,2,3,4,5,6,7,8,9,0)
193 v2(1,2)
194 v2(1,2,3)
195 v2(1,2,3,4)
196 v2(1,2,3,4,5,6,7,8,9,0)
197 v3(1,(2,3))
198 v3(1,(2,3),4)
199 v3(1,(2,3),4,5,6,7,8,9,0)
Guido van Rossum3bead091992-01-27 17:00:37 +0000200
Georg Brandlc6fdec62006-10-28 13:10:17 +0000201 # ceval unpacks the formal arguments into the first argcount names;
202 # thus, the names nested inside tuples must appear after these names.
203 if sys.platform.startswith('java'):
204 self.assertEquals(v3.func_code.co_varnames, ('a', '(b, c)', 'rest', 'b', 'c'))
205 else:
206 self.assertEquals(v3.func_code.co_varnames, ('a', '.1', 'rest', 'b', 'c'))
207 self.assertEquals(v3(1, (2, 3), 4), (1, 2, 3, (4,)))
208 def d01(a=1): pass
209 d01()
210 d01(1)
211 d01(*(1,))
212 d01(**{'a':2})
213 def d11(a, b=1): pass
214 d11(1)
215 d11(1, 2)
216 d11(1, **{'b':2})
217 def d21(a, b, c=1): pass
218 d21(1, 2)
219 d21(1, 2, 3)
220 d21(*(1, 2, 3))
221 d21(1, *(2, 3))
222 d21(1, 2, *(3,))
223 d21(1, 2, **{'c':3})
224 def d02(a=1, b=2): pass
225 d02()
226 d02(1)
227 d02(1, 2)
228 d02(*(1, 2))
229 d02(1, *(2,))
230 d02(1, **{'b':2})
231 d02(**{'a': 1, 'b': 2})
232 def d12(a, b=1, c=2): pass
233 d12(1)
234 d12(1, 2)
235 d12(1, 2, 3)
236 def d22(a, b, c=1, d=2): pass
237 d22(1, 2)
238 d22(1, 2, 3)
239 d22(1, 2, 3, 4)
240 def d01v(a=1, *rest): pass
241 d01v()
242 d01v(1)
243 d01v(1, 2)
244 d01v(*(1, 2, 3, 4))
245 d01v(*(1,))
246 d01v(**{'a':2})
247 def d11v(a, b=1, *rest): pass
248 d11v(1)
249 d11v(1, 2)
250 d11v(1, 2, 3)
251 def d21v(a, b, c=1, *rest): pass
252 d21v(1, 2)
253 d21v(1, 2, 3)
254 d21v(1, 2, 3, 4)
255 d21v(*(1, 2, 3, 4))
256 d21v(1, 2, **{'c': 3})
257 def d02v(a=1, b=2, *rest): pass
258 d02v()
259 d02v(1)
260 d02v(1, 2)
261 d02v(1, 2, 3)
262 d02v(1, *(2, 3, 4))
263 d02v(**{'a': 1, 'b': 2})
264 def d12v(a, b=1, c=2, *rest): pass
265 d12v(1)
266 d12v(1, 2)
267 d12v(1, 2, 3)
268 d12v(1, 2, 3, 4)
269 d12v(*(1, 2, 3, 4))
270 d12v(1, 2, *(3, 4, 5))
271 d12v(1, *(2,), **{'c': 3})
272 def d22v(a, b, c=1, d=2, *rest): pass
273 d22v(1, 2)
274 d22v(1, 2, 3)
275 d22v(1, 2, 3, 4)
276 d22v(1, 2, 3, 4, 5)
277 d22v(*(1, 2, 3, 4))
278 d22v(1, 2, *(3, 4, 5))
279 d22v(1, *(2, 3), **{'d': 4})
280 def d31v((x)): pass
281 d31v(1)
282 def d32v((x,)): pass
283 d32v((1,))
Guido van Rossum3bead091992-01-27 17:00:37 +0000284
Georg Brandlc6fdec62006-10-28 13:10:17 +0000285 def testLambdef(self):
286 ### lambdef: 'lambda' [varargslist] ':' test
287 l1 = lambda : 0
288 self.assertEquals(l1(), 0)
289 l2 = lambda : a[d] # XXX just testing the expression
290 l3 = lambda : [2 < x for x in [-1, 3, 0L]]
291 self.assertEquals(l3(), [0, 1, 0])
292 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
293 self.assertEquals(l4(), 1)
294 l5 = lambda x, y, z=2: x + y + z
295 self.assertEquals(l5(1, 2), 5)
296 self.assertEquals(l5(1, 2, 3), 6)
297 check_syntax_error(self, "lambda x: x = 2")
Jeremy Hylton619eea62001-01-25 20:12:27 +0000298
Georg Brandlc6fdec62006-10-28 13:10:17 +0000299 ### stmt: simple_stmt | compound_stmt
300 # Tested below
Guido van Rossum3bead091992-01-27 17:00:37 +0000301
Georg Brandlc6fdec62006-10-28 13:10:17 +0000302 def testSimpleStmt(self):
303 ### simple_stmt: small_stmt (';' small_stmt)* [';']
304 x = 1; pass; del x
305 def foo():
306 # verify statments that end with semi-colons
307 x = 1; pass; del x;
308 foo()
Guido van Rossum3bead091992-01-27 17:00:37 +0000309
Georg Brandlc6fdec62006-10-28 13:10:17 +0000310 ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt
311 # Tested below
Guido van Rossum3bead091992-01-27 17:00:37 +0000312
Georg Brandlc6fdec62006-10-28 13:10:17 +0000313 def testExprStmt(self):
314 # (exprlist '=')* exprlist
315 1
316 1, 2, 3
317 x = 1
318 x = 1, 2, 3
319 x = y = z = 1, 2, 3
320 x, y, z = 1, 2, 3
321 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000322
Georg Brandlc6fdec62006-10-28 13:10:17 +0000323 check_syntax_error(self, "x + 1 = 1")
324 check_syntax_error(self, "a + 1 = b + 2")
Jeremy Hylton47793992001-02-19 15:35:26 +0000325
Georg Brandlc6fdec62006-10-28 13:10:17 +0000326 def testPrintStmt(self):
327 # 'print' (test ',')* [test]
328 import StringIO
Guido van Rossum3bead091992-01-27 17:00:37 +0000329
Georg Brandlc6fdec62006-10-28 13:10:17 +0000330 # Can't test printing to real stdout without comparing output
331 # which is not available in unittest.
332 save_stdout = sys.stdout
333 sys.stdout = StringIO.StringIO()
Tim Petersabd8a332006-11-03 02:32:46 +0000334
Georg Brandlc6fdec62006-10-28 13:10:17 +0000335 print 1, 2, 3
336 print 1, 2, 3,
337 print
338 print 0 or 1, 0 or 1,
339 print 0 or 1
Barry Warsawefc92ee2000-08-21 15:46:50 +0000340
Georg Brandlc6fdec62006-10-28 13:10:17 +0000341 # 'print' '>>' test ','
342 print >> sys.stdout, 1, 2, 3
343 print >> sys.stdout, 1, 2, 3,
344 print >> sys.stdout
345 print >> sys.stdout, 0 or 1, 0 or 1,
346 print >> sys.stdout, 0 or 1
Barry Warsaw9182b452000-08-29 04:57:10 +0000347
Georg Brandlc6fdec62006-10-28 13:10:17 +0000348 # test printing to an instance
349 class Gulp:
350 def write(self, msg): pass
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000351
Georg Brandlc6fdec62006-10-28 13:10:17 +0000352 gulp = Gulp()
353 print >> gulp, 1, 2, 3
354 print >> gulp, 1, 2, 3,
355 print >> gulp
356 print >> gulp, 0 or 1, 0 or 1,
357 print >> gulp, 0 or 1
Barry Warsaw9182b452000-08-29 04:57:10 +0000358
Georg Brandlc6fdec62006-10-28 13:10:17 +0000359 # test print >> None
360 def driver():
361 oldstdout = sys.stdout
362 sys.stdout = Gulp()
363 try:
364 tellme(Gulp())
365 tellme()
366 finally:
367 sys.stdout = oldstdout
Barry Warsaw9182b452000-08-29 04:57:10 +0000368
Georg Brandlc6fdec62006-10-28 13:10:17 +0000369 # we should see this once
370 def tellme(file=sys.stdout):
371 print >> file, 'hello world'
Barry Warsaw9182b452000-08-29 04:57:10 +0000372
Georg Brandlc6fdec62006-10-28 13:10:17 +0000373 driver()
Barry Warsaw9182b452000-08-29 04:57:10 +0000374
Georg Brandlc6fdec62006-10-28 13:10:17 +0000375 # we should not see this at all
376 def tellme(file=None):
377 print >> file, 'goodbye universe'
Barry Warsaw9182b452000-08-29 04:57:10 +0000378
Georg Brandlc6fdec62006-10-28 13:10:17 +0000379 driver()
Barry Warsawefc92ee2000-08-21 15:46:50 +0000380
Georg Brandlc6fdec62006-10-28 13:10:17 +0000381 self.assertEqual(sys.stdout.getvalue(), '''\
3821 2 3
3831 2 3
3841 1 1
3851 2 3
3861 2 3
3871 1 1
388hello world
389''')
390 sys.stdout = save_stdout
Guido van Rossum3bead091992-01-27 17:00:37 +0000391
Georg Brandlc6fdec62006-10-28 13:10:17 +0000392 # syntax errors
393 check_syntax_error(self, 'print ,')
394 check_syntax_error(self, 'print >> x,')
Guido van Rossum3bead091992-01-27 17:00:37 +0000395
Georg Brandlc6fdec62006-10-28 13:10:17 +0000396 def testDelStmt(self):
397 # 'del' exprlist
398 abc = [1,2,3]
399 x, y, z = abc
400 xyz = x, y, z
Guido van Rossum3bead091992-01-27 17:00:37 +0000401
Georg Brandlc6fdec62006-10-28 13:10:17 +0000402 del abc
403 del x, y, (z, xyz)
Guido van Rossum3bead091992-01-27 17:00:37 +0000404
Georg Brandlc6fdec62006-10-28 13:10:17 +0000405 def testPassStmt(self):
406 # 'pass'
407 pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000408
Georg Brandlc6fdec62006-10-28 13:10:17 +0000409 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
410 # Tested below
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000411
Georg Brandlc6fdec62006-10-28 13:10:17 +0000412 def testBreakStmt(self):
413 # 'break'
414 while 1: break
Tim Peters10fb3862001-02-09 20:17:14 +0000415
Georg Brandlc6fdec62006-10-28 13:10:17 +0000416 def testContinueStmt(self):
417 # 'continue'
418 i = 1
419 while i: i = 0; continue
Thomas Wouters80d373c2001-09-26 12:43:39 +0000420
Georg Brandlc6fdec62006-10-28 13:10:17 +0000421 msg = ""
422 while not msg:
423 msg = "ok"
424 try:
425 continue
426 msg = "continue failed to continue inside try"
427 except:
428 msg = "continue inside try called except block"
429 if msg != "ok":
430 self.fail(msg)
Thomas Wouters80d373c2001-09-26 12:43:39 +0000431
Georg Brandlc6fdec62006-10-28 13:10:17 +0000432 msg = ""
433 while not msg:
434 msg = "finally block not called"
435 try:
436 continue
437 finally:
438 msg = "ok"
439 if msg != "ok":
440 self.fail(msg)
441
442 def test_break_continue_loop(self):
443 # This test warrants an explanation. It is a test specifically for SF bugs
444 # #463359 and #462937. The bug is that a 'break' statement executed or
445 # exception raised inside a try/except inside a loop, *after* a continue
446 # statement has been executed in that loop, will cause the wrong number of
447 # arguments to be popped off the stack and the instruction pointer reset to
448 # a very small number (usually 0.) Because of this, the following test
449 # *must* written as a function, and the tracking vars *must* be function
450 # arguments with default values. Otherwise, the test will loop and loop.
451
452 def test_inner(extra_burning_oil = 1, count=0):
453 big_hippo = 2
454 while big_hippo:
455 count += 1
456 try:
457 if extra_burning_oil and big_hippo == 1:
458 extra_burning_oil -= 1
459 break
460 big_hippo -= 1
461 continue
462 except:
463 raise
464 if count > 2 or big_hippo <> 1:
465 self.fail("continue then break in try/except in loop broken!")
466 test_inner()
467
468 def testReturn(self):
469 # 'return' [testlist]
470 def g1(): return
471 def g2(): return 1
472 g1()
473 x = g2()
474 check_syntax_error(self, "class foo:return 1")
475
476 def testYield(self):
477 check_syntax_error(self, "class foo:yield 1")
478
479 def testRaise(self):
480 # 'raise' test [',' test]
481 try: raise RuntimeError, 'just testing'
482 except RuntimeError: pass
483 try: raise KeyboardInterrupt
484 except KeyboardInterrupt: pass
485
486 def testImport(self):
487 # 'import' dotted_as_names
488 import sys
489 import time, sys
490 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
491 from time import time
492 from time import (time)
493 # not testable inside a function, but already done at top of the module
494 # from sys import *
495 from sys import path, argv
496 from sys import (path, argv)
497 from sys import (path, argv,)
498
499 def testGlobal(self):
500 # 'global' NAME (',' NAME)*
501 global a
502 global a, b
503 global one, two, three, four, five, six, seven, eight, nine, ten
504
505 def testExec(self):
506 # 'exec' expr ['in' expr [',' expr]]
507 z = None
508 del z
509 exec 'z=1+1\n'
510 if z != 2: self.fail('exec \'z=1+1\'\\n')
511 del z
512 exec 'z=1+1'
513 if z != 2: self.fail('exec \'z=1+1\'')
514 z = None
515 del z
516 import types
517 if hasattr(types, "UnicodeType"):
518 exec r"""if 1:
519 exec u'z=1+1\n'
520 if z != 2: self.fail('exec u\'z=1+1\'\\n')
521 del z
522 exec u'z=1+1'
523 if z != 2: self.fail('exec u\'z=1+1\'')"""
524 g = {}
525 exec 'z = 1' in g
526 if g.has_key('__builtins__'): del g['__builtins__']
527 if g != {'z': 1}: self.fail('exec \'z = 1\' in g')
528 g = {}
529 l = {}
530
531 import warnings
532 warnings.filterwarnings("ignore", "global statement", module="<string>")
533 exec 'global a; a = 1; b = 2' in g, l
534 if g.has_key('__builtins__'): del g['__builtins__']
535 if l.has_key('__builtins__'): del l['__builtins__']
536 if (g, l) != ({'a':1}, {'b':2}):
537 self.fail('exec ... in g (%s), l (%s)' %(g,l))
538
539 def testAssert(self):
540 # assert_stmt: 'assert' test [',' test]
541 assert 1
542 assert 1, 1
543 assert lambda x:x
544 assert 1, lambda x:x+1
Thomas Wouters80d373c2001-09-26 12:43:39 +0000545 try:
Georg Brandlc6fdec62006-10-28 13:10:17 +0000546 assert 0, "msg"
547 except AssertionError, e:
548 self.assertEquals(e.args[0], "msg")
Georg Brandlfacd2732006-10-29 09:18:00 +0000549 else:
550 if __debug__:
551 self.fail("AssertionError not raised by assert 0")
Thomas Wouters80d373c2001-09-26 12:43:39 +0000552
Georg Brandlc6fdec62006-10-28 13:10:17 +0000553 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
554 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000555
Georg Brandlc6fdec62006-10-28 13:10:17 +0000556 def testIf(self):
557 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
558 if 1: pass
559 if 1: pass
560 else: pass
561 if 0: pass
562 elif 0: pass
563 if 0: pass
564 elif 0: pass
565 elif 0: pass
566 elif 0: pass
567 else: pass
Tim Petersabd8a332006-11-03 02:32:46 +0000568
Georg Brandlc6fdec62006-10-28 13:10:17 +0000569 def testWhile(self):
570 # 'while' test ':' suite ['else' ':' suite]
571 while 0: pass
572 while 0: pass
573 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000574
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +0000575 # Issue1920: "while 0" is optimized away,
576 # ensure that the "else" clause is still present.
577 x = 0
578 while 0:
579 x = 1
580 else:
581 x = 2
582 self.assertEquals(x, 2)
583
Georg Brandlc6fdec62006-10-28 13:10:17 +0000584 def testFor(self):
585 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
586 for i in 1, 2, 3: pass
587 for i, j, k in (): pass
588 else: pass
589 class Squares:
590 def __init__(self, max):
591 self.max = max
592 self.sofar = []
593 def __len__(self): return len(self.sofar)
594 def __getitem__(self, i):
595 if not 0 <= i < self.max: raise IndexError
596 n = len(self.sofar)
597 while n <= i:
598 self.sofar.append(n*n)
599 n = n+1
600 return self.sofar[i]
601 n = 0
602 for x in Squares(10): n = n+x
603 if n != 285:
604 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000605
Georg Brandlc6fdec62006-10-28 13:10:17 +0000606 result = []
607 for x, in [(1,), (2,), (3,)]:
608 result.append(x)
609 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000610
Georg Brandlc6fdec62006-10-28 13:10:17 +0000611 def testTry(self):
612 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
613 ### | 'try' ':' suite 'finally' ':' suite
Collin Winter62903052007-05-18 23:11:24 +0000614 ### except_clause: 'except' [expr [('as' | ',') expr]]
Georg Brandlc6fdec62006-10-28 13:10:17 +0000615 try:
616 1/0
617 except ZeroDivisionError:
618 pass
619 else:
620 pass
621 try: 1/0
622 except EOFError: pass
Collin Winter62903052007-05-18 23:11:24 +0000623 except TypeError as msg: pass
Georg Brandlc6fdec62006-10-28 13:10:17 +0000624 except RuntimeError, msg: pass
625 except: pass
626 else: pass
627 try: 1/0
628 except (EOFError, TypeError, ZeroDivisionError): pass
629 try: 1/0
630 except (EOFError, TypeError, ZeroDivisionError), msg: pass
631 try: pass
632 finally: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000633
Georg Brandlc6fdec62006-10-28 13:10:17 +0000634 def testSuite(self):
635 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
636 if 1: pass
637 if 1:
638 pass
639 if 1:
640 #
641 #
642 #
643 pass
644 pass
645 #
646 pass
647 #
Jeremy Hylton2922ea82001-02-28 23:49:19 +0000648
Georg Brandlc6fdec62006-10-28 13:10:17 +0000649 def testTest(self):
650 ### and_test ('or' and_test)*
651 ### and_test: not_test ('and' not_test)*
652 ### not_test: 'not' not_test | comparison
653 if not 1: pass
654 if 1 and 1: pass
655 if 1 or 1: pass
656 if not not not 1: pass
657 if not 1 and 1 and 1: pass
658 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
659
660 def testComparison(self):
661 ### comparison: expr (comp_op expr)*
662 ### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
663 if 1: pass
664 x = (1 == 1)
665 if 1 == 1: pass
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 != 1 in 1 not in 1 is 1 is not 1: pass
677
678 def testBinaryMaskOps(self):
679 x = 1 & 1
680 x = 1 ^ 1
681 x = 1 | 1
682
683 def testShiftOps(self):
684 x = 1 << 1
685 x = 1 >> 1
686 x = 1 << 1 >> 1
687
688 def testAdditiveOps(self):
689 x = 1
690 x = 1 + 1
691 x = 1 - 1 - 1
692 x = 1 - 1 + 1 - 1 + 1
693
694 def testMultiplicativeOps(self):
695 x = 1 * 1
696 x = 1 / 1
697 x = 1 % 1
698 x = 1 / 1 * 1 % 1
699
700 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
706
707 def testSelectors(self):
708 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
709 ### subscript: expr | [expr] ':' [expr]
Tim Petersabd8a332006-11-03 02:32:46 +0000710
Georg Brandlc6fdec62006-10-28 13:10:17 +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()
735 self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
736
737 def testAtoms(self):
738 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
739 ### dictmaker: test ':' test (',' test ':' test)* [',']
740
741 x = (1)
742 x = (1 or 2 or 3)
743 x = (1 or 2 or 3, 2, 3)
744
745 x = []
746 x = [1]
747 x = [1 or 2 or 3]
748 x = [1 or 2 or 3, 2, 3]
749 x = []
750
751 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}
758
759 x = `x`
760 x = `1 or 2 or 3`
Neal Norwitz85dbec62006-11-04 19:25:22 +0000761 self.assertEqual(`1,2`, '(1, 2)')
762
Georg Brandlc6fdec62006-10-28 13:10:17 +0000763 x = x
764 x = 'x'
765 x = 123
766
767 ### exprlist: expr (',' expr)* [',']
768 ### testlist: test (',' test)* [',']
769 # These have been exercised enough above
770
771 def testClassdef(self):
772 # 'class' NAME ['(' [testlist] ')'] ':' suite
773 class B: pass
774 class B2(): pass
775 class C1(B): pass
776 class C2(B): pass
777 class D(C1, C2, B): pass
778 class C:
779 def meth1(self): pass
780 def meth2(self, arg): pass
781 def meth3(self, a1, a2): pass
Christian Heimes5224d282008-02-23 15:01:05 +0000782 # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
783 # decorators: decorator+
784 # decorated: decorators (classdef | funcdef)
785 def class_decorator(x):
786 x.decorated = True
787 return x
788 @class_decorator
789 class G:
790 pass
791 self.assertEqual(G.decorated, True)
Georg Brandlc6fdec62006-10-28 13:10:17 +0000792
793 def testListcomps(self):
794 # list comprehension tests
795 nums = [1, 2, 3, 4, 5]
796 strs = ["Apple", "Banana", "Coconut"]
797 spcs = [" Apple", " Banana ", "Coco nut "]
798
799 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
800 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
801 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
802 self.assertEqual([(i, s) for i in nums for s in strs],
803 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
804 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
805 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
806 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
807 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
808 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
809 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
810 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
811 (5, 'Banana'), (5, 'Coconut')])
812 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
813 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
814
815 def test_in_func(l):
816 return [None < x < 3 for x in l if x > 2]
817
818 self.assertEqual(test_in_func(nums), [False, False, False])
819
820 def test_nested_front():
821 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
822 [[1, 2], [3, 4], [5, 6]])
823
824 test_nested_front()
825
826 check_syntax_error(self, "[i, s for i in nums for s in strs]")
827 check_syntax_error(self, "[x if y]")
828
829 suppliers = [
830 (1, "Boeing"),
831 (2, "Ford"),
832 (3, "Macdonalds")
833 ]
834
835 parts = [
836 (10, "Airliner"),
837 (20, "Engine"),
838 (30, "Cheeseburger")
839 ]
840
841 suppart = [
842 (1, 10), (1, 20), (2, 20), (3, 30)
843 ]
844
845 x = [
846 (sname, pname)
847 for (sno, sname) in suppliers
848 for (pno, pname) in parts
849 for (sp_sno, sp_pno) in suppart
850 if sno == sp_sno and pno == sp_pno
851 ]
852
853 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
854 ('Macdonalds', 'Cheeseburger')])
855
856 def testGenexps(self):
857 # generator expression tests
858 g = ([x for x in range(10)] for x in range(1))
859 self.assertEqual(g.next(), [x for x in range(10)])
860 try:
861 g.next()
862 self.fail('should produce StopIteration exception')
863 except StopIteration:
864 pass
865
866 a = 1
867 try:
868 g = (a for d in a)
869 g.next()
870 self.fail('should produce TypeError')
871 except TypeError:
872 pass
873
874 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
875 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
876
877 a = [x for x in range(10)]
878 b = (x for x in (y for y in a))
879 self.assertEqual(sum(b), sum([x for x in range(10)]))
880
881 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
882 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
883 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
884 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
885 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
886 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)]))
887 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
888 check_syntax_error(self, "foo(x for x in range(10), 100)")
889 check_syntax_error(self, "foo(100, x for x in range(10))")
890
891 def testComprehensionSpecials(self):
892 # test for outmost iterable precomputation
893 x = 10; g = (i for i in range(x)); x = 5
894 self.assertEqual(len(list(g)), 10)
895
896 # This should hold, since we're only precomputing outmost iterable.
897 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
898 x = 5; t = True;
899 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
900
901 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
902 # even though it's silly. Make sure it works (ifelse broke this.)
903 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
904 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
905
906 # verify unpacking single element tuples in listcomp/genexp.
907 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
908 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
909
910 def testIfElseExpr(self):
911 # Test ifelse expressions in various cases
912 def _checkeval(msg, ret):
913 "helper to check that evaluation of expressions is done correctly"
914 print x
915 return ret
916
917 self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
918 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
919 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])
920 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
921 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
922 self.assertEqual((5 and 6 if 0 else 1), 1)
923 self.assertEqual(((5 and 6) if 0 else 1), 1)
924 self.assertEqual((5 and (6 if 1 else 1)), 6)
925 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
926 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
927 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
928 self.assertEqual((not 5 if 1 else 1), False)
929 self.assertEqual((not 5 if 0 else 1), 1)
930 self.assertEqual((6 + 1 if 1 else 2), 7)
931 self.assertEqual((6 - 1 if 1 else 2), 5)
932 self.assertEqual((6 * 2 if 1 else 4), 12)
933 self.assertEqual((6 / 2 if 1 else 3), 3)
934 self.assertEqual((6 < 4 if 0 else 2), 2)
Guido van Rossumb3b09c91993-10-22 14:24:22 +0000935
936
Georg Brandlc6fdec62006-10-28 13:10:17 +0000937def test_main():
938 run_unittest(TokenTests, GrammarTests)
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000939
Georg Brandlc6fdec62006-10-28 13:10:17 +0000940if __name__ == '__main__':
941 test_main()