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