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