blob: 573a512131c54934c27cb0b68146ed86a084641a [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
Senthil Kumaran3ddc4352010-01-08 18:41:40 +000014import warnings
Georg Brandlc6fdec62006-10-28 13:10:17 +000015# testing import *
16from sys import *
Guido van Rossum3bead091992-01-27 17:00:37 +000017
Georg Brandlc6fdec62006-10-28 13:10:17 +000018class TokenTests(unittest.TestCase):
Guido van Rossum3bead091992-01-27 17:00:37 +000019
Georg Brandlc6fdec62006-10-28 13:10:17 +000020 def testBackslash(self):
21 # Backslash means line continuation:
22 x = 1 \
23 + 1
24 self.assertEquals(x, 2, 'backslash for line continuation')
Guido van Rossum3bead091992-01-27 17:00:37 +000025
Georg Brandlc6fdec62006-10-28 13:10:17 +000026 # Backslash does not means continuation in comments :\
27 x = 0
28 self.assertEquals(x, 0, 'backslash ending comment')
Guido van Rossum3bead091992-01-27 17:00:37 +000029
Georg Brandlc6fdec62006-10-28 13:10:17 +000030 def testPlainIntegers(self):
31 self.assertEquals(0xff, 255)
32 self.assertEquals(0377, 255)
33 self.assertEquals(2147483647, 017777777777)
Georg Brandl14404b62008-01-19 19:27:05 +000034 # "0x" is not a valid literal
35 self.assertRaises(SyntaxError, eval, "0x")
Georg Brandlc6fdec62006-10-28 13:10:17 +000036 from sys import maxint
37 if maxint == 2147483647:
38 self.assertEquals(-2147483647-1, -020000000000)
39 # XXX -2147483648
Benjamin Peterson5c8da862009-06-30 22:57:08 +000040 self.assertTrue(037777777777 > 0)
41 self.assertTrue(0xffffffff > 0)
Georg Brandlc6fdec62006-10-28 13:10:17 +000042 for s in '2147483648', '040000000000', '0x100000000':
43 try:
44 x = eval(s)
45 except OverflowError:
46 self.fail("OverflowError on huge integer literal %r" % s)
47 elif maxint == 9223372036854775807:
48 self.assertEquals(-9223372036854775807-1, -01000000000000000000000)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000049 self.assertTrue(01777777777777777777777 > 0)
50 self.assertTrue(0xffffffffffffffff > 0)
Georg Brandlc6fdec62006-10-28 13:10:17 +000051 for s in '9223372036854775808', '02000000000000000000000', \
52 '0x10000000000000000':
53 try:
54 x = eval(s)
55 except OverflowError:
56 self.fail("OverflowError on huge integer literal %r" % s)
57 else:
58 self.fail('Weird maxint value %r' % maxint)
Guido van Rossum3bead091992-01-27 17:00:37 +000059
Georg Brandlc6fdec62006-10-28 13:10:17 +000060 def testLongIntegers(self):
61 x = 0L
62 x = 0l
63 x = 0xffffffffffffffffL
64 x = 0xffffffffffffffffl
65 x = 077777777777777777L
66 x = 077777777777777777l
67 x = 123456789012345678901234567890L
68 x = 123456789012345678901234567890l
Guido van Rossum3bead091992-01-27 17:00:37 +000069
Georg Brandlc6fdec62006-10-28 13:10:17 +000070 def testFloats(self):
71 x = 3.14
72 x = 314.
73 x = 0.314
74 # XXX x = 000.314
75 x = .314
76 x = 3e14
77 x = 3E14
78 x = 3e-14
79 x = 3e+14
80 x = 3.e14
81 x = .3e14
82 x = 3.1e4
Guido van Rossum3bead091992-01-27 17:00:37 +000083
Georg Brandlc6fdec62006-10-28 13:10:17 +000084 def testStringLiterals(self):
Benjamin Peterson5c8da862009-06-30 22:57:08 +000085 x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y)
86 x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39)
87 x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34)
Georg Brandlc6fdec62006-10-28 13:10:17 +000088 x = "doesn't \"shrink\" does it"
89 y = 'doesn\'t "shrink" does it'
Benjamin Peterson5c8da862009-06-30 22:57:08 +000090 self.assertTrue(len(x) == 24 and x == y)
Georg Brandlc6fdec62006-10-28 13:10:17 +000091 x = "does \"shrink\" doesn't it"
92 y = 'does "shrink" doesn\'t it'
Benjamin Peterson5c8da862009-06-30 22:57:08 +000093 self.assertTrue(len(x) == 24 and x == y)
Georg Brandlc6fdec62006-10-28 13:10:17 +000094 x = """
Guido van Rossumb6775db1994-08-01 11:34:53 +000095The "quick"
96brown fox
97jumps over
98the 'lazy' dog.
99"""
Georg Brandlc6fdec62006-10-28 13:10:17 +0000100 y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
101 self.assertEquals(x, y)
102 y = '''
Guido van Rossumb6775db1994-08-01 11:34:53 +0000103The "quick"
104brown fox
105jumps over
106the 'lazy' dog.
Georg Brandlc6fdec62006-10-28 13:10:17 +0000107'''
108 self.assertEquals(x, y)
109 y = "\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000110The \"quick\"\n\
111brown fox\n\
112jumps over\n\
113the 'lazy' dog.\n\
Georg Brandlc6fdec62006-10-28 13:10:17 +0000114"
115 self.assertEquals(x, y)
116 y = '\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000117The \"quick\"\n\
118brown fox\n\
119jumps over\n\
120the \'lazy\' dog.\n\
Georg Brandlc6fdec62006-10-28 13:10:17 +0000121'
122 self.assertEquals(x, y)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000123
124
Georg Brandlc6fdec62006-10-28 13:10:17 +0000125class GrammarTests(unittest.TestCase):
Guido van Rossum3bead091992-01-27 17:00:37 +0000126
Georg Brandlc6fdec62006-10-28 13:10:17 +0000127 # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
128 # XXX can't test in a script -- this rule is only used when interactive
Tim Petersabd8a332006-11-03 02:32:46 +0000129
Georg Brandlc6fdec62006-10-28 13:10:17 +0000130 # file_input: (NEWLINE | stmt)* ENDMARKER
131 # Being tested as this very moment this very module
Tim Petersabd8a332006-11-03 02:32:46 +0000132
Georg Brandlc6fdec62006-10-28 13:10:17 +0000133 # expr_input: testlist NEWLINE
134 # XXX Hard to test -- used only in calls to input()
Guido van Rossum3bead091992-01-27 17:00:37 +0000135
Georg Brandlc6fdec62006-10-28 13:10:17 +0000136 def testEvalInput(self):
137 # testlist ENDMARKER
138 x = eval('1, 0 or 1')
Guido van Rossum3bead091992-01-27 17:00:37 +0000139
Georg Brandlc6fdec62006-10-28 13:10:17 +0000140 def testFuncdef(self):
141 ### 'def' NAME parameters ':' suite
142 ### parameters: '(' [varargslist] ')'
143 ### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME]
144 ### | ('**'|'*' '*') NAME)
145 ### | fpdef ['=' test] (',' fpdef ['=' test])* [',']
146 ### fpdef: NAME | '(' fplist ')'
147 ### fplist: fpdef (',' fpdef)* [',']
148 ### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test)
149 ### argument: [test '='] test # Really [keyword '='] test
150 def f1(): pass
151 f1()
152 f1(*())
153 f1(*(), **{})
154 def f2(one_argument): pass
155 def f3(two, arguments): pass
Senthil Kumaran3ddc4352010-01-08 18:41:40 +0000156 # Silence Py3k warning
157 exec('def f4(two, (compound, (argument, list))): pass')
158 exec('def f5((compound, first), two): pass')
Georg Brandlc6fdec62006-10-28 13:10:17 +0000159 self.assertEquals(f2.func_code.co_varnames, ('one_argument',))
160 self.assertEquals(f3.func_code.co_varnames, ('two', 'arguments'))
161 if sys.platform.startswith('java'):
162 self.assertEquals(f4.func_code.co_varnames,
163 ('two', '(compound, (argument, list))', 'compound', 'argument',
164 'list',))
165 self.assertEquals(f5.func_code.co_varnames,
166 ('(compound, first)', 'two', 'compound', 'first'))
167 else:
168 self.assertEquals(f4.func_code.co_varnames,
169 ('two', '.1', 'compound', 'argument', 'list'))
170 self.assertEquals(f5.func_code.co_varnames,
171 ('.0', 'two', 'compound', 'first'))
172 def a1(one_arg,): pass
173 def a2(two, args,): pass
174 def v0(*rest): pass
175 def v1(a, *rest): pass
176 def v2(a, b, *rest): pass
Senthil Kumaran3ddc4352010-01-08 18:41:40 +0000177 # Silence Py3k warning
178 exec('def v3(a, (b, c), *rest): return a, b, c, rest')
Guido van Rossum3bead091992-01-27 17:00:37 +0000179
Georg Brandlc6fdec62006-10-28 13:10:17 +0000180 f1()
181 f2(1)
182 f2(1,)
183 f3(1, 2)
184 f3(1, 2,)
185 f4(1, (2, (3, 4)))
186 v0()
187 v0(1)
188 v0(1,)
189 v0(1,2)
190 v0(1,2,3,4,5,6,7,8,9,0)
191 v1(1)
192 v1(1,)
193 v1(1,2)
194 v1(1,2,3)
195 v1(1,2,3,4,5,6,7,8,9,0)
196 v2(1,2)
197 v2(1,2,3)
198 v2(1,2,3,4)
199 v2(1,2,3,4,5,6,7,8,9,0)
200 v3(1,(2,3))
201 v3(1,(2,3),4)
202 v3(1,(2,3),4,5,6,7,8,9,0)
Guido van Rossum3bead091992-01-27 17:00:37 +0000203
Georg Brandlc6fdec62006-10-28 13:10:17 +0000204 # ceval unpacks the formal arguments into the first argcount names;
205 # thus, the names nested inside tuples must appear after these names.
206 if sys.platform.startswith('java'):
207 self.assertEquals(v3.func_code.co_varnames, ('a', '(b, c)', 'rest', 'b', 'c'))
208 else:
209 self.assertEquals(v3.func_code.co_varnames, ('a', '.1', 'rest', 'b', 'c'))
210 self.assertEquals(v3(1, (2, 3), 4), (1, 2, 3, (4,)))
211 def d01(a=1): pass
212 d01()
213 d01(1)
214 d01(*(1,))
215 d01(**{'a':2})
216 def d11(a, b=1): pass
217 d11(1)
218 d11(1, 2)
219 d11(1, **{'b':2})
220 def d21(a, b, c=1): pass
221 d21(1, 2)
222 d21(1, 2, 3)
223 d21(*(1, 2, 3))
224 d21(1, *(2, 3))
225 d21(1, 2, *(3,))
226 d21(1, 2, **{'c':3})
227 def d02(a=1, b=2): pass
228 d02()
229 d02(1)
230 d02(1, 2)
231 d02(*(1, 2))
232 d02(1, *(2,))
233 d02(1, **{'b':2})
234 d02(**{'a': 1, 'b': 2})
235 def d12(a, b=1, c=2): pass
236 d12(1)
237 d12(1, 2)
238 d12(1, 2, 3)
239 def d22(a, b, c=1, d=2): pass
240 d22(1, 2)
241 d22(1, 2, 3)
242 d22(1, 2, 3, 4)
243 def d01v(a=1, *rest): pass
244 d01v()
245 d01v(1)
246 d01v(1, 2)
247 d01v(*(1, 2, 3, 4))
248 d01v(*(1,))
249 d01v(**{'a':2})
250 def d11v(a, b=1, *rest): pass
251 d11v(1)
252 d11v(1, 2)
253 d11v(1, 2, 3)
254 def d21v(a, b, c=1, *rest): pass
255 d21v(1, 2)
256 d21v(1, 2, 3)
257 d21v(1, 2, 3, 4)
258 d21v(*(1, 2, 3, 4))
259 d21v(1, 2, **{'c': 3})
260 def d02v(a=1, b=2, *rest): pass
261 d02v()
262 d02v(1)
263 d02v(1, 2)
264 d02v(1, 2, 3)
265 d02v(1, *(2, 3, 4))
266 d02v(**{'a': 1, 'b': 2})
267 def d12v(a, b=1, c=2, *rest): pass
268 d12v(1)
269 d12v(1, 2)
270 d12v(1, 2, 3)
271 d12v(1, 2, 3, 4)
272 d12v(*(1, 2, 3, 4))
273 d12v(1, 2, *(3, 4, 5))
274 d12v(1, *(2,), **{'c': 3})
275 def d22v(a, b, c=1, d=2, *rest): pass
276 d22v(1, 2)
277 d22v(1, 2, 3)
278 d22v(1, 2, 3, 4)
279 d22v(1, 2, 3, 4, 5)
280 d22v(*(1, 2, 3, 4))
281 d22v(1, 2, *(3, 4, 5))
282 d22v(1, *(2, 3), **{'d': 4})
Senthil Kumaran3ddc4352010-01-08 18:41:40 +0000283 # Silence Py3k warning
284 exec('def d31v((x)): pass')
285 exec('def d32v((x,)): pass')
Georg Brandlc6fdec62006-10-28 13:10:17 +0000286 d31v(1)
Georg Brandlc6fdec62006-10-28 13:10:17 +0000287 d32v((1,))
Guido van Rossum3bead091992-01-27 17:00:37 +0000288
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000289 # keyword arguments after *arglist
290 def f(*args, **kwargs):
291 return args, kwargs
292 self.assertEquals(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
293 {'x':2, 'y':5}))
294 self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)")
295 self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
296
Amaury Forgeot d'Arcd21fb4c2008-03-05 01:50:33 +0000297 # Check ast errors in *args and *kwargs
298 check_syntax_error(self, "f(*g(1=2))")
299 check_syntax_error(self, "f(**g(1=2))")
300
Georg Brandlc6fdec62006-10-28 13:10:17 +0000301 def testLambdef(self):
302 ### lambdef: 'lambda' [varargslist] ':' test
303 l1 = lambda : 0
304 self.assertEquals(l1(), 0)
305 l2 = lambda : a[d] # XXX just testing the expression
306 l3 = lambda : [2 < x for x in [-1, 3, 0L]]
307 self.assertEquals(l3(), [0, 1, 0])
308 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
309 self.assertEquals(l4(), 1)
310 l5 = lambda x, y, z=2: x + y + z
311 self.assertEquals(l5(1, 2), 5)
312 self.assertEquals(l5(1, 2, 3), 6)
313 check_syntax_error(self, "lambda x: x = 2")
Georg Brandla161f602008-06-15 19:54:36 +0000314 check_syntax_error(self, "lambda (None,): None")
Jeremy Hylton619eea62001-01-25 20:12:27 +0000315
Georg Brandlc6fdec62006-10-28 13:10:17 +0000316 ### stmt: simple_stmt | compound_stmt
317 # Tested below
Guido van Rossum3bead091992-01-27 17:00:37 +0000318
Georg Brandlc6fdec62006-10-28 13:10:17 +0000319 def testSimpleStmt(self):
320 ### simple_stmt: small_stmt (';' small_stmt)* [';']
321 x = 1; pass; del x
322 def foo():
323 # verify statments that end with semi-colons
324 x = 1; pass; del x;
325 foo()
Guido van Rossum3bead091992-01-27 17:00:37 +0000326
Georg Brandlc6fdec62006-10-28 13:10:17 +0000327 ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt
328 # Tested below
Guido van Rossum3bead091992-01-27 17:00:37 +0000329
Georg Brandlc6fdec62006-10-28 13:10:17 +0000330 def testExprStmt(self):
331 # (exprlist '=')* exprlist
332 1
333 1, 2, 3
334 x = 1
335 x = 1, 2, 3
336 x = y = z = 1, 2, 3
337 x, y, z = 1, 2, 3
338 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000339
Georg Brandlc6fdec62006-10-28 13:10:17 +0000340 check_syntax_error(self, "x + 1 = 1")
341 check_syntax_error(self, "a + 1 = b + 2")
Jeremy Hylton47793992001-02-19 15:35:26 +0000342
Georg Brandlc6fdec62006-10-28 13:10:17 +0000343 def testPrintStmt(self):
344 # 'print' (test ',')* [test]
345 import StringIO
Guido van Rossum3bead091992-01-27 17:00:37 +0000346
Georg Brandlc6fdec62006-10-28 13:10:17 +0000347 # Can't test printing to real stdout without comparing output
348 # which is not available in unittest.
349 save_stdout = sys.stdout
350 sys.stdout = StringIO.StringIO()
Tim Petersabd8a332006-11-03 02:32:46 +0000351
Georg Brandlc6fdec62006-10-28 13:10:17 +0000352 print 1, 2, 3
353 print 1, 2, 3,
354 print
355 print 0 or 1, 0 or 1,
356 print 0 or 1
Barry Warsawefc92ee2000-08-21 15:46:50 +0000357
Georg Brandlc6fdec62006-10-28 13:10:17 +0000358 # 'print' '>>' test ','
359 print >> sys.stdout, 1, 2, 3
360 print >> sys.stdout, 1, 2, 3,
361 print >> sys.stdout
362 print >> sys.stdout, 0 or 1, 0 or 1,
363 print >> sys.stdout, 0 or 1
Barry Warsaw9182b452000-08-29 04:57:10 +0000364
Georg Brandlc6fdec62006-10-28 13:10:17 +0000365 # test printing to an instance
366 class Gulp:
367 def write(self, msg): pass
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000368
Georg Brandlc6fdec62006-10-28 13:10:17 +0000369 gulp = Gulp()
370 print >> gulp, 1, 2, 3
371 print >> gulp, 1, 2, 3,
372 print >> gulp
373 print >> gulp, 0 or 1, 0 or 1,
374 print >> gulp, 0 or 1
Barry Warsaw9182b452000-08-29 04:57:10 +0000375
Georg Brandlc6fdec62006-10-28 13:10:17 +0000376 # test print >> None
377 def driver():
378 oldstdout = sys.stdout
379 sys.stdout = Gulp()
380 try:
381 tellme(Gulp())
382 tellme()
383 finally:
384 sys.stdout = oldstdout
Barry Warsaw9182b452000-08-29 04:57:10 +0000385
Georg Brandlc6fdec62006-10-28 13:10:17 +0000386 # we should see this once
387 def tellme(file=sys.stdout):
388 print >> file, 'hello world'
Barry Warsaw9182b452000-08-29 04:57:10 +0000389
Georg Brandlc6fdec62006-10-28 13:10:17 +0000390 driver()
Barry Warsaw9182b452000-08-29 04:57:10 +0000391
Georg Brandlc6fdec62006-10-28 13:10:17 +0000392 # we should not see this at all
393 def tellme(file=None):
394 print >> file, 'goodbye universe'
Barry Warsaw9182b452000-08-29 04:57:10 +0000395
Georg Brandlc6fdec62006-10-28 13:10:17 +0000396 driver()
Barry Warsawefc92ee2000-08-21 15:46:50 +0000397
Georg Brandlc6fdec62006-10-28 13:10:17 +0000398 self.assertEqual(sys.stdout.getvalue(), '''\
3991 2 3
4001 2 3
4011 1 1
4021 2 3
4031 2 3
4041 1 1
405hello world
406''')
407 sys.stdout = save_stdout
Guido van Rossum3bead091992-01-27 17:00:37 +0000408
Georg Brandlc6fdec62006-10-28 13:10:17 +0000409 # syntax errors
410 check_syntax_error(self, 'print ,')
411 check_syntax_error(self, 'print >> x,')
Guido van Rossum3bead091992-01-27 17:00:37 +0000412
Georg Brandlc6fdec62006-10-28 13:10:17 +0000413 def testDelStmt(self):
414 # 'del' exprlist
415 abc = [1,2,3]
416 x, y, z = abc
417 xyz = x, y, z
Guido van Rossum3bead091992-01-27 17:00:37 +0000418
Georg Brandlc6fdec62006-10-28 13:10:17 +0000419 del abc
420 del x, y, (z, xyz)
Guido van Rossum3bead091992-01-27 17:00:37 +0000421
Georg Brandlc6fdec62006-10-28 13:10:17 +0000422 def testPassStmt(self):
423 # 'pass'
424 pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000425
Georg Brandlc6fdec62006-10-28 13:10:17 +0000426 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
427 # Tested below
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000428
Georg Brandlc6fdec62006-10-28 13:10:17 +0000429 def testBreakStmt(self):
430 # 'break'
431 while 1: break
Tim Peters10fb3862001-02-09 20:17:14 +0000432
Georg Brandlc6fdec62006-10-28 13:10:17 +0000433 def testContinueStmt(self):
434 # 'continue'
435 i = 1
436 while i: i = 0; continue
Thomas Wouters80d373c2001-09-26 12:43:39 +0000437
Georg Brandlc6fdec62006-10-28 13:10:17 +0000438 msg = ""
439 while not msg:
440 msg = "ok"
441 try:
442 continue
443 msg = "continue failed to continue inside try"
444 except:
445 msg = "continue inside try called except block"
446 if msg != "ok":
447 self.fail(msg)
Thomas Wouters80d373c2001-09-26 12:43:39 +0000448
Georg Brandlc6fdec62006-10-28 13:10:17 +0000449 msg = ""
450 while not msg:
451 msg = "finally block not called"
452 try:
453 continue
454 finally:
455 msg = "ok"
456 if msg != "ok":
457 self.fail(msg)
458
459 def test_break_continue_loop(self):
460 # This test warrants an explanation. It is a test specifically for SF bugs
461 # #463359 and #462937. The bug is that a 'break' statement executed or
462 # exception raised inside a try/except inside a loop, *after* a continue
463 # statement has been executed in that loop, will cause the wrong number of
464 # arguments to be popped off the stack and the instruction pointer reset to
465 # a very small number (usually 0.) Because of this, the following test
466 # *must* written as a function, and the tracking vars *must* be function
467 # arguments with default values. Otherwise, the test will loop and loop.
468
469 def test_inner(extra_burning_oil = 1, count=0):
470 big_hippo = 2
471 while big_hippo:
472 count += 1
473 try:
474 if extra_burning_oil and big_hippo == 1:
475 extra_burning_oil -= 1
476 break
477 big_hippo -= 1
478 continue
479 except:
480 raise
Senthil Kumaran3ddc4352010-01-08 18:41:40 +0000481 if count > 2 or big_hippo != 1:
Georg Brandlc6fdec62006-10-28 13:10:17 +0000482 self.fail("continue then break in try/except in loop broken!")
483 test_inner()
484
485 def testReturn(self):
486 # 'return' [testlist]
487 def g1(): return
488 def g2(): return 1
489 g1()
490 x = g2()
491 check_syntax_error(self, "class foo:return 1")
492
493 def testYield(self):
494 check_syntax_error(self, "class foo:yield 1")
495
496 def testRaise(self):
497 # 'raise' test [',' test]
498 try: raise RuntimeError, 'just testing'
499 except RuntimeError: pass
500 try: raise KeyboardInterrupt
501 except KeyboardInterrupt: pass
502
503 def testImport(self):
504 # 'import' dotted_as_names
505 import sys
506 import time, sys
507 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
508 from time import time
509 from time import (time)
510 # not testable inside a function, but already done at top of the module
511 # from sys import *
512 from sys import path, argv
513 from sys import (path, argv)
514 from sys import (path, argv,)
515
516 def testGlobal(self):
517 # 'global' NAME (',' NAME)*
518 global a
519 global a, b
520 global one, two, three, four, five, six, seven, eight, nine, ten
521
522 def testExec(self):
523 # 'exec' expr ['in' expr [',' expr]]
524 z = None
525 del z
526 exec 'z=1+1\n'
527 if z != 2: self.fail('exec \'z=1+1\'\\n')
528 del z
529 exec 'z=1+1'
530 if z != 2: self.fail('exec \'z=1+1\'')
531 z = None
532 del z
533 import types
534 if hasattr(types, "UnicodeType"):
535 exec r"""if 1:
536 exec u'z=1+1\n'
537 if z != 2: self.fail('exec u\'z=1+1\'\\n')
538 del z
539 exec u'z=1+1'
540 if z != 2: self.fail('exec u\'z=1+1\'')"""
541 g = {}
542 exec 'z = 1' in g
543 if g.has_key('__builtins__'): del g['__builtins__']
544 if g != {'z': 1}: self.fail('exec \'z = 1\' in g')
545 g = {}
546 l = {}
547
548 import warnings
549 warnings.filterwarnings("ignore", "global statement", module="<string>")
550 exec 'global a; a = 1; b = 2' in g, l
551 if g.has_key('__builtins__'): del g['__builtins__']
552 if l.has_key('__builtins__'): del l['__builtins__']
553 if (g, l) != ({'a':1}, {'b':2}):
554 self.fail('exec ... in g (%s), l (%s)' %(g,l))
555
556 def testAssert(self):
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000557 # assertTruestmt: 'assert' test [',' test]
Georg Brandlc6fdec62006-10-28 13:10:17 +0000558 assert 1
559 assert 1, 1
560 assert lambda x:x
561 assert 1, lambda x:x+1
Thomas Wouters80d373c2001-09-26 12:43:39 +0000562 try:
Georg Brandlc6fdec62006-10-28 13:10:17 +0000563 assert 0, "msg"
564 except AssertionError, e:
565 self.assertEquals(e.args[0], "msg")
Georg Brandlfacd2732006-10-29 09:18:00 +0000566 else:
567 if __debug__:
568 self.fail("AssertionError not raised by assert 0")
Thomas Wouters80d373c2001-09-26 12:43:39 +0000569
Georg Brandlc6fdec62006-10-28 13:10:17 +0000570 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
571 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000572
Georg Brandlc6fdec62006-10-28 13:10:17 +0000573 def testIf(self):
574 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
575 if 1: pass
576 if 1: pass
577 else: pass
578 if 0: pass
579 elif 0: pass
580 if 0: pass
581 elif 0: pass
582 elif 0: pass
583 elif 0: pass
584 else: pass
Tim Petersabd8a332006-11-03 02:32:46 +0000585
Georg Brandlc6fdec62006-10-28 13:10:17 +0000586 def testWhile(self):
587 # 'while' test ':' suite ['else' ':' suite]
588 while 0: pass
589 while 0: pass
590 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000591
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +0000592 # Issue1920: "while 0" is optimized away,
593 # ensure that the "else" clause is still present.
594 x = 0
595 while 0:
596 x = 1
597 else:
598 x = 2
599 self.assertEquals(x, 2)
600
Georg Brandlc6fdec62006-10-28 13:10:17 +0000601 def testFor(self):
602 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
603 for i in 1, 2, 3: pass
604 for i, j, k in (): pass
605 else: pass
606 class Squares:
607 def __init__(self, max):
608 self.max = max
609 self.sofar = []
610 def __len__(self): return len(self.sofar)
611 def __getitem__(self, i):
612 if not 0 <= i < self.max: raise IndexError
613 n = len(self.sofar)
614 while n <= i:
615 self.sofar.append(n*n)
616 n = n+1
617 return self.sofar[i]
618 n = 0
619 for x in Squares(10): n = n+x
620 if n != 285:
621 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000622
Georg Brandlc6fdec62006-10-28 13:10:17 +0000623 result = []
624 for x, in [(1,), (2,), (3,)]:
625 result.append(x)
626 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000627
Georg Brandlc6fdec62006-10-28 13:10:17 +0000628 def testTry(self):
629 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
630 ### | 'try' ':' suite 'finally' ':' suite
Collin Winter62903052007-05-18 23:11:24 +0000631 ### except_clause: 'except' [expr [('as' | ',') expr]]
Georg Brandlc6fdec62006-10-28 13:10:17 +0000632 try:
633 1/0
634 except ZeroDivisionError:
635 pass
636 else:
637 pass
638 try: 1/0
639 except EOFError: pass
Collin Winter62903052007-05-18 23:11:24 +0000640 except TypeError as msg: pass
Georg Brandlc6fdec62006-10-28 13:10:17 +0000641 except RuntimeError, msg: pass
642 except: pass
643 else: pass
644 try: 1/0
645 except (EOFError, TypeError, ZeroDivisionError): pass
646 try: 1/0
647 except (EOFError, TypeError, ZeroDivisionError), msg: pass
648 try: pass
649 finally: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000650
Georg Brandlc6fdec62006-10-28 13:10:17 +0000651 def testSuite(self):
652 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
653 if 1: pass
654 if 1:
655 pass
656 if 1:
657 #
658 #
659 #
660 pass
661 pass
662 #
663 pass
664 #
Jeremy Hylton2922ea82001-02-28 23:49:19 +0000665
Georg Brandlc6fdec62006-10-28 13:10:17 +0000666 def testTest(self):
667 ### and_test ('or' and_test)*
668 ### and_test: not_test ('and' not_test)*
669 ### not_test: 'not' not_test | comparison
670 if not 1: pass
671 if 1 and 1: pass
672 if 1 or 1: pass
673 if not not not 1: pass
674 if not 1 and 1 and 1: pass
675 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
676
677 def testComparison(self):
678 ### comparison: expr (comp_op expr)*
679 ### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
680 if 1: pass
681 x = (1 == 1)
682 if 1 == 1: pass
683 if 1 != 1: pass
Georg Brandlc6fdec62006-10-28 13:10:17 +0000684 if 1 < 1: pass
685 if 1 > 1: pass
686 if 1 <= 1: pass
687 if 1 >= 1: pass
688 if 1 is 1: pass
689 if 1 is not 1: pass
690 if 1 in (): pass
691 if 1 not in (): pass
Senthil Kumaran3ddc4352010-01-08 18:41:40 +0000692 if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass
693 # Silence Py3k warning
694 if eval('1 <> 1'): pass
695 if eval('1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1'): pass
Georg Brandlc6fdec62006-10-28 13:10:17 +0000696
697 def testBinaryMaskOps(self):
698 x = 1 & 1
699 x = 1 ^ 1
700 x = 1 | 1
701
702 def testShiftOps(self):
703 x = 1 << 1
704 x = 1 >> 1
705 x = 1 << 1 >> 1
706
707 def testAdditiveOps(self):
708 x = 1
709 x = 1 + 1
710 x = 1 - 1 - 1
711 x = 1 - 1 + 1 - 1 + 1
712
713 def testMultiplicativeOps(self):
714 x = 1 * 1
715 x = 1 / 1
716 x = 1 % 1
717 x = 1 / 1 * 1 % 1
718
719 def testUnaryOps(self):
720 x = +1
721 x = -1
722 x = ~1
723 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
724 x = -1*1/1 + 1*1 - ---1*1
725
726 def testSelectors(self):
727 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
728 ### subscript: expr | [expr] ':' [expr]
Tim Petersabd8a332006-11-03 02:32:46 +0000729
Georg Brandlc6fdec62006-10-28 13:10:17 +0000730 import sys, time
731 c = sys.path[0]
732 x = time.time()
733 x = sys.modules['time'].time()
734 a = '01234'
735 c = a[0]
736 c = a[-1]
737 s = a[0:5]
738 s = a[:5]
739 s = a[0:]
740 s = a[:]
741 s = a[-5:]
742 s = a[:-1]
743 s = a[-4:-3]
744 # A rough test of SF bug 1333982. http://python.org/sf/1333982
745 # The testing here is fairly incomplete.
746 # Test cases should include: commas with 1 and 2 colons
747 d = {}
748 d[1] = 1
749 d[1,] = 2
750 d[1,2] = 3
751 d[1,2,3] = 4
752 L = list(d)
753 L.sort()
754 self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
755
756 def testAtoms(self):
757 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
758 ### dictmaker: test ':' test (',' test ':' test)* [',']
759
760 x = (1)
761 x = (1 or 2 or 3)
762 x = (1 or 2 or 3, 2, 3)
763
764 x = []
765 x = [1]
766 x = [1 or 2 or 3]
767 x = [1 or 2 or 3, 2, 3]
768 x = []
769
770 x = {}
771 x = {'one': 1}
772 x = {'one': 1,}
773 x = {'one' or 'two': 1 or 2}
774 x = {'one': 1, 'two': 2}
775 x = {'one': 1, 'two': 2,}
776 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
777
Senthil Kumaran3ddc4352010-01-08 18:41:40 +0000778 # Silence Py3k warning
779 x = eval('`x`')
780 x = eval('`1 or 2 or 3`')
781 self.assertEqual(eval('`1,2`'), '(1, 2)')
Neal Norwitz85dbec62006-11-04 19:25:22 +0000782
Georg Brandlc6fdec62006-10-28 13:10:17 +0000783 x = x
784 x = 'x'
785 x = 123
786
787 ### exprlist: expr (',' expr)* [',']
788 ### testlist: test (',' test)* [',']
789 # These have been exercised enough above
790
791 def testClassdef(self):
792 # 'class' NAME ['(' [testlist] ')'] ':' suite
793 class B: pass
794 class B2(): pass
795 class C1(B): pass
796 class C2(B): pass
797 class D(C1, C2, B): pass
798 class C:
799 def meth1(self): pass
800 def meth2(self, arg): pass
801 def meth3(self, a1, a2): pass
Christian Heimes5224d282008-02-23 15:01:05 +0000802 # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
803 # decorators: decorator+
804 # decorated: decorators (classdef | funcdef)
805 def class_decorator(x):
806 x.decorated = True
807 return x
808 @class_decorator
809 class G:
810 pass
811 self.assertEqual(G.decorated, True)
Georg Brandlc6fdec62006-10-28 13:10:17 +0000812
813 def testListcomps(self):
814 # list comprehension tests
815 nums = [1, 2, 3, 4, 5]
816 strs = ["Apple", "Banana", "Coconut"]
817 spcs = [" Apple", " Banana ", "Coco nut "]
818
819 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
820 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
821 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
822 self.assertEqual([(i, s) for i in nums for s in strs],
823 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
824 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
825 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
826 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
827 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
828 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
829 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
830 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
831 (5, 'Banana'), (5, 'Coconut')])
832 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
833 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
834
835 def test_in_func(l):
836 return [None < x < 3 for x in l if x > 2]
837
838 self.assertEqual(test_in_func(nums), [False, False, False])
839
840 def test_nested_front():
841 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
842 [[1, 2], [3, 4], [5, 6]])
843
844 test_nested_front()
845
846 check_syntax_error(self, "[i, s for i in nums for s in strs]")
847 check_syntax_error(self, "[x if y]")
848
849 suppliers = [
850 (1, "Boeing"),
851 (2, "Ford"),
852 (3, "Macdonalds")
853 ]
854
855 parts = [
856 (10, "Airliner"),
857 (20, "Engine"),
858 (30, "Cheeseburger")
859 ]
860
861 suppart = [
862 (1, 10), (1, 20), (2, 20), (3, 30)
863 ]
864
865 x = [
866 (sname, pname)
867 for (sno, sname) in suppliers
868 for (pno, pname) in parts
869 for (sp_sno, sp_pno) in suppart
870 if sno == sp_sno and pno == sp_pno
871 ]
872
873 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
874 ('Macdonalds', 'Cheeseburger')])
875
876 def testGenexps(self):
877 # generator expression tests
878 g = ([x for x in range(10)] for x in range(1))
879 self.assertEqual(g.next(), [x for x in range(10)])
880 try:
881 g.next()
882 self.fail('should produce StopIteration exception')
883 except StopIteration:
884 pass
885
886 a = 1
887 try:
888 g = (a for d in a)
889 g.next()
890 self.fail('should produce TypeError')
891 except TypeError:
892 pass
893
894 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
895 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
896
897 a = [x for x in range(10)]
898 b = (x for x in (y for y in a))
899 self.assertEqual(sum(b), sum([x for x in range(10)]))
900
901 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
902 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
903 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
904 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
905 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
906 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)]))
907 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
908 check_syntax_error(self, "foo(x for x in range(10), 100)")
909 check_syntax_error(self, "foo(100, x for x in range(10))")
910
911 def testComprehensionSpecials(self):
912 # test for outmost iterable precomputation
913 x = 10; g = (i for i in range(x)); x = 5
914 self.assertEqual(len(list(g)), 10)
915
916 # This should hold, since we're only precomputing outmost iterable.
917 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
918 x = 5; t = True;
919 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
920
921 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
922 # even though it's silly. Make sure it works (ifelse broke this.)
923 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
924 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
925
926 # verify unpacking single element tuples in listcomp/genexp.
927 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
928 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
929
Benjamin Peterson46508922009-05-29 21:48:19 +0000930 def test_with_statement(self):
931 class manager(object):
932 def __enter__(self):
933 return (1, 2)
934 def __exit__(self, *args):
935 pass
936
937 with manager():
938 pass
939 with manager() as x:
940 pass
941 with manager() as (x, y):
942 pass
943 with manager(), manager():
944 pass
945 with manager() as x, manager() as y:
946 pass
947 with manager() as x, manager():
948 pass
949
Georg Brandlc6fdec62006-10-28 13:10:17 +0000950 def testIfElseExpr(self):
951 # Test ifelse expressions in various cases
952 def _checkeval(msg, ret):
953 "helper to check that evaluation of expressions is done correctly"
954 print x
955 return ret
956
957 self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
958 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
959 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])
960 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
961 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
962 self.assertEqual((5 and 6 if 0 else 1), 1)
963 self.assertEqual(((5 and 6) if 0 else 1), 1)
964 self.assertEqual((5 and (6 if 1 else 1)), 6)
965 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
966 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
967 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
968 self.assertEqual((not 5 if 1 else 1), False)
969 self.assertEqual((not 5 if 0 else 1), 1)
970 self.assertEqual((6 + 1 if 1 else 2), 7)
971 self.assertEqual((6 - 1 if 1 else 2), 5)
972 self.assertEqual((6 * 2 if 1 else 4), 12)
973 self.assertEqual((6 / 2 if 1 else 3), 3)
974 self.assertEqual((6 < 4 if 0 else 2), 2)
Guido van Rossumb3b09c91993-10-22 14:24:22 +0000975
Benjamin Petersonb2e31a12009-10-31 03:56:15 +0000976 def test_paren_evaluation(self):
977 self.assertEqual(16 // (4 // 2), 8)
978 self.assertEqual((16 // 4) // 2, 2)
979 self.assertEqual(16 // 4 // 2, 2)
980 self.assertTrue(False is (2 is 3))
981 self.assertFalse((False is 2) is 3)
982 self.assertFalse(False is 2 is 3)
983
Guido van Rossumb3b09c91993-10-22 14:24:22 +0000984
Georg Brandlc6fdec62006-10-28 13:10:17 +0000985def test_main():
Senthil Kumaran3ddc4352010-01-08 18:41:40 +0000986 with warnings.catch_warnings():
987 # Silence Py3k warnings
988 warnings.filterwarnings("ignore", "backquote not supported",
989 SyntaxWarning)
990 warnings.filterwarnings("ignore", "tuple parameter unpacking has been removed",
991 SyntaxWarning)
992 warnings.filterwarnings("ignore", "parenthesized argument names are invalid",
993 SyntaxWarning)
994 warnings.filterwarnings("ignore", "classic int division",
995 DeprecationWarning)
996 warnings.filterwarnings("ignore", ".+ not supported in 3.x",
997 DeprecationWarning)
998 run_unittest(TokenTests, GrammarTests)
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000999
Georg Brandlc6fdec62006-10-28 13:10:17 +00001000if __name__ == '__main__':
1001 test_main()