blob: 250452322ccc08617c89baf43964ba765e06c0b6 [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
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004from test.support import run_unittest, check_syntax_error
Thomas Wouters89f507f2006-12-13 04:49:30 +00005import unittest
Jeremy Hylton7d3dff22001-10-10 01:45:02 +00006import sys
Thomas Wouters89f507f2006-12-13 04:49:30 +00007# testing import *
8from sys import *
Guido van Rossum3bead091992-01-27 17:00:37 +00009
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000010
Thomas Wouters89f507f2006-12-13 04:49:30 +000011class TokenTests(unittest.TestCase):
Guido van Rossum3bead091992-01-27 17:00:37 +000012
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050013 def test_backslash(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +000014 # Backslash means line continuation:
15 x = 1 \
16 + 1
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000017 self.assertEqual(x, 2, 'backslash for line continuation')
Guido van Rossum3bead091992-01-27 17:00:37 +000018
Thomas Wouters89f507f2006-12-13 04:49:30 +000019 # Backslash does not means continuation in comments :\
20 x = 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000021 self.assertEqual(x, 0, 'backslash ending comment')
Guido van Rossum3bead091992-01-27 17:00:37 +000022
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050023 def test_plain_integers(self):
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000024 self.assertEqual(type(000), type(0))
25 self.assertEqual(0xff, 255)
26 self.assertEqual(0o377, 255)
27 self.assertEqual(2147483647, 0o17777777777)
28 self.assertEqual(0b1001, 9)
Georg Brandlfceab5a2008-01-19 20:08:23 +000029 # "0x" is not a valid literal
30 self.assertRaises(SyntaxError, eval, "0x")
Christian Heimesa37d4c62007-12-04 23:02:19 +000031 from sys import maxsize
32 if maxsize == 2147483647:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000033 self.assertEqual(-2147483647-1, -0o20000000000)
Thomas Wouters89f507f2006-12-13 04:49:30 +000034 # XXX -2147483648
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000035 self.assertTrue(0o37777777777 > 0)
36 self.assertTrue(0xffffffff > 0)
37 self.assertTrue(0b1111111111111111111111111111111 > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +000038 for s in ('2147483648', '0o40000000000', '0x100000000',
39 '0b10000000000000000000000000000000'):
Thomas Wouters89f507f2006-12-13 04:49:30 +000040 try:
41 x = eval(s)
42 except OverflowError:
43 self.fail("OverflowError on huge integer literal %r" % s)
Christian Heimesa37d4c62007-12-04 23:02:19 +000044 elif maxsize == 9223372036854775807:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000045 self.assertEqual(-9223372036854775807-1, -0o1000000000000000000000)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000046 self.assertTrue(0o1777777777777777777777 > 0)
47 self.assertTrue(0xffffffffffffffff > 0)
48 self.assertTrue(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +000049 for s in '9223372036854775808', '0o2000000000000000000000', \
50 '0x10000000000000000', \
51 '0b100000000000000000000000000000000000000000000000000000000000000':
Thomas Wouters89f507f2006-12-13 04:49:30 +000052 try:
53 x = eval(s)
54 except OverflowError:
55 self.fail("OverflowError on huge integer literal %r" % s)
56 else:
Christian Heimesa37d4c62007-12-04 23:02:19 +000057 self.fail('Weird maxsize value %r' % maxsize)
Guido van Rossum3bead091992-01-27 17:00:37 +000058
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050059 def test_long_integers(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +000060 x = 0
Guido van Rossume2a383d2007-01-15 16:59:06 +000061 x = 0xffffffffffffffff
Guido van Rossumcd16bf62007-06-13 18:07:49 +000062 x = 0Xffffffffffffffff
63 x = 0o77777777777777777
64 x = 0O77777777777777777
Guido van Rossume2a383d2007-01-15 16:59:06 +000065 x = 123456789012345678901234567890
Guido van Rossumcd16bf62007-06-13 18:07:49 +000066 x = 0b100000000000000000000000000000000000000000000000000000000000000000000
67 x = 0B111111111111111111111111111111111111111111111111111111111111111111111
Guido van Rossum3bead091992-01-27 17:00:37 +000068
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050069 def test_floats(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +000070 x = 3.14
71 x = 314.
72 x = 0.314
73 # XXX x = 000.314
74 x = .314
75 x = 3e14
76 x = 3E14
77 x = 3e-14
78 x = 3e+14
79 x = 3.e14
80 x = .3e14
81 x = 3.1e4
Guido van Rossum3bead091992-01-27 17:00:37 +000082
Benjamin Petersonc4161622014-06-07 12:36:39 -070083 def test_float_exponent_tokenization(self):
84 # See issue 21642.
85 self.assertEqual(1 if 1else 0, 1)
86 self.assertEqual(1 if 0else 0, 0)
87 self.assertRaises(SyntaxError, eval, "0 if 1Else 0")
88
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050089 def test_string_literals(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000090 x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y)
91 x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39)
92 x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34)
Thomas Wouters89f507f2006-12-13 04:49:30 +000093 x = "doesn't \"shrink\" does it"
94 y = 'doesn\'t "shrink" does it'
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000095 self.assertTrue(len(x) == 24 and x == y)
Thomas Wouters89f507f2006-12-13 04:49:30 +000096 x = "does \"shrink\" doesn't it"
97 y = 'does "shrink" doesn\'t it'
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000098 self.assertTrue(len(x) == 24 and x == y)
Thomas Wouters89f507f2006-12-13 04:49:30 +000099 x = """
Guido van Rossumb6775db1994-08-01 11:34:53 +0000100The "quick"
101brown fox
102jumps over
103the 'lazy' dog.
104"""
Thomas Wouters89f507f2006-12-13 04:49:30 +0000105 y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000106 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000107 y = '''
Guido van Rossumb6775db1994-08-01 11:34:53 +0000108The "quick"
109brown fox
110jumps over
111the 'lazy' dog.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000112'''
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000113 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000114 y = "\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000115The \"quick\"\n\
116brown fox\n\
117jumps over\n\
118the 'lazy' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000119"
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000120 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000121 y = '\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000122The \"quick\"\n\
123brown fox\n\
124jumps over\n\
125the \'lazy\' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000126'
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000127 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000128
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500129 def test_ellipsis(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000130 x = ...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000131 self.assertTrue(x is Ellipsis)
Georg Brandldde00282007-03-18 19:01:53 +0000132 self.assertRaises(SyntaxError, eval, ".. .")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000133
Benjamin Peterson758888d2011-05-30 11:12:38 -0500134 def test_eof_error(self):
135 samples = ("def foo(", "\ndef foo(", "def foo(\n")
136 for s in samples:
137 with self.assertRaises(SyntaxError) as cm:
138 compile(s, "<test>", "exec")
139 self.assertIn("unexpected EOF", str(cm.exception))
140
Thomas Wouters89f507f2006-12-13 04:49:30 +0000141class GrammarTests(unittest.TestCase):
142
143 # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
144 # XXX can't test in a script -- this rule is only used when interactive
145
146 # file_input: (NEWLINE | stmt)* ENDMARKER
147 # Being tested as this very moment this very module
148
149 # expr_input: testlist NEWLINE
150 # XXX Hard to test -- used only in calls to input()
151
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500152 def test_eval_input(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000153 # testlist ENDMARKER
154 x = eval('1, 0 or 1')
155
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500156 def test_funcdef(self):
Neal Norwitzc1505362006-12-28 06:47:50 +0000157 ### [decorators] 'def' NAME parameters ['->' test] ':' suite
158 ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
159 ### decorators: decorator+
160 ### parameters: '(' [typedargslist] ')'
161 ### typedargslist: ((tfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000162 ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000163 ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000164 ### tfpdef: NAME [':' test]
Neal Norwitzc1505362006-12-28 06:47:50 +0000165 ### varargslist: ((vfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000166 ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000167 ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000168 ### vfpdef: NAME
Thomas Wouters89f507f2006-12-13 04:49:30 +0000169 def f1(): pass
170 f1()
171 f1(*())
172 f1(*(), **{})
173 def f2(one_argument): pass
174 def f3(two, arguments): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000175 self.assertEqual(f2.__code__.co_varnames, ('one_argument',))
176 self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments'))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000177 def a1(one_arg,): pass
178 def a2(two, args,): pass
179 def v0(*rest): pass
180 def v1(a, *rest): pass
181 def v2(a, b, *rest): pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000182
183 f1()
184 f2(1)
185 f2(1,)
186 f3(1, 2)
187 f3(1, 2,)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000188 v0()
189 v0(1)
190 v0(1,)
191 v0(1,2)
192 v0(1,2,3,4,5,6,7,8,9,0)
193 v1(1)
194 v1(1,)
195 v1(1,2)
196 v1(1,2,3)
197 v1(1,2,3,4,5,6,7,8,9,0)
198 v2(1,2)
199 v2(1,2,3)
200 v2(1,2,3,4)
201 v2(1,2,3,4,5,6,7,8,9,0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000202
Thomas Wouters89f507f2006-12-13 04:49:30 +0000203 def d01(a=1): pass
204 d01()
205 d01(1)
206 d01(*(1,))
Zachary Ware36948d72015-08-04 22:49:55 -0500207 d01(*[] or [2])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000208 d01(**{'a':2})
Zachary Ware36948d72015-08-04 22:49:55 -0500209 d01(**{'a':2} or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000210 def d11(a, b=1): pass
211 d11(1)
212 d11(1, 2)
213 d11(1, **{'b':2})
214 def d21(a, b, c=1): pass
215 d21(1, 2)
216 d21(1, 2, 3)
217 d21(*(1, 2, 3))
218 d21(1, *(2, 3))
219 d21(1, 2, *(3,))
220 d21(1, 2, **{'c':3})
221 def d02(a=1, b=2): pass
222 d02()
223 d02(1)
224 d02(1, 2)
225 d02(*(1, 2))
226 d02(1, *(2,))
227 d02(1, **{'b':2})
228 d02(**{'a': 1, 'b': 2})
229 def d12(a, b=1, c=2): pass
230 d12(1)
231 d12(1, 2)
232 d12(1, 2, 3)
233 def d22(a, b, c=1, d=2): pass
234 d22(1, 2)
235 d22(1, 2, 3)
236 d22(1, 2, 3, 4)
237 def d01v(a=1, *rest): pass
238 d01v()
239 d01v(1)
240 d01v(1, 2)
241 d01v(*(1, 2, 3, 4))
242 d01v(*(1,))
243 d01v(**{'a':2})
244 def d11v(a, b=1, *rest): pass
245 d11v(1)
246 d11v(1, 2)
247 d11v(1, 2, 3)
248 def d21v(a, b, c=1, *rest): pass
249 d21v(1, 2)
250 d21v(1, 2, 3)
251 d21v(1, 2, 3, 4)
252 d21v(*(1, 2, 3, 4))
253 d21v(1, 2, **{'c': 3})
254 def d02v(a=1, b=2, *rest): pass
255 d02v()
256 d02v(1)
257 d02v(1, 2)
258 d02v(1, 2, 3)
259 d02v(1, *(2, 3, 4))
260 d02v(**{'a': 1, 'b': 2})
261 def d12v(a, b=1, c=2, *rest): pass
262 d12v(1)
263 d12v(1, 2)
264 d12v(1, 2, 3)
265 d12v(1, 2, 3, 4)
266 d12v(*(1, 2, 3, 4))
267 d12v(1, 2, *(3, 4, 5))
268 d12v(1, *(2,), **{'c': 3})
269 def d22v(a, b, c=1, d=2, *rest): pass
270 d22v(1, 2)
271 d22v(1, 2, 3)
272 d22v(1, 2, 3, 4)
273 d22v(1, 2, 3, 4, 5)
274 d22v(*(1, 2, 3, 4))
275 d22v(1, 2, *(3, 4, 5))
276 d22v(1, *(2, 3), **{'d': 4})
Georg Brandld8b690f2008-05-16 17:28:50 +0000277
278 # keyword argument type tests
279 try:
280 str('x', **{b'foo':1 })
281 except TypeError:
282 pass
283 else:
284 self.fail('Bytes should not work as keyword argument names')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000285 # keyword only argument tests
286 def pos0key1(*, key): return key
287 pos0key1(key=100)
288 def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
289 pos2key2(1, 2, k1=100)
290 pos2key2(1, 2, k1=100, k2=200)
291 pos2key2(1, 2, k2=100, k1=200)
292 def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
293 pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
294 pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
295
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000296 # keyword arguments after *arglist
297 def f(*args, **kwargs):
298 return args, kwargs
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000299 self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000300 {'x':2, 'y':5}))
301 self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)")
302 self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
303
Neal Norwitzc1505362006-12-28 06:47:50 +0000304 # argument annotation tests
305 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000306 self.assertEqual(f.__annotations__, {'return': list})
Zachary Warece17f762015-08-01 21:55:36 -0500307 def f(x: int): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000308 self.assertEqual(f.__annotations__, {'x': int})
Zachary Warece17f762015-08-01 21:55:36 -0500309 def f(*x: str): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000310 self.assertEqual(f.__annotations__, {'x': str})
Zachary Warece17f762015-08-01 21:55:36 -0500311 def f(**x: float): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000312 self.assertEqual(f.__annotations__, {'x': float})
Zachary Warece17f762015-08-01 21:55:36 -0500313 def f(x, y: 1+2): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000314 self.assertEqual(f.__annotations__, {'y': 3})
Zachary Warece17f762015-08-01 21:55:36 -0500315 def f(a, b: 1, c: 2, d): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000316 self.assertEqual(f.__annotations__, {'b': 1, 'c': 2})
Zachary Warece17f762015-08-01 21:55:36 -0500317 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000318 self.assertEqual(f.__annotations__,
Zachary Warece17f762015-08-01 21:55:36 -0500319 {'b': 1, 'c': 2, 'e': 3, 'g': 6})
320 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6, h: 7, i=8, j: 9 = 10,
321 **k: 11) -> 12: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000322 self.assertEqual(f.__annotations__,
Zachary Warece17f762015-08-01 21:55:36 -0500323 {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
324 'k': 11, 'return': 12})
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500325 # Check for issue #20625 -- annotations mangling
326 class Spam:
Zachary Warece17f762015-08-01 21:55:36 -0500327 def f(self, *, __kw: 1):
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500328 pass
329 class Ham(Spam): pass
Benjamin Petersonbcfcfc52014-03-09 20:59:24 -0500330 self.assertEqual(Spam.f.__annotations__, {'_Spam__kw': 1})
331 self.assertEqual(Ham.f.__annotations__, {'_Spam__kw': 1})
Nick Coghlan71011e22007-04-23 11:05:01 +0000332 # Check for SF Bug #1697248 - mixing decorators and a return annotation
333 def null(x): return x
334 @null
335 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000336 self.assertEqual(f.__annotations__, {'return': list})
Nick Coghlan71011e22007-04-23 11:05:01 +0000337
Guido van Rossum0240b922007-02-26 21:23:50 +0000338 # test MAKE_CLOSURE with a variety of oparg's
339 closure = 1
340 def f(): return closure
341 def f(x=1): return closure
342 def f(*, k=1): return closure
343 def f() -> int: return closure
Neal Norwitzc1505362006-12-28 06:47:50 +0000344
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000345 # Check ast errors in *args and *kwargs
346 check_syntax_error(self, "f(*g(1=2))")
347 check_syntax_error(self, "f(**g(1=2))")
348
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500349 def test_lambdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000350 ### lambdef: 'lambda' [varargslist] ':' test
351 l1 = lambda : 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000352 self.assertEqual(l1(), 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000353 l2 = lambda : a[d] # XXX just testing the expression
Guido van Rossume2a383d2007-01-15 16:59:06 +0000354 l3 = lambda : [2 < x for x in [-1, 3, 0]]
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000355 self.assertEqual(l3(), [0, 1, 0])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000356 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000357 self.assertEqual(l4(), 1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000358 l5 = lambda x, y, z=2: x + y + z
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000359 self.assertEqual(l5(1, 2), 5)
360 self.assertEqual(l5(1, 2, 3), 6)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000361 check_syntax_error(self, "lambda x: x = 2")
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000362 check_syntax_error(self, "lambda (None,): None")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000363 l6 = lambda x, y, *, k=20: x+y+k
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000364 self.assertEqual(l6(1,2), 1+2+20)
365 self.assertEqual(l6(1,2,k=10), 1+2+10)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000366
367
Thomas Wouters89f507f2006-12-13 04:49:30 +0000368 ### stmt: simple_stmt | compound_stmt
369 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000370
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500371 def test_simple_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000372 ### simple_stmt: small_stmt (';' small_stmt)* [';']
373 x = 1; pass; del x
374 def foo():
Ezio Melotti13925002011-03-16 11:05:33 +0200375 # verify statements that end with semi-colons
Thomas Wouters89f507f2006-12-13 04:49:30 +0000376 x = 1; pass; del x;
377 foo()
Georg Brandl52318d62006-09-06 07:06:08 +0000378
Guido van Rossumd8faa362007-04-27 19:54:29 +0000379 ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
Thomas Wouters89f507f2006-12-13 04:49:30 +0000380 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000381
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500382 def test_expr_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000383 # (exprlist '=')* exprlist
384 1
385 1, 2, 3
386 x = 1
387 x = 1, 2, 3
388 x = y = z = 1, 2, 3
389 x, y, z = 1, 2, 3
390 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000391
Thomas Wouters89f507f2006-12-13 04:49:30 +0000392 check_syntax_error(self, "x + 1 = 1")
393 check_syntax_error(self, "a + 1 = b + 2")
Guido van Rossum3bead091992-01-27 17:00:37 +0000394
Nick Coghlan5b1fdc12014-06-16 19:48:02 +1000395 # Check the heuristic for print & exec covers significant cases
396 # As well as placing some limits on false positives
397 def test_former_statements_refer_to_builtins(self):
398 keywords = "print", "exec"
399 # Cases where we want the custom error
400 cases = [
401 "{} foo",
402 "{} {{1:foo}}",
403 "if 1: {} foo",
404 "if 1: {} {{1:foo}}",
405 "if 1:\n {} foo",
406 "if 1:\n {} {{1:foo}}",
407 ]
408 for keyword in keywords:
409 custom_msg = "call to '{}'".format(keyword)
410 for case in cases:
411 source = case.format(keyword)
412 with self.subTest(source=source):
413 with self.assertRaisesRegex(SyntaxError, custom_msg):
414 exec(source)
415 source = source.replace("foo", "(foo.)")
416 with self.subTest(source=source):
417 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
418 exec(source)
419
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500420 def test_del_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000421 # 'del' exprlist
422 abc = [1,2,3]
423 x, y, z = abc
424 xyz = x, y, z
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000425
Thomas Wouters89f507f2006-12-13 04:49:30 +0000426 del abc
427 del x, y, (z, xyz)
Barry Warsaw9182b452000-08-29 04:57:10 +0000428
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500429 def test_pass_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000430 # 'pass'
431 pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000432
Thomas Wouters89f507f2006-12-13 04:49:30 +0000433 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
434 # Tested below
Barry Warsaw9182b452000-08-29 04:57:10 +0000435
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500436 def test_break_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000437 # 'break'
438 while 1: break
Barry Warsaw9182b452000-08-29 04:57:10 +0000439
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500440 def test_continue_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000441 # 'continue'
442 i = 1
443 while i: i = 0; continue
Barry Warsaw9182b452000-08-29 04:57:10 +0000444
Thomas Wouters89f507f2006-12-13 04:49:30 +0000445 msg = ""
446 while not msg:
447 msg = "ok"
448 try:
449 continue
450 msg = "continue failed to continue inside try"
451 except:
452 msg = "continue inside try called except block"
453 if msg != "ok":
454 self.fail(msg)
Barry Warsawefc92ee2000-08-21 15:46:50 +0000455
Thomas Wouters89f507f2006-12-13 04:49:30 +0000456 msg = ""
457 while not msg:
458 msg = "finally block not called"
459 try:
460 continue
461 finally:
462 msg = "ok"
463 if msg != "ok":
464 self.fail(msg)
Guido van Rossum3bead091992-01-27 17:00:37 +0000465
Thomas Wouters89f507f2006-12-13 04:49:30 +0000466 def test_break_continue_loop(self):
467 # This test warrants an explanation. It is a test specifically for SF bugs
468 # #463359 and #462937. The bug is that a 'break' statement executed or
469 # exception raised inside a try/except inside a loop, *after* a continue
470 # statement has been executed in that loop, will cause the wrong number of
471 # arguments to be popped off the stack and the instruction pointer reset to
472 # a very small number (usually 0.) Because of this, the following test
473 # *must* written as a function, and the tracking vars *must* be function
474 # arguments with default values. Otherwise, the test will loop and loop.
Guido van Rossum3bead091992-01-27 17:00:37 +0000475
Thomas Wouters89f507f2006-12-13 04:49:30 +0000476 def test_inner(extra_burning_oil = 1, count=0):
477 big_hippo = 2
478 while big_hippo:
479 count += 1
480 try:
481 if extra_burning_oil and big_hippo == 1:
482 extra_burning_oil -= 1
483 break
484 big_hippo -= 1
485 continue
486 except:
487 raise
488 if count > 2 or big_hippo != 1:
489 self.fail("continue then break in try/except in loop broken!")
490 test_inner()
Guido van Rossum3bead091992-01-27 17:00:37 +0000491
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500492 def test_return(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000493 # 'return' [testlist]
494 def g1(): return
495 def g2(): return 1
496 g1()
497 x = g2()
498 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000499
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500500 def test_yield(self):
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000501 # Allowed as standalone statement
502 def g(): yield 1
503 def g(): yield from ()
504 # Allowed as RHS of assignment
505 def g(): x = yield 1
506 def g(): x = yield from ()
507 # Ordinary yield accepts implicit tuples
508 def g(): yield 1, 1
509 def g(): x = yield 1, 1
510 # 'yield from' does not
511 check_syntax_error(self, "def g(): yield from (), 1")
512 check_syntax_error(self, "def g(): x = yield from (), 1")
513 # Requires parentheses as subexpression
514 def g(): 1, (yield 1)
515 def g(): 1, (yield from ())
516 check_syntax_error(self, "def g(): 1, yield 1")
517 check_syntax_error(self, "def g(): 1, yield from ()")
518 # Requires parentheses as call argument
519 def g(): f((yield 1))
520 def g(): f((yield 1), 1)
521 def g(): f((yield from ()))
522 def g(): f((yield from ()), 1)
523 check_syntax_error(self, "def g(): f(yield 1)")
524 check_syntax_error(self, "def g(): f(yield 1, 1)")
525 check_syntax_error(self, "def g(): f(yield from ())")
526 check_syntax_error(self, "def g(): f(yield from (), 1)")
527 # Not allowed at top level
528 check_syntax_error(self, "yield")
529 check_syntax_error(self, "yield from")
530 # Not allowed at class scope
Thomas Wouters89f507f2006-12-13 04:49:30 +0000531 check_syntax_error(self, "class foo:yield 1")
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000532 check_syntax_error(self, "class foo:yield from ()")
533
Guido van Rossum3bead091992-01-27 17:00:37 +0000534
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500535 def test_raise(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000536 # 'raise' test [',' test]
Collin Winter828f04a2007-08-31 00:04:24 +0000537 try: raise RuntimeError('just testing')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000538 except RuntimeError: pass
539 try: raise KeyboardInterrupt
540 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000541
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500542 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000543 # 'import' dotted_as_names
544 import sys
545 import time, sys
546 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
547 from time import time
548 from time import (time)
549 # not testable inside a function, but already done at top of the module
550 # from sys import *
551 from sys import path, argv
552 from sys import (path, argv)
553 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +0000554
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500555 def test_global(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000556 # 'global' NAME (',' NAME)*
557 global a
558 global a, b
559 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +0000560
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500561 def test_nonlocal(self):
Benjamin Petersona933e522008-10-24 22:16:39 +0000562 # 'nonlocal' NAME (',' NAME)*
563 x = 0
564 y = 0
565 def f():
566 nonlocal x
567 nonlocal x, y
568
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500569 def test_assert(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000570 # assertTruestmt: 'assert' test [',' test]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000571 assert 1
572 assert 1, 1
573 assert lambda x:x
574 assert 1, lambda x:x+1
Ezio Melotti6cc5bf72011-12-02 18:22:52 +0200575
576 try:
577 assert True
578 except AssertionError as e:
579 self.fail("'assert True' should not have raised an AssertionError")
580
581 try:
582 assert True, 'this should always pass'
583 except AssertionError as e:
584 self.fail("'assert True, msg' should not have "
585 "raised an AssertionError")
586
587 # these tests fail if python is run with -O, so check __debug__
588 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
589 def testAssert2(self):
Thomas Wouters80d373c2001-09-26 12:43:39 +0000590 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000591 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +0000592 except AssertionError as e:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000593 self.assertEqual(e.args[0], "msg")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000594 else:
Ezio Melotti6cc5bf72011-12-02 18:22:52 +0200595 self.fail("AssertionError not raised by assert 0")
596
597 try:
598 assert False
599 except AssertionError as e:
600 self.assertEqual(len(e.args), 0)
601 else:
602 self.fail("AssertionError not raised by 'assert False'")
603
Thomas Wouters80d373c2001-09-26 12:43:39 +0000604
Thomas Wouters89f507f2006-12-13 04:49:30 +0000605 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
606 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000607
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500608 def test_if(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000609 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
610 if 1: pass
611 if 1: pass
612 else: pass
613 if 0: pass
614 elif 0: pass
615 if 0: pass
616 elif 0: pass
617 elif 0: pass
618 elif 0: pass
619 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000620
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500621 def test_while(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000622 # 'while' test ':' suite ['else' ':' suite]
623 while 0: pass
624 while 0: pass
625 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000626
Christian Heimes969fe572008-01-25 11:23:10 +0000627 # Issue1920: "while 0" is optimized away,
628 # ensure that the "else" clause is still present.
629 x = 0
630 while 0:
631 x = 1
632 else:
633 x = 2
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000634 self.assertEqual(x, 2)
Christian Heimes969fe572008-01-25 11:23:10 +0000635
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500636 def test_for(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000637 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
638 for i in 1, 2, 3: pass
639 for i, j, k in (): pass
640 else: pass
641 class Squares:
642 def __init__(self, max):
643 self.max = max
644 self.sofar = []
645 def __len__(self): return len(self.sofar)
646 def __getitem__(self, i):
647 if not 0 <= i < self.max: raise IndexError
648 n = len(self.sofar)
649 while n <= i:
650 self.sofar.append(n*n)
651 n = n+1
652 return self.sofar[i]
653 n = 0
654 for x in Squares(10): n = n+x
655 if n != 285:
656 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000657
Thomas Wouters89f507f2006-12-13 04:49:30 +0000658 result = []
659 for x, in [(1,), (2,), (3,)]:
660 result.append(x)
661 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000662
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500663 def test_try(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000664 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
665 ### | 'try' ':' suite 'finally' ':' suite
Guido van Rossumb940e112007-01-10 16:19:56 +0000666 ### except_clause: 'except' [expr ['as' expr]]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000667 try:
668 1/0
669 except ZeroDivisionError:
670 pass
671 else:
672 pass
673 try: 1/0
674 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000675 except TypeError as msg: pass
676 except RuntimeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000677 except: pass
678 else: pass
679 try: 1/0
680 except (EOFError, TypeError, ZeroDivisionError): pass
681 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000682 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000683 try: pass
684 finally: pass
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000685
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500686 def test_suite(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000687 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
688 if 1: pass
689 if 1:
690 pass
691 if 1:
692 #
693 #
694 #
695 pass
696 pass
697 #
698 pass
699 #
Guido van Rossum3bead091992-01-27 17:00:37 +0000700
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500701 def test_test(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000702 ### and_test ('or' and_test)*
703 ### and_test: not_test ('and' not_test)*
704 ### not_test: 'not' not_test | comparison
705 if not 1: pass
706 if 1 and 1: pass
707 if 1 or 1: pass
708 if not not not 1: pass
709 if not 1 and 1 and 1: pass
710 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000711
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500712 def test_comparison(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000713 ### comparison: expr (comp_op expr)*
714 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
715 if 1: pass
716 x = (1 == 1)
717 if 1 == 1: pass
718 if 1 != 1: pass
719 if 1 < 1: pass
720 if 1 > 1: pass
721 if 1 <= 1: pass
722 if 1 >= 1: pass
723 if 1 is 1: pass
724 if 1 is not 1: pass
725 if 1 in (): pass
726 if 1 not in (): pass
727 if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000728
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500729 def test_binary_mask_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000730 x = 1 & 1
731 x = 1 ^ 1
732 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000733
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500734 def test_shift_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000735 x = 1 << 1
736 x = 1 >> 1
737 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000738
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500739 def test_additive_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000740 x = 1
741 x = 1 + 1
742 x = 1 - 1 - 1
743 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000744
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500745 def test_multiplicative_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000746 x = 1 * 1
747 x = 1 / 1
748 x = 1 % 1
749 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000750
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500751 def test_unary_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000752 x = +1
753 x = -1
754 x = ~1
755 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
756 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +0000757
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500758 def test_selectors(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000759 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
760 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +0000761
Thomas Wouters89f507f2006-12-13 04:49:30 +0000762 import sys, time
763 c = sys.path[0]
764 x = time.time()
765 x = sys.modules['time'].time()
766 a = '01234'
767 c = a[0]
768 c = a[-1]
769 s = a[0:5]
770 s = a[:5]
771 s = a[0:]
772 s = a[:]
773 s = a[-5:]
774 s = a[:-1]
775 s = a[-4:-3]
776 # A rough test of SF bug 1333982. http://python.org/sf/1333982
777 # The testing here is fairly incomplete.
778 # Test cases should include: commas with 1 and 2 colons
779 d = {}
780 d[1] = 1
781 d[1,] = 2
782 d[1,2] = 3
783 d[1,2,3] = 4
784 L = list(d)
785 L.sort(key=lambda x: x if isinstance(x, tuple) else ())
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000786 self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +0000787
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500788 def test_atoms(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000789 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
790 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +0000791
Thomas Wouters89f507f2006-12-13 04:49:30 +0000792 x = (1)
793 x = (1 or 2 or 3)
794 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +0000795
Thomas Wouters89f507f2006-12-13 04:49:30 +0000796 x = []
797 x = [1]
798 x = [1 or 2 or 3]
799 x = [1 or 2 or 3, 2, 3]
800 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +0000801
Thomas Wouters89f507f2006-12-13 04:49:30 +0000802 x = {}
803 x = {'one': 1}
804 x = {'one': 1,}
805 x = {'one' or 'two': 1 or 2}
806 x = {'one': 1, 'two': 2}
807 x = {'one': 1, 'two': 2,}
808 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +0000809
Thomas Wouters89f507f2006-12-13 04:49:30 +0000810 x = {'one'}
811 x = {'one', 1,}
812 x = {'one', 'two', 'three'}
813 x = {2, 3, 4,}
814
815 x = x
816 x = 'x'
817 x = 123
818
819 ### exprlist: expr (',' expr)* [',']
820 ### testlist: test (',' test)* [',']
821 # These have been exercised enough above
822
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500823 def test_classdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000824 # 'class' NAME ['(' [testlist] ')'] ':' suite
825 class B: pass
826 class B2(): pass
827 class C1(B): pass
828 class C2(B): pass
829 class D(C1, C2, B): pass
830 class C:
831 def meth1(self): pass
832 def meth2(self, arg): pass
833 def meth3(self, a1, a2): pass
834
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000835 # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
836 # decorators: decorator+
837 # decorated: decorators (classdef | funcdef)
838 def class_decorator(x): return x
839 @class_decorator
840 class G: pass
841
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500842 def test_dictcomps(self):
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000843 # dictorsetmaker: ( (test ':' test (comp_for |
844 # (',' test ':' test)* [','])) |
845 # (test (comp_for | (',' test)* [','])) )
846 nums = [1, 2, 3]
847 self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
848
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500849 def test_listcomps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000850 # list comprehension tests
851 nums = [1, 2, 3, 4, 5]
852 strs = ["Apple", "Banana", "Coconut"]
853 spcs = [" Apple", " Banana ", "Coco nut "]
854
855 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
856 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
857 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
858 self.assertEqual([(i, s) for i in nums for s in strs],
859 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
860 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
861 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
862 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
863 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
864 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
865 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
866 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
867 (5, 'Banana'), (5, 'Coconut')])
868 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
869 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
870
871 def test_in_func(l):
872 return [0 < x < 3 for x in l if x > 2]
873
874 self.assertEqual(test_in_func(nums), [False, False, False])
875
876 def test_nested_front():
877 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
878 [[1, 2], [3, 4], [5, 6]])
879
880 test_nested_front()
881
882 check_syntax_error(self, "[i, s for i in nums for s in strs]")
883 check_syntax_error(self, "[x if y]")
884
885 suppliers = [
886 (1, "Boeing"),
887 (2, "Ford"),
888 (3, "Macdonalds")
889 ]
890
891 parts = [
892 (10, "Airliner"),
893 (20, "Engine"),
894 (30, "Cheeseburger")
895 ]
896
897 suppart = [
898 (1, 10), (1, 20), (2, 20), (3, 30)
899 ]
900
901 x = [
902 (sname, pname)
903 for (sno, sname) in suppliers
904 for (pno, pname) in parts
905 for (sp_sno, sp_pno) in suppart
906 if sno == sp_sno and pno == sp_pno
907 ]
908
909 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
910 ('Macdonalds', 'Cheeseburger')])
911
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500912 def test_genexps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000913 # generator expression tests
914 g = ([x for x in range(10)] for x in range(1))
Georg Brandla18af4e2007-04-21 15:47:16 +0000915 self.assertEqual(next(g), [x for x in range(10)])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000916 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000917 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000918 self.fail('should produce StopIteration exception')
919 except StopIteration:
920 pass
921
922 a = 1
923 try:
924 g = (a for d in a)
Georg Brandla18af4e2007-04-21 15:47:16 +0000925 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000926 self.fail('should produce TypeError')
927 except TypeError:
928 pass
929
930 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
931 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
932
933 a = [x for x in range(10)]
934 b = (x for x in (y for y in a))
935 self.assertEqual(sum(b), sum([x for x in range(10)]))
936
937 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
938 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
939 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
940 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
941 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
942 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)]))
943 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
944 check_syntax_error(self, "foo(x for x in range(10), 100)")
945 check_syntax_error(self, "foo(100, x for x in range(10))")
946
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500947 def test_comprehension_specials(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000948 # test for outmost iterable precomputation
949 x = 10; g = (i for i in range(x)); x = 5
950 self.assertEqual(len(list(g)), 10)
951
952 # This should hold, since we're only precomputing outmost iterable.
953 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
954 x = 5; t = True;
955 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
956
957 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
958 # even though it's silly. Make sure it works (ifelse broke this.)
959 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
960 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
961
962 # verify unpacking single element tuples in listcomp/genexp.
963 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
964 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
965
Benjamin Petersonf17ab892009-05-29 21:55:57 +0000966 def test_with_statement(self):
967 class manager(object):
968 def __enter__(self):
969 return (1, 2)
970 def __exit__(self, *args):
971 pass
972
973 with manager():
974 pass
975 with manager() as x:
976 pass
977 with manager() as (x, y):
978 pass
979 with manager(), manager():
980 pass
981 with manager() as x, manager() as y:
982 pass
983 with manager() as x, manager():
984 pass
985
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500986 def test_if_else_expr(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000987 # Test ifelse expressions in various cases
988 def _checkeval(msg, ret):
989 "helper to check that evaluation of expressions is done correctly"
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000990 print(x)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000991 return ret
992
Nick Coghlan650f0d02007-04-15 12:05:43 +0000993 # the next line is not allowed anymore
994 #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000995 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
996 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])
997 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
998 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
999 self.assertEqual((5 and 6 if 0 else 1), 1)
1000 self.assertEqual(((5 and 6) if 0 else 1), 1)
1001 self.assertEqual((5 and (6 if 1 else 1)), 6)
1002 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
1003 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
1004 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
1005 self.assertEqual((not 5 if 1 else 1), False)
1006 self.assertEqual((not 5 if 0 else 1), 1)
1007 self.assertEqual((6 + 1 if 1 else 2), 7)
1008 self.assertEqual((6 - 1 if 1 else 2), 5)
1009 self.assertEqual((6 * 2 if 1 else 4), 12)
1010 self.assertEqual((6 / 2 if 1 else 3), 3)
1011 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +00001012
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001013 def test_paren_evaluation(self):
1014 self.assertEqual(16 // (4 // 2), 8)
1015 self.assertEqual((16 // 4) // 2, 2)
1016 self.assertEqual(16 // 4 // 2, 2)
1017 self.assertTrue(False is (2 is 3))
1018 self.assertFalse((False is 2) is 3)
1019 self.assertFalse(False is 2 is 3)
1020
Guido van Rossum3bead091992-01-27 17:00:37 +00001021
Thomas Wouters89f507f2006-12-13 04:49:30 +00001022def test_main():
1023 run_unittest(TokenTests, GrammarTests)
Guido van Rossum3bead091992-01-27 17:00:37 +00001024
Thomas Wouters89f507f2006-12-13 04:49:30 +00001025if __name__ == '__main__':
1026 test_main()