blob: 435227521e7829469352d356ba909f5e916e84e9 [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
Georg Brandlc6fdec62006-10-28 13:10:17 +0000575 def testFor(self):
576 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
577 for i in 1, 2, 3: pass
578 for i, j, k in (): pass
579 else: pass
580 class Squares:
581 def __init__(self, max):
582 self.max = max
583 self.sofar = []
584 def __len__(self): return len(self.sofar)
585 def __getitem__(self, i):
586 if not 0 <= i < self.max: raise IndexError
587 n = len(self.sofar)
588 while n <= i:
589 self.sofar.append(n*n)
590 n = n+1
591 return self.sofar[i]
592 n = 0
593 for x in Squares(10): n = n+x
594 if n != 285:
595 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000596
Georg Brandlc6fdec62006-10-28 13:10:17 +0000597 result = []
598 for x, in [(1,), (2,), (3,)]:
599 result.append(x)
600 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000601
Georg Brandlc6fdec62006-10-28 13:10:17 +0000602 def testTry(self):
603 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
604 ### | 'try' ':' suite 'finally' ':' suite
Collin Winter62903052007-05-18 23:11:24 +0000605 ### except_clause: 'except' [expr [('as' | ',') expr]]
Georg Brandlc6fdec62006-10-28 13:10:17 +0000606 try:
607 1/0
608 except ZeroDivisionError:
609 pass
610 else:
611 pass
612 try: 1/0
613 except EOFError: pass
Collin Winter62903052007-05-18 23:11:24 +0000614 except TypeError as msg: pass
Georg Brandlc6fdec62006-10-28 13:10:17 +0000615 except RuntimeError, msg: pass
616 except: pass
617 else: pass
618 try: 1/0
619 except (EOFError, TypeError, ZeroDivisionError): pass
620 try: 1/0
621 except (EOFError, TypeError, ZeroDivisionError), msg: pass
622 try: pass
623 finally: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000624
Georg Brandlc6fdec62006-10-28 13:10:17 +0000625 def testSuite(self):
626 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
627 if 1: pass
628 if 1:
629 pass
630 if 1:
631 #
632 #
633 #
634 pass
635 pass
636 #
637 pass
638 #
Jeremy Hylton2922ea82001-02-28 23:49:19 +0000639
Georg Brandlc6fdec62006-10-28 13:10:17 +0000640 def testTest(self):
641 ### and_test ('or' and_test)*
642 ### and_test: not_test ('and' not_test)*
643 ### not_test: 'not' not_test | comparison
644 if not 1: pass
645 if 1 and 1: pass
646 if 1 or 1: pass
647 if not not not 1: pass
648 if not 1 and 1 and 1: pass
649 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
650
651 def testComparison(self):
652 ### comparison: expr (comp_op expr)*
653 ### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
654 if 1: pass
655 x = (1 == 1)
656 if 1 == 1: pass
657 if 1 != 1: pass
658 if 1 <> 1: pass
659 if 1 < 1: pass
660 if 1 > 1: pass
661 if 1 <= 1: pass
662 if 1 >= 1: pass
663 if 1 is 1: pass
664 if 1 is not 1: pass
665 if 1 in (): pass
666 if 1 not in (): pass
667 if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass
668
669 def testBinaryMaskOps(self):
670 x = 1 & 1
671 x = 1 ^ 1
672 x = 1 | 1
673
674 def testShiftOps(self):
675 x = 1 << 1
676 x = 1 >> 1
677 x = 1 << 1 >> 1
678
679 def testAdditiveOps(self):
680 x = 1
681 x = 1 + 1
682 x = 1 - 1 - 1
683 x = 1 - 1 + 1 - 1 + 1
684
685 def testMultiplicativeOps(self):
686 x = 1 * 1
687 x = 1 / 1
688 x = 1 % 1
689 x = 1 / 1 * 1 % 1
690
691 def testUnaryOps(self):
692 x = +1
693 x = -1
694 x = ~1
695 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
696 x = -1*1/1 + 1*1 - ---1*1
697
698 def testSelectors(self):
699 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
700 ### subscript: expr | [expr] ':' [expr]
Tim Petersabd8a332006-11-03 02:32:46 +0000701
Georg Brandlc6fdec62006-10-28 13:10:17 +0000702 import sys, time
703 c = sys.path[0]
704 x = time.time()
705 x = sys.modules['time'].time()
706 a = '01234'
707 c = a[0]
708 c = a[-1]
709 s = a[0:5]
710 s = a[:5]
711 s = a[0:]
712 s = a[:]
713 s = a[-5:]
714 s = a[:-1]
715 s = a[-4:-3]
716 # A rough test of SF bug 1333982. http://python.org/sf/1333982
717 # The testing here is fairly incomplete.
718 # Test cases should include: commas with 1 and 2 colons
719 d = {}
720 d[1] = 1
721 d[1,] = 2
722 d[1,2] = 3
723 d[1,2,3] = 4
724 L = list(d)
725 L.sort()
726 self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
727
728 def testAtoms(self):
729 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
730 ### dictmaker: test ':' test (',' test ':' test)* [',']
731
732 x = (1)
733 x = (1 or 2 or 3)
734 x = (1 or 2 or 3, 2, 3)
735
736 x = []
737 x = [1]
738 x = [1 or 2 or 3]
739 x = [1 or 2 or 3, 2, 3]
740 x = []
741
742 x = {}
743 x = {'one': 1}
744 x = {'one': 1,}
745 x = {'one' or 'two': 1 or 2}
746 x = {'one': 1, 'two': 2}
747 x = {'one': 1, 'two': 2,}
748 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
749
750 x = `x`
751 x = `1 or 2 or 3`
Neal Norwitz85dbec62006-11-04 19:25:22 +0000752 self.assertEqual(`1,2`, '(1, 2)')
753
Georg Brandlc6fdec62006-10-28 13:10:17 +0000754 x = x
755 x = 'x'
756 x = 123
757
758 ### exprlist: expr (',' expr)* [',']
759 ### testlist: test (',' test)* [',']
760 # These have been exercised enough above
761
762 def testClassdef(self):
763 # 'class' NAME ['(' [testlist] ')'] ':' suite
764 class B: pass
765 class B2(): pass
766 class C1(B): pass
767 class C2(B): pass
768 class D(C1, C2, B): pass
769 class C:
770 def meth1(self): pass
771 def meth2(self, arg): pass
772 def meth3(self, a1, a2): pass
773
774 def testListcomps(self):
775 # list comprehension tests
776 nums = [1, 2, 3, 4, 5]
777 strs = ["Apple", "Banana", "Coconut"]
778 spcs = [" Apple", " Banana ", "Coco nut "]
779
780 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
781 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
782 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
783 self.assertEqual([(i, s) for i in nums for s in strs],
784 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
785 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
786 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
787 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
788 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
789 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
790 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
791 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
792 (5, 'Banana'), (5, 'Coconut')])
793 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
794 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
795
796 def test_in_func(l):
797 return [None < x < 3 for x in l if x > 2]
798
799 self.assertEqual(test_in_func(nums), [False, False, False])
800
801 def test_nested_front():
802 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
803 [[1, 2], [3, 4], [5, 6]])
804
805 test_nested_front()
806
807 check_syntax_error(self, "[i, s for i in nums for s in strs]")
808 check_syntax_error(self, "[x if y]")
809
810 suppliers = [
811 (1, "Boeing"),
812 (2, "Ford"),
813 (3, "Macdonalds")
814 ]
815
816 parts = [
817 (10, "Airliner"),
818 (20, "Engine"),
819 (30, "Cheeseburger")
820 ]
821
822 suppart = [
823 (1, 10), (1, 20), (2, 20), (3, 30)
824 ]
825
826 x = [
827 (sname, pname)
828 for (sno, sname) in suppliers
829 for (pno, pname) in parts
830 for (sp_sno, sp_pno) in suppart
831 if sno == sp_sno and pno == sp_pno
832 ]
833
834 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
835 ('Macdonalds', 'Cheeseburger')])
836
837 def testGenexps(self):
838 # generator expression tests
839 g = ([x for x in range(10)] for x in range(1))
840 self.assertEqual(g.next(), [x for x in range(10)])
841 try:
842 g.next()
843 self.fail('should produce StopIteration exception')
844 except StopIteration:
845 pass
846
847 a = 1
848 try:
849 g = (a for d in a)
850 g.next()
851 self.fail('should produce TypeError')
852 except TypeError:
853 pass
854
855 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
856 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
857
858 a = [x for x in range(10)]
859 b = (x for x in (y for y in a))
860 self.assertEqual(sum(b), sum([x for x in range(10)]))
861
862 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
863 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
864 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
865 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
866 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
867 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)]))
868 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
869 check_syntax_error(self, "foo(x for x in range(10), 100)")
870 check_syntax_error(self, "foo(100, x for x in range(10))")
871
872 def testComprehensionSpecials(self):
873 # test for outmost iterable precomputation
874 x = 10; g = (i for i in range(x)); x = 5
875 self.assertEqual(len(list(g)), 10)
876
877 # This should hold, since we're only precomputing outmost iterable.
878 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
879 x = 5; t = True;
880 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
881
882 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
883 # even though it's silly. Make sure it works (ifelse broke this.)
884 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
885 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
886
887 # verify unpacking single element tuples in listcomp/genexp.
888 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
889 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
890
891 def testIfElseExpr(self):
892 # Test ifelse expressions in various cases
893 def _checkeval(msg, ret):
894 "helper to check that evaluation of expressions is done correctly"
895 print x
896 return ret
897
898 self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
899 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
900 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])
901 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
902 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
903 self.assertEqual((5 and 6 if 0 else 1), 1)
904 self.assertEqual(((5 and 6) if 0 else 1), 1)
905 self.assertEqual((5 and (6 if 1 else 1)), 6)
906 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
907 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
908 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
909 self.assertEqual((not 5 if 1 else 1), False)
910 self.assertEqual((not 5 if 0 else 1), 1)
911 self.assertEqual((6 + 1 if 1 else 2), 7)
912 self.assertEqual((6 - 1 if 1 else 2), 5)
913 self.assertEqual((6 * 2 if 1 else 4), 12)
914 self.assertEqual((6 / 2 if 1 else 3), 3)
915 self.assertEqual((6 < 4 if 0 else 2), 2)
Guido van Rossumb3b09c91993-10-22 14:24:22 +0000916
917
Georg Brandlc6fdec62006-10-28 13:10:17 +0000918def test_main():
919 run_unittest(TokenTests, GrammarTests)
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000920
Georg Brandlc6fdec62006-10-28 13:10:17 +0000921if __name__ == '__main__':
922 test_main()