blob: 0e593677fd50d249452d9dfaa1509a8876807d5b [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
Amaury Forgeot d'Arcd21fb4c2008-03-05 01:50:33 +0000285 # Check ast errors in *args and *kwargs
286 check_syntax_error(self, "f(*g(1=2))")
287 check_syntax_error(self, "f(**g(1=2))")
288
Georg Brandlc6fdec62006-10-28 13:10:17 +0000289 def testLambdef(self):
290 ### lambdef: 'lambda' [varargslist] ':' test
291 l1 = lambda : 0
292 self.assertEquals(l1(), 0)
293 l2 = lambda : a[d] # XXX just testing the expression
294 l3 = lambda : [2 < x for x in [-1, 3, 0L]]
295 self.assertEquals(l3(), [0, 1, 0])
296 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
297 self.assertEquals(l4(), 1)
298 l5 = lambda x, y, z=2: x + y + z
299 self.assertEquals(l5(1, 2), 5)
300 self.assertEquals(l5(1, 2, 3), 6)
301 check_syntax_error(self, "lambda x: x = 2")
Jeremy Hylton619eea62001-01-25 20:12:27 +0000302
Georg Brandlc6fdec62006-10-28 13:10:17 +0000303 ### stmt: simple_stmt | compound_stmt
304 # Tested below
Guido van Rossum3bead091992-01-27 17:00:37 +0000305
Georg Brandlc6fdec62006-10-28 13:10:17 +0000306 def testSimpleStmt(self):
307 ### simple_stmt: small_stmt (';' small_stmt)* [';']
308 x = 1; pass; del x
309 def foo():
310 # verify statments that end with semi-colons
311 x = 1; pass; del x;
312 foo()
Guido van Rossum3bead091992-01-27 17:00:37 +0000313
Georg Brandlc6fdec62006-10-28 13:10:17 +0000314 ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt
315 # Tested below
Guido van Rossum3bead091992-01-27 17:00:37 +0000316
Georg Brandlc6fdec62006-10-28 13:10:17 +0000317 def testExprStmt(self):
318 # (exprlist '=')* exprlist
319 1
320 1, 2, 3
321 x = 1
322 x = 1, 2, 3
323 x = y = z = 1, 2, 3
324 x, y, z = 1, 2, 3
325 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000326
Georg Brandlc6fdec62006-10-28 13:10:17 +0000327 check_syntax_error(self, "x + 1 = 1")
328 check_syntax_error(self, "a + 1 = b + 2")
Jeremy Hylton47793992001-02-19 15:35:26 +0000329
Georg Brandlc6fdec62006-10-28 13:10:17 +0000330 def testPrintStmt(self):
331 # 'print' (test ',')* [test]
332 import StringIO
Guido van Rossum3bead091992-01-27 17:00:37 +0000333
Georg Brandlc6fdec62006-10-28 13:10:17 +0000334 # Can't test printing to real stdout without comparing output
335 # which is not available in unittest.
336 save_stdout = sys.stdout
337 sys.stdout = StringIO.StringIO()
Tim Petersabd8a332006-11-03 02:32:46 +0000338
Georg Brandlc6fdec62006-10-28 13:10:17 +0000339 print 1, 2, 3
340 print 1, 2, 3,
341 print
342 print 0 or 1, 0 or 1,
343 print 0 or 1
Barry Warsawefc92ee2000-08-21 15:46:50 +0000344
Georg Brandlc6fdec62006-10-28 13:10:17 +0000345 # 'print' '>>' test ','
346 print >> sys.stdout, 1, 2, 3
347 print >> sys.stdout, 1, 2, 3,
348 print >> sys.stdout
349 print >> sys.stdout, 0 or 1, 0 or 1,
350 print >> sys.stdout, 0 or 1
Barry Warsaw9182b452000-08-29 04:57:10 +0000351
Georg Brandlc6fdec62006-10-28 13:10:17 +0000352 # test printing to an instance
353 class Gulp:
354 def write(self, msg): pass
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000355
Georg Brandlc6fdec62006-10-28 13:10:17 +0000356 gulp = Gulp()
357 print >> gulp, 1, 2, 3
358 print >> gulp, 1, 2, 3,
359 print >> gulp
360 print >> gulp, 0 or 1, 0 or 1,
361 print >> gulp, 0 or 1
Barry Warsaw9182b452000-08-29 04:57:10 +0000362
Georg Brandlc6fdec62006-10-28 13:10:17 +0000363 # test print >> None
364 def driver():
365 oldstdout = sys.stdout
366 sys.stdout = Gulp()
367 try:
368 tellme(Gulp())
369 tellme()
370 finally:
371 sys.stdout = oldstdout
Barry Warsaw9182b452000-08-29 04:57:10 +0000372
Georg Brandlc6fdec62006-10-28 13:10:17 +0000373 # we should see this once
374 def tellme(file=sys.stdout):
375 print >> file, 'hello world'
Barry Warsaw9182b452000-08-29 04:57:10 +0000376
Georg Brandlc6fdec62006-10-28 13:10:17 +0000377 driver()
Barry Warsaw9182b452000-08-29 04:57:10 +0000378
Georg Brandlc6fdec62006-10-28 13:10:17 +0000379 # we should not see this at all
380 def tellme(file=None):
381 print >> file, 'goodbye universe'
Barry Warsaw9182b452000-08-29 04:57:10 +0000382
Georg Brandlc6fdec62006-10-28 13:10:17 +0000383 driver()
Barry Warsawefc92ee2000-08-21 15:46:50 +0000384
Georg Brandlc6fdec62006-10-28 13:10:17 +0000385 self.assertEqual(sys.stdout.getvalue(), '''\
3861 2 3
3871 2 3
3881 1 1
3891 2 3
3901 2 3
3911 1 1
392hello world
393''')
394 sys.stdout = save_stdout
Guido van Rossum3bead091992-01-27 17:00:37 +0000395
Georg Brandlc6fdec62006-10-28 13:10:17 +0000396 # syntax errors
397 check_syntax_error(self, 'print ,')
398 check_syntax_error(self, 'print >> x,')
Guido van Rossum3bead091992-01-27 17:00:37 +0000399
Georg Brandlc6fdec62006-10-28 13:10:17 +0000400 def testDelStmt(self):
401 # 'del' exprlist
402 abc = [1,2,3]
403 x, y, z = abc
404 xyz = x, y, z
Guido van Rossum3bead091992-01-27 17:00:37 +0000405
Georg Brandlc6fdec62006-10-28 13:10:17 +0000406 del abc
407 del x, y, (z, xyz)
Guido van Rossum3bead091992-01-27 17:00:37 +0000408
Georg Brandlc6fdec62006-10-28 13:10:17 +0000409 def testPassStmt(self):
410 # 'pass'
411 pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000412
Georg Brandlc6fdec62006-10-28 13:10:17 +0000413 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
414 # Tested below
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000415
Georg Brandlc6fdec62006-10-28 13:10:17 +0000416 def testBreakStmt(self):
417 # 'break'
418 while 1: break
Tim Peters10fb3862001-02-09 20:17:14 +0000419
Georg Brandlc6fdec62006-10-28 13:10:17 +0000420 def testContinueStmt(self):
421 # 'continue'
422 i = 1
423 while i: i = 0; continue
Thomas Wouters80d373c2001-09-26 12:43:39 +0000424
Georg Brandlc6fdec62006-10-28 13:10:17 +0000425 msg = ""
426 while not msg:
427 msg = "ok"
428 try:
429 continue
430 msg = "continue failed to continue inside try"
431 except:
432 msg = "continue inside try called except block"
433 if msg != "ok":
434 self.fail(msg)
Thomas Wouters80d373c2001-09-26 12:43:39 +0000435
Georg Brandlc6fdec62006-10-28 13:10:17 +0000436 msg = ""
437 while not msg:
438 msg = "finally block not called"
439 try:
440 continue
441 finally:
442 msg = "ok"
443 if msg != "ok":
444 self.fail(msg)
445
446 def test_break_continue_loop(self):
447 # This test warrants an explanation. It is a test specifically for SF bugs
448 # #463359 and #462937. The bug is that a 'break' statement executed or
449 # exception raised inside a try/except inside a loop, *after* a continue
450 # statement has been executed in that loop, will cause the wrong number of
451 # arguments to be popped off the stack and the instruction pointer reset to
452 # a very small number (usually 0.) Because of this, the following test
453 # *must* written as a function, and the tracking vars *must* be function
454 # arguments with default values. Otherwise, the test will loop and loop.
455
456 def test_inner(extra_burning_oil = 1, count=0):
457 big_hippo = 2
458 while big_hippo:
459 count += 1
460 try:
461 if extra_burning_oil and big_hippo == 1:
462 extra_burning_oil -= 1
463 break
464 big_hippo -= 1
465 continue
466 except:
467 raise
468 if count > 2 or big_hippo <> 1:
469 self.fail("continue then break in try/except in loop broken!")
470 test_inner()
471
472 def testReturn(self):
473 # 'return' [testlist]
474 def g1(): return
475 def g2(): return 1
476 g1()
477 x = g2()
478 check_syntax_error(self, "class foo:return 1")
479
480 def testYield(self):
481 check_syntax_error(self, "class foo:yield 1")
482
483 def testRaise(self):
484 # 'raise' test [',' test]
485 try: raise RuntimeError, 'just testing'
486 except RuntimeError: pass
487 try: raise KeyboardInterrupt
488 except KeyboardInterrupt: pass
489
490 def testImport(self):
491 # 'import' dotted_as_names
492 import sys
493 import time, sys
494 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
495 from time import time
496 from time import (time)
497 # not testable inside a function, but already done at top of the module
498 # from sys import *
499 from sys import path, argv
500 from sys import (path, argv)
501 from sys import (path, argv,)
502
503 def testGlobal(self):
504 # 'global' NAME (',' NAME)*
505 global a
506 global a, b
507 global one, two, three, four, five, six, seven, eight, nine, ten
508
509 def testExec(self):
510 # 'exec' expr ['in' expr [',' expr]]
511 z = None
512 del z
513 exec 'z=1+1\n'
514 if z != 2: self.fail('exec \'z=1+1\'\\n')
515 del z
516 exec 'z=1+1'
517 if z != 2: self.fail('exec \'z=1+1\'')
518 z = None
519 del z
520 import types
521 if hasattr(types, "UnicodeType"):
522 exec r"""if 1:
523 exec u'z=1+1\n'
524 if z != 2: self.fail('exec u\'z=1+1\'\\n')
525 del z
526 exec u'z=1+1'
527 if z != 2: self.fail('exec u\'z=1+1\'')"""
528 g = {}
529 exec 'z = 1' in g
530 if g.has_key('__builtins__'): del g['__builtins__']
531 if g != {'z': 1}: self.fail('exec \'z = 1\' in g')
532 g = {}
533 l = {}
534
535 import warnings
536 warnings.filterwarnings("ignore", "global statement", module="<string>")
537 exec 'global a; a = 1; b = 2' in g, l
538 if g.has_key('__builtins__'): del g['__builtins__']
539 if l.has_key('__builtins__'): del l['__builtins__']
540 if (g, l) != ({'a':1}, {'b':2}):
541 self.fail('exec ... in g (%s), l (%s)' %(g,l))
542
543 def testAssert(self):
544 # assert_stmt: 'assert' test [',' test]
545 assert 1
546 assert 1, 1
547 assert lambda x:x
548 assert 1, lambda x:x+1
Thomas Wouters80d373c2001-09-26 12:43:39 +0000549 try:
Georg Brandlc6fdec62006-10-28 13:10:17 +0000550 assert 0, "msg"
551 except AssertionError, e:
552 self.assertEquals(e.args[0], "msg")
Georg Brandlfacd2732006-10-29 09:18:00 +0000553 else:
554 if __debug__:
555 self.fail("AssertionError not raised by assert 0")
Thomas Wouters80d373c2001-09-26 12:43:39 +0000556
Georg Brandlc6fdec62006-10-28 13:10:17 +0000557 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
558 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000559
Georg Brandlc6fdec62006-10-28 13:10:17 +0000560 def testIf(self):
561 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
562 if 1: pass
563 if 1: pass
564 else: pass
565 if 0: pass
566 elif 0: pass
567 if 0: pass
568 elif 0: pass
569 elif 0: pass
570 elif 0: pass
571 else: pass
Tim Petersabd8a332006-11-03 02:32:46 +0000572
Georg Brandlc6fdec62006-10-28 13:10:17 +0000573 def testWhile(self):
574 # 'while' test ':' suite ['else' ':' suite]
575 while 0: pass
576 while 0: pass
577 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000578
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +0000579 # Issue1920: "while 0" is optimized away,
580 # ensure that the "else" clause is still present.
581 x = 0
582 while 0:
583 x = 1
584 else:
585 x = 2
586 self.assertEquals(x, 2)
587
Georg Brandlc6fdec62006-10-28 13:10:17 +0000588 def testFor(self):
589 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
590 for i in 1, 2, 3: pass
591 for i, j, k in (): pass
592 else: pass
593 class Squares:
594 def __init__(self, max):
595 self.max = max
596 self.sofar = []
597 def __len__(self): return len(self.sofar)
598 def __getitem__(self, i):
599 if not 0 <= i < self.max: raise IndexError
600 n = len(self.sofar)
601 while n <= i:
602 self.sofar.append(n*n)
603 n = n+1
604 return self.sofar[i]
605 n = 0
606 for x in Squares(10): n = n+x
607 if n != 285:
608 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000609
Georg Brandlc6fdec62006-10-28 13:10:17 +0000610 result = []
611 for x, in [(1,), (2,), (3,)]:
612 result.append(x)
613 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000614
Georg Brandlc6fdec62006-10-28 13:10:17 +0000615 def testTry(self):
616 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
617 ### | 'try' ':' suite 'finally' ':' suite
Collin Winter62903052007-05-18 23:11:24 +0000618 ### except_clause: 'except' [expr [('as' | ',') expr]]
Georg Brandlc6fdec62006-10-28 13:10:17 +0000619 try:
620 1/0
621 except ZeroDivisionError:
622 pass
623 else:
624 pass
625 try: 1/0
626 except EOFError: pass
Collin Winter62903052007-05-18 23:11:24 +0000627 except TypeError as msg: pass
Georg Brandlc6fdec62006-10-28 13:10:17 +0000628 except RuntimeError, msg: pass
629 except: pass
630 else: pass
631 try: 1/0
632 except (EOFError, TypeError, ZeroDivisionError): pass
633 try: 1/0
634 except (EOFError, TypeError, ZeroDivisionError), msg: pass
635 try: pass
636 finally: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000637
Georg Brandlc6fdec62006-10-28 13:10:17 +0000638 def testSuite(self):
639 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
640 if 1: pass
641 if 1:
642 pass
643 if 1:
644 #
645 #
646 #
647 pass
648 pass
649 #
650 pass
651 #
Jeremy Hylton2922ea82001-02-28 23:49:19 +0000652
Georg Brandlc6fdec62006-10-28 13:10:17 +0000653 def testTest(self):
654 ### and_test ('or' and_test)*
655 ### and_test: not_test ('and' not_test)*
656 ### not_test: 'not' not_test | comparison
657 if not 1: pass
658 if 1 and 1: pass
659 if 1 or 1: pass
660 if not not not 1: pass
661 if not 1 and 1 and 1: pass
662 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
663
664 def testComparison(self):
665 ### comparison: expr (comp_op expr)*
666 ### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
667 if 1: pass
668 x = (1 == 1)
669 if 1 == 1: pass
670 if 1 != 1: pass
671 if 1 <> 1: pass
672 if 1 < 1: pass
673 if 1 > 1: pass
674 if 1 <= 1: pass
675 if 1 >= 1: pass
676 if 1 is 1: pass
677 if 1 is not 1: pass
678 if 1 in (): pass
679 if 1 not in (): pass
680 if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass
681
682 def testBinaryMaskOps(self):
683 x = 1 & 1
684 x = 1 ^ 1
685 x = 1 | 1
686
687 def testShiftOps(self):
688 x = 1 << 1
689 x = 1 >> 1
690 x = 1 << 1 >> 1
691
692 def testAdditiveOps(self):
693 x = 1
694 x = 1 + 1
695 x = 1 - 1 - 1
696 x = 1 - 1 + 1 - 1 + 1
697
698 def testMultiplicativeOps(self):
699 x = 1 * 1
700 x = 1 / 1
701 x = 1 % 1
702 x = 1 / 1 * 1 % 1
703
704 def testUnaryOps(self):
705 x = +1
706 x = -1
707 x = ~1
708 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
709 x = -1*1/1 + 1*1 - ---1*1
710
711 def testSelectors(self):
712 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
713 ### subscript: expr | [expr] ':' [expr]
Tim Petersabd8a332006-11-03 02:32:46 +0000714
Georg Brandlc6fdec62006-10-28 13:10:17 +0000715 import sys, time
716 c = sys.path[0]
717 x = time.time()
718 x = sys.modules['time'].time()
719 a = '01234'
720 c = a[0]
721 c = a[-1]
722 s = a[0:5]
723 s = a[:5]
724 s = a[0:]
725 s = a[:]
726 s = a[-5:]
727 s = a[:-1]
728 s = a[-4:-3]
729 # A rough test of SF bug 1333982. http://python.org/sf/1333982
730 # The testing here is fairly incomplete.
731 # Test cases should include: commas with 1 and 2 colons
732 d = {}
733 d[1] = 1
734 d[1,] = 2
735 d[1,2] = 3
736 d[1,2,3] = 4
737 L = list(d)
738 L.sort()
739 self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
740
741 def testAtoms(self):
742 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
743 ### dictmaker: test ':' test (',' test ':' test)* [',']
744
745 x = (1)
746 x = (1 or 2 or 3)
747 x = (1 or 2 or 3, 2, 3)
748
749 x = []
750 x = [1]
751 x = [1 or 2 or 3]
752 x = [1 or 2 or 3, 2, 3]
753 x = []
754
755 x = {}
756 x = {'one': 1}
757 x = {'one': 1,}
758 x = {'one' or 'two': 1 or 2}
759 x = {'one': 1, 'two': 2}
760 x = {'one': 1, 'two': 2,}
761 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
762
763 x = `x`
764 x = `1 or 2 or 3`
Neal Norwitz85dbec62006-11-04 19:25:22 +0000765 self.assertEqual(`1,2`, '(1, 2)')
766
Georg Brandlc6fdec62006-10-28 13:10:17 +0000767 x = x
768 x = 'x'
769 x = 123
770
771 ### exprlist: expr (',' expr)* [',']
772 ### testlist: test (',' test)* [',']
773 # These have been exercised enough above
774
775 def testClassdef(self):
776 # 'class' NAME ['(' [testlist] ')'] ':' suite
777 class B: pass
778 class B2(): pass
779 class C1(B): pass
780 class C2(B): pass
781 class D(C1, C2, B): pass
782 class C:
783 def meth1(self): pass
784 def meth2(self, arg): pass
785 def meth3(self, a1, a2): pass
Christian Heimes5224d282008-02-23 15:01:05 +0000786 # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
787 # decorators: decorator+
788 # decorated: decorators (classdef | funcdef)
789 def class_decorator(x):
790 x.decorated = True
791 return x
792 @class_decorator
793 class G:
794 pass
795 self.assertEqual(G.decorated, True)
Georg Brandlc6fdec62006-10-28 13:10:17 +0000796
797 def testListcomps(self):
798 # list comprehension tests
799 nums = [1, 2, 3, 4, 5]
800 strs = ["Apple", "Banana", "Coconut"]
801 spcs = [" Apple", " Banana ", "Coco nut "]
802
803 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
804 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
805 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
806 self.assertEqual([(i, s) for i in nums for s in strs],
807 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
808 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
809 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
810 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
811 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
812 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
813 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
814 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
815 (5, 'Banana'), (5, 'Coconut')])
816 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
817 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
818
819 def test_in_func(l):
820 return [None < x < 3 for x in l if x > 2]
821
822 self.assertEqual(test_in_func(nums), [False, False, False])
823
824 def test_nested_front():
825 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
826 [[1, 2], [3, 4], [5, 6]])
827
828 test_nested_front()
829
830 check_syntax_error(self, "[i, s for i in nums for s in strs]")
831 check_syntax_error(self, "[x if y]")
832
833 suppliers = [
834 (1, "Boeing"),
835 (2, "Ford"),
836 (3, "Macdonalds")
837 ]
838
839 parts = [
840 (10, "Airliner"),
841 (20, "Engine"),
842 (30, "Cheeseburger")
843 ]
844
845 suppart = [
846 (1, 10), (1, 20), (2, 20), (3, 30)
847 ]
848
849 x = [
850 (sname, pname)
851 for (sno, sname) in suppliers
852 for (pno, pname) in parts
853 for (sp_sno, sp_pno) in suppart
854 if sno == sp_sno and pno == sp_pno
855 ]
856
857 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
858 ('Macdonalds', 'Cheeseburger')])
859
860 def testGenexps(self):
861 # generator expression tests
862 g = ([x for x in range(10)] for x in range(1))
863 self.assertEqual(g.next(), [x for x in range(10)])
864 try:
865 g.next()
866 self.fail('should produce StopIteration exception')
867 except StopIteration:
868 pass
869
870 a = 1
871 try:
872 g = (a for d in a)
873 g.next()
874 self.fail('should produce TypeError')
875 except TypeError:
876 pass
877
878 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
879 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
880
881 a = [x for x in range(10)]
882 b = (x for x in (y for y in a))
883 self.assertEqual(sum(b), sum([x for x in range(10)]))
884
885 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
886 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
887 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
888 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
889 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
890 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)]))
891 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
892 check_syntax_error(self, "foo(x for x in range(10), 100)")
893 check_syntax_error(self, "foo(100, x for x in range(10))")
894
895 def testComprehensionSpecials(self):
896 # test for outmost iterable precomputation
897 x = 10; g = (i for i in range(x)); x = 5
898 self.assertEqual(len(list(g)), 10)
899
900 # This should hold, since we're only precomputing outmost iterable.
901 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
902 x = 5; t = True;
903 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
904
905 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
906 # even though it's silly. Make sure it works (ifelse broke this.)
907 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
908 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
909
910 # verify unpacking single element tuples in listcomp/genexp.
911 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
912 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
913
914 def testIfElseExpr(self):
915 # Test ifelse expressions in various cases
916 def _checkeval(msg, ret):
917 "helper to check that evaluation of expressions is done correctly"
918 print x
919 return ret
920
921 self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
922 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
923 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])
924 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
925 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
926 self.assertEqual((5 and 6 if 0 else 1), 1)
927 self.assertEqual(((5 and 6) if 0 else 1), 1)
928 self.assertEqual((5 and (6 if 1 else 1)), 6)
929 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
930 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
931 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
932 self.assertEqual((not 5 if 1 else 1), False)
933 self.assertEqual((not 5 if 0 else 1), 1)
934 self.assertEqual((6 + 1 if 1 else 2), 7)
935 self.assertEqual((6 - 1 if 1 else 2), 5)
936 self.assertEqual((6 * 2 if 1 else 4), 12)
937 self.assertEqual((6 / 2 if 1 else 3), 3)
938 self.assertEqual((6 < 4 if 0 else 2), 2)
Guido van Rossumb3b09c91993-10-22 14:24:22 +0000939
940
Georg Brandlc6fdec62006-10-28 13:10:17 +0000941def test_main():
942 run_unittest(TokenTests, GrammarTests)
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000943
Georg Brandlc6fdec62006-10-28 13:10:17 +0000944if __name__ == '__main__':
945 test_main()