blob: 7d2ba377e70f3007a57e83fc4eb9b29b00ffacb9 [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)
33 from sys import maxint
34 if maxint == 2147483647:
35 self.assertEquals(-2147483647-1, -020000000000)
36 # XXX -2147483648
37 self.assert_(037777777777 > 0)
38 self.assert_(0xffffffff > 0)
39 for s in '2147483648', '040000000000', '0x100000000':
40 try:
41 x = eval(s)
42 except OverflowError:
43 self.fail("OverflowError on huge integer literal %r" % s)
44 elif maxint == 9223372036854775807:
45 self.assertEquals(-9223372036854775807-1, -01000000000000000000000)
46 self.assert_(01777777777777777777777 > 0)
47 self.assert_(0xffffffffffffffff > 0)
48 for s in '9223372036854775808', '02000000000000000000000', \
49 '0x10000000000000000':
50 try:
51 x = eval(s)
52 except OverflowError:
53 self.fail("OverflowError on huge integer literal %r" % s)
54 else:
55 self.fail('Weird maxint value %r' % maxint)
Guido van Rossum3bead091992-01-27 17:00:37 +000056
Georg Brandlc6fdec62006-10-28 13:10:17 +000057 def testLongIntegers(self):
58 x = 0L
59 x = 0l
60 x = 0xffffffffffffffffL
61 x = 0xffffffffffffffffl
62 x = 077777777777777777L
63 x = 077777777777777777l
64 x = 123456789012345678901234567890L
65 x = 123456789012345678901234567890l
Guido van Rossum3bead091992-01-27 17:00:37 +000066
Georg Brandlc6fdec62006-10-28 13:10:17 +000067 def testFloats(self):
68 x = 3.14
69 x = 314.
70 x = 0.314
71 # XXX x = 000.314
72 x = .314
73 x = 3e14
74 x = 3E14
75 x = 3e-14
76 x = 3e+14
77 x = 3.e14
78 x = .3e14
79 x = 3.1e4
Guido van Rossum3bead091992-01-27 17:00:37 +000080
Georg Brandlc6fdec62006-10-28 13:10:17 +000081 def testStringLiterals(self):
82 x = ''; y = ""; self.assert_(len(x) == 0 and x == y)
83 x = '\''; y = "'"; self.assert_(len(x) == 1 and x == y and ord(x) == 39)
84 x = '"'; y = "\""; self.assert_(len(x) == 1 and x == y and ord(x) == 34)
85 x = "doesn't \"shrink\" does it"
86 y = 'doesn\'t "shrink" does it'
87 self.assert_(len(x) == 24 and x == y)
88 x = "does \"shrink\" doesn't it"
89 y = 'does "shrink" doesn\'t it'
90 self.assert_(len(x) == 24 and x == y)
91 x = """
Guido van Rossumb6775db1994-08-01 11:34:53 +000092The "quick"
93brown fox
94jumps over
95the 'lazy' dog.
96"""
Georg Brandlc6fdec62006-10-28 13:10:17 +000097 y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
98 self.assertEquals(x, y)
99 y = '''
Guido van Rossumb6775db1994-08-01 11:34:53 +0000100The "quick"
101brown fox
102jumps over
103the 'lazy' dog.
Georg Brandlc6fdec62006-10-28 13:10:17 +0000104'''
105 self.assertEquals(x, y)
106 y = "\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000107The \"quick\"\n\
108brown fox\n\
109jumps over\n\
110the 'lazy' dog.\n\
Georg Brandlc6fdec62006-10-28 13:10:17 +0000111"
112 self.assertEquals(x, y)
113 y = '\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000114The \"quick\"\n\
115brown fox\n\
116jumps over\n\
117the \'lazy\' dog.\n\
Georg Brandlc6fdec62006-10-28 13:10:17 +0000118'
119 self.assertEquals(x, y)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000120
121
Georg Brandlc6fdec62006-10-28 13:10:17 +0000122class GrammarTests(unittest.TestCase):
Guido van Rossum3bead091992-01-27 17:00:37 +0000123
Georg Brandlc6fdec62006-10-28 13:10:17 +0000124 # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
125 # XXX can't test in a script -- this rule is only used when interactive
126
127 # file_input: (NEWLINE | stmt)* ENDMARKER
128 # Being tested as this very moment this very module
129
130 # expr_input: testlist NEWLINE
131 # XXX Hard to test -- used only in calls to input()
Guido van Rossum3bead091992-01-27 17:00:37 +0000132
Georg Brandlc6fdec62006-10-28 13:10:17 +0000133 def testEvalInput(self):
134 # testlist ENDMARKER
135 x = eval('1, 0 or 1')
Guido van Rossum3bead091992-01-27 17:00:37 +0000136
Georg Brandlc6fdec62006-10-28 13:10:17 +0000137 def testFuncdef(self):
138 ### 'def' NAME parameters ':' suite
139 ### parameters: '(' [varargslist] ')'
140 ### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME]
141 ### | ('**'|'*' '*') NAME)
142 ### | fpdef ['=' test] (',' fpdef ['=' test])* [',']
143 ### fpdef: NAME | '(' fplist ')'
144 ### fplist: fpdef (',' fpdef)* [',']
145 ### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test)
146 ### argument: [test '='] test # Really [keyword '='] test
147 def f1(): pass
148 f1()
149 f1(*())
150 f1(*(), **{})
151 def f2(one_argument): pass
152 def f3(two, arguments): pass
153 def f4(two, (compound, (argument, list))): pass
154 def f5((compound, first), two): pass
155 self.assertEquals(f2.func_code.co_varnames, ('one_argument',))
156 self.assertEquals(f3.func_code.co_varnames, ('two', 'arguments'))
157 if sys.platform.startswith('java'):
158 self.assertEquals(f4.func_code.co_varnames,
159 ('two', '(compound, (argument, list))', 'compound', 'argument',
160 'list',))
161 self.assertEquals(f5.func_code.co_varnames,
162 ('(compound, first)', 'two', 'compound', 'first'))
163 else:
164 self.assertEquals(f4.func_code.co_varnames,
165 ('two', '.1', 'compound', 'argument', 'list'))
166 self.assertEquals(f5.func_code.co_varnames,
167 ('.0', 'two', 'compound', 'first'))
168 def a1(one_arg,): pass
169 def a2(two, args,): pass
170 def v0(*rest): pass
171 def v1(a, *rest): pass
172 def v2(a, b, *rest): pass
173 def v3(a, (b, c), *rest): return a, b, c, rest
Guido van Rossum3bead091992-01-27 17:00:37 +0000174
Georg Brandlc6fdec62006-10-28 13:10:17 +0000175 f1()
176 f2(1)
177 f2(1,)
178 f3(1, 2)
179 f3(1, 2,)
180 f4(1, (2, (3, 4)))
181 v0()
182 v0(1)
183 v0(1,)
184 v0(1,2)
185 v0(1,2,3,4,5,6,7,8,9,0)
186 v1(1)
187 v1(1,)
188 v1(1,2)
189 v1(1,2,3)
190 v1(1,2,3,4,5,6,7,8,9,0)
191 v2(1,2)
192 v2(1,2,3)
193 v2(1,2,3,4)
194 v2(1,2,3,4,5,6,7,8,9,0)
195 v3(1,(2,3))
196 v3(1,(2,3),4)
197 v3(1,(2,3),4,5,6,7,8,9,0)
Guido van Rossum3bead091992-01-27 17:00:37 +0000198
Georg Brandlc6fdec62006-10-28 13:10:17 +0000199 # ceval unpacks the formal arguments into the first argcount names;
200 # thus, the names nested inside tuples must appear after these names.
201 if sys.platform.startswith('java'):
202 self.assertEquals(v3.func_code.co_varnames, ('a', '(b, c)', 'rest', 'b', 'c'))
203 else:
204 self.assertEquals(v3.func_code.co_varnames, ('a', '.1', 'rest', 'b', 'c'))
205 self.assertEquals(v3(1, (2, 3), 4), (1, 2, 3, (4,)))
206 def d01(a=1): pass
207 d01()
208 d01(1)
209 d01(*(1,))
210 d01(**{'a':2})
211 def d11(a, b=1): pass
212 d11(1)
213 d11(1, 2)
214 d11(1, **{'b':2})
215 def d21(a, b, c=1): pass
216 d21(1, 2)
217 d21(1, 2, 3)
218 d21(*(1, 2, 3))
219 d21(1, *(2, 3))
220 d21(1, 2, *(3,))
221 d21(1, 2, **{'c':3})
222 def d02(a=1, b=2): pass
223 d02()
224 d02(1)
225 d02(1, 2)
226 d02(*(1, 2))
227 d02(1, *(2,))
228 d02(1, **{'b':2})
229 d02(**{'a': 1, 'b': 2})
230 def d12(a, b=1, c=2): pass
231 d12(1)
232 d12(1, 2)
233 d12(1, 2, 3)
234 def d22(a, b, c=1, d=2): pass
235 d22(1, 2)
236 d22(1, 2, 3)
237 d22(1, 2, 3, 4)
238 def d01v(a=1, *rest): pass
239 d01v()
240 d01v(1)
241 d01v(1, 2)
242 d01v(*(1, 2, 3, 4))
243 d01v(*(1,))
244 d01v(**{'a':2})
245 def d11v(a, b=1, *rest): pass
246 d11v(1)
247 d11v(1, 2)
248 d11v(1, 2, 3)
249 def d21v(a, b, c=1, *rest): pass
250 d21v(1, 2)
251 d21v(1, 2, 3)
252 d21v(1, 2, 3, 4)
253 d21v(*(1, 2, 3, 4))
254 d21v(1, 2, **{'c': 3})
255 def d02v(a=1, b=2, *rest): pass
256 d02v()
257 d02v(1)
258 d02v(1, 2)
259 d02v(1, 2, 3)
260 d02v(1, *(2, 3, 4))
261 d02v(**{'a': 1, 'b': 2})
262 def d12v(a, b=1, c=2, *rest): pass
263 d12v(1)
264 d12v(1, 2)
265 d12v(1, 2, 3)
266 d12v(1, 2, 3, 4)
267 d12v(*(1, 2, 3, 4))
268 d12v(1, 2, *(3, 4, 5))
269 d12v(1, *(2,), **{'c': 3})
270 def d22v(a, b, c=1, d=2, *rest): pass
271 d22v(1, 2)
272 d22v(1, 2, 3)
273 d22v(1, 2, 3, 4)
274 d22v(1, 2, 3, 4, 5)
275 d22v(*(1, 2, 3, 4))
276 d22v(1, 2, *(3, 4, 5))
277 d22v(1, *(2, 3), **{'d': 4})
278 def d31v((x)): pass
279 d31v(1)
280 def d32v((x,)): pass
281 d32v((1,))
Guido van Rossum3bead091992-01-27 17:00:37 +0000282
Georg Brandlc6fdec62006-10-28 13:10:17 +0000283 def testLambdef(self):
284 ### lambdef: 'lambda' [varargslist] ':' test
285 l1 = lambda : 0
286 self.assertEquals(l1(), 0)
287 l2 = lambda : a[d] # XXX just testing the expression
288 l3 = lambda : [2 < x for x in [-1, 3, 0L]]
289 self.assertEquals(l3(), [0, 1, 0])
290 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
291 self.assertEquals(l4(), 1)
292 l5 = lambda x, y, z=2: x + y + z
293 self.assertEquals(l5(1, 2), 5)
294 self.assertEquals(l5(1, 2, 3), 6)
295 check_syntax_error(self, "lambda x: x = 2")
Jeremy Hylton619eea62001-01-25 20:12:27 +0000296
Georg Brandlc6fdec62006-10-28 13:10:17 +0000297 ### stmt: simple_stmt | compound_stmt
298 # Tested below
Guido van Rossum3bead091992-01-27 17:00:37 +0000299
Georg Brandlc6fdec62006-10-28 13:10:17 +0000300 def testSimpleStmt(self):
301 ### simple_stmt: small_stmt (';' small_stmt)* [';']
302 x = 1; pass; del x
303 def foo():
304 # verify statments that end with semi-colons
305 x = 1; pass; del x;
306 foo()
Guido van Rossum3bead091992-01-27 17:00:37 +0000307
Georg Brandlc6fdec62006-10-28 13:10:17 +0000308 ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt
309 # Tested below
Guido van Rossum3bead091992-01-27 17:00:37 +0000310
Georg Brandlc6fdec62006-10-28 13:10:17 +0000311 def testExprStmt(self):
312 # (exprlist '=')* exprlist
313 1
314 1, 2, 3
315 x = 1
316 x = 1, 2, 3
317 x = y = z = 1, 2, 3
318 x, y, z = 1, 2, 3
319 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000320
Georg Brandlc6fdec62006-10-28 13:10:17 +0000321 check_syntax_error(self, "x + 1 = 1")
322 check_syntax_error(self, "a + 1 = b + 2")
Jeremy Hylton47793992001-02-19 15:35:26 +0000323
Georg Brandlc6fdec62006-10-28 13:10:17 +0000324 def testPrintStmt(self):
325 # 'print' (test ',')* [test]
326 import StringIO
Guido van Rossum3bead091992-01-27 17:00:37 +0000327
Georg Brandlc6fdec62006-10-28 13:10:17 +0000328 # Can't test printing to real stdout without comparing output
329 # which is not available in unittest.
330 save_stdout = sys.stdout
331 sys.stdout = StringIO.StringIO()
332
333 print 1, 2, 3
334 print 1, 2, 3,
335 print
336 print 0 or 1, 0 or 1,
337 print 0 or 1
Barry Warsawefc92ee2000-08-21 15:46:50 +0000338
Georg Brandlc6fdec62006-10-28 13:10:17 +0000339 # 'print' '>>' test ','
340 print >> sys.stdout, 1, 2, 3
341 print >> sys.stdout, 1, 2, 3,
342 print >> sys.stdout
343 print >> sys.stdout, 0 or 1, 0 or 1,
344 print >> sys.stdout, 0 or 1
Barry Warsaw9182b452000-08-29 04:57:10 +0000345
Georg Brandlc6fdec62006-10-28 13:10:17 +0000346 # test printing to an instance
347 class Gulp:
348 def write(self, msg): pass
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000349
Georg Brandlc6fdec62006-10-28 13:10:17 +0000350 gulp = Gulp()
351 print >> gulp, 1, 2, 3
352 print >> gulp, 1, 2, 3,
353 print >> gulp
354 print >> gulp, 0 or 1, 0 or 1,
355 print >> gulp, 0 or 1
Barry Warsaw9182b452000-08-29 04:57:10 +0000356
Georg Brandlc6fdec62006-10-28 13:10:17 +0000357 # test print >> None
358 def driver():
359 oldstdout = sys.stdout
360 sys.stdout = Gulp()
361 try:
362 tellme(Gulp())
363 tellme()
364 finally:
365 sys.stdout = oldstdout
Barry Warsaw9182b452000-08-29 04:57:10 +0000366
Georg Brandlc6fdec62006-10-28 13:10:17 +0000367 # we should see this once
368 def tellme(file=sys.stdout):
369 print >> file, 'hello world'
Barry Warsaw9182b452000-08-29 04:57:10 +0000370
Georg Brandlc6fdec62006-10-28 13:10:17 +0000371 driver()
Barry Warsaw9182b452000-08-29 04:57:10 +0000372
Georg Brandlc6fdec62006-10-28 13:10:17 +0000373 # we should not see this at all
374 def tellme(file=None):
375 print >> file, 'goodbye universe'
Barry Warsaw9182b452000-08-29 04:57:10 +0000376
Georg Brandlc6fdec62006-10-28 13:10:17 +0000377 driver()
Barry Warsawefc92ee2000-08-21 15:46:50 +0000378
Georg Brandlc6fdec62006-10-28 13:10:17 +0000379 self.assertEqual(sys.stdout.getvalue(), '''\
3801 2 3
3811 2 3
3821 1 1
3831 2 3
3841 2 3
3851 1 1
386hello world
387''')
388 sys.stdout = save_stdout
Guido van Rossum3bead091992-01-27 17:00:37 +0000389
Georg Brandlc6fdec62006-10-28 13:10:17 +0000390 # syntax errors
391 check_syntax_error(self, 'print ,')
392 check_syntax_error(self, 'print >> x,')
Guido van Rossum3bead091992-01-27 17:00:37 +0000393
Georg Brandlc6fdec62006-10-28 13:10:17 +0000394 def testDelStmt(self):
395 # 'del' exprlist
396 abc = [1,2,3]
397 x, y, z = abc
398 xyz = x, y, z
Guido van Rossum3bead091992-01-27 17:00:37 +0000399
Georg Brandlc6fdec62006-10-28 13:10:17 +0000400 del abc
401 del x, y, (z, xyz)
Guido van Rossum3bead091992-01-27 17:00:37 +0000402
Georg Brandlc6fdec62006-10-28 13:10:17 +0000403 def testPassStmt(self):
404 # 'pass'
405 pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000406
Georg Brandlc6fdec62006-10-28 13:10:17 +0000407 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
408 # Tested below
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000409
Georg Brandlc6fdec62006-10-28 13:10:17 +0000410 def testBreakStmt(self):
411 # 'break'
412 while 1: break
Tim Peters10fb3862001-02-09 20:17:14 +0000413
Georg Brandlc6fdec62006-10-28 13:10:17 +0000414 def testContinueStmt(self):
415 # 'continue'
416 i = 1
417 while i: i = 0; continue
Thomas Wouters80d373c2001-09-26 12:43:39 +0000418
Georg Brandlc6fdec62006-10-28 13:10:17 +0000419 msg = ""
420 while not msg:
421 msg = "ok"
422 try:
423 continue
424 msg = "continue failed to continue inside try"
425 except:
426 msg = "continue inside try called except block"
427 if msg != "ok":
428 self.fail(msg)
Thomas Wouters80d373c2001-09-26 12:43:39 +0000429
Georg Brandlc6fdec62006-10-28 13:10:17 +0000430 msg = ""
431 while not msg:
432 msg = "finally block not called"
433 try:
434 continue
435 finally:
436 msg = "ok"
437 if msg != "ok":
438 self.fail(msg)
439
440 def test_break_continue_loop(self):
441 # This test warrants an explanation. It is a test specifically for SF bugs
442 # #463359 and #462937. The bug is that a 'break' statement executed or
443 # exception raised inside a try/except inside a loop, *after* a continue
444 # statement has been executed in that loop, will cause the wrong number of
445 # arguments to be popped off the stack and the instruction pointer reset to
446 # a very small number (usually 0.) Because of this, the following test
447 # *must* written as a function, and the tracking vars *must* be function
448 # arguments with default values. Otherwise, the test will loop and loop.
449
450 def test_inner(extra_burning_oil = 1, count=0):
451 big_hippo = 2
452 while big_hippo:
453 count += 1
454 try:
455 if extra_burning_oil and big_hippo == 1:
456 extra_burning_oil -= 1
457 break
458 big_hippo -= 1
459 continue
460 except:
461 raise
462 if count > 2 or big_hippo <> 1:
463 self.fail("continue then break in try/except in loop broken!")
464 test_inner()
465
466 def testReturn(self):
467 # 'return' [testlist]
468 def g1(): return
469 def g2(): return 1
470 g1()
471 x = g2()
472 check_syntax_error(self, "class foo:return 1")
473
474 def testYield(self):
475 check_syntax_error(self, "class foo:yield 1")
476
477 def testRaise(self):
478 # 'raise' test [',' test]
479 try: raise RuntimeError, 'just testing'
480 except RuntimeError: pass
481 try: raise KeyboardInterrupt
482 except KeyboardInterrupt: pass
483
484 def testImport(self):
485 # 'import' dotted_as_names
486 import sys
487 import time, sys
488 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
489 from time import time
490 from time import (time)
491 # not testable inside a function, but already done at top of the module
492 # from sys import *
493 from sys import path, argv
494 from sys import (path, argv)
495 from sys import (path, argv,)
496
497 def testGlobal(self):
498 # 'global' NAME (',' NAME)*
499 global a
500 global a, b
501 global one, two, three, four, five, six, seven, eight, nine, ten
502
503 def testExec(self):
504 # 'exec' expr ['in' expr [',' expr]]
505 z = None
506 del z
507 exec 'z=1+1\n'
508 if z != 2: self.fail('exec \'z=1+1\'\\n')
509 del z
510 exec 'z=1+1'
511 if z != 2: self.fail('exec \'z=1+1\'')
512 z = None
513 del z
514 import types
515 if hasattr(types, "UnicodeType"):
516 exec r"""if 1:
517 exec u'z=1+1\n'
518 if z != 2: self.fail('exec u\'z=1+1\'\\n')
519 del z
520 exec u'z=1+1'
521 if z != 2: self.fail('exec u\'z=1+1\'')"""
522 g = {}
523 exec 'z = 1' in g
524 if g.has_key('__builtins__'): del g['__builtins__']
525 if g != {'z': 1}: self.fail('exec \'z = 1\' in g')
526 g = {}
527 l = {}
528
529 import warnings
530 warnings.filterwarnings("ignore", "global statement", module="<string>")
531 exec 'global a; a = 1; b = 2' in g, l
532 if g.has_key('__builtins__'): del g['__builtins__']
533 if l.has_key('__builtins__'): del l['__builtins__']
534 if (g, l) != ({'a':1}, {'b':2}):
535 self.fail('exec ... in g (%s), l (%s)' %(g,l))
536
537 def testAssert(self):
538 # assert_stmt: 'assert' test [',' test]
539 assert 1
540 assert 1, 1
541 assert lambda x:x
542 assert 1, lambda x:x+1
Thomas Wouters80d373c2001-09-26 12:43:39 +0000543 try:
Georg Brandlc6fdec62006-10-28 13:10:17 +0000544 assert 0, "msg"
545 except AssertionError, e:
546 self.assertEquals(e.args[0], "msg")
Georg Brandlb21e0812006-10-28 20:25:09 +0000547 # we can not expect an assertion error to be raised
548 # if the tests are run in an optimized python
549 #else:
550 # self.fail("AssertionError not raised by assert 0")
Thomas Wouters80d373c2001-09-26 12:43:39 +0000551
Georg Brandlc6fdec62006-10-28 13:10:17 +0000552 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
553 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000554
Georg Brandlc6fdec62006-10-28 13:10:17 +0000555 def testIf(self):
556 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
557 if 1: pass
558 if 1: pass
559 else: pass
560 if 0: pass
561 elif 0: pass
562 if 0: pass
563 elif 0: pass
564 elif 0: pass
565 elif 0: pass
566 else: pass
567
568 def testWhile(self):
569 # 'while' test ':' suite ['else' ':' suite]
570 while 0: pass
571 while 0: pass
572 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000573
Georg Brandlc6fdec62006-10-28 13:10:17 +0000574 def testFor(self):
575 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
576 for i in 1, 2, 3: pass
577 for i, j, k in (): pass
578 else: pass
579 class Squares:
580 def __init__(self, max):
581 self.max = max
582 self.sofar = []
583 def __len__(self): return len(self.sofar)
584 def __getitem__(self, i):
585 if not 0 <= i < self.max: raise IndexError
586 n = len(self.sofar)
587 while n <= i:
588 self.sofar.append(n*n)
589 n = n+1
590 return self.sofar[i]
591 n = 0
592 for x in Squares(10): n = n+x
593 if n != 285:
594 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000595
Georg Brandlc6fdec62006-10-28 13:10:17 +0000596 result = []
597 for x, in [(1,), (2,), (3,)]:
598 result.append(x)
599 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000600
Georg Brandlc6fdec62006-10-28 13:10:17 +0000601 def testTry(self):
602 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
603 ### | 'try' ':' suite 'finally' ':' suite
604 ### except_clause: 'except' [expr [',' expr]]
605 try:
606 1/0
607 except ZeroDivisionError:
608 pass
609 else:
610 pass
611 try: 1/0
612 except EOFError: pass
613 except TypeError, msg: pass
614 except RuntimeError, msg: pass
615 except: pass
616 else: pass
617 try: 1/0
618 except (EOFError, TypeError, ZeroDivisionError): pass
619 try: 1/0
620 except (EOFError, TypeError, ZeroDivisionError), msg: pass
621 try: pass
622 finally: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000623
Georg Brandlc6fdec62006-10-28 13:10:17 +0000624 def testSuite(self):
625 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
626 if 1: pass
627 if 1:
628 pass
629 if 1:
630 #
631 #
632 #
633 pass
634 pass
635 #
636 pass
637 #
Jeremy Hylton2922ea82001-02-28 23:49:19 +0000638
Georg Brandlc6fdec62006-10-28 13:10:17 +0000639 def testTest(self):
640 ### and_test ('or' and_test)*
641 ### and_test: not_test ('and' not_test)*
642 ### not_test: 'not' not_test | comparison
643 if not 1: pass
644 if 1 and 1: pass
645 if 1 or 1: pass
646 if not not not 1: pass
647 if not 1 and 1 and 1: pass
648 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
649
650 def testComparison(self):
651 ### comparison: expr (comp_op expr)*
652 ### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
653 if 1: pass
654 x = (1 == 1)
655 if 1 == 1: pass
656 if 1 != 1: pass
657 if 1 <> 1: pass
658 if 1 < 1: pass
659 if 1 > 1: pass
660 if 1 <= 1: pass
661 if 1 >= 1: pass
662 if 1 is 1: pass
663 if 1 is not 1: pass
664 if 1 in (): pass
665 if 1 not in (): pass
666 if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass
667
668 def testBinaryMaskOps(self):
669 x = 1 & 1
670 x = 1 ^ 1
671 x = 1 | 1
672
673 def testShiftOps(self):
674 x = 1 << 1
675 x = 1 >> 1
676 x = 1 << 1 >> 1
677
678 def testAdditiveOps(self):
679 x = 1
680 x = 1 + 1
681 x = 1 - 1 - 1
682 x = 1 - 1 + 1 - 1 + 1
683
684 def testMultiplicativeOps(self):
685 x = 1 * 1
686 x = 1 / 1
687 x = 1 % 1
688 x = 1 / 1 * 1 % 1
689
690 def testUnaryOps(self):
691 x = +1
692 x = -1
693 x = ~1
694 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
695 x = -1*1/1 + 1*1 - ---1*1
696
697 def testSelectors(self):
698 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
699 ### subscript: expr | [expr] ':' [expr]
700
701 import sys, time
702 c = sys.path[0]
703 x = time.time()
704 x = sys.modules['time'].time()
705 a = '01234'
706 c = a[0]
707 c = a[-1]
708 s = a[0:5]
709 s = a[:5]
710 s = a[0:]
711 s = a[:]
712 s = a[-5:]
713 s = a[:-1]
714 s = a[-4:-3]
715 # A rough test of SF bug 1333982. http://python.org/sf/1333982
716 # The testing here is fairly incomplete.
717 # Test cases should include: commas with 1 and 2 colons
718 d = {}
719 d[1] = 1
720 d[1,] = 2
721 d[1,2] = 3
722 d[1,2,3] = 4
723 L = list(d)
724 L.sort()
725 self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
726
727 def testAtoms(self):
728 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
729 ### dictmaker: test ':' test (',' test ':' test)* [',']
730
731 x = (1)
732 x = (1 or 2 or 3)
733 x = (1 or 2 or 3, 2, 3)
734
735 x = []
736 x = [1]
737 x = [1 or 2 or 3]
738 x = [1 or 2 or 3, 2, 3]
739 x = []
740
741 x = {}
742 x = {'one': 1}
743 x = {'one': 1,}
744 x = {'one' or 'two': 1 or 2}
745 x = {'one': 1, 'two': 2}
746 x = {'one': 1, 'two': 2,}
747 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
748
749 x = `x`
750 x = `1 or 2 or 3`
751 x = x
752 x = 'x'
753 x = 123
754
755 ### exprlist: expr (',' expr)* [',']
756 ### testlist: test (',' test)* [',']
757 # These have been exercised enough above
758
759 def testClassdef(self):
760 # 'class' NAME ['(' [testlist] ')'] ':' suite
761 class B: pass
762 class B2(): pass
763 class C1(B): pass
764 class C2(B): pass
765 class D(C1, C2, B): pass
766 class C:
767 def meth1(self): pass
768 def meth2(self, arg): pass
769 def meth3(self, a1, a2): pass
770
771 def testListcomps(self):
772 # list comprehension tests
773 nums = [1, 2, 3, 4, 5]
774 strs = ["Apple", "Banana", "Coconut"]
775 spcs = [" Apple", " Banana ", "Coco nut "]
776
777 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
778 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
779 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
780 self.assertEqual([(i, s) for i in nums for s in strs],
781 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
782 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
783 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
784 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
785 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
786 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
787 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
788 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
789 (5, 'Banana'), (5, 'Coconut')])
790 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
791 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
792
793 def test_in_func(l):
794 return [None < x < 3 for x in l if x > 2]
795
796 self.assertEqual(test_in_func(nums), [False, False, False])
797
798 def test_nested_front():
799 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
800 [[1, 2], [3, 4], [5, 6]])
801
802 test_nested_front()
803
804 check_syntax_error(self, "[i, s for i in nums for s in strs]")
805 check_syntax_error(self, "[x if y]")
806
807 suppliers = [
808 (1, "Boeing"),
809 (2, "Ford"),
810 (3, "Macdonalds")
811 ]
812
813 parts = [
814 (10, "Airliner"),
815 (20, "Engine"),
816 (30, "Cheeseburger")
817 ]
818
819 suppart = [
820 (1, 10), (1, 20), (2, 20), (3, 30)
821 ]
822
823 x = [
824 (sname, pname)
825 for (sno, sname) in suppliers
826 for (pno, pname) in parts
827 for (sp_sno, sp_pno) in suppart
828 if sno == sp_sno and pno == sp_pno
829 ]
830
831 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
832 ('Macdonalds', 'Cheeseburger')])
833
834 def testGenexps(self):
835 # generator expression tests
836 g = ([x for x in range(10)] for x in range(1))
837 self.assertEqual(g.next(), [x for x in range(10)])
838 try:
839 g.next()
840 self.fail('should produce StopIteration exception')
841 except StopIteration:
842 pass
843
844 a = 1
845 try:
846 g = (a for d in a)
847 g.next()
848 self.fail('should produce TypeError')
849 except TypeError:
850 pass
851
852 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
853 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
854
855 a = [x for x in range(10)]
856 b = (x for x in (y for y in a))
857 self.assertEqual(sum(b), sum([x for x in range(10)]))
858
859 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
860 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
861 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
862 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
863 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
864 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)]))
865 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
866 check_syntax_error(self, "foo(x for x in range(10), 100)")
867 check_syntax_error(self, "foo(100, x for x in range(10))")
868
869 def testComprehensionSpecials(self):
870 # test for outmost iterable precomputation
871 x = 10; g = (i for i in range(x)); x = 5
872 self.assertEqual(len(list(g)), 10)
873
874 # This should hold, since we're only precomputing outmost iterable.
875 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
876 x = 5; t = True;
877 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
878
879 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
880 # even though it's silly. Make sure it works (ifelse broke this.)
881 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
882 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
883
884 # verify unpacking single element tuples in listcomp/genexp.
885 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
886 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
887
888 def testIfElseExpr(self):
889 # Test ifelse expressions in various cases
890 def _checkeval(msg, ret):
891 "helper to check that evaluation of expressions is done correctly"
892 print x
893 return ret
894
895 self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
896 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
897 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])
898 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
899 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
900 self.assertEqual((5 and 6 if 0 else 1), 1)
901 self.assertEqual(((5 and 6) if 0 else 1), 1)
902 self.assertEqual((5 and (6 if 1 else 1)), 6)
903 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
904 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
905 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
906 self.assertEqual((not 5 if 1 else 1), False)
907 self.assertEqual((not 5 if 0 else 1), 1)
908 self.assertEqual((6 + 1 if 1 else 2), 7)
909 self.assertEqual((6 - 1 if 1 else 2), 5)
910 self.assertEqual((6 * 2 if 1 else 4), 12)
911 self.assertEqual((6 / 2 if 1 else 3), 3)
912 self.assertEqual((6 < 4 if 0 else 2), 2)
Guido van Rossumb3b09c91993-10-22 14:24:22 +0000913
914
Georg Brandlc6fdec62006-10-28 13:10:17 +0000915def test_main():
916 run_unittest(TokenTests, GrammarTests)
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000917
Georg Brandlc6fdec62006-10-28 13:10:17 +0000918if __name__ == '__main__':
919 test_main()