blob: 109013f5e2f89a25710f89638bb3d65e3ed339ff [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
Yury Selivanovf8cb8a12016-09-08 20:50:03 -070011# different import patterns to check that __annotations__ does not interfere
12# with import machinery
13import test.ann_module as ann_module
14import typing
15from collections import ChainMap
16from test import ann_module2
17import test
18
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000019
Thomas Wouters89f507f2006-12-13 04:49:30 +000020class TokenTests(unittest.TestCase):
Guido van Rossum3bead091992-01-27 17:00:37 +000021
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050022 def test_backslash(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +000023 # Backslash means line continuation:
24 x = 1 \
25 + 1
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000026 self.assertEqual(x, 2, 'backslash for line continuation')
Guido van Rossum3bead091992-01-27 17:00:37 +000027
Thomas Wouters89f507f2006-12-13 04:49:30 +000028 # Backslash does not means continuation in comments :\
29 x = 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000030 self.assertEqual(x, 0, 'backslash ending comment')
Guido van Rossum3bead091992-01-27 17:00:37 +000031
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050032 def test_plain_integers(self):
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000033 self.assertEqual(type(000), type(0))
34 self.assertEqual(0xff, 255)
35 self.assertEqual(0o377, 255)
36 self.assertEqual(2147483647, 0o17777777777)
37 self.assertEqual(0b1001, 9)
Georg Brandlfceab5a2008-01-19 20:08:23 +000038 # "0x" is not a valid literal
39 self.assertRaises(SyntaxError, eval, "0x")
Christian Heimesa37d4c62007-12-04 23:02:19 +000040 from sys import maxsize
41 if maxsize == 2147483647:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000042 self.assertEqual(-2147483647-1, -0o20000000000)
Thomas Wouters89f507f2006-12-13 04:49:30 +000043 # XXX -2147483648
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000044 self.assertTrue(0o37777777777 > 0)
45 self.assertTrue(0xffffffff > 0)
46 self.assertTrue(0b1111111111111111111111111111111 > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +000047 for s in ('2147483648', '0o40000000000', '0x100000000',
48 '0b10000000000000000000000000000000'):
Thomas Wouters89f507f2006-12-13 04:49:30 +000049 try:
50 x = eval(s)
51 except OverflowError:
52 self.fail("OverflowError on huge integer literal %r" % s)
Christian Heimesa37d4c62007-12-04 23:02:19 +000053 elif maxsize == 9223372036854775807:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +000054 self.assertEqual(-9223372036854775807-1, -0o1000000000000000000000)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000055 self.assertTrue(0o1777777777777777777777 > 0)
56 self.assertTrue(0xffffffffffffffff > 0)
57 self.assertTrue(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +000058 for s in '9223372036854775808', '0o2000000000000000000000', \
59 '0x10000000000000000', \
60 '0b100000000000000000000000000000000000000000000000000000000000000':
Thomas Wouters89f507f2006-12-13 04:49:30 +000061 try:
62 x = eval(s)
63 except OverflowError:
64 self.fail("OverflowError on huge integer literal %r" % s)
65 else:
Christian Heimesa37d4c62007-12-04 23:02:19 +000066 self.fail('Weird maxsize value %r' % maxsize)
Guido van Rossum3bead091992-01-27 17:00:37 +000067
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050068 def test_long_integers(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +000069 x = 0
Guido van Rossume2a383d2007-01-15 16:59:06 +000070 x = 0xffffffffffffffff
Guido van Rossumcd16bf62007-06-13 18:07:49 +000071 x = 0Xffffffffffffffff
72 x = 0o77777777777777777
73 x = 0O77777777777777777
Guido van Rossume2a383d2007-01-15 16:59:06 +000074 x = 123456789012345678901234567890
Guido van Rossumcd16bf62007-06-13 18:07:49 +000075 x = 0b100000000000000000000000000000000000000000000000000000000000000000000
76 x = 0B111111111111111111111111111111111111111111111111111111111111111111111
Guido van Rossum3bead091992-01-27 17:00:37 +000077
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050078 def test_floats(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +000079 x = 3.14
80 x = 314.
81 x = 0.314
82 # XXX x = 000.314
83 x = .314
84 x = 3e14
85 x = 3E14
86 x = 3e-14
87 x = 3e+14
88 x = 3.e14
89 x = .3e14
90 x = 3.1e4
Guido van Rossum3bead091992-01-27 17:00:37 +000091
Benjamin Petersonc4161622014-06-07 12:36:39 -070092 def test_float_exponent_tokenization(self):
93 # See issue 21642.
94 self.assertEqual(1 if 1else 0, 1)
95 self.assertEqual(1 if 0else 0, 0)
96 self.assertRaises(SyntaxError, eval, "0 if 1Else 0")
97
Benjamin Petersonc8507bf2011-05-30 10:52:48 -050098 def test_string_literals(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000099 x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y)
100 x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39)
101 x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000102 x = "doesn't \"shrink\" does it"
103 y = 'doesn\'t "shrink" does it'
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000104 self.assertTrue(len(x) == 24 and x == y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000105 x = "does \"shrink\" doesn't it"
106 y = 'does "shrink" doesn\'t it'
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000107 self.assertTrue(len(x) == 24 and x == y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000108 x = """
Guido van Rossumb6775db1994-08-01 11:34:53 +0000109The "quick"
110brown fox
111jumps over
112the 'lazy' dog.
113"""
Thomas Wouters89f507f2006-12-13 04:49:30 +0000114 y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000115 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000116 y = '''
Guido van Rossumb6775db1994-08-01 11:34:53 +0000117The "quick"
118brown fox
119jumps over
120the 'lazy' dog.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000121'''
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000122 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000123 y = "\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000124The \"quick\"\n\
125brown fox\n\
126jumps over\n\
127the 'lazy' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000128"
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000129 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000130 y = '\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000131The \"quick\"\n\
132brown fox\n\
133jumps over\n\
134the \'lazy\' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000135'
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000136 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000137
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500138 def test_ellipsis(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000139 x = ...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000140 self.assertTrue(x is Ellipsis)
Georg Brandldde00282007-03-18 19:01:53 +0000141 self.assertRaises(SyntaxError, eval, ".. .")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000142
Benjamin Peterson758888d2011-05-30 11:12:38 -0500143 def test_eof_error(self):
144 samples = ("def foo(", "\ndef foo(", "def foo(\n")
145 for s in samples:
146 with self.assertRaises(SyntaxError) as cm:
147 compile(s, "<test>", "exec")
148 self.assertIn("unexpected EOF", str(cm.exception))
149
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700150var_annot_global: int # a global annotated is necessary for test_var_annot
151
152# custom namespace for testing __annotations__
153
154class CNS:
155 def __init__(self):
156 self._dct = {}
157 def __setitem__(self, item, value):
158 self._dct[item.lower()] = value
159 def __getitem__(self, item):
160 return self._dct[item]
161
162
Thomas Wouters89f507f2006-12-13 04:49:30 +0000163class GrammarTests(unittest.TestCase):
164
165 # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
166 # XXX can't test in a script -- this rule is only used when interactive
167
168 # file_input: (NEWLINE | stmt)* ENDMARKER
169 # Being tested as this very moment this very module
170
171 # expr_input: testlist NEWLINE
172 # XXX Hard to test -- used only in calls to input()
173
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500174 def test_eval_input(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000175 # testlist ENDMARKER
176 x = eval('1, 0 or 1')
177
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700178 def test_var_annot_basics(self):
179 # all these should be allowed
180 var1: int = 5
181 var2: [int, str]
182 my_lst = [42]
183 def one():
184 return 1
185 int.new_attr: int
186 [list][0]: type
187 my_lst[one()-1]: int = 5
188 self.assertEqual(my_lst, [5])
189
190 def test_var_annot_syntax_errors(self):
191 # parser pass
192 check_syntax_error(self, "def f: int")
193 check_syntax_error(self, "x: int: str")
194 check_syntax_error(self, "def f():\n"
195 " nonlocal x: int\n")
196 # AST pass
197 check_syntax_error(self, "[x, 0]: int\n")
198 check_syntax_error(self, "f(): int\n")
199 check_syntax_error(self, "(x,): int")
200 check_syntax_error(self, "def f():\n"
201 " (x, y): int = (1, 2)\n")
202 # symtable pass
203 check_syntax_error(self, "def f():\n"
204 " x: int\n"
205 " global x\n")
206 check_syntax_error(self, "def f():\n"
207 " global x\n"
208 " x: int\n")
209
210 def test_var_annot_basic_semantics(self):
211 # execution order
212 with self.assertRaises(ZeroDivisionError):
213 no_name[does_not_exist]: no_name_again = 1/0
214 with self.assertRaises(NameError):
215 no_name[does_not_exist]: 1/0 = 0
216 global var_annot_global
217
218 # function semantics
219 def f():
220 st: str = "Hello"
221 a.b: int = (1, 2)
222 return st
223 self.assertEqual(f.__annotations__, {})
224 def f_OK():
225 x: 1/0
226 f_OK()
227 def fbad():
228 x: int
229 print(x)
230 with self.assertRaises(UnboundLocalError):
231 fbad()
232 def f2bad():
233 (no_such_global): int
234 print(no_such_global)
235 try:
236 f2bad()
237 except Exception as e:
238 self.assertIs(type(e), NameError)
239
240 # class semantics
241 class C:
242 x: int
243 s: str = "attr"
244 z = 2
245 def __init__(self, x):
246 self.x: int = x
247 self.assertEqual(C.__annotations__, {'x': int, 's': str})
248 with self.assertRaises(NameError):
249 class CBad:
250 no_such_name_defined.attr: int = 0
251 with self.assertRaises(NameError):
252 class Cbad2(C):
253 x: int
254 x.y: list = []
255
256 def test_var_annot_metaclass_semantics(self):
257 class CMeta(type):
258 @classmethod
259 def __prepare__(metacls, name, bases, **kwds):
260 return {'__annotations__': CNS()}
261 class CC(metaclass=CMeta):
262 XX: 'ANNOT'
263 self.assertEqual(CC.__annotations__['xx'], 'ANNOT')
264
265 def test_var_annot_module_semantics(self):
266 with self.assertRaises(AttributeError):
267 print(test.__annotations__)
268 self.assertEqual(ann_module.__annotations__,
269 {1: 2, 'x': int, 'y': str, 'f': typing.Tuple[int, int]})
270 self.assertEqual(ann_module.M.__annotations__,
271 {'123': 123, 'o': type})
272 self.assertEqual(ann_module2.__annotations__, {})
273 self.assertEqual(typing.get_type_hints(ann_module2.CV,
274 ann_module2.__dict__),
275 ChainMap({'var': typing.ClassVar[ann_module2.CV]}, {}))
276
277 def test_var_annot_in_module(self):
278 # check that functions fail the same way when executed
279 # outside of module where they were defined
280 from test.ann_module3 import f_bad_ann, g_bad_ann, D_bad_ann
281 with self.assertRaises(NameError):
282 f_bad_ann()
283 with self.assertRaises(NameError):
284 g_bad_ann()
285 with self.assertRaises(NameError):
286 D_bad_ann(5)
287
288 def test_var_annot_simple_exec(self):
289 gns = {}; lns= {}
290 exec("'docstring'\n"
291 "__annotations__[1] = 2\n"
292 "x: int = 5\n", gns, lns)
293 self.assertEqual(lns["__annotations__"], {1: 2, 'x': int})
294 with self.assertRaises(KeyError):
295 gns['__annotations__']
296
297 def test_var_annot_custom_maps(self):
298 # tests with custom locals() and __annotations__
299 ns = {'__annotations__': CNS()}
300 exec('X: int; Z: str = "Z"; (w): complex = 1j', ns)
301 self.assertEqual(ns['__annotations__']['x'], int)
302 self.assertEqual(ns['__annotations__']['z'], str)
303 with self.assertRaises(KeyError):
304 ns['__annotations__']['w']
305 nonloc_ns = {}
306 class CNS2:
307 def __init__(self):
308 self._dct = {}
309 def __setitem__(self, item, value):
310 nonlocal nonloc_ns
311 self._dct[item] = value
312 nonloc_ns[item] = value
313 def __getitem__(self, item):
314 return self._dct[item]
315 exec('x: int = 1', {}, CNS2())
316 self.assertEqual(nonloc_ns['__annotations__']['x'], int)
317
318 def test_var_annot_refleak(self):
319 # complex case: custom locals plus custom __annotations__
320 # this was causing refleak
321 cns = CNS()
322 nonloc_ns = {'__annotations__': cns}
323 class CNS2:
324 def __init__(self):
325 self._dct = {'__annotations__': cns}
326 def __setitem__(self, item, value):
327 nonlocal nonloc_ns
328 self._dct[item] = value
329 nonloc_ns[item] = value
330 def __getitem__(self, item):
331 return self._dct[item]
332 exec('X: str', {}, CNS2())
333 self.assertEqual(nonloc_ns['__annotations__']['x'], str)
334
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500335 def test_funcdef(self):
Neal Norwitzc1505362006-12-28 06:47:50 +0000336 ### [decorators] 'def' NAME parameters ['->' test] ':' suite
337 ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
338 ### decorators: decorator+
339 ### parameters: '(' [typedargslist] ')'
340 ### typedargslist: ((tfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000341 ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000342 ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000343 ### tfpdef: NAME [':' test]
Neal Norwitzc1505362006-12-28 06:47:50 +0000344 ### varargslist: ((vfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000345 ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000346 ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000347 ### vfpdef: NAME
Thomas Wouters89f507f2006-12-13 04:49:30 +0000348 def f1(): pass
349 f1()
350 f1(*())
351 f1(*(), **{})
352 def f2(one_argument): pass
353 def f3(two, arguments): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000354 self.assertEqual(f2.__code__.co_varnames, ('one_argument',))
355 self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments'))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000356 def a1(one_arg,): pass
357 def a2(two, args,): pass
358 def v0(*rest): pass
359 def v1(a, *rest): pass
360 def v2(a, b, *rest): pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000361
362 f1()
363 f2(1)
364 f2(1,)
365 f3(1, 2)
366 f3(1, 2,)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000367 v0()
368 v0(1)
369 v0(1,)
370 v0(1,2)
371 v0(1,2,3,4,5,6,7,8,9,0)
372 v1(1)
373 v1(1,)
374 v1(1,2)
375 v1(1,2,3)
376 v1(1,2,3,4,5,6,7,8,9,0)
377 v2(1,2)
378 v2(1,2,3)
379 v2(1,2,3,4)
380 v2(1,2,3,4,5,6,7,8,9,0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000381
Thomas Wouters89f507f2006-12-13 04:49:30 +0000382 def d01(a=1): pass
383 d01()
384 d01(1)
385 d01(*(1,))
Yury Selivanov14acf5f2015-08-05 17:54:10 -0400386 d01(*[] or [2])
387 d01(*() or (), *{} and (), **() or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000388 d01(**{'a':2})
Benjamin Petersonde12b792015-05-16 09:44:45 -0400389 d01(**{'a':2} or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000390 def d11(a, b=1): pass
391 d11(1)
392 d11(1, 2)
393 d11(1, **{'b':2})
394 def d21(a, b, c=1): pass
395 d21(1, 2)
396 d21(1, 2, 3)
397 d21(*(1, 2, 3))
398 d21(1, *(2, 3))
399 d21(1, 2, *(3,))
400 d21(1, 2, **{'c':3})
401 def d02(a=1, b=2): pass
402 d02()
403 d02(1)
404 d02(1, 2)
405 d02(*(1, 2))
406 d02(1, *(2,))
407 d02(1, **{'b':2})
408 d02(**{'a': 1, 'b': 2})
409 def d12(a, b=1, c=2): pass
410 d12(1)
411 d12(1, 2)
412 d12(1, 2, 3)
413 def d22(a, b, c=1, d=2): pass
414 d22(1, 2)
415 d22(1, 2, 3)
416 d22(1, 2, 3, 4)
417 def d01v(a=1, *rest): pass
418 d01v()
419 d01v(1)
420 d01v(1, 2)
421 d01v(*(1, 2, 3, 4))
422 d01v(*(1,))
423 d01v(**{'a':2})
424 def d11v(a, b=1, *rest): pass
425 d11v(1)
426 d11v(1, 2)
427 d11v(1, 2, 3)
428 def d21v(a, b, c=1, *rest): pass
429 d21v(1, 2)
430 d21v(1, 2, 3)
431 d21v(1, 2, 3, 4)
432 d21v(*(1, 2, 3, 4))
433 d21v(1, 2, **{'c': 3})
434 def d02v(a=1, b=2, *rest): pass
435 d02v()
436 d02v(1)
437 d02v(1, 2)
438 d02v(1, 2, 3)
439 d02v(1, *(2, 3, 4))
440 d02v(**{'a': 1, 'b': 2})
441 def d12v(a, b=1, c=2, *rest): pass
442 d12v(1)
443 d12v(1, 2)
444 d12v(1, 2, 3)
445 d12v(1, 2, 3, 4)
446 d12v(*(1, 2, 3, 4))
447 d12v(1, 2, *(3, 4, 5))
448 d12v(1, *(2,), **{'c': 3})
449 def d22v(a, b, c=1, d=2, *rest): pass
450 d22v(1, 2)
451 d22v(1, 2, 3)
452 d22v(1, 2, 3, 4)
453 d22v(1, 2, 3, 4, 5)
454 d22v(*(1, 2, 3, 4))
455 d22v(1, 2, *(3, 4, 5))
456 d22v(1, *(2, 3), **{'d': 4})
Georg Brandld8b690f2008-05-16 17:28:50 +0000457
458 # keyword argument type tests
459 try:
460 str('x', **{b'foo':1 })
461 except TypeError:
462 pass
463 else:
464 self.fail('Bytes should not work as keyword argument names')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000465 # keyword only argument tests
466 def pos0key1(*, key): return key
467 pos0key1(key=100)
468 def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
469 pos2key2(1, 2, k1=100)
470 pos2key2(1, 2, k1=100, k2=200)
471 pos2key2(1, 2, k2=100, k1=200)
472 def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
473 pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
474 pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
475
Robert Collinsdf395992015-08-12 08:00:06 +1200476 self.assertRaises(SyntaxError, eval, "def f(*): pass")
477 self.assertRaises(SyntaxError, eval, "def f(*,): pass")
478 self.assertRaises(SyntaxError, eval, "def f(*, **kwds): pass")
479
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000480 # keyword arguments after *arglist
481 def f(*args, **kwargs):
482 return args, kwargs
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000483 self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000484 {'x':2, 'y':5}))
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400485 self.assertEqual(f(1, *(2,3), 4), ((1, 2, 3, 4), {}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000486 self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400487 self.assertEqual(f(**{'eggs':'scrambled', 'spam':'fried'}),
488 ((), {'eggs':'scrambled', 'spam':'fried'}))
489 self.assertEqual(f(spam='fried', **{'eggs':'scrambled'}),
490 ((), {'eggs':'scrambled', 'spam':'fried'}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000491
Neal Norwitzc1505362006-12-28 06:47:50 +0000492 # argument annotation tests
493 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000494 self.assertEqual(f.__annotations__, {'return': list})
Zachary Warece17f762015-08-01 21:55:36 -0500495 def f(x: int): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000496 self.assertEqual(f.__annotations__, {'x': int})
Zachary Warece17f762015-08-01 21:55:36 -0500497 def f(*x: str): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000498 self.assertEqual(f.__annotations__, {'x': str})
Zachary Warece17f762015-08-01 21:55:36 -0500499 def f(**x: float): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000500 self.assertEqual(f.__annotations__, {'x': float})
Zachary Warece17f762015-08-01 21:55:36 -0500501 def f(x, y: 1+2): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000502 self.assertEqual(f.__annotations__, {'y': 3})
Zachary Warece17f762015-08-01 21:55:36 -0500503 def f(a, b: 1, c: 2, d): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000504 self.assertEqual(f.__annotations__, {'b': 1, 'c': 2})
Zachary Warece17f762015-08-01 21:55:36 -0500505 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000506 self.assertEqual(f.__annotations__,
Zachary Warece17f762015-08-01 21:55:36 -0500507 {'b': 1, 'c': 2, 'e': 3, 'g': 6})
508 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6, h: 7, i=8, j: 9 = 10,
509 **k: 11) -> 12: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000510 self.assertEqual(f.__annotations__,
Zachary Warece17f762015-08-01 21:55:36 -0500511 {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
512 'k': 11, 'return': 12})
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500513 # Check for issue #20625 -- annotations mangling
514 class Spam:
Zachary Warece17f762015-08-01 21:55:36 -0500515 def f(self, *, __kw: 1):
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500516 pass
517 class Ham(Spam): pass
Benjamin Petersonbcfcfc52014-03-09 20:59:24 -0500518 self.assertEqual(Spam.f.__annotations__, {'_Spam__kw': 1})
519 self.assertEqual(Ham.f.__annotations__, {'_Spam__kw': 1})
Nick Coghlan71011e22007-04-23 11:05:01 +0000520 # Check for SF Bug #1697248 - mixing decorators and a return annotation
521 def null(x): return x
522 @null
523 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000524 self.assertEqual(f.__annotations__, {'return': list})
Nick Coghlan71011e22007-04-23 11:05:01 +0000525
Serhiy Storchaka64204de2016-06-12 17:36:24 +0300526 # test closures with a variety of opargs
Guido van Rossum0240b922007-02-26 21:23:50 +0000527 closure = 1
528 def f(): return closure
529 def f(x=1): return closure
530 def f(*, k=1): return closure
531 def f() -> int: return closure
Neal Norwitzc1505362006-12-28 06:47:50 +0000532
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000533 # Check ast errors in *args and *kwargs
534 check_syntax_error(self, "f(*g(1=2))")
535 check_syntax_error(self, "f(**g(1=2))")
536
Robert Collinsdf395992015-08-12 08:00:06 +1200537 # Check trailing commas are permitted in funcdef argument list
538 def f(a,): pass
539 def f(*args,): pass
540 def f(**kwds,): pass
541 def f(a, *args,): pass
542 def f(a, **kwds,): pass
543 def f(*args, b,): pass
544 def f(*, b,): pass
545 def f(*args, **kwds,): pass
546 def f(a, *args, b,): pass
547 def f(a, *, b,): pass
548 def f(a, *args, **kwds,): pass
549 def f(*args, b, **kwds,): pass
550 def f(*, b, **kwds,): pass
551 def f(a, *args, b, **kwds,): pass
552 def f(a, *, b, **kwds,): pass
553
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500554 def test_lambdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000555 ### lambdef: 'lambda' [varargslist] ':' test
556 l1 = lambda : 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000557 self.assertEqual(l1(), 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000558 l2 = lambda : a[d] # XXX just testing the expression
Guido van Rossume2a383d2007-01-15 16:59:06 +0000559 l3 = lambda : [2 < x for x in [-1, 3, 0]]
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000560 self.assertEqual(l3(), [0, 1, 0])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000561 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000562 self.assertEqual(l4(), 1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000563 l5 = lambda x, y, z=2: x + y + z
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000564 self.assertEqual(l5(1, 2), 5)
565 self.assertEqual(l5(1, 2, 3), 6)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000566 check_syntax_error(self, "lambda x: x = 2")
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000567 check_syntax_error(self, "lambda (None,): None")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000568 l6 = lambda x, y, *, k=20: x+y+k
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000569 self.assertEqual(l6(1,2), 1+2+20)
570 self.assertEqual(l6(1,2,k=10), 1+2+10)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000571
Robert Collinsdf395992015-08-12 08:00:06 +1200572 # check that trailing commas are permitted
573 l10 = lambda a,: 0
574 l11 = lambda *args,: 0
575 l12 = lambda **kwds,: 0
576 l13 = lambda a, *args,: 0
577 l14 = lambda a, **kwds,: 0
578 l15 = lambda *args, b,: 0
579 l16 = lambda *, b,: 0
580 l17 = lambda *args, **kwds,: 0
581 l18 = lambda a, *args, b,: 0
582 l19 = lambda a, *, b,: 0
583 l20 = lambda a, *args, **kwds,: 0
584 l21 = lambda *args, b, **kwds,: 0
585 l22 = lambda *, b, **kwds,: 0
586 l23 = lambda a, *args, b, **kwds,: 0
587 l24 = lambda a, *, b, **kwds,: 0
588
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000589
Thomas Wouters89f507f2006-12-13 04:49:30 +0000590 ### stmt: simple_stmt | compound_stmt
591 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000592
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500593 def test_simple_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000594 ### simple_stmt: small_stmt (';' small_stmt)* [';']
595 x = 1; pass; del x
596 def foo():
Ezio Melotti13925002011-03-16 11:05:33 +0200597 # verify statements that end with semi-colons
Thomas Wouters89f507f2006-12-13 04:49:30 +0000598 x = 1; pass; del x;
599 foo()
Georg Brandl52318d62006-09-06 07:06:08 +0000600
Guido van Rossumd8faa362007-04-27 19:54:29 +0000601 ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
Thomas Wouters89f507f2006-12-13 04:49:30 +0000602 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000603
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500604 def test_expr_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000605 # (exprlist '=')* exprlist
Victor Stinner15a30952016-02-08 22:45:06 +0100606 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000607 1, 2, 3
608 x = 1
609 x = 1, 2, 3
610 x = y = z = 1, 2, 3
611 x, y, z = 1, 2, 3
612 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000613
Thomas Wouters89f507f2006-12-13 04:49:30 +0000614 check_syntax_error(self, "x + 1 = 1")
615 check_syntax_error(self, "a + 1 = b + 2")
Guido van Rossum3bead091992-01-27 17:00:37 +0000616
Nick Coghlan5b1fdc12014-06-16 19:48:02 +1000617 # Check the heuristic for print & exec covers significant cases
618 # As well as placing some limits on false positives
619 def test_former_statements_refer_to_builtins(self):
620 keywords = "print", "exec"
621 # Cases where we want the custom error
622 cases = [
623 "{} foo",
624 "{} {{1:foo}}",
625 "if 1: {} foo",
626 "if 1: {} {{1:foo}}",
627 "if 1:\n {} foo",
628 "if 1:\n {} {{1:foo}}",
629 ]
630 for keyword in keywords:
631 custom_msg = "call to '{}'".format(keyword)
632 for case in cases:
633 source = case.format(keyword)
634 with self.subTest(source=source):
635 with self.assertRaisesRegex(SyntaxError, custom_msg):
636 exec(source)
637 source = source.replace("foo", "(foo.)")
638 with self.subTest(source=source):
639 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
640 exec(source)
641
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500642 def test_del_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000643 # 'del' exprlist
644 abc = [1,2,3]
645 x, y, z = abc
646 xyz = x, y, z
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000647
Thomas Wouters89f507f2006-12-13 04:49:30 +0000648 del abc
649 del x, y, (z, xyz)
Barry Warsaw9182b452000-08-29 04:57:10 +0000650
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500651 def test_pass_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000652 # 'pass'
653 pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000654
Thomas Wouters89f507f2006-12-13 04:49:30 +0000655 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
656 # Tested below
Barry Warsaw9182b452000-08-29 04:57:10 +0000657
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500658 def test_break_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000659 # 'break'
660 while 1: break
Barry Warsaw9182b452000-08-29 04:57:10 +0000661
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500662 def test_continue_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000663 # 'continue'
664 i = 1
665 while i: i = 0; continue
Barry Warsaw9182b452000-08-29 04:57:10 +0000666
Thomas Wouters89f507f2006-12-13 04:49:30 +0000667 msg = ""
668 while not msg:
669 msg = "ok"
670 try:
671 continue
672 msg = "continue failed to continue inside try"
673 except:
674 msg = "continue inside try called except block"
675 if msg != "ok":
676 self.fail(msg)
Barry Warsawefc92ee2000-08-21 15:46:50 +0000677
Thomas Wouters89f507f2006-12-13 04:49:30 +0000678 msg = ""
679 while not msg:
680 msg = "finally block not called"
681 try:
682 continue
683 finally:
684 msg = "ok"
685 if msg != "ok":
686 self.fail(msg)
Guido van Rossum3bead091992-01-27 17:00:37 +0000687
Thomas Wouters89f507f2006-12-13 04:49:30 +0000688 def test_break_continue_loop(self):
689 # This test warrants an explanation. It is a test specifically for SF bugs
690 # #463359 and #462937. The bug is that a 'break' statement executed or
691 # exception raised inside a try/except inside a loop, *after* a continue
692 # statement has been executed in that loop, will cause the wrong number of
693 # arguments to be popped off the stack and the instruction pointer reset to
694 # a very small number (usually 0.) Because of this, the following test
695 # *must* written as a function, and the tracking vars *must* be function
696 # arguments with default values. Otherwise, the test will loop and loop.
Guido van Rossum3bead091992-01-27 17:00:37 +0000697
Thomas Wouters89f507f2006-12-13 04:49:30 +0000698 def test_inner(extra_burning_oil = 1, count=0):
699 big_hippo = 2
700 while big_hippo:
701 count += 1
702 try:
703 if extra_burning_oil and big_hippo == 1:
704 extra_burning_oil -= 1
705 break
706 big_hippo -= 1
707 continue
708 except:
709 raise
710 if count > 2 or big_hippo != 1:
711 self.fail("continue then break in try/except in loop broken!")
712 test_inner()
Guido van Rossum3bead091992-01-27 17:00:37 +0000713
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500714 def test_return(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000715 # 'return' [testlist]
716 def g1(): return
717 def g2(): return 1
718 g1()
719 x = g2()
720 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000721
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500722 def test_yield(self):
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000723 # Allowed as standalone statement
724 def g(): yield 1
725 def g(): yield from ()
726 # Allowed as RHS of assignment
727 def g(): x = yield 1
728 def g(): x = yield from ()
729 # Ordinary yield accepts implicit tuples
730 def g(): yield 1, 1
731 def g(): x = yield 1, 1
732 # 'yield from' does not
733 check_syntax_error(self, "def g(): yield from (), 1")
734 check_syntax_error(self, "def g(): x = yield from (), 1")
735 # Requires parentheses as subexpression
736 def g(): 1, (yield 1)
737 def g(): 1, (yield from ())
738 check_syntax_error(self, "def g(): 1, yield 1")
739 check_syntax_error(self, "def g(): 1, yield from ()")
740 # Requires parentheses as call argument
741 def g(): f((yield 1))
742 def g(): f((yield 1), 1)
743 def g(): f((yield from ()))
744 def g(): f((yield from ()), 1)
745 check_syntax_error(self, "def g(): f(yield 1)")
746 check_syntax_error(self, "def g(): f(yield 1, 1)")
747 check_syntax_error(self, "def g(): f(yield from ())")
748 check_syntax_error(self, "def g(): f(yield from (), 1)")
749 # Not allowed at top level
750 check_syntax_error(self, "yield")
751 check_syntax_error(self, "yield from")
752 # Not allowed at class scope
Thomas Wouters89f507f2006-12-13 04:49:30 +0000753 check_syntax_error(self, "class foo:yield 1")
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000754 check_syntax_error(self, "class foo:yield from ()")
Yury Selivanovf315c1c2015-07-23 09:10:44 +0300755 # Check annotation refleak on SyntaxError
756 check_syntax_error(self, "def g(a:(yield)): pass")
Guido van Rossum3bead091992-01-27 17:00:37 +0000757
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500758 def test_raise(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000759 # 'raise' test [',' test]
Collin Winter828f04a2007-08-31 00:04:24 +0000760 try: raise RuntimeError('just testing')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000761 except RuntimeError: pass
762 try: raise KeyboardInterrupt
763 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000764
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500765 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000766 # 'import' dotted_as_names
767 import sys
768 import time, sys
769 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
770 from time import time
771 from time import (time)
772 # not testable inside a function, but already done at top of the module
773 # from sys import *
774 from sys import path, argv
775 from sys import (path, argv)
776 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +0000777
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500778 def test_global(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000779 # 'global' NAME (',' NAME)*
780 global a
781 global a, b
782 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +0000783
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500784 def test_nonlocal(self):
Benjamin Petersona933e522008-10-24 22:16:39 +0000785 # 'nonlocal' NAME (',' NAME)*
786 x = 0
787 y = 0
788 def f():
789 nonlocal x
790 nonlocal x, y
791
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500792 def test_assert(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000793 # assertTruestmt: 'assert' test [',' test]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000794 assert 1
795 assert 1, 1
796 assert lambda x:x
797 assert 1, lambda x:x+1
Ezio Melotti6cc5bf72011-12-02 18:22:52 +0200798
799 try:
800 assert True
801 except AssertionError as e:
802 self.fail("'assert True' should not have raised an AssertionError")
803
804 try:
805 assert True, 'this should always pass'
806 except AssertionError as e:
807 self.fail("'assert True, msg' should not have "
808 "raised an AssertionError")
809
810 # these tests fail if python is run with -O, so check __debug__
811 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
812 def testAssert2(self):
Thomas Wouters80d373c2001-09-26 12:43:39 +0000813 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000814 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +0000815 except AssertionError as e:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000816 self.assertEqual(e.args[0], "msg")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000817 else:
Ezio Melotti6cc5bf72011-12-02 18:22:52 +0200818 self.fail("AssertionError not raised by assert 0")
819
820 try:
821 assert False
822 except AssertionError as e:
823 self.assertEqual(len(e.args), 0)
824 else:
825 self.fail("AssertionError not raised by 'assert False'")
826
Thomas Wouters80d373c2001-09-26 12:43:39 +0000827
Thomas Wouters89f507f2006-12-13 04:49:30 +0000828 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
829 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000830
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500831 def test_if(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000832 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
833 if 1: pass
834 if 1: pass
835 else: pass
836 if 0: pass
837 elif 0: pass
838 if 0: pass
839 elif 0: pass
840 elif 0: pass
841 elif 0: pass
842 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000843
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500844 def test_while(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000845 # 'while' test ':' suite ['else' ':' suite]
846 while 0: pass
847 while 0: pass
848 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000849
Christian Heimes969fe572008-01-25 11:23:10 +0000850 # Issue1920: "while 0" is optimized away,
851 # ensure that the "else" clause is still present.
852 x = 0
853 while 0:
854 x = 1
855 else:
856 x = 2
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000857 self.assertEqual(x, 2)
Christian Heimes969fe572008-01-25 11:23:10 +0000858
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500859 def test_for(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000860 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
861 for i in 1, 2, 3: pass
862 for i, j, k in (): pass
863 else: pass
864 class Squares:
865 def __init__(self, max):
866 self.max = max
867 self.sofar = []
868 def __len__(self): return len(self.sofar)
869 def __getitem__(self, i):
870 if not 0 <= i < self.max: raise IndexError
871 n = len(self.sofar)
872 while n <= i:
873 self.sofar.append(n*n)
874 n = n+1
875 return self.sofar[i]
876 n = 0
877 for x in Squares(10): n = n+x
878 if n != 285:
879 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +0000880
Thomas Wouters89f507f2006-12-13 04:49:30 +0000881 result = []
882 for x, in [(1,), (2,), (3,)]:
883 result.append(x)
884 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +0000885
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500886 def test_try(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000887 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
888 ### | 'try' ':' suite 'finally' ':' suite
Guido van Rossumb940e112007-01-10 16:19:56 +0000889 ### except_clause: 'except' [expr ['as' expr]]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000890 try:
891 1/0
892 except ZeroDivisionError:
893 pass
894 else:
895 pass
896 try: 1/0
897 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000898 except TypeError as msg: pass
899 except RuntimeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000900 except: pass
901 else: pass
902 try: 1/0
903 except (EOFError, TypeError, ZeroDivisionError): pass
904 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000905 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000906 try: pass
907 finally: pass
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +0000908
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500909 def test_suite(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000910 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
911 if 1: pass
912 if 1:
913 pass
914 if 1:
915 #
916 #
917 #
918 pass
919 pass
920 #
921 pass
922 #
Guido van Rossum3bead091992-01-27 17:00:37 +0000923
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500924 def test_test(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000925 ### and_test ('or' and_test)*
926 ### and_test: not_test ('and' not_test)*
927 ### not_test: 'not' not_test | comparison
928 if not 1: pass
929 if 1 and 1: pass
930 if 1 or 1: pass
931 if not not not 1: pass
932 if not 1 and 1 and 1: pass
933 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000934
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500935 def test_comparison(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000936 ### comparison: expr (comp_op expr)*
937 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
938 if 1: pass
939 x = (1 == 1)
940 if 1 == 1: pass
941 if 1 != 1: pass
942 if 1 < 1: pass
943 if 1 > 1: pass
944 if 1 <= 1: pass
945 if 1 >= 1: pass
946 if 1 is 1: pass
947 if 1 is not 1: pass
948 if 1 in (): pass
949 if 1 not in (): pass
950 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 +0000951
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500952 def test_binary_mask_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000953 x = 1 & 1
954 x = 1 ^ 1
955 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000956
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500957 def test_shift_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000958 x = 1 << 1
959 x = 1 >> 1
960 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000961
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500962 def test_additive_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000963 x = 1
964 x = 1 + 1
965 x = 1 - 1 - 1
966 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000967
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500968 def test_multiplicative_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000969 x = 1 * 1
970 x = 1 / 1
971 x = 1 % 1
972 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +0000973
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500974 def test_unary_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000975 x = +1
976 x = -1
977 x = ~1
978 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
979 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +0000980
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500981 def test_selectors(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000982 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
983 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +0000984
Thomas Wouters89f507f2006-12-13 04:49:30 +0000985 import sys, time
986 c = sys.path[0]
987 x = time.time()
988 x = sys.modules['time'].time()
989 a = '01234'
990 c = a[0]
991 c = a[-1]
992 s = a[0:5]
993 s = a[:5]
994 s = a[0:]
995 s = a[:]
996 s = a[-5:]
997 s = a[:-1]
998 s = a[-4:-3]
999 # A rough test of SF bug 1333982. http://python.org/sf/1333982
1000 # The testing here is fairly incomplete.
1001 # Test cases should include: commas with 1 and 2 colons
1002 d = {}
1003 d[1] = 1
1004 d[1,] = 2
1005 d[1,2] = 3
1006 d[1,2,3] = 4
1007 L = list(d)
1008 L.sort(key=lambda x: x if isinstance(x, tuple) else ())
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001009 self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +00001010
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001011 def test_atoms(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001012 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
1013 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +00001014
Thomas Wouters89f507f2006-12-13 04:49:30 +00001015 x = (1)
1016 x = (1 or 2 or 3)
1017 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +00001018
Thomas Wouters89f507f2006-12-13 04:49:30 +00001019 x = []
1020 x = [1]
1021 x = [1 or 2 or 3]
1022 x = [1 or 2 or 3, 2, 3]
1023 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +00001024
Thomas Wouters89f507f2006-12-13 04:49:30 +00001025 x = {}
1026 x = {'one': 1}
1027 x = {'one': 1,}
1028 x = {'one' or 'two': 1 or 2}
1029 x = {'one': 1, 'two': 2}
1030 x = {'one': 1, 'two': 2,}
1031 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +00001032
Thomas Wouters89f507f2006-12-13 04:49:30 +00001033 x = {'one'}
1034 x = {'one', 1,}
1035 x = {'one', 'two', 'three'}
1036 x = {2, 3, 4,}
1037
1038 x = x
1039 x = 'x'
1040 x = 123
1041
1042 ### exprlist: expr (',' expr)* [',']
1043 ### testlist: test (',' test)* [',']
1044 # These have been exercised enough above
1045
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001046 def test_classdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001047 # 'class' NAME ['(' [testlist] ')'] ':' suite
1048 class B: pass
1049 class B2(): pass
1050 class C1(B): pass
1051 class C2(B): pass
1052 class D(C1, C2, B): pass
1053 class C:
1054 def meth1(self): pass
1055 def meth2(self, arg): pass
1056 def meth3(self, a1, a2): pass
1057
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001058 # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
1059 # decorators: decorator+
1060 # decorated: decorators (classdef | funcdef)
1061 def class_decorator(x): return x
1062 @class_decorator
1063 class G: pass
1064
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001065 def test_dictcomps(self):
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001066 # dictorsetmaker: ( (test ':' test (comp_for |
1067 # (',' test ':' test)* [','])) |
1068 # (test (comp_for | (',' test)* [','])) )
1069 nums = [1, 2, 3]
1070 self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
1071
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001072 def test_listcomps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001073 # list comprehension tests
1074 nums = [1, 2, 3, 4, 5]
1075 strs = ["Apple", "Banana", "Coconut"]
1076 spcs = [" Apple", " Banana ", "Coco nut "]
1077
1078 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
1079 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
1080 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
1081 self.assertEqual([(i, s) for i in nums for s in strs],
1082 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
1083 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
1084 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
1085 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
1086 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
1087 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
1088 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
1089 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
1090 (5, 'Banana'), (5, 'Coconut')])
1091 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
1092 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
1093
1094 def test_in_func(l):
1095 return [0 < x < 3 for x in l if x > 2]
1096
1097 self.assertEqual(test_in_func(nums), [False, False, False])
1098
1099 def test_nested_front():
1100 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
1101 [[1, 2], [3, 4], [5, 6]])
1102
1103 test_nested_front()
1104
1105 check_syntax_error(self, "[i, s for i in nums for s in strs]")
1106 check_syntax_error(self, "[x if y]")
1107
1108 suppliers = [
1109 (1, "Boeing"),
1110 (2, "Ford"),
1111 (3, "Macdonalds")
1112 ]
1113
1114 parts = [
1115 (10, "Airliner"),
1116 (20, "Engine"),
1117 (30, "Cheeseburger")
1118 ]
1119
1120 suppart = [
1121 (1, 10), (1, 20), (2, 20), (3, 30)
1122 ]
1123
1124 x = [
1125 (sname, pname)
1126 for (sno, sname) in suppliers
1127 for (pno, pname) in parts
1128 for (sp_sno, sp_pno) in suppart
1129 if sno == sp_sno and pno == sp_pno
1130 ]
1131
1132 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
1133 ('Macdonalds', 'Cheeseburger')])
1134
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001135 def test_genexps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001136 # generator expression tests
1137 g = ([x for x in range(10)] for x in range(1))
Georg Brandla18af4e2007-04-21 15:47:16 +00001138 self.assertEqual(next(g), [x for x in range(10)])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001139 try:
Georg Brandla18af4e2007-04-21 15:47:16 +00001140 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001141 self.fail('should produce StopIteration exception')
1142 except StopIteration:
1143 pass
1144
1145 a = 1
1146 try:
1147 g = (a for d in a)
Georg Brandla18af4e2007-04-21 15:47:16 +00001148 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001149 self.fail('should produce TypeError')
1150 except TypeError:
1151 pass
1152
1153 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
1154 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
1155
1156 a = [x for x in range(10)]
1157 b = (x for x in (y for y in a))
1158 self.assertEqual(sum(b), sum([x for x in range(10)]))
1159
1160 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
1161 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
1162 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
1163 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
1164 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
1165 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)]))
1166 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
1167 check_syntax_error(self, "foo(x for x in range(10), 100)")
1168 check_syntax_error(self, "foo(100, x for x in range(10))")
1169
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001170 def test_comprehension_specials(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001171 # test for outmost iterable precomputation
1172 x = 10; g = (i for i in range(x)); x = 5
1173 self.assertEqual(len(list(g)), 10)
1174
1175 # This should hold, since we're only precomputing outmost iterable.
1176 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
1177 x = 5; t = True;
1178 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
1179
1180 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
1181 # even though it's silly. Make sure it works (ifelse broke this.)
1182 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
1183 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
1184
1185 # verify unpacking single element tuples in listcomp/genexp.
1186 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
1187 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
1188
Benjamin Petersonf17ab892009-05-29 21:55:57 +00001189 def test_with_statement(self):
1190 class manager(object):
1191 def __enter__(self):
1192 return (1, 2)
1193 def __exit__(self, *args):
1194 pass
1195
1196 with manager():
1197 pass
1198 with manager() as x:
1199 pass
1200 with manager() as (x, y):
1201 pass
1202 with manager(), manager():
1203 pass
1204 with manager() as x, manager() as y:
1205 pass
1206 with manager() as x, manager():
1207 pass
1208
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001209 def test_if_else_expr(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001210 # Test ifelse expressions in various cases
1211 def _checkeval(msg, ret):
1212 "helper to check that evaluation of expressions is done correctly"
Victor Stinnerc6ec54d2016-04-12 18:33:41 +02001213 print(msg)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001214 return ret
1215
Nick Coghlan650f0d02007-04-15 12:05:43 +00001216 # the next line is not allowed anymore
1217 #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001218 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
1219 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])
1220 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
1221 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
1222 self.assertEqual((5 and 6 if 0 else 1), 1)
1223 self.assertEqual(((5 and 6) if 0 else 1), 1)
1224 self.assertEqual((5 and (6 if 1 else 1)), 6)
1225 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
1226 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
1227 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
1228 self.assertEqual((not 5 if 1 else 1), False)
1229 self.assertEqual((not 5 if 0 else 1), 1)
1230 self.assertEqual((6 + 1 if 1 else 2), 7)
1231 self.assertEqual((6 - 1 if 1 else 2), 5)
1232 self.assertEqual((6 * 2 if 1 else 4), 12)
1233 self.assertEqual((6 / 2 if 1 else 3), 3)
1234 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +00001235
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001236 def test_paren_evaluation(self):
1237 self.assertEqual(16 // (4 // 2), 8)
1238 self.assertEqual((16 // 4) // 2, 2)
1239 self.assertEqual(16 // 4 // 2, 2)
1240 self.assertTrue(False is (2 is 3))
1241 self.assertFalse((False is 2) is 3)
1242 self.assertFalse(False is 2 is 3)
1243
Benjamin Petersond51374e2014-04-09 23:55:56 -04001244 def test_matrix_mul(self):
1245 # This is not intended to be a comprehensive test, rather just to be few
1246 # samples of the @ operator in test_grammar.py.
1247 class M:
1248 def __matmul__(self, o):
1249 return 4
1250 def __imatmul__(self, o):
1251 self.other = o
1252 return self
1253 m = M()
1254 self.assertEqual(m @ m, 4)
1255 m @= 42
1256 self.assertEqual(m.other, 42)
1257
Yury Selivanov75445082015-05-11 22:57:16 -04001258 def test_async_await(self):
1259 async = 1
1260 await = 2
1261 self.assertEqual(async, 1)
1262
1263 def async():
1264 nonlocal await
1265 await = 10
1266 async()
1267 self.assertEqual(await, 10)
1268
1269 self.assertFalse(bool(async.__code__.co_flags & inspect.CO_COROUTINE))
1270
1271 async def test():
1272 def sum():
Yury Selivanov8fb307c2015-07-22 13:33:45 +03001273 pass
Yury Selivanov75445082015-05-11 22:57:16 -04001274 if 1:
1275 await someobj()
1276
1277 self.assertEqual(test.__name__, 'test')
1278 self.assertTrue(bool(test.__code__.co_flags & inspect.CO_COROUTINE))
1279
1280 def decorator(func):
1281 setattr(func, '_marked', True)
1282 return func
1283
1284 @decorator
1285 async def test2():
1286 return 22
1287 self.assertTrue(test2._marked)
1288 self.assertEqual(test2.__name__, 'test2')
1289 self.assertTrue(bool(test2.__code__.co_flags & inspect.CO_COROUTINE))
1290
1291 def test_async_for(self):
1292 class Done(Exception): pass
1293
1294 class AIter:
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001295 def __aiter__(self):
Yury Selivanov75445082015-05-11 22:57:16 -04001296 return self
1297 async def __anext__(self):
1298 raise StopAsyncIteration
1299
1300 async def foo():
1301 async for i in AIter():
1302 pass
1303 async for i, j in AIter():
1304 pass
1305 async for i in AIter():
1306 pass
1307 else:
1308 pass
1309 raise Done
1310
1311 with self.assertRaises(Done):
1312 foo().send(None)
1313
1314 def test_async_with(self):
1315 class Done(Exception): pass
1316
1317 class manager:
1318 async def __aenter__(self):
1319 return (1, 2)
1320 async def __aexit__(self, *exc):
1321 return False
1322
1323 async def foo():
1324 async with manager():
1325 pass
1326 async with manager() as x:
1327 pass
1328 async with manager() as (x, y):
1329 pass
1330 async with manager(), manager():
1331 pass
1332 async with manager() as x, manager() as y:
1333 pass
1334 async with manager() as x, manager():
1335 pass
1336 raise Done
1337
1338 with self.assertRaises(Done):
1339 foo().send(None)
1340
Guido van Rossum3bead091992-01-27 17:00:37 +00001341
Thomas Wouters89f507f2006-12-13 04:49:30 +00001342if __name__ == '__main__':
Zachary Ware38c707e2015-04-13 15:00:43 -05001343 unittest.main()