blob: 154e3b608cb49c9b626ca7f6e855e2bb965a6b61 [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
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000298 # keyword arguments after *arglist
299 def f(*args, **kwargs):
300 return args, kwargs
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000301 self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000302 {'x':2, 'y':5}))
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400303 self.assertEqual(f(1, *(2,3), 4), ((1, 2, 3, 4), {}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000304 self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400305 self.assertEqual(f(**{'eggs':'scrambled', 'spam':'fried'}),
306 ((), {'eggs':'scrambled', 'spam':'fried'}))
307 self.assertEqual(f(spam='fried', **{'eggs':'scrambled'}),
308 ((), {'eggs':'scrambled', 'spam':'fried'}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000309
Neal Norwitzc1505362006-12-28 06:47:50 +0000310 # argument annotation tests
311 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000312 self.assertEqual(f.__annotations__, {'return': list})
Zachary Warece17f762015-08-01 21:55:36 -0500313 def f(x: int): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000314 self.assertEqual(f.__annotations__, {'x': int})
Zachary Warece17f762015-08-01 21:55:36 -0500315 def f(*x: str): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000316 self.assertEqual(f.__annotations__, {'x': str})
Zachary Warece17f762015-08-01 21:55:36 -0500317 def f(**x: float): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000318 self.assertEqual(f.__annotations__, {'x': float})
Zachary Warece17f762015-08-01 21:55:36 -0500319 def f(x, y: 1+2): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000320 self.assertEqual(f.__annotations__, {'y': 3})
Zachary Warece17f762015-08-01 21:55:36 -0500321 def f(a, b: 1, c: 2, d): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000322 self.assertEqual(f.__annotations__, {'b': 1, 'c': 2})
Zachary Warece17f762015-08-01 21:55:36 -0500323 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000324 self.assertEqual(f.__annotations__,
Zachary Warece17f762015-08-01 21:55:36 -0500325 {'b': 1, 'c': 2, 'e': 3, 'g': 6})
326 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6, h: 7, i=8, j: 9 = 10,
327 **k: 11) -> 12: 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, 'h': 7, 'j': 9,
330 'k': 11, 'return': 12})
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500331 # Check for issue #20625 -- annotations mangling
332 class Spam:
Zachary Warece17f762015-08-01 21:55:36 -0500333 def f(self, *, __kw: 1):
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500334 pass
335 class Ham(Spam): pass
Benjamin Petersonbcfcfc52014-03-09 20:59:24 -0500336 self.assertEqual(Spam.f.__annotations__, {'_Spam__kw': 1})
337 self.assertEqual(Ham.f.__annotations__, {'_Spam__kw': 1})
Nick Coghlan71011e22007-04-23 11:05:01 +0000338 # Check for SF Bug #1697248 - mixing decorators and a return annotation
339 def null(x): return x
340 @null
341 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000342 self.assertEqual(f.__annotations__, {'return': list})
Nick Coghlan71011e22007-04-23 11:05:01 +0000343
Guido van Rossum0240b922007-02-26 21:23:50 +0000344 # test MAKE_CLOSURE with a variety of oparg's
345 closure = 1
346 def f(): return closure
347 def f(x=1): return closure
348 def f(*, k=1): return closure
349 def f() -> int: return closure
Neal Norwitzc1505362006-12-28 06:47:50 +0000350
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000351 # Check ast errors in *args and *kwargs
352 check_syntax_error(self, "f(*g(1=2))")
353 check_syntax_error(self, "f(**g(1=2))")
354
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500355 def test_lambdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000356 ### lambdef: 'lambda' [varargslist] ':' test
357 l1 = lambda : 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000358 self.assertEqual(l1(), 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000359 l2 = lambda : a[d] # XXX just testing the expression
Guido van Rossume2a383d2007-01-15 16:59:06 +0000360 l3 = lambda : [2 < x for x in [-1, 3, 0]]
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000361 self.assertEqual(l3(), [0, 1, 0])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000362 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000363 self.assertEqual(l4(), 1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000364 l5 = lambda x, y, z=2: x + y + z
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000365 self.assertEqual(l5(1, 2), 5)
366 self.assertEqual(l5(1, 2, 3), 6)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000367 check_syntax_error(self, "lambda x: x = 2")
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000368 check_syntax_error(self, "lambda (None,): None")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000369 l6 = lambda x, y, *, k=20: x+y+k
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000370 self.assertEqual(l6(1,2), 1+2+20)
371 self.assertEqual(l6(1,2,k=10), 1+2+10)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000372
373
Thomas Wouters89f507f2006-12-13 04:49:30 +0000374 ### stmt: simple_stmt | compound_stmt
375 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000376
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500377 def test_simple_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000378 ### simple_stmt: small_stmt (';' small_stmt)* [';']
379 x = 1; pass; del x
380 def foo():
Ezio Melotti13925002011-03-16 11:05:33 +0200381 # verify statements that end with semi-colons
Thomas Wouters89f507f2006-12-13 04:49:30 +0000382 x = 1; pass; del x;
383 foo()
Georg Brandl52318d62006-09-06 07:06:08 +0000384
Guido van Rossumd8faa362007-04-27 19:54:29 +0000385 ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
Thomas Wouters89f507f2006-12-13 04:49:30 +0000386 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000387
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500388 def test_expr_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000389 # (exprlist '=')* exprlist
390 1
391 1, 2, 3
392 x = 1
393 x = 1, 2, 3
394 x = y = z = 1, 2, 3
395 x, y, z = 1, 2, 3
396 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000397
Thomas Wouters89f507f2006-12-13 04:49:30 +0000398 check_syntax_error(self, "x + 1 = 1")
399 check_syntax_error(self, "a + 1 = b + 2")
Guido van Rossum3bead091992-01-27 17:00:37 +0000400
Nick Coghlan5b1fdc12014-06-16 19:48:02 +1000401 # Check the heuristic for print & exec covers significant cases
402 # As well as placing some limits on false positives
403 def test_former_statements_refer_to_builtins(self):
404 keywords = "print", "exec"
405 # Cases where we want the custom error
406 cases = [
407 "{} foo",
408 "{} {{1:foo}}",
409 "if 1: {} foo",
410 "if 1: {} {{1:foo}}",
411 "if 1:\n {} foo",
412 "if 1:\n {} {{1:foo}}",
413 ]
414 for keyword in keywords:
415 custom_msg = "call to '{}'".format(keyword)
416 for case in cases:
417 source = case.format(keyword)
418 with self.subTest(source=source):
419 with self.assertRaisesRegex(SyntaxError, custom_msg):
420 exec(source)
421 source = source.replace("foo", "(foo.)")
422 with self.subTest(source=source):
423 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
424 exec(source)
425
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500426 def test_del_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000427 # 'del' exprlist
428 abc = [1,2,3]
429 x, y, z = abc
430 xyz = x, y, z
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000431
Thomas Wouters89f507f2006-12-13 04:49:30 +0000432 del abc
433 del x, y, (z, xyz)
Barry Warsaw9182b452000-08-29 04:57:10 +0000434
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500435 def test_pass_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000436 # 'pass'
437 pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000438
Thomas Wouters89f507f2006-12-13 04:49:30 +0000439 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
440 # Tested below
Barry Warsaw9182b452000-08-29 04:57:10 +0000441
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500442 def test_break_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000443 # 'break'
444 while 1: break
Barry Warsaw9182b452000-08-29 04:57:10 +0000445
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500446 def test_continue_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000447 # 'continue'
448 i = 1
449 while i: i = 0; continue
Barry Warsaw9182b452000-08-29 04:57:10 +0000450
Thomas Wouters89f507f2006-12-13 04:49:30 +0000451 msg = ""
452 while not msg:
453 msg = "ok"
454 try:
455 continue
456 msg = "continue failed to continue inside try"
457 except:
458 msg = "continue inside try called except block"
459 if msg != "ok":
460 self.fail(msg)
Barry Warsawefc92ee2000-08-21 15:46:50 +0000461
Thomas Wouters89f507f2006-12-13 04:49:30 +0000462 msg = ""
463 while not msg:
464 msg = "finally block not called"
465 try:
466 continue
467 finally:
468 msg = "ok"
469 if msg != "ok":
470 self.fail(msg)
Guido van Rossum3bead091992-01-27 17:00:37 +0000471
Thomas Wouters89f507f2006-12-13 04:49:30 +0000472 def test_break_continue_loop(self):
473 # This test warrants an explanation. It is a test specifically for SF bugs
474 # #463359 and #462937. The bug is that a 'break' statement executed or
475 # exception raised inside a try/except inside a loop, *after* a continue
476 # statement has been executed in that loop, will cause the wrong number of
477 # arguments to be popped off the stack and the instruction pointer reset to
478 # a very small number (usually 0.) Because of this, the following test
479 # *must* written as a function, and the tracking vars *must* be function
480 # arguments with default values. Otherwise, the test will loop and loop.
Guido van Rossum3bead091992-01-27 17:00:37 +0000481
Thomas Wouters89f507f2006-12-13 04:49:30 +0000482 def test_inner(extra_burning_oil = 1, count=0):
483 big_hippo = 2
484 while big_hippo:
485 count += 1
486 try:
487 if extra_burning_oil and big_hippo == 1:
488 extra_burning_oil -= 1
489 break
490 big_hippo -= 1
491 continue
492 except:
493 raise
494 if count > 2 or big_hippo != 1:
495 self.fail("continue then break in try/except in loop broken!")
496 test_inner()
Guido van Rossum3bead091992-01-27 17:00:37 +0000497
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500498 def test_return(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000499 # 'return' [testlist]
500 def g1(): return
501 def g2(): return 1
502 g1()
503 x = g2()
504 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000505
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500506 def test_yield(self):
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000507 # Allowed as standalone statement
508 def g(): yield 1
509 def g(): yield from ()
510 # Allowed as RHS of assignment
511 def g(): x = yield 1
512 def g(): x = yield from ()
513 # Ordinary yield accepts implicit tuples
514 def g(): yield 1, 1
515 def g(): x = yield 1, 1
516 # 'yield from' does not
517 check_syntax_error(self, "def g(): yield from (), 1")
518 check_syntax_error(self, "def g(): x = yield from (), 1")
519 # Requires parentheses as subexpression
520 def g(): 1, (yield 1)
521 def g(): 1, (yield from ())
522 check_syntax_error(self, "def g(): 1, yield 1")
523 check_syntax_error(self, "def g(): 1, yield from ()")
524 # Requires parentheses as call argument
525 def g(): f((yield 1))
526 def g(): f((yield 1), 1)
527 def g(): f((yield from ()))
528 def g(): f((yield from ()), 1)
529 check_syntax_error(self, "def g(): f(yield 1)")
530 check_syntax_error(self, "def g(): f(yield 1, 1)")
531 check_syntax_error(self, "def g(): f(yield from ())")
532 check_syntax_error(self, "def g(): f(yield from (), 1)")
533 # Not allowed at top level
534 check_syntax_error(self, "yield")
535 check_syntax_error(self, "yield from")
536 # Not allowed at class scope
Thomas Wouters89f507f2006-12-13 04:49:30 +0000537 check_syntax_error(self, "class foo:yield 1")
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000538 check_syntax_error(self, "class foo:yield from ()")
Yury Selivanovf315c1c2015-07-23 09:10:44 +0300539 # Check annotation refleak on SyntaxError
540 check_syntax_error(self, "def g(a:(yield)): pass")
Guido van Rossum3bead091992-01-27 17:00:37 +0000541
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500542 def test_raise(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000543 # 'raise' test [',' test]
Collin Winter828f04a2007-08-31 00:04:24 +0000544 try: raise RuntimeError('just testing')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000545 except RuntimeError: pass
546 try: raise KeyboardInterrupt
547 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000548
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500549 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000550 # 'import' dotted_as_names
551 import sys
552 import time, sys
553 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
554 from time import time
555 from time import (time)
556 # not testable inside a function, but already done at top of the module
557 # from sys import *
558 from sys import path, argv
559 from sys import (path, argv)
560 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +0000561
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500562 def test_global(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000563 # 'global' NAME (',' NAME)*
564 global a
565 global a, b
566 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +0000567
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500568 def test_nonlocal(self):
Benjamin Petersona933e522008-10-24 22:16:39 +0000569 # 'nonlocal' NAME (',' NAME)*
570 x = 0
571 y = 0
572 def f():
573 nonlocal x
574 nonlocal x, y
575
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500576 def test_assert(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000577 # assertTruestmt: 'assert' test [',' test]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000578 assert 1
579 assert 1, 1
580 assert lambda x:x
581 assert 1, lambda x:x+1
Ezio Melotti6cc5bf72011-12-02 18:22:52 +0200582
583 try:
584 assert True
585 except AssertionError as e:
586 self.fail("'assert True' should not have raised an AssertionError")
587
588 try:
589 assert True, 'this should always pass'
590 except AssertionError as e:
591 self.fail("'assert True, msg' should not have "
592 "raised an AssertionError")
593
594 # these tests fail if python is run with -O, so check __debug__
595 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
596 def testAssert2(self):
Thomas Wouters80d373c2001-09-26 12:43:39 +0000597 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000598 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +0000599 except AssertionError as e:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000600 self.assertEqual(e.args[0], "msg")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000601 else:
Ezio Melotti6cc5bf72011-12-02 18:22:52 +0200602 self.fail("AssertionError not raised by assert 0")
603
604 try:
605 assert False
606 except AssertionError as e:
607 self.assertEqual(len(e.args), 0)
608 else:
609 self.fail("AssertionError not raised by 'assert False'")
610
Thomas Wouters80d373c2001-09-26 12:43:39 +0000611
Thomas Wouters89f507f2006-12-13 04:49:30 +0000612 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
613 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000614
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500615 def test_if(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000616 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
617 if 1: pass
618 if 1: pass
619 else: pass
620 if 0: pass
621 elif 0: pass
622 if 0: pass
623 elif 0: pass
624 elif 0: pass
625 elif 0: pass
626 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000627
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500628 def test_while(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000629 # 'while' test ':' suite ['else' ':' suite]
630 while 0: pass
631 while 0: pass
632 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000633
Christian Heimes969fe572008-01-25 11:23:10 +0000634 # Issue1920: "while 0" is optimized away,
635 # ensure that the "else" clause is still present.
636 x = 0
637 while 0:
638 x = 1
639 else:
640 x = 2
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000641 self.assertEqual(x, 2)
Christian Heimes969fe572008-01-25 11:23:10 +0000642
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500643 def test_for(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000644 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
645 for i in 1, 2, 3: pass
646 for i, j, k in (): pass
647 else: pass
648 class Squares:
649 def __init__(self, max):
650 self.max = max
651 self.sofar = []
652 def __len__(self): return len(self.sofar)
653 def __getitem__(self, i):
654 if not 0 <= i < self.max: raise IndexError
655 n = len(self.sofar)
656 while n <= i:
657 self.sofar.append(n*n)
658 n = n+1
659 return self.sofar[i]
660 n = 0
661 for x in Squares(10): n = n+x
662 if n != 285:
663 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000664
Thomas Wouters89f507f2006-12-13 04:49:30 +0000665 result = []
666 for x, in [(1,), (2,), (3,)]:
667 result.append(x)
668 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000669
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500670 def test_try(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000671 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
672 ### | 'try' ':' suite 'finally' ':' suite
Guido van Rossumb940e112007-01-10 16:19:56 +0000673 ### except_clause: 'except' [expr ['as' expr]]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000674 try:
675 1/0
676 except ZeroDivisionError:
677 pass
678 else:
679 pass
680 try: 1/0
681 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000682 except TypeError as msg: pass
683 except RuntimeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000684 except: pass
685 else: pass
686 try: 1/0
687 except (EOFError, TypeError, ZeroDivisionError): pass
688 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000689 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000690 try: pass
691 finally: pass
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000692
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500693 def test_suite(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000694 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
695 if 1: pass
696 if 1:
697 pass
698 if 1:
699 #
700 #
701 #
702 pass
703 pass
704 #
705 pass
706 #
Guido van Rossum3bead091992-01-27 17:00:37 +0000707
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500708 def test_test(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000709 ### and_test ('or' and_test)*
710 ### and_test: not_test ('and' not_test)*
711 ### not_test: 'not' not_test | comparison
712 if not 1: pass
713 if 1 and 1: pass
714 if 1 or 1: pass
715 if not not not 1: pass
716 if not 1 and 1 and 1: pass
717 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000718
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500719 def test_comparison(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000720 ### comparison: expr (comp_op expr)*
721 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
722 if 1: pass
723 x = (1 == 1)
724 if 1 == 1: pass
725 if 1 != 1: pass
726 if 1 < 1: pass
727 if 1 > 1: pass
728 if 1 <= 1: pass
729 if 1 >= 1: pass
730 if 1 is 1: pass
731 if 1 is not 1: pass
732 if 1 in (): pass
733 if 1 not in (): pass
734 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 +0000735
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500736 def test_binary_mask_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000737 x = 1 & 1
738 x = 1 ^ 1
739 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000740
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500741 def test_shift_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000742 x = 1 << 1
743 x = 1 >> 1
744 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000745
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500746 def test_additive_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000747 x = 1
748 x = 1 + 1
749 x = 1 - 1 - 1
750 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000751
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500752 def test_multiplicative_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000753 x = 1 * 1
754 x = 1 / 1
755 x = 1 % 1
756 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000757
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500758 def test_unary_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000759 x = +1
760 x = -1
761 x = ~1
762 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
763 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +0000764
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500765 def test_selectors(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000766 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
767 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +0000768
Thomas Wouters89f507f2006-12-13 04:49:30 +0000769 import sys, time
770 c = sys.path[0]
771 x = time.time()
772 x = sys.modules['time'].time()
773 a = '01234'
774 c = a[0]
775 c = a[-1]
776 s = a[0:5]
777 s = a[:5]
778 s = a[0:]
779 s = a[:]
780 s = a[-5:]
781 s = a[:-1]
782 s = a[-4:-3]
783 # A rough test of SF bug 1333982. http://python.org/sf/1333982
784 # The testing here is fairly incomplete.
785 # Test cases should include: commas with 1 and 2 colons
786 d = {}
787 d[1] = 1
788 d[1,] = 2
789 d[1,2] = 3
790 d[1,2,3] = 4
791 L = list(d)
792 L.sort(key=lambda x: x if isinstance(x, tuple) else ())
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000793 self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +0000794
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500795 def test_atoms(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000796 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
797 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +0000798
Thomas Wouters89f507f2006-12-13 04:49:30 +0000799 x = (1)
800 x = (1 or 2 or 3)
801 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +0000802
Thomas Wouters89f507f2006-12-13 04:49:30 +0000803 x = []
804 x = [1]
805 x = [1 or 2 or 3]
806 x = [1 or 2 or 3, 2, 3]
807 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +0000808
Thomas Wouters89f507f2006-12-13 04:49:30 +0000809 x = {}
810 x = {'one': 1}
811 x = {'one': 1,}
812 x = {'one' or 'two': 1 or 2}
813 x = {'one': 1, 'two': 2}
814 x = {'one': 1, 'two': 2,}
815 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +0000816
Thomas Wouters89f507f2006-12-13 04:49:30 +0000817 x = {'one'}
818 x = {'one', 1,}
819 x = {'one', 'two', 'three'}
820 x = {2, 3, 4,}
821
822 x = x
823 x = 'x'
824 x = 123
825
826 ### exprlist: expr (',' expr)* [',']
827 ### testlist: test (',' test)* [',']
828 # These have been exercised enough above
829
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500830 def test_classdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000831 # 'class' NAME ['(' [testlist] ')'] ':' suite
832 class B: pass
833 class B2(): pass
834 class C1(B): pass
835 class C2(B): pass
836 class D(C1, C2, B): pass
837 class C:
838 def meth1(self): pass
839 def meth2(self, arg): pass
840 def meth3(self, a1, a2): pass
841
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000842 # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
843 # decorators: decorator+
844 # decorated: decorators (classdef | funcdef)
845 def class_decorator(x): return x
846 @class_decorator
847 class G: pass
848
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500849 def test_dictcomps(self):
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000850 # dictorsetmaker: ( (test ':' test (comp_for |
851 # (',' test ':' test)* [','])) |
852 # (test (comp_for | (',' test)* [','])) )
853 nums = [1, 2, 3]
854 self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
855
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500856 def test_listcomps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000857 # list comprehension tests
858 nums = [1, 2, 3, 4, 5]
859 strs = ["Apple", "Banana", "Coconut"]
860 spcs = [" Apple", " Banana ", "Coco nut "]
861
862 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
863 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
864 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
865 self.assertEqual([(i, s) for i in nums for s in strs],
866 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
867 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
868 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
869 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
870 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
871 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
872 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
873 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
874 (5, 'Banana'), (5, 'Coconut')])
875 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
876 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
877
878 def test_in_func(l):
879 return [0 < x < 3 for x in l if x > 2]
880
881 self.assertEqual(test_in_func(nums), [False, False, False])
882
883 def test_nested_front():
884 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
885 [[1, 2], [3, 4], [5, 6]])
886
887 test_nested_front()
888
889 check_syntax_error(self, "[i, s for i in nums for s in strs]")
890 check_syntax_error(self, "[x if y]")
891
892 suppliers = [
893 (1, "Boeing"),
894 (2, "Ford"),
895 (3, "Macdonalds")
896 ]
897
898 parts = [
899 (10, "Airliner"),
900 (20, "Engine"),
901 (30, "Cheeseburger")
902 ]
903
904 suppart = [
905 (1, 10), (1, 20), (2, 20), (3, 30)
906 ]
907
908 x = [
909 (sname, pname)
910 for (sno, sname) in suppliers
911 for (pno, pname) in parts
912 for (sp_sno, sp_pno) in suppart
913 if sno == sp_sno and pno == sp_pno
914 ]
915
916 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
917 ('Macdonalds', 'Cheeseburger')])
918
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500919 def test_genexps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000920 # generator expression tests
921 g = ([x for x in range(10)] for x in range(1))
Georg Brandla18af4e2007-04-21 15:47:16 +0000922 self.assertEqual(next(g), [x for x in range(10)])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000923 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000924 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000925 self.fail('should produce StopIteration exception')
926 except StopIteration:
927 pass
928
929 a = 1
930 try:
931 g = (a for d in a)
Georg Brandla18af4e2007-04-21 15:47:16 +0000932 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000933 self.fail('should produce TypeError')
934 except TypeError:
935 pass
936
937 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
938 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
939
940 a = [x for x in range(10)]
941 b = (x for x in (y for y in a))
942 self.assertEqual(sum(b), sum([x for x in range(10)]))
943
944 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
945 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
946 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
947 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
948 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
949 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)]))
950 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
951 check_syntax_error(self, "foo(x for x in range(10), 100)")
952 check_syntax_error(self, "foo(100, x for x in range(10))")
953
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500954 def test_comprehension_specials(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000955 # test for outmost iterable precomputation
956 x = 10; g = (i for i in range(x)); x = 5
957 self.assertEqual(len(list(g)), 10)
958
959 # This should hold, since we're only precomputing outmost iterable.
960 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
961 x = 5; t = True;
962 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
963
964 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
965 # even though it's silly. Make sure it works (ifelse broke this.)
966 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
967 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
968
969 # verify unpacking single element tuples in listcomp/genexp.
970 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
971 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
972
Benjamin Petersonf17ab892009-05-29 21:55:57 +0000973 def test_with_statement(self):
974 class manager(object):
975 def __enter__(self):
976 return (1, 2)
977 def __exit__(self, *args):
978 pass
979
980 with manager():
981 pass
982 with manager() as x:
983 pass
984 with manager() as (x, y):
985 pass
986 with manager(), manager():
987 pass
988 with manager() as x, manager() as y:
989 pass
990 with manager() as x, manager():
991 pass
992
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500993 def test_if_else_expr(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000994 # Test ifelse expressions in various cases
995 def _checkeval(msg, ret):
996 "helper to check that evaluation of expressions is done correctly"
Victor Stinnerc6ec54d2016-04-12 18:33:41 +0200997 print(msg)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000998 return ret
999
Nick Coghlan650f0d02007-04-15 12:05:43 +00001000 # the next line is not allowed anymore
1001 #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001002 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
1003 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])
1004 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
1005 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
1006 self.assertEqual((5 and 6 if 0 else 1), 1)
1007 self.assertEqual(((5 and 6) if 0 else 1), 1)
1008 self.assertEqual((5 and (6 if 1 else 1)), 6)
1009 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
1010 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
1011 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
1012 self.assertEqual((not 5 if 1 else 1), False)
1013 self.assertEqual((not 5 if 0 else 1), 1)
1014 self.assertEqual((6 + 1 if 1 else 2), 7)
1015 self.assertEqual((6 - 1 if 1 else 2), 5)
1016 self.assertEqual((6 * 2 if 1 else 4), 12)
1017 self.assertEqual((6 / 2 if 1 else 3), 3)
1018 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +00001019
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001020 def test_paren_evaluation(self):
1021 self.assertEqual(16 // (4 // 2), 8)
1022 self.assertEqual((16 // 4) // 2, 2)
1023 self.assertEqual(16 // 4 // 2, 2)
1024 self.assertTrue(False is (2 is 3))
1025 self.assertFalse((False is 2) is 3)
1026 self.assertFalse(False is 2 is 3)
1027
Benjamin Petersond51374e2014-04-09 23:55:56 -04001028 def test_matrix_mul(self):
1029 # This is not intended to be a comprehensive test, rather just to be few
1030 # samples of the @ operator in test_grammar.py.
1031 class M:
1032 def __matmul__(self, o):
1033 return 4
1034 def __imatmul__(self, o):
1035 self.other = o
1036 return self
1037 m = M()
1038 self.assertEqual(m @ m, 4)
1039 m @= 42
1040 self.assertEqual(m.other, 42)
1041
Yury Selivanov75445082015-05-11 22:57:16 -04001042 def test_async_await(self):
1043 async = 1
1044 await = 2
1045 self.assertEqual(async, 1)
1046
1047 def async():
1048 nonlocal await
1049 await = 10
1050 async()
1051 self.assertEqual(await, 10)
1052
1053 self.assertFalse(bool(async.__code__.co_flags & inspect.CO_COROUTINE))
1054
1055 async def test():
1056 def sum():
Yury Selivanov8fb307c2015-07-22 13:33:45 +03001057 pass
Yury Selivanov75445082015-05-11 22:57:16 -04001058 if 1:
1059 await someobj()
1060
1061 self.assertEqual(test.__name__, 'test')
1062 self.assertTrue(bool(test.__code__.co_flags & inspect.CO_COROUTINE))
1063
1064 def decorator(func):
1065 setattr(func, '_marked', True)
1066 return func
1067
1068 @decorator
1069 async def test2():
1070 return 22
1071 self.assertTrue(test2._marked)
1072 self.assertEqual(test2.__name__, 'test2')
1073 self.assertTrue(bool(test2.__code__.co_flags & inspect.CO_COROUTINE))
1074
1075 def test_async_for(self):
1076 class Done(Exception): pass
1077
1078 class AIter:
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001079 def __aiter__(self):
Yury Selivanov75445082015-05-11 22:57:16 -04001080 return self
1081 async def __anext__(self):
1082 raise StopAsyncIteration
1083
1084 async def foo():
1085 async for i in AIter():
1086 pass
1087 async for i, j in AIter():
1088 pass
1089 async for i in AIter():
1090 pass
1091 else:
1092 pass
1093 raise Done
1094
1095 with self.assertRaises(Done):
1096 foo().send(None)
1097
1098 def test_async_with(self):
1099 class Done(Exception): pass
1100
1101 class manager:
1102 async def __aenter__(self):
1103 return (1, 2)
1104 async def __aexit__(self, *exc):
1105 return False
1106
1107 async def foo():
1108 async with manager():
1109 pass
1110 async with manager() as x:
1111 pass
1112 async with manager() as (x, y):
1113 pass
1114 async with manager(), manager():
1115 pass
1116 async with manager() as x, manager() as y:
1117 pass
1118 async with manager() as x, manager():
1119 pass
1120 raise Done
1121
1122 with self.assertRaises(Done):
1123 foo().send(None)
1124
Guido van Rossum3bead091992-01-27 17:00:37 +00001125
Thomas Wouters89f507f2006-12-13 04:49:30 +00001126if __name__ == '__main__':
Zachary Ware38c707e2015-04-13 15:00:43 -05001127 unittest.main()