blob: 331f48c54d0218ba6c22cf33777f641f821ffe78 [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
Zachary Ware38c707e2015-04-13 15:00:43 -05004from test.support import check_syntax_error
Yury Selivanov75445082015-05-11 22:57:16 -04005import inspect
Thomas Wouters89f507f2006-12-13 04:49:30 +00006import unittest
Jeremy Hylton7d3dff22001-10-10 01:45:02 +00007import sys
Thomas Wouters89f507f2006-12-13 04:49:30 +00008# testing import *
9from sys import *
Guido van Rossum3bead091992-01-27 17:00:37 +000010
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000011
Thomas Wouters89f507f2006-12-13 04:49:30 +000012class TokenTests(unittest.TestCase):
Guido van Rossum3bead091992-01-27 17:00:37 +000013
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050014 def test_backslash(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +000015 # Backslash means line continuation:
16 x = 1 \
17 + 1
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000018 self.assertEqual(x, 2, 'backslash for line continuation')
Guido van Rossum3bead091992-01-27 17:00:37 +000019
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 # Backslash does not means continuation in comments :\
21 x = 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000022 self.assertEqual(x, 0, 'backslash ending comment')
Guido van Rossum3bead091992-01-27 17:00:37 +000023
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050024 def test_plain_integers(self):
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000025 self.assertEqual(type(000), type(0))
26 self.assertEqual(0xff, 255)
27 self.assertEqual(0o377, 255)
28 self.assertEqual(2147483647, 0o17777777777)
29 self.assertEqual(0b1001, 9)
Georg Brandlfceab5a2008-01-19 20:08:23 +000030 # "0x" is not a valid literal
31 self.assertRaises(SyntaxError, eval, "0x")
Christian Heimesa37d4c62007-12-04 23:02:19 +000032 from sys import maxsize
33 if maxsize == 2147483647:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000034 self.assertEqual(-2147483647-1, -0o20000000000)
Thomas Wouters89f507f2006-12-13 04:49:30 +000035 # XXX -2147483648
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000036 self.assertTrue(0o37777777777 > 0)
37 self.assertTrue(0xffffffff > 0)
38 self.assertTrue(0b1111111111111111111111111111111 > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +000039 for s in ('2147483648', '0o40000000000', '0x100000000',
40 '0b10000000000000000000000000000000'):
Thomas Wouters89f507f2006-12-13 04:49:30 +000041 try:
42 x = eval(s)
43 except OverflowError:
44 self.fail("OverflowError on huge integer literal %r" % s)
Christian Heimesa37d4c62007-12-04 23:02:19 +000045 elif maxsize == 9223372036854775807:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000046 self.assertEqual(-9223372036854775807-1, -0o1000000000000000000000)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000047 self.assertTrue(0o1777777777777777777777 > 0)
48 self.assertTrue(0xffffffffffffffff > 0)
49 self.assertTrue(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +000050 for s in '9223372036854775808', '0o2000000000000000000000', \
51 '0x10000000000000000', \
52 '0b100000000000000000000000000000000000000000000000000000000000000':
Thomas Wouters89f507f2006-12-13 04:49:30 +000053 try:
54 x = eval(s)
55 except OverflowError:
56 self.fail("OverflowError on huge integer literal %r" % s)
57 else:
Christian Heimesa37d4c62007-12-04 23:02:19 +000058 self.fail('Weird maxsize value %r' % maxsize)
Guido van Rossum3bead091992-01-27 17:00:37 +000059
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050060 def test_long_integers(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +000061 x = 0
Guido van Rossume2a383d2007-01-15 16:59:06 +000062 x = 0xffffffffffffffff
Guido van Rossumcd16bf62007-06-13 18:07:49 +000063 x = 0Xffffffffffffffff
64 x = 0o77777777777777777
65 x = 0O77777777777777777
Guido van Rossume2a383d2007-01-15 16:59:06 +000066 x = 123456789012345678901234567890
Guido van Rossumcd16bf62007-06-13 18:07:49 +000067 x = 0b100000000000000000000000000000000000000000000000000000000000000000000
68 x = 0B111111111111111111111111111111111111111111111111111111111111111111111
Guido van Rossum3bead091992-01-27 17:00:37 +000069
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050070 def test_floats(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +000071 x = 3.14
72 x = 314.
73 x = 0.314
74 # XXX x = 000.314
75 x = .314
76 x = 3e14
77 x = 3E14
78 x = 3e-14
79 x = 3e+14
80 x = 3.e14
81 x = .3e14
82 x = 3.1e4
Guido van Rossum3bead091992-01-27 17:00:37 +000083
Benjamin Petersonc4161622014-06-07 12:36:39 -070084 def test_float_exponent_tokenization(self):
85 # See issue 21642.
86 self.assertEqual(1 if 1else 0, 1)
87 self.assertEqual(1 if 0else 0, 0)
88 self.assertRaises(SyntaxError, eval, "0 if 1Else 0")
89
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050090 def test_string_literals(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000091 x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y)
92 x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39)
93 x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34)
Thomas Wouters89f507f2006-12-13 04:49:30 +000094 x = "doesn't \"shrink\" does it"
95 y = 'doesn\'t "shrink" does it'
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000096 self.assertTrue(len(x) == 24 and x == y)
Thomas Wouters89f507f2006-12-13 04:49:30 +000097 x = "does \"shrink\" doesn't it"
98 y = 'does "shrink" doesn\'t it'
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000099 self.assertTrue(len(x) == 24 and x == y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000100 x = """
Guido van Rossumb6775db1994-08-01 11:34:53 +0000101The "quick"
102brown fox
103jumps over
104the 'lazy' dog.
105"""
Thomas Wouters89f507f2006-12-13 04:49:30 +0000106 y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000107 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000108 y = '''
Guido van Rossumb6775db1994-08-01 11:34:53 +0000109The "quick"
110brown fox
111jumps over
112the 'lazy' dog.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000113'''
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000114 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000115 y = "\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000116The \"quick\"\n\
117brown fox\n\
118jumps over\n\
119the 'lazy' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000120"
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000121 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000122 y = '\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000123The \"quick\"\n\
124brown fox\n\
125jumps over\n\
126the \'lazy\' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000127'
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000128 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000129
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500130 def test_ellipsis(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000131 x = ...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000132 self.assertTrue(x is Ellipsis)
Georg Brandldde00282007-03-18 19:01:53 +0000133 self.assertRaises(SyntaxError, eval, ".. .")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000134
Benjamin Peterson758888d2011-05-30 11:12:38 -0500135 def test_eof_error(self):
136 samples = ("def foo(", "\ndef foo(", "def foo(\n")
137 for s in samples:
138 with self.assertRaises(SyntaxError) as cm:
139 compile(s, "<test>", "exec")
140 self.assertIn("unexpected EOF", str(cm.exception))
141
Thomas Wouters89f507f2006-12-13 04:49:30 +0000142class GrammarTests(unittest.TestCase):
143
144 # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
145 # XXX can't test in a script -- this rule is only used when interactive
146
147 # file_input: (NEWLINE | stmt)* ENDMARKER
148 # Being tested as this very moment this very module
149
150 # expr_input: testlist NEWLINE
151 # XXX Hard to test -- used only in calls to input()
152
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500153 def test_eval_input(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000154 # testlist ENDMARKER
155 x = eval('1, 0 or 1')
156
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500157 def test_funcdef(self):
Neal Norwitzc1505362006-12-28 06:47:50 +0000158 ### [decorators] 'def' NAME parameters ['->' test] ':' suite
159 ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
160 ### decorators: decorator+
161 ### parameters: '(' [typedargslist] ')'
162 ### typedargslist: ((tfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000163 ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000164 ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000165 ### tfpdef: NAME [':' test]
Neal Norwitzc1505362006-12-28 06:47:50 +0000166 ### varargslist: ((vfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000167 ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000168 ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000169 ### vfpdef: NAME
Thomas Wouters89f507f2006-12-13 04:49:30 +0000170 def f1(): pass
171 f1()
172 f1(*())
173 f1(*(), **{})
174 def f2(one_argument): pass
175 def f3(two, arguments): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000176 self.assertEqual(f2.__code__.co_varnames, ('one_argument',))
177 self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments'))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000178 def a1(one_arg,): pass
179 def a2(two, args,): pass
180 def v0(*rest): pass
181 def v1(a, *rest): pass
182 def v2(a, b, *rest): pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000183
184 f1()
185 f2(1)
186 f2(1,)
187 f3(1, 2)
188 f3(1, 2,)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000189 v0()
190 v0(1)
191 v0(1,)
192 v0(1,2)
193 v0(1,2,3,4,5,6,7,8,9,0)
194 v1(1)
195 v1(1,)
196 v1(1,2)
197 v1(1,2,3)
198 v1(1,2,3,4,5,6,7,8,9,0)
199 v2(1,2)
200 v2(1,2,3)
201 v2(1,2,3,4)
202 v2(1,2,3,4,5,6,7,8,9,0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000203
Thomas Wouters89f507f2006-12-13 04:49:30 +0000204 def d01(a=1): pass
205 d01()
206 d01(1)
207 d01(*(1,))
Yury Selivanov14acf5f2015-08-05 17:54:10 -0400208 d01(*[] or [2])
209 d01(*() or (), *{} and (), **() or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000210 d01(**{'a':2})
Benjamin Petersonde12b792015-05-16 09:44:45 -0400211 d01(**{'a':2} or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000212 def d11(a, b=1): pass
213 d11(1)
214 d11(1, 2)
215 d11(1, **{'b':2})
216 def d21(a, b, c=1): pass
217 d21(1, 2)
218 d21(1, 2, 3)
219 d21(*(1, 2, 3))
220 d21(1, *(2, 3))
221 d21(1, 2, *(3,))
222 d21(1, 2, **{'c':3})
223 def d02(a=1, b=2): pass
224 d02()
225 d02(1)
226 d02(1, 2)
227 d02(*(1, 2))
228 d02(1, *(2,))
229 d02(1, **{'b':2})
230 d02(**{'a': 1, 'b': 2})
231 def d12(a, b=1, c=2): pass
232 d12(1)
233 d12(1, 2)
234 d12(1, 2, 3)
235 def d22(a, b, c=1, d=2): pass
236 d22(1, 2)
237 d22(1, 2, 3)
238 d22(1, 2, 3, 4)
239 def d01v(a=1, *rest): pass
240 d01v()
241 d01v(1)
242 d01v(1, 2)
243 d01v(*(1, 2, 3, 4))
244 d01v(*(1,))
245 d01v(**{'a':2})
246 def d11v(a, b=1, *rest): pass
247 d11v(1)
248 d11v(1, 2)
249 d11v(1, 2, 3)
250 def d21v(a, b, c=1, *rest): pass
251 d21v(1, 2)
252 d21v(1, 2, 3)
253 d21v(1, 2, 3, 4)
254 d21v(*(1, 2, 3, 4))
255 d21v(1, 2, **{'c': 3})
256 def d02v(a=1, b=2, *rest): pass
257 d02v()
258 d02v(1)
259 d02v(1, 2)
260 d02v(1, 2, 3)
261 d02v(1, *(2, 3, 4))
262 d02v(**{'a': 1, 'b': 2})
263 def d12v(a, b=1, c=2, *rest): pass
264 d12v(1)
265 d12v(1, 2)
266 d12v(1, 2, 3)
267 d12v(1, 2, 3, 4)
268 d12v(*(1, 2, 3, 4))
269 d12v(1, 2, *(3, 4, 5))
270 d12v(1, *(2,), **{'c': 3})
271 def d22v(a, b, c=1, d=2, *rest): pass
272 d22v(1, 2)
273 d22v(1, 2, 3)
274 d22v(1, 2, 3, 4)
275 d22v(1, 2, 3, 4, 5)
276 d22v(*(1, 2, 3, 4))
277 d22v(1, 2, *(3, 4, 5))
278 d22v(1, *(2, 3), **{'d': 4})
Georg Brandld8b690f2008-05-16 17:28:50 +0000279
280 # keyword argument type tests
281 try:
282 str('x', **{b'foo':1 })
283 except TypeError:
284 pass
285 else:
286 self.fail('Bytes should not work as keyword argument names')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000287 # keyword only argument tests
288 def pos0key1(*, key): return key
289 pos0key1(key=100)
290 def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
291 pos2key2(1, 2, k1=100)
292 pos2key2(1, 2, k1=100, k2=200)
293 pos2key2(1, 2, k2=100, k1=200)
294 def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
295 pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
296 pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
297
Robert Collinsdf395992015-08-12 08:00:06 +1200298 self.assertRaises(SyntaxError, eval, "def f(*): pass")
299 self.assertRaises(SyntaxError, eval, "def f(*,): pass")
300 self.assertRaises(SyntaxError, eval, "def f(*, **kwds): pass")
301
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000302 # keyword arguments after *arglist
303 def f(*args, **kwargs):
304 return args, kwargs
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000305 self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000306 {'x':2, 'y':5}))
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400307 self.assertEqual(f(1, *(2,3), 4), ((1, 2, 3, 4), {}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000308 self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400309 self.assertEqual(f(**{'eggs':'scrambled', 'spam':'fried'}),
310 ((), {'eggs':'scrambled', 'spam':'fried'}))
311 self.assertEqual(f(spam='fried', **{'eggs':'scrambled'}),
312 ((), {'eggs':'scrambled', 'spam':'fried'}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000313
Neal Norwitzc1505362006-12-28 06:47:50 +0000314 # argument annotation tests
315 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000316 self.assertEqual(f.__annotations__, {'return': list})
Zachary Warece17f762015-08-01 21:55:36 -0500317 def f(x: int): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000318 self.assertEqual(f.__annotations__, {'x': int})
Zachary Warece17f762015-08-01 21:55:36 -0500319 def f(*x: str): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000320 self.assertEqual(f.__annotations__, {'x': str})
Zachary Warece17f762015-08-01 21:55:36 -0500321 def f(**x: float): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000322 self.assertEqual(f.__annotations__, {'x': float})
Zachary Warece17f762015-08-01 21:55:36 -0500323 def f(x, y: 1+2): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000324 self.assertEqual(f.__annotations__, {'y': 3})
Zachary Warece17f762015-08-01 21:55:36 -0500325 def f(a, b: 1, c: 2, d): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000326 self.assertEqual(f.__annotations__, {'b': 1, 'c': 2})
Zachary Warece17f762015-08-01 21:55:36 -0500327 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000328 self.assertEqual(f.__annotations__,
Zachary Warece17f762015-08-01 21:55:36 -0500329 {'b': 1, 'c': 2, 'e': 3, 'g': 6})
330 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6, h: 7, i=8, j: 9 = 10,
331 **k: 11) -> 12: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000332 self.assertEqual(f.__annotations__,
Zachary Warece17f762015-08-01 21:55:36 -0500333 {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
334 'k': 11, 'return': 12})
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500335 # Check for issue #20625 -- annotations mangling
336 class Spam:
Zachary Warece17f762015-08-01 21:55:36 -0500337 def f(self, *, __kw: 1):
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500338 pass
339 class Ham(Spam): pass
Benjamin Petersonbcfcfc52014-03-09 20:59:24 -0500340 self.assertEqual(Spam.f.__annotations__, {'_Spam__kw': 1})
341 self.assertEqual(Ham.f.__annotations__, {'_Spam__kw': 1})
Nick Coghlan71011e22007-04-23 11:05:01 +0000342 # Check for SF Bug #1697248 - mixing decorators and a return annotation
343 def null(x): return x
344 @null
345 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000346 self.assertEqual(f.__annotations__, {'return': list})
Nick Coghlan71011e22007-04-23 11:05:01 +0000347
Guido van Rossum0240b922007-02-26 21:23:50 +0000348 # test MAKE_CLOSURE with a variety of oparg's
349 closure = 1
350 def f(): return closure
351 def f(x=1): return closure
352 def f(*, k=1): return closure
353 def f() -> int: return closure
Neal Norwitzc1505362006-12-28 06:47:50 +0000354
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000355 # Check ast errors in *args and *kwargs
356 check_syntax_error(self, "f(*g(1=2))")
357 check_syntax_error(self, "f(**g(1=2))")
358
Robert Collinsdf395992015-08-12 08:00:06 +1200359 # Check trailing commas are permitted in funcdef argument list
360 def f(a,): pass
361 def f(*args,): pass
362 def f(**kwds,): pass
363 def f(a, *args,): pass
364 def f(a, **kwds,): pass
365 def f(*args, b,): pass
366 def f(*, b,): pass
367 def f(*args, **kwds,): pass
368 def f(a, *args, b,): pass
369 def f(a, *, b,): pass
370 def f(a, *args, **kwds,): pass
371 def f(*args, b, **kwds,): pass
372 def f(*, b, **kwds,): pass
373 def f(a, *args, b, **kwds,): pass
374 def f(a, *, b, **kwds,): pass
375
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500376 def test_lambdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000377 ### lambdef: 'lambda' [varargslist] ':' test
378 l1 = lambda : 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000379 self.assertEqual(l1(), 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000380 l2 = lambda : a[d] # XXX just testing the expression
Guido van Rossume2a383d2007-01-15 16:59:06 +0000381 l3 = lambda : [2 < x for x in [-1, 3, 0]]
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000382 self.assertEqual(l3(), [0, 1, 0])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000383 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000384 self.assertEqual(l4(), 1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000385 l5 = lambda x, y, z=2: x + y + z
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000386 self.assertEqual(l5(1, 2), 5)
387 self.assertEqual(l5(1, 2, 3), 6)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000388 check_syntax_error(self, "lambda x: x = 2")
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000389 check_syntax_error(self, "lambda (None,): None")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000390 l6 = lambda x, y, *, k=20: x+y+k
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000391 self.assertEqual(l6(1,2), 1+2+20)
392 self.assertEqual(l6(1,2,k=10), 1+2+10)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000393
Robert Collinsdf395992015-08-12 08:00:06 +1200394 # check that trailing commas are permitted
395 l10 = lambda a,: 0
396 l11 = lambda *args,: 0
397 l12 = lambda **kwds,: 0
398 l13 = lambda a, *args,: 0
399 l14 = lambda a, **kwds,: 0
400 l15 = lambda *args, b,: 0
401 l16 = lambda *, b,: 0
402 l17 = lambda *args, **kwds,: 0
403 l18 = lambda a, *args, b,: 0
404 l19 = lambda a, *, b,: 0
405 l20 = lambda a, *args, **kwds,: 0
406 l21 = lambda *args, b, **kwds,: 0
407 l22 = lambda *, b, **kwds,: 0
408 l23 = lambda a, *args, b, **kwds,: 0
409 l24 = lambda a, *, b, **kwds,: 0
410
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000411
Thomas Wouters89f507f2006-12-13 04:49:30 +0000412 ### stmt: simple_stmt | compound_stmt
413 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000414
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500415 def test_simple_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000416 ### simple_stmt: small_stmt (';' small_stmt)* [';']
417 x = 1; pass; del x
418 def foo():
Ezio Melotti13925002011-03-16 11:05:33 +0200419 # verify statements that end with semi-colons
Thomas Wouters89f507f2006-12-13 04:49:30 +0000420 x = 1; pass; del x;
421 foo()
Georg Brandl52318d62006-09-06 07:06:08 +0000422
Guido van Rossumd8faa362007-04-27 19:54:29 +0000423 ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
Thomas Wouters89f507f2006-12-13 04:49:30 +0000424 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000425
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500426 def test_expr_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000427 # (exprlist '=')* exprlist
Victor Stinner15a30952016-02-08 22:45:06 +0100428 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000429 1, 2, 3
430 x = 1
431 x = 1, 2, 3
432 x = y = z = 1, 2, 3
433 x, y, z = 1, 2, 3
434 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000435
Thomas Wouters89f507f2006-12-13 04:49:30 +0000436 check_syntax_error(self, "x + 1 = 1")
437 check_syntax_error(self, "a + 1 = b + 2")
Guido van Rossum3bead091992-01-27 17:00:37 +0000438
Nick Coghlan5b1fdc12014-06-16 19:48:02 +1000439 # Check the heuristic for print & exec covers significant cases
440 # As well as placing some limits on false positives
441 def test_former_statements_refer_to_builtins(self):
442 keywords = "print", "exec"
443 # Cases where we want the custom error
444 cases = [
445 "{} foo",
446 "{} {{1:foo}}",
447 "if 1: {} foo",
448 "if 1: {} {{1:foo}}",
449 "if 1:\n {} foo",
450 "if 1:\n {} {{1:foo}}",
451 ]
452 for keyword in keywords:
453 custom_msg = "call to '{}'".format(keyword)
454 for case in cases:
455 source = case.format(keyword)
456 with self.subTest(source=source):
457 with self.assertRaisesRegex(SyntaxError, custom_msg):
458 exec(source)
459 source = source.replace("foo", "(foo.)")
460 with self.subTest(source=source):
461 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
462 exec(source)
463
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500464 def test_del_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000465 # 'del' exprlist
466 abc = [1,2,3]
467 x, y, z = abc
468 xyz = x, y, z
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000469
Thomas Wouters89f507f2006-12-13 04:49:30 +0000470 del abc
471 del x, y, (z, xyz)
Barry Warsaw9182b452000-08-29 04:57:10 +0000472
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500473 def test_pass_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000474 # 'pass'
475 pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000476
Thomas Wouters89f507f2006-12-13 04:49:30 +0000477 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
478 # Tested below
Barry Warsaw9182b452000-08-29 04:57:10 +0000479
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500480 def test_break_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000481 # 'break'
482 while 1: break
Barry Warsaw9182b452000-08-29 04:57:10 +0000483
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500484 def test_continue_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000485 # 'continue'
486 i = 1
487 while i: i = 0; continue
Barry Warsaw9182b452000-08-29 04:57:10 +0000488
Thomas Wouters89f507f2006-12-13 04:49:30 +0000489 msg = ""
490 while not msg:
491 msg = "ok"
492 try:
493 continue
494 msg = "continue failed to continue inside try"
495 except:
496 msg = "continue inside try called except block"
497 if msg != "ok":
498 self.fail(msg)
Barry Warsawefc92ee2000-08-21 15:46:50 +0000499
Thomas Wouters89f507f2006-12-13 04:49:30 +0000500 msg = ""
501 while not msg:
502 msg = "finally block not called"
503 try:
504 continue
505 finally:
506 msg = "ok"
507 if msg != "ok":
508 self.fail(msg)
Guido van Rossum3bead091992-01-27 17:00:37 +0000509
Thomas Wouters89f507f2006-12-13 04:49:30 +0000510 def test_break_continue_loop(self):
511 # This test warrants an explanation. It is a test specifically for SF bugs
512 # #463359 and #462937. The bug is that a 'break' statement executed or
513 # exception raised inside a try/except inside a loop, *after* a continue
514 # statement has been executed in that loop, will cause the wrong number of
515 # arguments to be popped off the stack and the instruction pointer reset to
516 # a very small number (usually 0.) Because of this, the following test
517 # *must* written as a function, and the tracking vars *must* be function
518 # arguments with default values. Otherwise, the test will loop and loop.
Guido van Rossum3bead091992-01-27 17:00:37 +0000519
Thomas Wouters89f507f2006-12-13 04:49:30 +0000520 def test_inner(extra_burning_oil = 1, count=0):
521 big_hippo = 2
522 while big_hippo:
523 count += 1
524 try:
525 if extra_burning_oil and big_hippo == 1:
526 extra_burning_oil -= 1
527 break
528 big_hippo -= 1
529 continue
530 except:
531 raise
532 if count > 2 or big_hippo != 1:
533 self.fail("continue then break in try/except in loop broken!")
534 test_inner()
Guido van Rossum3bead091992-01-27 17:00:37 +0000535
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500536 def test_return(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000537 # 'return' [testlist]
538 def g1(): return
539 def g2(): return 1
540 g1()
541 x = g2()
542 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000543
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500544 def test_yield(self):
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000545 # Allowed as standalone statement
546 def g(): yield 1
547 def g(): yield from ()
548 # Allowed as RHS of assignment
549 def g(): x = yield 1
550 def g(): x = yield from ()
551 # Ordinary yield accepts implicit tuples
552 def g(): yield 1, 1
553 def g(): x = yield 1, 1
554 # 'yield from' does not
555 check_syntax_error(self, "def g(): yield from (), 1")
556 check_syntax_error(self, "def g(): x = yield from (), 1")
557 # Requires parentheses as subexpression
558 def g(): 1, (yield 1)
559 def g(): 1, (yield from ())
560 check_syntax_error(self, "def g(): 1, yield 1")
561 check_syntax_error(self, "def g(): 1, yield from ()")
562 # Requires parentheses as call argument
563 def g(): f((yield 1))
564 def g(): f((yield 1), 1)
565 def g(): f((yield from ()))
566 def g(): f((yield from ()), 1)
567 check_syntax_error(self, "def g(): f(yield 1)")
568 check_syntax_error(self, "def g(): f(yield 1, 1)")
569 check_syntax_error(self, "def g(): f(yield from ())")
570 check_syntax_error(self, "def g(): f(yield from (), 1)")
571 # Not allowed at top level
572 check_syntax_error(self, "yield")
573 check_syntax_error(self, "yield from")
574 # Not allowed at class scope
Thomas Wouters89f507f2006-12-13 04:49:30 +0000575 check_syntax_error(self, "class foo:yield 1")
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000576 check_syntax_error(self, "class foo:yield from ()")
Yury Selivanovf315c1c2015-07-23 09:10:44 +0300577 # Check annotation refleak on SyntaxError
578 check_syntax_error(self, "def g(a:(yield)): pass")
Guido van Rossum3bead091992-01-27 17:00:37 +0000579
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500580 def test_raise(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000581 # 'raise' test [',' test]
Collin Winter828f04a2007-08-31 00:04:24 +0000582 try: raise RuntimeError('just testing')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000583 except RuntimeError: pass
584 try: raise KeyboardInterrupt
585 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000586
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500587 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000588 # 'import' dotted_as_names
589 import sys
590 import time, sys
591 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
592 from time import time
593 from time import (time)
594 # not testable inside a function, but already done at top of the module
595 # from sys import *
596 from sys import path, argv
597 from sys import (path, argv)
598 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +0000599
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500600 def test_global(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000601 # 'global' NAME (',' NAME)*
602 global a
603 global a, b
604 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +0000605
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500606 def test_nonlocal(self):
Benjamin Petersona933e522008-10-24 22:16:39 +0000607 # 'nonlocal' NAME (',' NAME)*
608 x = 0
609 y = 0
610 def f():
611 nonlocal x
612 nonlocal x, y
613
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500614 def test_assert(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000615 # assertTruestmt: 'assert' test [',' test]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000616 assert 1
617 assert 1, 1
618 assert lambda x:x
619 assert 1, lambda x:x+1
Ezio Melotti6cc5bf72011-12-02 18:22:52 +0200620
621 try:
622 assert True
623 except AssertionError as e:
624 self.fail("'assert True' should not have raised an AssertionError")
625
626 try:
627 assert True, 'this should always pass'
628 except AssertionError as e:
629 self.fail("'assert True, msg' should not have "
630 "raised an AssertionError")
631
632 # these tests fail if python is run with -O, so check __debug__
633 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
634 def testAssert2(self):
Thomas Wouters80d373c2001-09-26 12:43:39 +0000635 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000636 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +0000637 except AssertionError as e:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000638 self.assertEqual(e.args[0], "msg")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000639 else:
Ezio Melotti6cc5bf72011-12-02 18:22:52 +0200640 self.fail("AssertionError not raised by assert 0")
641
642 try:
643 assert False
644 except AssertionError as e:
645 self.assertEqual(len(e.args), 0)
646 else:
647 self.fail("AssertionError not raised by 'assert False'")
648
Thomas Wouters80d373c2001-09-26 12:43:39 +0000649
Thomas Wouters89f507f2006-12-13 04:49:30 +0000650 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
651 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000652
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500653 def test_if(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000654 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
655 if 1: pass
656 if 1: pass
657 else: pass
658 if 0: pass
659 elif 0: pass
660 if 0: pass
661 elif 0: pass
662 elif 0: pass
663 elif 0: pass
664 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000665
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500666 def test_while(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000667 # 'while' test ':' suite ['else' ':' suite]
668 while 0: pass
669 while 0: pass
670 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000671
Christian Heimes969fe572008-01-25 11:23:10 +0000672 # Issue1920: "while 0" is optimized away,
673 # ensure that the "else" clause is still present.
674 x = 0
675 while 0:
676 x = 1
677 else:
678 x = 2
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000679 self.assertEqual(x, 2)
Christian Heimes969fe572008-01-25 11:23:10 +0000680
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500681 def test_for(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000682 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
683 for i in 1, 2, 3: pass
684 for i, j, k in (): pass
685 else: pass
686 class Squares:
687 def __init__(self, max):
688 self.max = max
689 self.sofar = []
690 def __len__(self): return len(self.sofar)
691 def __getitem__(self, i):
692 if not 0 <= i < self.max: raise IndexError
693 n = len(self.sofar)
694 while n <= i:
695 self.sofar.append(n*n)
696 n = n+1
697 return self.sofar[i]
698 n = 0
699 for x in Squares(10): n = n+x
700 if n != 285:
701 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000702
Thomas Wouters89f507f2006-12-13 04:49:30 +0000703 result = []
704 for x, in [(1,), (2,), (3,)]:
705 result.append(x)
706 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000707
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500708 def test_try(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000709 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
710 ### | 'try' ':' suite 'finally' ':' suite
Guido van Rossumb940e112007-01-10 16:19:56 +0000711 ### except_clause: 'except' [expr ['as' expr]]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000712 try:
713 1/0
714 except ZeroDivisionError:
715 pass
716 else:
717 pass
718 try: 1/0
719 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000720 except TypeError as msg: pass
721 except RuntimeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000722 except: pass
723 else: pass
724 try: 1/0
725 except (EOFError, TypeError, ZeroDivisionError): pass
726 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000727 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000728 try: pass
729 finally: pass
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000730
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500731 def test_suite(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000732 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
733 if 1: pass
734 if 1:
735 pass
736 if 1:
737 #
738 #
739 #
740 pass
741 pass
742 #
743 pass
744 #
Guido van Rossum3bead091992-01-27 17:00:37 +0000745
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500746 def test_test(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000747 ### and_test ('or' and_test)*
748 ### and_test: not_test ('and' not_test)*
749 ### not_test: 'not' not_test | comparison
750 if not 1: pass
751 if 1 and 1: pass
752 if 1 or 1: pass
753 if not not not 1: pass
754 if not 1 and 1 and 1: pass
755 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000756
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500757 def test_comparison(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000758 ### comparison: expr (comp_op expr)*
759 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
760 if 1: pass
761 x = (1 == 1)
762 if 1 == 1: pass
763 if 1 != 1: pass
764 if 1 < 1: pass
765 if 1 > 1: pass
766 if 1 <= 1: pass
767 if 1 >= 1: pass
768 if 1 is 1: pass
769 if 1 is not 1: pass
770 if 1 in (): pass
771 if 1 not in (): pass
772 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 +0000773
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500774 def test_binary_mask_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000775 x = 1 & 1
776 x = 1 ^ 1
777 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000778
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500779 def test_shift_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000780 x = 1 << 1
781 x = 1 >> 1
782 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000783
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500784 def test_additive_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000785 x = 1
786 x = 1 + 1
787 x = 1 - 1 - 1
788 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000789
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500790 def test_multiplicative_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000791 x = 1 * 1
792 x = 1 / 1
793 x = 1 % 1
794 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000795
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500796 def test_unary_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000797 x = +1
798 x = -1
799 x = ~1
800 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
801 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +0000802
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500803 def test_selectors(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000804 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
805 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +0000806
Thomas Wouters89f507f2006-12-13 04:49:30 +0000807 import sys, time
808 c = sys.path[0]
809 x = time.time()
810 x = sys.modules['time'].time()
811 a = '01234'
812 c = a[0]
813 c = a[-1]
814 s = a[0:5]
815 s = a[:5]
816 s = a[0:]
817 s = a[:]
818 s = a[-5:]
819 s = a[:-1]
820 s = a[-4:-3]
821 # A rough test of SF bug 1333982. http://python.org/sf/1333982
822 # The testing here is fairly incomplete.
823 # Test cases should include: commas with 1 and 2 colons
824 d = {}
825 d[1] = 1
826 d[1,] = 2
827 d[1,2] = 3
828 d[1,2,3] = 4
829 L = list(d)
830 L.sort(key=lambda x: x if isinstance(x, tuple) else ())
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000831 self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +0000832
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500833 def test_atoms(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000834 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
835 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +0000836
Thomas Wouters89f507f2006-12-13 04:49:30 +0000837 x = (1)
838 x = (1 or 2 or 3)
839 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +0000840
Thomas Wouters89f507f2006-12-13 04:49:30 +0000841 x = []
842 x = [1]
843 x = [1 or 2 or 3]
844 x = [1 or 2 or 3, 2, 3]
845 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +0000846
Thomas Wouters89f507f2006-12-13 04:49:30 +0000847 x = {}
848 x = {'one': 1}
849 x = {'one': 1,}
850 x = {'one' or 'two': 1 or 2}
851 x = {'one': 1, 'two': 2}
852 x = {'one': 1, 'two': 2,}
853 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +0000854
Thomas Wouters89f507f2006-12-13 04:49:30 +0000855 x = {'one'}
856 x = {'one', 1,}
857 x = {'one', 'two', 'three'}
858 x = {2, 3, 4,}
859
860 x = x
861 x = 'x'
862 x = 123
863
864 ### exprlist: expr (',' expr)* [',']
865 ### testlist: test (',' test)* [',']
866 # These have been exercised enough above
867
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500868 def test_classdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000869 # 'class' NAME ['(' [testlist] ')'] ':' suite
870 class B: pass
871 class B2(): pass
872 class C1(B): pass
873 class C2(B): pass
874 class D(C1, C2, B): pass
875 class C:
876 def meth1(self): pass
877 def meth2(self, arg): pass
878 def meth3(self, a1, a2): pass
879
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000880 # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
881 # decorators: decorator+
882 # decorated: decorators (classdef | funcdef)
883 def class_decorator(x): return x
884 @class_decorator
885 class G: pass
886
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500887 def test_dictcomps(self):
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000888 # dictorsetmaker: ( (test ':' test (comp_for |
889 # (',' test ':' test)* [','])) |
890 # (test (comp_for | (',' test)* [','])) )
891 nums = [1, 2, 3]
892 self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
893
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500894 def test_listcomps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000895 # list comprehension tests
896 nums = [1, 2, 3, 4, 5]
897 strs = ["Apple", "Banana", "Coconut"]
898 spcs = [" Apple", " Banana ", "Coco nut "]
899
900 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
901 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
902 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
903 self.assertEqual([(i, s) for i in nums for s in strs],
904 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
905 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
906 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
907 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
908 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
909 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
910 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
911 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
912 (5, 'Banana'), (5, 'Coconut')])
913 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
914 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
915
916 def test_in_func(l):
917 return [0 < x < 3 for x in l if x > 2]
918
919 self.assertEqual(test_in_func(nums), [False, False, False])
920
921 def test_nested_front():
922 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
923 [[1, 2], [3, 4], [5, 6]])
924
925 test_nested_front()
926
927 check_syntax_error(self, "[i, s for i in nums for s in strs]")
928 check_syntax_error(self, "[x if y]")
929
930 suppliers = [
931 (1, "Boeing"),
932 (2, "Ford"),
933 (3, "Macdonalds")
934 ]
935
936 parts = [
937 (10, "Airliner"),
938 (20, "Engine"),
939 (30, "Cheeseburger")
940 ]
941
942 suppart = [
943 (1, 10), (1, 20), (2, 20), (3, 30)
944 ]
945
946 x = [
947 (sname, pname)
948 for (sno, sname) in suppliers
949 for (pno, pname) in parts
950 for (sp_sno, sp_pno) in suppart
951 if sno == sp_sno and pno == sp_pno
952 ]
953
954 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
955 ('Macdonalds', 'Cheeseburger')])
956
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500957 def test_genexps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000958 # generator expression tests
959 g = ([x for x in range(10)] for x in range(1))
Georg Brandla18af4e2007-04-21 15:47:16 +0000960 self.assertEqual(next(g), [x for x in range(10)])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000961 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000962 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000963 self.fail('should produce StopIteration exception')
964 except StopIteration:
965 pass
966
967 a = 1
968 try:
969 g = (a for d in a)
Georg Brandla18af4e2007-04-21 15:47:16 +0000970 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000971 self.fail('should produce TypeError')
972 except TypeError:
973 pass
974
975 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
976 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
977
978 a = [x for x in range(10)]
979 b = (x for x in (y for y in a))
980 self.assertEqual(sum(b), sum([x for x in range(10)]))
981
982 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
983 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
984 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
985 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
986 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
987 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)]))
988 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
989 check_syntax_error(self, "foo(x for x in range(10), 100)")
990 check_syntax_error(self, "foo(100, x for x in range(10))")
991
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500992 def test_comprehension_specials(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000993 # test for outmost iterable precomputation
994 x = 10; g = (i for i in range(x)); x = 5
995 self.assertEqual(len(list(g)), 10)
996
997 # This should hold, since we're only precomputing outmost iterable.
998 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
999 x = 5; t = True;
1000 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
1001
1002 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
1003 # even though it's silly. Make sure it works (ifelse broke this.)
1004 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
1005 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
1006
1007 # verify unpacking single element tuples in listcomp/genexp.
1008 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
1009 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
1010
Benjamin Petersonf17ab892009-05-29 21:55:57 +00001011 def test_with_statement(self):
1012 class manager(object):
1013 def __enter__(self):
1014 return (1, 2)
1015 def __exit__(self, *args):
1016 pass
1017
1018 with manager():
1019 pass
1020 with manager() as x:
1021 pass
1022 with manager() as (x, y):
1023 pass
1024 with manager(), manager():
1025 pass
1026 with manager() as x, manager() as y:
1027 pass
1028 with manager() as x, manager():
1029 pass
1030
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001031 def test_if_else_expr(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001032 # Test ifelse expressions in various cases
1033 def _checkeval(msg, ret):
1034 "helper to check that evaluation of expressions is done correctly"
Victor Stinnerc6ec54d2016-04-12 18:33:41 +02001035 print(msg)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001036 return ret
1037
Nick Coghlan650f0d02007-04-15 12:05:43 +00001038 # the next line is not allowed anymore
1039 #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001040 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
1041 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])
1042 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
1043 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
1044 self.assertEqual((5 and 6 if 0 else 1), 1)
1045 self.assertEqual(((5 and 6) if 0 else 1), 1)
1046 self.assertEqual((5 and (6 if 1 else 1)), 6)
1047 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
1048 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
1049 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
1050 self.assertEqual((not 5 if 1 else 1), False)
1051 self.assertEqual((not 5 if 0 else 1), 1)
1052 self.assertEqual((6 + 1 if 1 else 2), 7)
1053 self.assertEqual((6 - 1 if 1 else 2), 5)
1054 self.assertEqual((6 * 2 if 1 else 4), 12)
1055 self.assertEqual((6 / 2 if 1 else 3), 3)
1056 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +00001057
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001058 def test_paren_evaluation(self):
1059 self.assertEqual(16 // (4 // 2), 8)
1060 self.assertEqual((16 // 4) // 2, 2)
1061 self.assertEqual(16 // 4 // 2, 2)
1062 self.assertTrue(False is (2 is 3))
1063 self.assertFalse((False is 2) is 3)
1064 self.assertFalse(False is 2 is 3)
1065
Benjamin Petersond51374e2014-04-09 23:55:56 -04001066 def test_matrix_mul(self):
1067 # This is not intended to be a comprehensive test, rather just to be few
1068 # samples of the @ operator in test_grammar.py.
1069 class M:
1070 def __matmul__(self, o):
1071 return 4
1072 def __imatmul__(self, o):
1073 self.other = o
1074 return self
1075 m = M()
1076 self.assertEqual(m @ m, 4)
1077 m @= 42
1078 self.assertEqual(m.other, 42)
1079
Yury Selivanov75445082015-05-11 22:57:16 -04001080 def test_async_await(self):
1081 async = 1
1082 await = 2
1083 self.assertEqual(async, 1)
1084
1085 def async():
1086 nonlocal await
1087 await = 10
1088 async()
1089 self.assertEqual(await, 10)
1090
1091 self.assertFalse(bool(async.__code__.co_flags & inspect.CO_COROUTINE))
1092
1093 async def test():
1094 def sum():
Yury Selivanov8fb307c2015-07-22 13:33:45 +03001095 pass
Yury Selivanov75445082015-05-11 22:57:16 -04001096 if 1:
1097 await someobj()
1098
1099 self.assertEqual(test.__name__, 'test')
1100 self.assertTrue(bool(test.__code__.co_flags & inspect.CO_COROUTINE))
1101
1102 def decorator(func):
1103 setattr(func, '_marked', True)
1104 return func
1105
1106 @decorator
1107 async def test2():
1108 return 22
1109 self.assertTrue(test2._marked)
1110 self.assertEqual(test2.__name__, 'test2')
1111 self.assertTrue(bool(test2.__code__.co_flags & inspect.CO_COROUTINE))
1112
1113 def test_async_for(self):
1114 class Done(Exception): pass
1115
1116 class AIter:
1117 async def __aiter__(self):
1118 return self
1119 async def __anext__(self):
1120 raise StopAsyncIteration
1121
1122 async def foo():
1123 async for i in AIter():
1124 pass
1125 async for i, j in AIter():
1126 pass
1127 async for i in AIter():
1128 pass
1129 else:
1130 pass
1131 raise Done
1132
1133 with self.assertRaises(Done):
1134 foo().send(None)
1135
1136 def test_async_with(self):
1137 class Done(Exception): pass
1138
1139 class manager:
1140 async def __aenter__(self):
1141 return (1, 2)
1142 async def __aexit__(self, *exc):
1143 return False
1144
1145 async def foo():
1146 async with manager():
1147 pass
1148 async with manager() as x:
1149 pass
1150 async with manager() as (x, y):
1151 pass
1152 async with manager(), manager():
1153 pass
1154 async with manager() as x, manager() as y:
1155 pass
1156 async with manager() as x, manager():
1157 pass
1158 raise Done
1159
1160 with self.assertRaises(Done):
1161 foo().send(None)
1162
Guido van Rossum3bead091992-01-27 17:00:37 +00001163
Thomas Wouters89f507f2006-12-13 04:49:30 +00001164if __name__ == '__main__':
Zachary Ware38c707e2015-04-13 15:00:43 -05001165 unittest.main()