blob: fc675c35a307d86b083ba7c2dd5fa19df6c42cdd [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
Ezio Melottid80b4bf2010-03-17 13:52:48 +00004from test.test_support import run_unittest, check_syntax_error, \
5 check_py3k_warnings
Georg Brandlc6fdec62006-10-28 13:10:17 +00006import unittest
Jeremy Hylton7d3dff22001-10-10 01:45:02 +00007import sys
Georg Brandlc6fdec62006-10-28 13:10:17 +00008# testing import *
9from sys import *
Guido van Rossum3bead091992-01-27 17:00:37 +000010
Florent Xiclunabc27c6a2010-03-19 18:34:55 +000011
Georg Brandlc6fdec62006-10-28 13:10:17 +000012class TokenTests(unittest.TestCase):
Guido van Rossum3bead091992-01-27 17:00:37 +000013
Georg Brandlc6fdec62006-10-28 13:10:17 +000014 def testBackslash(self):
15 # Backslash means line continuation:
16 x = 1 \
17 + 1
Florent Xiclunabc27c6a2010-03-19 18:34:55 +000018 self.assertEqual(x, 2, 'backslash for line continuation')
Guido van Rossum3bead091992-01-27 17:00:37 +000019
Georg Brandlc6fdec62006-10-28 13:10:17 +000020 # Backslash does not means continuation in comments :\
21 x = 0
Florent Xiclunabc27c6a2010-03-19 18:34:55 +000022 self.assertEqual(x, 0, 'backslash ending comment')
Guido van Rossum3bead091992-01-27 17:00:37 +000023
Georg Brandlc6fdec62006-10-28 13:10:17 +000024 def testPlainIntegers(self):
Florent Xiclunabc27c6a2010-03-19 18:34:55 +000025 self.assertEqual(0xff, 255)
26 self.assertEqual(0377, 255)
27 self.assertEqual(2147483647, 017777777777)
Georg Brandl14404b62008-01-19 19:27:05 +000028 # "0x" is not a valid literal
29 self.assertRaises(SyntaxError, eval, "0x")
Georg Brandlc6fdec62006-10-28 13:10:17 +000030 from sys import maxint
31 if maxint == 2147483647:
Florent Xiclunabc27c6a2010-03-19 18:34:55 +000032 self.assertEqual(-2147483647-1, -020000000000)
Georg Brandlc6fdec62006-10-28 13:10:17 +000033 # XXX -2147483648
Benjamin Peterson5c8da862009-06-30 22:57:08 +000034 self.assertTrue(037777777777 > 0)
35 self.assertTrue(0xffffffff > 0)
Georg Brandlc6fdec62006-10-28 13:10:17 +000036 for s in '2147483648', '040000000000', '0x100000000':
37 try:
38 x = eval(s)
39 except OverflowError:
40 self.fail("OverflowError on huge integer literal %r" % s)
41 elif maxint == 9223372036854775807:
Florent Xiclunabc27c6a2010-03-19 18:34:55 +000042 self.assertEqual(-9223372036854775807-1, -01000000000000000000000)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000043 self.assertTrue(01777777777777777777777 > 0)
44 self.assertTrue(0xffffffffffffffff > 0)
Georg Brandlc6fdec62006-10-28 13:10:17 +000045 for s in '9223372036854775808', '02000000000000000000000', \
46 '0x10000000000000000':
47 try:
48 x = eval(s)
49 except OverflowError:
50 self.fail("OverflowError on huge integer literal %r" % s)
51 else:
52 self.fail('Weird maxint value %r' % maxint)
Guido van Rossum3bead091992-01-27 17:00:37 +000053
Georg Brandlc6fdec62006-10-28 13:10:17 +000054 def testLongIntegers(self):
55 x = 0L
56 x = 0l
57 x = 0xffffffffffffffffL
58 x = 0xffffffffffffffffl
59 x = 077777777777777777L
60 x = 077777777777777777l
61 x = 123456789012345678901234567890L
62 x = 123456789012345678901234567890l
Guido van Rossum3bead091992-01-27 17:00:37 +000063
Georg Brandlc6fdec62006-10-28 13:10:17 +000064 def testFloats(self):
65 x = 3.14
66 x = 314.
67 x = 0.314
68 # XXX x = 000.314
69 x = .314
70 x = 3e14
71 x = 3E14
72 x = 3e-14
73 x = 3e+14
74 x = 3.e14
75 x = .3e14
76 x = 3.1e4
Guido van Rossum3bead091992-01-27 17:00:37 +000077
Benjamin Peterson93e51aa2014-06-07 12:36:39 -070078 def test_float_exponent_tokenization(self):
79 # See issue 21642.
80 self.assertEqual(1 if 1else 0, 1)
81 self.assertEqual(1 if 0else 0, 0)
82 self.assertRaises(SyntaxError, eval, "0 if 1Else 0")
83
Georg Brandlc6fdec62006-10-28 13:10:17 +000084 def testStringLiterals(self):
Benjamin Peterson5c8da862009-06-30 22:57:08 +000085 x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y)
86 x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39)
87 x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34)
Georg Brandlc6fdec62006-10-28 13:10:17 +000088 x = "doesn't \"shrink\" does it"
89 y = 'doesn\'t "shrink" does it'
Benjamin Peterson5c8da862009-06-30 22:57:08 +000090 self.assertTrue(len(x) == 24 and x == y)
Georg Brandlc6fdec62006-10-28 13:10:17 +000091 x = "does \"shrink\" doesn't it"
92 y = 'does "shrink" doesn\'t it'
Benjamin Peterson5c8da862009-06-30 22:57:08 +000093 self.assertTrue(len(x) == 24 and x == y)
Georg Brandlc6fdec62006-10-28 13:10:17 +000094 x = """
Guido van Rossumb6775db1994-08-01 11:34:53 +000095The "quick"
96brown fox
97jumps over
98the 'lazy' dog.
99"""
Georg Brandlc6fdec62006-10-28 13:10:17 +0000100 y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000101 self.assertEqual(x, y)
Georg Brandlc6fdec62006-10-28 13:10:17 +0000102 y = '''
Guido van Rossumb6775db1994-08-01 11:34:53 +0000103The "quick"
104brown fox
105jumps over
106the 'lazy' dog.
Georg Brandlc6fdec62006-10-28 13:10:17 +0000107'''
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000108 self.assertEqual(x, y)
Georg Brandlc6fdec62006-10-28 13:10:17 +0000109 y = "\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000110The \"quick\"\n\
111brown fox\n\
112jumps over\n\
113the 'lazy' dog.\n\
Georg Brandlc6fdec62006-10-28 13:10:17 +0000114"
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000115 self.assertEqual(x, y)
Georg Brandlc6fdec62006-10-28 13:10:17 +0000116 y = '\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000117The \"quick\"\n\
118brown fox\n\
119jumps over\n\
120the \'lazy\' dog.\n\
Georg Brandlc6fdec62006-10-28 13:10:17 +0000121'
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000122 self.assertEqual(x, y)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000123
124
Georg Brandlc6fdec62006-10-28 13:10:17 +0000125class GrammarTests(unittest.TestCase):
Guido van Rossum3bead091992-01-27 17:00:37 +0000126
Georg Brandlc6fdec62006-10-28 13:10:17 +0000127 # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
128 # XXX can't test in a script -- this rule is only used when interactive
Tim Petersabd8a332006-11-03 02:32:46 +0000129
Georg Brandlc6fdec62006-10-28 13:10:17 +0000130 # file_input: (NEWLINE | stmt)* ENDMARKER
131 # Being tested as this very moment this very module
Tim Petersabd8a332006-11-03 02:32:46 +0000132
Georg Brandlc6fdec62006-10-28 13:10:17 +0000133 # expr_input: testlist NEWLINE
134 # XXX Hard to test -- used only in calls to input()
Guido van Rossum3bead091992-01-27 17:00:37 +0000135
Georg Brandlc6fdec62006-10-28 13:10:17 +0000136 def testEvalInput(self):
137 # testlist ENDMARKER
138 x = eval('1, 0 or 1')
Guido van Rossum3bead091992-01-27 17:00:37 +0000139
Georg Brandlc6fdec62006-10-28 13:10:17 +0000140 def testFuncdef(self):
141 ### 'def' NAME parameters ':' suite
142 ### parameters: '(' [varargslist] ')'
143 ### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME]
144 ### | ('**'|'*' '*') NAME)
145 ### | fpdef ['=' test] (',' fpdef ['=' test])* [',']
146 ### fpdef: NAME | '(' fplist ')'
147 ### fplist: fpdef (',' fpdef)* [',']
148 ### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test)
149 ### argument: [test '='] test # Really [keyword '='] test
150 def f1(): pass
151 f1()
152 f1(*())
153 f1(*(), **{})
154 def f2(one_argument): pass
155 def f3(two, arguments): pass
Ezio Melottid80b4bf2010-03-17 13:52:48 +0000156 # Silence Py3k warning
157 exec('def f4(two, (compound, (argument, list))): pass')
158 exec('def f5((compound, first), two): pass')
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000159 self.assertEqual(f2.func_code.co_varnames, ('one_argument',))
160 self.assertEqual(f3.func_code.co_varnames, ('two', 'arguments'))
Georg Brandlc6fdec62006-10-28 13:10:17 +0000161 if sys.platform.startswith('java'):
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000162 self.assertEqual(f4.func_code.co_varnames,
Georg Brandlc6fdec62006-10-28 13:10:17 +0000163 ('two', '(compound, (argument, list))', 'compound', 'argument',
164 'list',))
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000165 self.assertEqual(f5.func_code.co_varnames,
Georg Brandlc6fdec62006-10-28 13:10:17 +0000166 ('(compound, first)', 'two', 'compound', 'first'))
167 else:
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000168 self.assertEqual(f4.func_code.co_varnames,
Georg Brandlc6fdec62006-10-28 13:10:17 +0000169 ('two', '.1', 'compound', 'argument', 'list'))
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000170 self.assertEqual(f5.func_code.co_varnames,
Georg Brandlc6fdec62006-10-28 13:10:17 +0000171 ('.0', 'two', 'compound', 'first'))
172 def a1(one_arg,): pass
173 def a2(two, args,): pass
174 def v0(*rest): pass
175 def v1(a, *rest): pass
176 def v2(a, b, *rest): pass
Ezio Melottid80b4bf2010-03-17 13:52:48 +0000177 # Silence Py3k warning
178 exec('def v3(a, (b, c), *rest): return a, b, c, rest')
Guido van Rossum3bead091992-01-27 17:00:37 +0000179
Georg Brandlc6fdec62006-10-28 13:10:17 +0000180 f1()
181 f2(1)
182 f2(1,)
183 f3(1, 2)
184 f3(1, 2,)
185 f4(1, (2, (3, 4)))
186 v0()
187 v0(1)
188 v0(1,)
189 v0(1,2)
190 v0(1,2,3,4,5,6,7,8,9,0)
191 v1(1)
192 v1(1,)
193 v1(1,2)
194 v1(1,2,3)
195 v1(1,2,3,4,5,6,7,8,9,0)
196 v2(1,2)
197 v2(1,2,3)
198 v2(1,2,3,4)
199 v2(1,2,3,4,5,6,7,8,9,0)
200 v3(1,(2,3))
201 v3(1,(2,3),4)
202 v3(1,(2,3),4,5,6,7,8,9,0)
Guido van Rossum3bead091992-01-27 17:00:37 +0000203
Georg Brandlc6fdec62006-10-28 13:10:17 +0000204 # ceval unpacks the formal arguments into the first argcount names;
205 # thus, the names nested inside tuples must appear after these names.
206 if sys.platform.startswith('java'):
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000207 self.assertEqual(v3.func_code.co_varnames, ('a', '(b, c)', 'rest', 'b', 'c'))
Georg Brandlc6fdec62006-10-28 13:10:17 +0000208 else:
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000209 self.assertEqual(v3.func_code.co_varnames, ('a', '.1', 'rest', 'b', 'c'))
210 self.assertEqual(v3(1, (2, 3), 4), (1, 2, 3, (4,)))
Georg Brandlc6fdec62006-10-28 13:10:17 +0000211 def d01(a=1): pass
212 d01()
213 d01(1)
214 d01(*(1,))
215 d01(**{'a':2})
216 def d11(a, b=1): pass
217 d11(1)
218 d11(1, 2)
219 d11(1, **{'b':2})
220 def d21(a, b, c=1): pass
221 d21(1, 2)
222 d21(1, 2, 3)
223 d21(*(1, 2, 3))
224 d21(1, *(2, 3))
225 d21(1, 2, *(3,))
226 d21(1, 2, **{'c':3})
227 def d02(a=1, b=2): pass
228 d02()
229 d02(1)
230 d02(1, 2)
231 d02(*(1, 2))
232 d02(1, *(2,))
233 d02(1, **{'b':2})
234 d02(**{'a': 1, 'b': 2})
235 def d12(a, b=1, c=2): pass
236 d12(1)
237 d12(1, 2)
238 d12(1, 2, 3)
239 def d22(a, b, c=1, d=2): pass
240 d22(1, 2)
241 d22(1, 2, 3)
242 d22(1, 2, 3, 4)
243 def d01v(a=1, *rest): pass
244 d01v()
245 d01v(1)
246 d01v(1, 2)
247 d01v(*(1, 2, 3, 4))
248 d01v(*(1,))
249 d01v(**{'a':2})
250 def d11v(a, b=1, *rest): pass
251 d11v(1)
252 d11v(1, 2)
253 d11v(1, 2, 3)
254 def d21v(a, b, c=1, *rest): pass
255 d21v(1, 2)
256 d21v(1, 2, 3)
257 d21v(1, 2, 3, 4)
258 d21v(*(1, 2, 3, 4))
259 d21v(1, 2, **{'c': 3})
260 def d02v(a=1, b=2, *rest): pass
261 d02v()
262 d02v(1)
263 d02v(1, 2)
264 d02v(1, 2, 3)
265 d02v(1, *(2, 3, 4))
266 d02v(**{'a': 1, 'b': 2})
267 def d12v(a, b=1, c=2, *rest): pass
268 d12v(1)
269 d12v(1, 2)
270 d12v(1, 2, 3)
271 d12v(1, 2, 3, 4)
272 d12v(*(1, 2, 3, 4))
273 d12v(1, 2, *(3, 4, 5))
274 d12v(1, *(2,), **{'c': 3})
275 def d22v(a, b, c=1, d=2, *rest): pass
276 d22v(1, 2)
277 d22v(1, 2, 3)
278 d22v(1, 2, 3, 4)
279 d22v(1, 2, 3, 4, 5)
280 d22v(*(1, 2, 3, 4))
281 d22v(1, 2, *(3, 4, 5))
282 d22v(1, *(2, 3), **{'d': 4})
Ezio Melottid80b4bf2010-03-17 13:52:48 +0000283 # Silence Py3k warning
284 exec('def d31v((x)): pass')
285 exec('def d32v((x,)): pass')
Georg Brandlc6fdec62006-10-28 13:10:17 +0000286 d31v(1)
Georg Brandlc6fdec62006-10-28 13:10:17 +0000287 d32v((1,))
Guido van Rossum3bead091992-01-27 17:00:37 +0000288
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000289 # keyword arguments after *arglist
290 def f(*args, **kwargs):
291 return args, kwargs
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000292 self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000293 {'x':2, 'y':5}))
294 self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)")
295 self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
296
Amaury Forgeot d'Arcd21fb4c2008-03-05 01:50:33 +0000297 # Check ast errors in *args and *kwargs
298 check_syntax_error(self, "f(*g(1=2))")
299 check_syntax_error(self, "f(**g(1=2))")
300
Georg Brandlc6fdec62006-10-28 13:10:17 +0000301 def testLambdef(self):
302 ### lambdef: 'lambda' [varargslist] ':' test
303 l1 = lambda : 0
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000304 self.assertEqual(l1(), 0)
Georg Brandlc6fdec62006-10-28 13:10:17 +0000305 l2 = lambda : a[d] # XXX just testing the expression
306 l3 = lambda : [2 < x for x in [-1, 3, 0L]]
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000307 self.assertEqual(l3(), [0, 1, 0])
Georg Brandlc6fdec62006-10-28 13:10:17 +0000308 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000309 self.assertEqual(l4(), 1)
Georg Brandlc6fdec62006-10-28 13:10:17 +0000310 l5 = lambda x, y, z=2: x + y + z
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000311 self.assertEqual(l5(1, 2), 5)
312 self.assertEqual(l5(1, 2, 3), 6)
Georg Brandlc6fdec62006-10-28 13:10:17 +0000313 check_syntax_error(self, "lambda x: x = 2")
Georg Brandla161f602008-06-15 19:54:36 +0000314 check_syntax_error(self, "lambda (None,): None")
Jeremy Hylton619eea62001-01-25 20:12:27 +0000315
Georg Brandlc6fdec62006-10-28 13:10:17 +0000316 ### stmt: simple_stmt | compound_stmt
317 # Tested below
Guido van Rossum3bead091992-01-27 17:00:37 +0000318
Georg Brandlc6fdec62006-10-28 13:10:17 +0000319 def testSimpleStmt(self):
320 ### simple_stmt: small_stmt (';' small_stmt)* [';']
321 x = 1; pass; del x
322 def foo():
Ezio Melottic2077b02011-03-16 12:34:31 +0200323 # verify statements that end with semi-colons
Georg Brandlc6fdec62006-10-28 13:10:17 +0000324 x = 1; pass; del x;
325 foo()
Guido van Rossum3bead091992-01-27 17:00:37 +0000326
Georg Brandlc6fdec62006-10-28 13:10:17 +0000327 ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt
328 # Tested below
Guido van Rossum3bead091992-01-27 17:00:37 +0000329
Georg Brandlc6fdec62006-10-28 13:10:17 +0000330 def testExprStmt(self):
331 # (exprlist '=')* exprlist
332 1
333 1, 2, 3
334 x = 1
335 x = 1, 2, 3
336 x = y = z = 1, 2, 3
337 x, y, z = 1, 2, 3
338 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000339
Georg Brandlc6fdec62006-10-28 13:10:17 +0000340 check_syntax_error(self, "x + 1 = 1")
341 check_syntax_error(self, "a + 1 = b + 2")
Jeremy Hylton47793992001-02-19 15:35:26 +0000342
Georg Brandlc6fdec62006-10-28 13:10:17 +0000343 def testPrintStmt(self):
344 # 'print' (test ',')* [test]
345 import StringIO
Guido van Rossum3bead091992-01-27 17:00:37 +0000346
Georg Brandlc6fdec62006-10-28 13:10:17 +0000347 # Can't test printing to real stdout without comparing output
348 # which is not available in unittest.
349 save_stdout = sys.stdout
350 sys.stdout = StringIO.StringIO()
Tim Petersabd8a332006-11-03 02:32:46 +0000351
Georg Brandlc6fdec62006-10-28 13:10:17 +0000352 print 1, 2, 3
353 print 1, 2, 3,
354 print
355 print 0 or 1, 0 or 1,
356 print 0 or 1
Barry Warsawefc92ee2000-08-21 15:46:50 +0000357
Georg Brandlc6fdec62006-10-28 13:10:17 +0000358 # 'print' '>>' test ','
359 print >> sys.stdout, 1, 2, 3
360 print >> sys.stdout, 1, 2, 3,
361 print >> sys.stdout
362 print >> sys.stdout, 0 or 1, 0 or 1,
363 print >> sys.stdout, 0 or 1
Barry Warsaw9182b452000-08-29 04:57:10 +0000364
Georg Brandlc6fdec62006-10-28 13:10:17 +0000365 # test printing to an instance
366 class Gulp:
367 def write(self, msg): pass
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000368
Georg Brandlc6fdec62006-10-28 13:10:17 +0000369 gulp = Gulp()
370 print >> gulp, 1, 2, 3
371 print >> gulp, 1, 2, 3,
372 print >> gulp
373 print >> gulp, 0 or 1, 0 or 1,
374 print >> gulp, 0 or 1
Barry Warsaw9182b452000-08-29 04:57:10 +0000375
Georg Brandlc6fdec62006-10-28 13:10:17 +0000376 # test print >> None
377 def driver():
378 oldstdout = sys.stdout
379 sys.stdout = Gulp()
380 try:
381 tellme(Gulp())
382 tellme()
383 finally:
384 sys.stdout = oldstdout
Barry Warsaw9182b452000-08-29 04:57:10 +0000385
Georg Brandlc6fdec62006-10-28 13:10:17 +0000386 # we should see this once
387 def tellme(file=sys.stdout):
388 print >> file, 'hello world'
Barry Warsaw9182b452000-08-29 04:57:10 +0000389
Georg Brandlc6fdec62006-10-28 13:10:17 +0000390 driver()
Barry Warsaw9182b452000-08-29 04:57:10 +0000391
Georg Brandlc6fdec62006-10-28 13:10:17 +0000392 # we should not see this at all
393 def tellme(file=None):
394 print >> file, 'goodbye universe'
Barry Warsaw9182b452000-08-29 04:57:10 +0000395
Georg Brandlc6fdec62006-10-28 13:10:17 +0000396 driver()
Barry Warsawefc92ee2000-08-21 15:46:50 +0000397
Georg Brandlc6fdec62006-10-28 13:10:17 +0000398 self.assertEqual(sys.stdout.getvalue(), '''\
3991 2 3
4001 2 3
4011 1 1
4021 2 3
4031 2 3
4041 1 1
405hello world
406''')
407 sys.stdout = save_stdout
Guido van Rossum3bead091992-01-27 17:00:37 +0000408
Georg Brandlc6fdec62006-10-28 13:10:17 +0000409 # syntax errors
410 check_syntax_error(self, 'print ,')
411 check_syntax_error(self, 'print >> x,')
Guido van Rossum3bead091992-01-27 17:00:37 +0000412
Georg Brandlc6fdec62006-10-28 13:10:17 +0000413 def testDelStmt(self):
414 # 'del' exprlist
415 abc = [1,2,3]
416 x, y, z = abc
417 xyz = x, y, z
Guido van Rossum3bead091992-01-27 17:00:37 +0000418
Georg Brandlc6fdec62006-10-28 13:10:17 +0000419 del abc
420 del x, y, (z, xyz)
Guido van Rossum3bead091992-01-27 17:00:37 +0000421
Georg Brandlc6fdec62006-10-28 13:10:17 +0000422 def testPassStmt(self):
423 # 'pass'
424 pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000425
Georg Brandlc6fdec62006-10-28 13:10:17 +0000426 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
427 # Tested below
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000428
Georg Brandlc6fdec62006-10-28 13:10:17 +0000429 def testBreakStmt(self):
430 # 'break'
431 while 1: break
Tim Peters10fb3862001-02-09 20:17:14 +0000432
Georg Brandlc6fdec62006-10-28 13:10:17 +0000433 def testContinueStmt(self):
434 # 'continue'
435 i = 1
436 while i: i = 0; continue
Thomas Wouters80d373c2001-09-26 12:43:39 +0000437
Georg Brandlc6fdec62006-10-28 13:10:17 +0000438 msg = ""
439 while not msg:
440 msg = "ok"
441 try:
442 continue
443 msg = "continue failed to continue inside try"
444 except:
445 msg = "continue inside try called except block"
446 if msg != "ok":
447 self.fail(msg)
Thomas Wouters80d373c2001-09-26 12:43:39 +0000448
Georg Brandlc6fdec62006-10-28 13:10:17 +0000449 msg = ""
450 while not msg:
451 msg = "finally block not called"
452 try:
453 continue
454 finally:
455 msg = "ok"
456 if msg != "ok":
457 self.fail(msg)
458
459 def test_break_continue_loop(self):
460 # This test warrants an explanation. It is a test specifically for SF bugs
461 # #463359 and #462937. The bug is that a 'break' statement executed or
462 # exception raised inside a try/except inside a loop, *after* a continue
463 # statement has been executed in that loop, will cause the wrong number of
464 # arguments to be popped off the stack and the instruction pointer reset to
465 # a very small number (usually 0.) Because of this, the following test
466 # *must* written as a function, and the tracking vars *must* be function
467 # arguments with default values. Otherwise, the test will loop and loop.
468
469 def test_inner(extra_burning_oil = 1, count=0):
470 big_hippo = 2
471 while big_hippo:
472 count += 1
473 try:
474 if extra_burning_oil and big_hippo == 1:
475 extra_burning_oil -= 1
476 break
477 big_hippo -= 1
478 continue
479 except:
480 raise
Ezio Melottid80b4bf2010-03-17 13:52:48 +0000481 if count > 2 or big_hippo != 1:
Georg Brandlc6fdec62006-10-28 13:10:17 +0000482 self.fail("continue then break in try/except in loop broken!")
483 test_inner()
484
485 def testReturn(self):
486 # 'return' [testlist]
487 def g1(): return
488 def g2(): return 1
489 g1()
490 x = g2()
491 check_syntax_error(self, "class foo:return 1")
492
493 def testYield(self):
494 check_syntax_error(self, "class foo:yield 1")
495
Serhiy Storchaka65d18872017-12-02 21:00:09 +0200496 def test_yield_in_comprehensions(self):
497 # Check yield in comprehensions
498 def g(): [x for x in [(yield 1)]]
499
500 def check(code, warntext):
501 with check_py3k_warnings((warntext, DeprecationWarning)):
502 compile(code, '<test string>', 'exec')
503 if sys.py3kwarning:
504 import warnings
505 with warnings.catch_warnings():
506 warnings.filterwarnings('error', category=DeprecationWarning)
507 with self.assertRaises(SyntaxError) as cm:
508 compile(code, '<test string>', 'exec')
509 self.assertIn(warntext, str(cm.exception))
510
511 check("def g(): [(yield x) for x in ()]",
512 "'yield' inside list comprehension")
513 check("def g(): [x for x in () if not (yield x)]",
514 "'yield' inside list comprehension")
515 check("def g(): [y for x in () for y in [(yield x)]]",
516 "'yield' inside list comprehension")
517 check("def g(): {(yield x) for x in ()}",
518 "'yield' inside set comprehension")
519 check("def g(): {(yield x): x for x in ()}",
520 "'yield' inside dict comprehension")
521 check("def g(): {x: (yield x) for x in ()}",
522 "'yield' inside dict comprehension")
523 check("def g(): ((yield x) for x in ())",
524 "'yield' inside generator expression")
525 with check_py3k_warnings(("'yield' inside list comprehension",
526 DeprecationWarning)):
527 check_syntax_error(self, "class C: [(yield x) for x in ()]")
528 check("class C: ((yield x) for x in ())",
529 "'yield' inside generator expression")
530 with check_py3k_warnings(("'yield' inside list comprehension",
531 DeprecationWarning)):
532 check_syntax_error(self, "[(yield x) for x in ()]")
533 check("((yield x) for x in ())",
534 "'yield' inside generator expression")
535
Georg Brandlc6fdec62006-10-28 13:10:17 +0000536 def testRaise(self):
537 # 'raise' test [',' test]
538 try: raise RuntimeError, 'just testing'
539 except RuntimeError: pass
540 try: raise KeyboardInterrupt
541 except KeyboardInterrupt: pass
542
543 def testImport(self):
544 # 'import' dotted_as_names
545 import sys
546 import time, sys
547 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
548 from time import time
549 from time import (time)
550 # not testable inside a function, but already done at top of the module
551 # from sys import *
552 from sys import path, argv
553 from sys import (path, argv)
554 from sys import (path, argv,)
555
556 def testGlobal(self):
557 # 'global' NAME (',' NAME)*
558 global a
559 global a, b
560 global one, two, three, four, five, six, seven, eight, nine, ten
561
562 def testExec(self):
563 # 'exec' expr ['in' expr [',' expr]]
564 z = None
565 del z
566 exec 'z=1+1\n'
567 if z != 2: self.fail('exec \'z=1+1\'\\n')
568 del z
569 exec 'z=1+1'
570 if z != 2: self.fail('exec \'z=1+1\'')
571 z = None
572 del z
573 import types
574 if hasattr(types, "UnicodeType"):
575 exec r"""if 1:
576 exec u'z=1+1\n'
577 if z != 2: self.fail('exec u\'z=1+1\'\\n')
578 del z
579 exec u'z=1+1'
580 if z != 2: self.fail('exec u\'z=1+1\'')"""
581 g = {}
582 exec 'z = 1' in g
Ezio Melottid80b4bf2010-03-17 13:52:48 +0000583 if '__builtins__' in g: del g['__builtins__']
Georg Brandlc6fdec62006-10-28 13:10:17 +0000584 if g != {'z': 1}: self.fail('exec \'z = 1\' in g')
585 g = {}
586 l = {}
587
Georg Brandlc6fdec62006-10-28 13:10:17 +0000588 exec 'global a; a = 1; b = 2' in g, l
Ezio Melottid80b4bf2010-03-17 13:52:48 +0000589 if '__builtins__' in g: del g['__builtins__']
590 if '__builtins__' in l: del l['__builtins__']
Georg Brandlc6fdec62006-10-28 13:10:17 +0000591 if (g, l) != ({'a':1}, {'b':2}):
592 self.fail('exec ... in g (%s), l (%s)' %(g,l))
593
594 def testAssert(self):
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000595 # assertTruestmt: 'assert' test [',' test]
Georg Brandlc6fdec62006-10-28 13:10:17 +0000596 assert 1
597 assert 1, 1
598 assert lambda x:x
599 assert 1, lambda x:x+1
Ezio Melottiab731a32011-12-02 18:17:30 +0200600
601 try:
602 assert True
603 except AssertionError as e:
604 self.fail("'assert True' should not have raised an AssertionError")
605
606 try:
607 assert True, 'this should always pass'
608 except AssertionError as e:
609 self.fail("'assert True, msg' should not have "
610 "raised an AssertionError")
611
612 # these tests fail if python is run with -O, so check __debug__
613 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
614 def testAssert2(self):
Thomas Wouters80d373c2001-09-26 12:43:39 +0000615 try:
Georg Brandlc6fdec62006-10-28 13:10:17 +0000616 assert 0, "msg"
617 except AssertionError, e:
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000618 self.assertEqual(e.args[0], "msg")
Georg Brandlfacd2732006-10-29 09:18:00 +0000619 else:
Ezio Melottiab731a32011-12-02 18:17:30 +0200620 self.fail("AssertionError not raised by assert 0")
621
622 try:
623 assert False
624 except AssertionError as e:
625 self.assertEqual(len(e.args), 0)
626 else:
627 self.fail("AssertionError not raised by 'assert False'")
628
Thomas Wouters80d373c2001-09-26 12:43:39 +0000629
Georg Brandlc6fdec62006-10-28 13:10:17 +0000630 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
631 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000632
Georg Brandlc6fdec62006-10-28 13:10:17 +0000633 def testIf(self):
634 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
635 if 1: pass
636 if 1: pass
637 else: pass
638 if 0: pass
639 elif 0: pass
640 if 0: pass
641 elif 0: pass
642 elif 0: pass
643 elif 0: pass
644 else: pass
Tim Petersabd8a332006-11-03 02:32:46 +0000645
Georg Brandlc6fdec62006-10-28 13:10:17 +0000646 def testWhile(self):
647 # 'while' test ':' suite ['else' ':' suite]
648 while 0: pass
649 while 0: pass
650 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000651
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +0000652 # Issue1920: "while 0" is optimized away,
653 # ensure that the "else" clause is still present.
654 x = 0
655 while 0:
656 x = 1
657 else:
658 x = 2
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000659 self.assertEqual(x, 2)
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +0000660
Georg Brandlc6fdec62006-10-28 13:10:17 +0000661 def testFor(self):
662 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
663 for i in 1, 2, 3: pass
664 for i, j, k in (): pass
665 else: pass
666 class Squares:
667 def __init__(self, max):
668 self.max = max
669 self.sofar = []
670 def __len__(self): return len(self.sofar)
671 def __getitem__(self, i):
672 if not 0 <= i < self.max: raise IndexError
673 n = len(self.sofar)
674 while n <= i:
675 self.sofar.append(n*n)
676 n = n+1
677 return self.sofar[i]
678 n = 0
679 for x in Squares(10): n = n+x
680 if n != 285:
681 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000682
Georg Brandlc6fdec62006-10-28 13:10:17 +0000683 result = []
684 for x, in [(1,), (2,), (3,)]:
685 result.append(x)
686 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000687
Georg Brandlc6fdec62006-10-28 13:10:17 +0000688 def testTry(self):
689 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
690 ### | 'try' ':' suite 'finally' ':' suite
Collin Winter62903052007-05-18 23:11:24 +0000691 ### except_clause: 'except' [expr [('as' | ',') expr]]
Georg Brandlc6fdec62006-10-28 13:10:17 +0000692 try:
693 1/0
694 except ZeroDivisionError:
695 pass
696 else:
697 pass
698 try: 1/0
699 except EOFError: pass
Collin Winter62903052007-05-18 23:11:24 +0000700 except TypeError as msg: pass
Georg Brandlc6fdec62006-10-28 13:10:17 +0000701 except RuntimeError, msg: pass
702 except: pass
703 else: pass
704 try: 1/0
705 except (EOFError, TypeError, ZeroDivisionError): pass
706 try: 1/0
707 except (EOFError, TypeError, ZeroDivisionError), msg: pass
708 try: pass
709 finally: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000710
Georg Brandlc6fdec62006-10-28 13:10:17 +0000711 def testSuite(self):
712 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
713 if 1: pass
714 if 1:
715 pass
716 if 1:
717 #
718 #
719 #
720 pass
721 pass
722 #
723 pass
724 #
Jeremy Hylton2922ea82001-02-28 23:49:19 +0000725
Georg Brandlc6fdec62006-10-28 13:10:17 +0000726 def testTest(self):
727 ### and_test ('or' and_test)*
728 ### and_test: not_test ('and' not_test)*
729 ### not_test: 'not' not_test | comparison
730 if not 1: pass
731 if 1 and 1: pass
732 if 1 or 1: pass
733 if not not not 1: pass
734 if not 1 and 1 and 1: pass
735 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
736
737 def testComparison(self):
738 ### comparison: expr (comp_op expr)*
739 ### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
740 if 1: pass
741 x = (1 == 1)
742 if 1 == 1: pass
743 if 1 != 1: pass
Georg Brandlc6fdec62006-10-28 13:10:17 +0000744 if 1 < 1: pass
745 if 1 > 1: pass
746 if 1 <= 1: pass
747 if 1 >= 1: pass
748 if 1 is 1: pass
749 if 1 is not 1: pass
750 if 1 in (): pass
751 if 1 not in (): pass
Ezio Melottid80b4bf2010-03-17 13:52:48 +0000752 if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass
753 # Silence Py3k warning
754 if eval('1 <> 1'): pass
755 if eval('1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1'): pass
Georg Brandlc6fdec62006-10-28 13:10:17 +0000756
757 def testBinaryMaskOps(self):
758 x = 1 & 1
759 x = 1 ^ 1
760 x = 1 | 1
761
762 def testShiftOps(self):
763 x = 1 << 1
764 x = 1 >> 1
765 x = 1 << 1 >> 1
766
767 def testAdditiveOps(self):
768 x = 1
769 x = 1 + 1
770 x = 1 - 1 - 1
771 x = 1 - 1 + 1 - 1 + 1
772
773 def testMultiplicativeOps(self):
774 x = 1 * 1
775 x = 1 / 1
776 x = 1 % 1
777 x = 1 / 1 * 1 % 1
778
779 def testUnaryOps(self):
780 x = +1
781 x = -1
782 x = ~1
783 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
784 x = -1*1/1 + 1*1 - ---1*1
785
786 def testSelectors(self):
787 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
788 ### subscript: expr | [expr] ':' [expr]
Tim Petersabd8a332006-11-03 02:32:46 +0000789
Georg Brandlc6fdec62006-10-28 13:10:17 +0000790 import sys, time
791 c = sys.path[0]
792 x = time.time()
793 x = sys.modules['time'].time()
794 a = '01234'
795 c = a[0]
796 c = a[-1]
797 s = a[0:5]
798 s = a[:5]
799 s = a[0:]
800 s = a[:]
801 s = a[-5:]
802 s = a[:-1]
803 s = a[-4:-3]
804 # A rough test of SF bug 1333982. http://python.org/sf/1333982
805 # The testing here is fairly incomplete.
806 # Test cases should include: commas with 1 and 2 colons
807 d = {}
808 d[1] = 1
809 d[1,] = 2
810 d[1,2] = 3
811 d[1,2,3] = 4
812 L = list(d)
813 L.sort()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000814 self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Georg Brandlc6fdec62006-10-28 13:10:17 +0000815
816 def testAtoms(self):
817 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
Alexandre Vassalottiee936a22010-01-09 23:35:54 +0000818 ### dictorsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Georg Brandlc6fdec62006-10-28 13:10:17 +0000819
820 x = (1)
821 x = (1 or 2 or 3)
822 x = (1 or 2 or 3, 2, 3)
823
824 x = []
825 x = [1]
826 x = [1 or 2 or 3]
827 x = [1 or 2 or 3, 2, 3]
828 x = []
829
830 x = {}
831 x = {'one': 1}
832 x = {'one': 1,}
833 x = {'one' or 'two': 1 or 2}
834 x = {'one': 1, 'two': 2}
835 x = {'one': 1, 'two': 2,}
836 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
837
Alexandre Vassalottiee936a22010-01-09 23:35:54 +0000838 x = {'one'}
839 x = {'one', 1,}
840 x = {'one', 'two', 'three'}
841 x = {2, 3, 4,}
842
Ezio Melottid80b4bf2010-03-17 13:52:48 +0000843 # Silence Py3k warning
844 x = eval('`x`')
845 x = eval('`1 or 2 or 3`')
846 self.assertEqual(eval('`1,2`'), '(1, 2)')
Neal Norwitz85dbec62006-11-04 19:25:22 +0000847
Georg Brandlc6fdec62006-10-28 13:10:17 +0000848 x = x
849 x = 'x'
850 x = 123
851
852 ### exprlist: expr (',' expr)* [',']
853 ### testlist: test (',' test)* [',']
854 # These have been exercised enough above
855
856 def testClassdef(self):
857 # 'class' NAME ['(' [testlist] ')'] ':' suite
858 class B: pass
859 class B2(): pass
860 class C1(B): pass
861 class C2(B): pass
862 class D(C1, C2, B): pass
863 class C:
864 def meth1(self): pass
865 def meth2(self, arg): pass
866 def meth3(self, a1, a2): pass
Christian Heimes5224d282008-02-23 15:01:05 +0000867 # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
868 # decorators: decorator+
869 # decorated: decorators (classdef | funcdef)
870 def class_decorator(x):
871 x.decorated = True
872 return x
873 @class_decorator
874 class G:
875 pass
876 self.assertEqual(G.decorated, True)
Georg Brandlc6fdec62006-10-28 13:10:17 +0000877
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000878 def testDictcomps(self):
879 # dictorsetmaker: ( (test ':' test (comp_for |
880 # (',' test ':' test)* [','])) |
881 # (test (comp_for | (',' test)* [','])) )
882 nums = [1, 2, 3]
883 self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
884
Georg Brandlc6fdec62006-10-28 13:10:17 +0000885 def testListcomps(self):
886 # list comprehension tests
887 nums = [1, 2, 3, 4, 5]
888 strs = ["Apple", "Banana", "Coconut"]
889 spcs = [" Apple", " Banana ", "Coco nut "]
890
891 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
892 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
893 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
894 self.assertEqual([(i, s) for i in nums for s in strs],
895 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
896 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
897 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
898 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
899 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
900 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
901 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
902 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
903 (5, 'Banana'), (5, 'Coconut')])
904 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
905 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
906
907 def test_in_func(l):
908 return [None < x < 3 for x in l if x > 2]
909
910 self.assertEqual(test_in_func(nums), [False, False, False])
911
912 def test_nested_front():
913 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
914 [[1, 2], [3, 4], [5, 6]])
915
916 test_nested_front()
917
918 check_syntax_error(self, "[i, s for i in nums for s in strs]")
919 check_syntax_error(self, "[x if y]")
920
921 suppliers = [
922 (1, "Boeing"),
923 (2, "Ford"),
924 (3, "Macdonalds")
925 ]
926
927 parts = [
928 (10, "Airliner"),
929 (20, "Engine"),
930 (30, "Cheeseburger")
931 ]
932
933 suppart = [
934 (1, 10), (1, 20), (2, 20), (3, 30)
935 ]
936
937 x = [
938 (sname, pname)
939 for (sno, sname) in suppliers
940 for (pno, pname) in parts
941 for (sp_sno, sp_pno) in suppart
942 if sno == sp_sno and pno == sp_pno
943 ]
944
945 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
946 ('Macdonalds', 'Cheeseburger')])
947
948 def testGenexps(self):
949 # generator expression tests
950 g = ([x for x in range(10)] for x in range(1))
951 self.assertEqual(g.next(), [x for x in range(10)])
952 try:
953 g.next()
954 self.fail('should produce StopIteration exception')
955 except StopIteration:
956 pass
957
958 a = 1
959 try:
960 g = (a for d in a)
961 g.next()
962 self.fail('should produce TypeError')
963 except TypeError:
964 pass
965
966 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
967 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
968
969 a = [x for x in range(10)]
970 b = (x for x in (y for y in a))
971 self.assertEqual(sum(b), sum([x for x in range(10)]))
972
973 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
974 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
975 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
976 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
977 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
978 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)]))
979 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
980 check_syntax_error(self, "foo(x for x in range(10), 100)")
981 check_syntax_error(self, "foo(100, x for x in range(10))")
982
983 def testComprehensionSpecials(self):
984 # test for outmost iterable precomputation
985 x = 10; g = (i for i in range(x)); x = 5
986 self.assertEqual(len(list(g)), 10)
987
988 # This should hold, since we're only precomputing outmost iterable.
989 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
990 x = 5; t = True;
991 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
992
993 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
994 # even though it's silly. Make sure it works (ifelse broke this.)
995 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
996 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
997
998 # verify unpacking single element tuples in listcomp/genexp.
999 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
1000 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
1001
Benjamin Peterson46508922009-05-29 21:48:19 +00001002 def test_with_statement(self):
1003 class manager(object):
1004 def __enter__(self):
1005 return (1, 2)
1006 def __exit__(self, *args):
1007 pass
1008
1009 with manager():
1010 pass
1011 with manager() as x:
1012 pass
1013 with manager() as (x, y):
1014 pass
1015 with manager(), manager():
1016 pass
1017 with manager() as x, manager() as y:
1018 pass
1019 with manager() as x, manager():
1020 pass
1021
Georg Brandlc6fdec62006-10-28 13:10:17 +00001022 def testIfElseExpr(self):
1023 # Test ifelse expressions in various cases
1024 def _checkeval(msg, ret):
1025 "helper to check that evaluation of expressions is done correctly"
1026 print x
1027 return ret
1028
1029 self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
1030 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
1031 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])
1032 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
1033 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
1034 self.assertEqual((5 and 6 if 0 else 1), 1)
1035 self.assertEqual(((5 and 6) if 0 else 1), 1)
1036 self.assertEqual((5 and (6 if 1 else 1)), 6)
1037 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
1038 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
1039 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
1040 self.assertEqual((not 5 if 1 else 1), False)
1041 self.assertEqual((not 5 if 0 else 1), 1)
1042 self.assertEqual((6 + 1 if 1 else 2), 7)
1043 self.assertEqual((6 - 1 if 1 else 2), 5)
1044 self.assertEqual((6 * 2 if 1 else 4), 12)
1045 self.assertEqual((6 / 2 if 1 else 3), 3)
1046 self.assertEqual((6 < 4 if 0 else 2), 2)
Guido van Rossumb3b09c91993-10-22 14:24:22 +00001047
Benjamin Petersonb2e31a12009-10-31 03:56:15 +00001048 def test_paren_evaluation(self):
1049 self.assertEqual(16 // (4 // 2), 8)
1050 self.assertEqual((16 // 4) // 2, 2)
1051 self.assertEqual(16 // 4 // 2, 2)
1052 self.assertTrue(False is (2 is 3))
1053 self.assertFalse((False is 2) is 3)
1054 self.assertFalse(False is 2 is 3)
1055
Guido van Rossumb3b09c91993-10-22 14:24:22 +00001056
Georg Brandlc6fdec62006-10-28 13:10:17 +00001057def test_main():
Ezio Melottid80b4bf2010-03-17 13:52:48 +00001058 with check_py3k_warnings(
1059 ("backquote not supported", SyntaxWarning),
1060 ("tuple parameter unpacking has been removed", SyntaxWarning),
1061 ("parenthesized argument names are invalid", SyntaxWarning),
1062 ("classic int division", DeprecationWarning),
1063 (".+ not supported in 3.x", DeprecationWarning)):
1064 run_unittest(TokenTests, GrammarTests)
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +00001065
Georg Brandlc6fdec62006-10-28 13:10:17 +00001066if __name__ == '__main__':
1067 test_main()