blob: d89bfdc063352dbfbd1d7d0c66a7ff3616a5141e [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
Brett Cannona721aba2016-09-09 14:57:09 -070019# These are shared with test_tokenize and other test modules.
20#
21# Note: since several test cases filter out floats by looking for "e" and ".",
22# don't add hexadecimal literals that contain "e" or "E".
23VALID_UNDERSCORE_LITERALS = [
24 '0_0_0',
25 '4_2',
26 '1_0000_0000',
27 '0b1001_0100',
28 '0xffff_ffff',
29 '0o5_7_7',
30 '1_00_00.5',
31 '1_00_00.5e5',
32 '1_00_00e5_1',
33 '1e1_0',
34 '.1_4',
35 '.1_4e1',
36 '0b_0',
37 '0x_f',
38 '0o_5',
39 '1_00_00j',
40 '1_00_00.5j',
41 '1_00_00e5_1j',
42 '.1_4j',
43 '(1_2.5+3_3j)',
44 '(.5_6j)',
45]
46INVALID_UNDERSCORE_LITERALS = [
47 # Trailing underscores:
48 '0_',
49 '42_',
50 '1.4j_',
51 '0x_',
52 '0b1_',
53 '0xf_',
54 '0o5_',
55 '0 if 1_Else 1',
56 # Underscores in the base selector:
57 '0_b0',
58 '0_xf',
59 '0_o5',
60 # Old-style octal, still disallowed:
61 '0_7',
62 '09_99',
63 # Multiple consecutive underscores:
64 '4_______2',
65 '0.1__4',
66 '0.1__4j',
67 '0b1001__0100',
68 '0xffff__ffff',
69 '0x___',
70 '0o5__77',
71 '1e1__0',
72 '1e1__0j',
73 # Underscore right before a dot:
74 '1_.4',
75 '1_.4j',
76 # Underscore right after a dot:
77 '1._4',
78 '1._4j',
79 '._5',
80 '._5j',
81 # Underscore right after a sign:
82 '1.0e+_1',
83 '1.0e+_1j',
84 # Underscore right before j:
85 '1.4_j',
86 '1.4e5_j',
87 # Underscore right before e:
88 '1_e1',
89 '1.4_e1',
90 '1.4_e1j',
91 # Underscore right after e:
92 '1e_1',
93 '1.4e_1',
94 '1.4e_1j',
95 # Complex cases with parens:
96 '(1+1.5_j_)',
97 '(1+1.5_j)',
98]
99
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000100
Thomas Wouters89f507f2006-12-13 04:49:30 +0000101class TokenTests(unittest.TestCase):
Guido van Rossum3bead091992-01-27 17:00:37 +0000102
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500103 def test_backslash(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000104 # Backslash means line continuation:
105 x = 1 \
106 + 1
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000107 self.assertEqual(x, 2, 'backslash for line continuation')
Guido van Rossum3bead091992-01-27 17:00:37 +0000108
Thomas Wouters89f507f2006-12-13 04:49:30 +0000109 # Backslash does not means continuation in comments :\
110 x = 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000111 self.assertEqual(x, 0, 'backslash ending comment')
Guido van Rossum3bead091992-01-27 17:00:37 +0000112
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500113 def test_plain_integers(self):
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000114 self.assertEqual(type(000), type(0))
115 self.assertEqual(0xff, 255)
116 self.assertEqual(0o377, 255)
117 self.assertEqual(2147483647, 0o17777777777)
118 self.assertEqual(0b1001, 9)
Georg Brandlfceab5a2008-01-19 20:08:23 +0000119 # "0x" is not a valid literal
120 self.assertRaises(SyntaxError, eval, "0x")
Christian Heimesa37d4c62007-12-04 23:02:19 +0000121 from sys import maxsize
122 if maxsize == 2147483647:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000123 self.assertEqual(-2147483647-1, -0o20000000000)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000124 # XXX -2147483648
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000125 self.assertTrue(0o37777777777 > 0)
126 self.assertTrue(0xffffffff > 0)
127 self.assertTrue(0b1111111111111111111111111111111 > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000128 for s in ('2147483648', '0o40000000000', '0x100000000',
129 '0b10000000000000000000000000000000'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000130 try:
131 x = eval(s)
132 except OverflowError:
133 self.fail("OverflowError on huge integer literal %r" % s)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000134 elif maxsize == 9223372036854775807:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000135 self.assertEqual(-9223372036854775807-1, -0o1000000000000000000000)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000136 self.assertTrue(0o1777777777777777777777 > 0)
137 self.assertTrue(0xffffffffffffffff > 0)
138 self.assertTrue(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000139 for s in '9223372036854775808', '0o2000000000000000000000', \
140 '0x10000000000000000', \
141 '0b100000000000000000000000000000000000000000000000000000000000000':
Thomas Wouters89f507f2006-12-13 04:49:30 +0000142 try:
143 x = eval(s)
144 except OverflowError:
145 self.fail("OverflowError on huge integer literal %r" % s)
146 else:
Christian Heimesa37d4c62007-12-04 23:02:19 +0000147 self.fail('Weird maxsize value %r' % maxsize)
Guido van Rossum3bead091992-01-27 17:00:37 +0000148
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500149 def test_long_integers(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000150 x = 0
Guido van Rossume2a383d2007-01-15 16:59:06 +0000151 x = 0xffffffffffffffff
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000152 x = 0Xffffffffffffffff
153 x = 0o77777777777777777
154 x = 0O77777777777777777
Guido van Rossume2a383d2007-01-15 16:59:06 +0000155 x = 123456789012345678901234567890
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000156 x = 0b100000000000000000000000000000000000000000000000000000000000000000000
157 x = 0B111111111111111111111111111111111111111111111111111111111111111111111
Guido van Rossum3bead091992-01-27 17:00:37 +0000158
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500159 def test_floats(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000160 x = 3.14
161 x = 314.
162 x = 0.314
163 # XXX x = 000.314
164 x = .314
165 x = 3e14
166 x = 3E14
167 x = 3e-14
168 x = 3e+14
169 x = 3.e14
170 x = .3e14
171 x = 3.1e4
Guido van Rossum3bead091992-01-27 17:00:37 +0000172
Benjamin Petersonc4161622014-06-07 12:36:39 -0700173 def test_float_exponent_tokenization(self):
174 # See issue 21642.
175 self.assertEqual(1 if 1else 0, 1)
176 self.assertEqual(1 if 0else 0, 0)
177 self.assertRaises(SyntaxError, eval, "0 if 1Else 0")
178
Brett Cannona721aba2016-09-09 14:57:09 -0700179 def test_underscore_literals(self):
180 for lit in VALID_UNDERSCORE_LITERALS:
181 self.assertEqual(eval(lit), eval(lit.replace('_', '')))
182 for lit in INVALID_UNDERSCORE_LITERALS:
183 self.assertRaises(SyntaxError, eval, lit)
184 # Sanity check: no literal begins with an underscore
185 self.assertRaises(NameError, eval, "_0")
186
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500187 def test_string_literals(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000188 x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y)
189 x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39)
190 x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000191 x = "doesn't \"shrink\" does it"
192 y = 'doesn\'t "shrink" does it'
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000193 self.assertTrue(len(x) == 24 and x == y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000194 x = "does \"shrink\" doesn't it"
195 y = 'does "shrink" doesn\'t it'
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000196 self.assertTrue(len(x) == 24 and x == y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000197 x = """
Guido van Rossumb6775db1994-08-01 11:34:53 +0000198The "quick"
199brown fox
200jumps over
201the 'lazy' dog.
202"""
Thomas Wouters89f507f2006-12-13 04:49:30 +0000203 y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000204 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000205 y = '''
Guido van Rossumb6775db1994-08-01 11:34:53 +0000206The "quick"
207brown fox
208jumps over
209the 'lazy' dog.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000210'''
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000211 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000212 y = "\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000213The \"quick\"\n\
214brown fox\n\
215jumps over\n\
216the 'lazy' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000217"
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000218 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000219 y = '\n\
Guido van Rossumb6775db1994-08-01 11:34:53 +0000220The \"quick\"\n\
221brown fox\n\
222jumps over\n\
223the \'lazy\' dog.\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000224'
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000225 self.assertEqual(x, y)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000226
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500227 def test_ellipsis(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000228 x = ...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000229 self.assertTrue(x is Ellipsis)
Georg Brandldde00282007-03-18 19:01:53 +0000230 self.assertRaises(SyntaxError, eval, ".. .")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000231
Benjamin Peterson758888d2011-05-30 11:12:38 -0500232 def test_eof_error(self):
233 samples = ("def foo(", "\ndef foo(", "def foo(\n")
234 for s in samples:
235 with self.assertRaises(SyntaxError) as cm:
236 compile(s, "<test>", "exec")
237 self.assertIn("unexpected EOF", str(cm.exception))
238
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700239var_annot_global: int # a global annotated is necessary for test_var_annot
240
241# custom namespace for testing __annotations__
242
243class CNS:
244 def __init__(self):
245 self._dct = {}
246 def __setitem__(self, item, value):
247 self._dct[item.lower()] = value
248 def __getitem__(self, item):
249 return self._dct[item]
250
251
Thomas Wouters89f507f2006-12-13 04:49:30 +0000252class GrammarTests(unittest.TestCase):
253
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200254 check_syntax_error = check_syntax_error
255
Thomas Wouters89f507f2006-12-13 04:49:30 +0000256 # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
257 # XXX can't test in a script -- this rule is only used when interactive
258
259 # file_input: (NEWLINE | stmt)* ENDMARKER
260 # Being tested as this very moment this very module
261
262 # expr_input: testlist NEWLINE
263 # XXX Hard to test -- used only in calls to input()
264
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500265 def test_eval_input(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000266 # testlist ENDMARKER
267 x = eval('1, 0 or 1')
268
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700269 def test_var_annot_basics(self):
270 # all these should be allowed
271 var1: int = 5
272 var2: [int, str]
273 my_lst = [42]
274 def one():
275 return 1
276 int.new_attr: int
277 [list][0]: type
278 my_lst[one()-1]: int = 5
279 self.assertEqual(my_lst, [5])
280
281 def test_var_annot_syntax_errors(self):
282 # parser pass
283 check_syntax_error(self, "def f: int")
284 check_syntax_error(self, "x: int: str")
285 check_syntax_error(self, "def f():\n"
286 " nonlocal x: int\n")
287 # AST pass
288 check_syntax_error(self, "[x, 0]: int\n")
289 check_syntax_error(self, "f(): int\n")
290 check_syntax_error(self, "(x,): int")
291 check_syntax_error(self, "def f():\n"
292 " (x, y): int = (1, 2)\n")
293 # symtable pass
294 check_syntax_error(self, "def f():\n"
295 " x: int\n"
296 " global x\n")
297 check_syntax_error(self, "def f():\n"
298 " global x\n"
299 " x: int\n")
300
301 def test_var_annot_basic_semantics(self):
302 # execution order
303 with self.assertRaises(ZeroDivisionError):
304 no_name[does_not_exist]: no_name_again = 1/0
305 with self.assertRaises(NameError):
306 no_name[does_not_exist]: 1/0 = 0
307 global var_annot_global
308
309 # function semantics
310 def f():
311 st: str = "Hello"
312 a.b: int = (1, 2)
313 return st
314 self.assertEqual(f.__annotations__, {})
315 def f_OK():
316 x: 1/0
317 f_OK()
318 def fbad():
319 x: int
320 print(x)
321 with self.assertRaises(UnboundLocalError):
322 fbad()
323 def f2bad():
324 (no_such_global): int
325 print(no_such_global)
326 try:
327 f2bad()
328 except Exception as e:
329 self.assertIs(type(e), NameError)
330
331 # class semantics
332 class C:
Guido van Rossum015d8742016-09-11 09:45:24 -0700333 __foo: int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700334 s: str = "attr"
335 z = 2
336 def __init__(self, x):
337 self.x: int = x
Guido van Rossum015d8742016-09-11 09:45:24 -0700338 self.assertEqual(C.__annotations__, {'_C__foo': int, 's': str})
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700339 with self.assertRaises(NameError):
340 class CBad:
341 no_such_name_defined.attr: int = 0
342 with self.assertRaises(NameError):
343 class Cbad2(C):
344 x: int
345 x.y: list = []
346
347 def test_var_annot_metaclass_semantics(self):
348 class CMeta(type):
349 @classmethod
350 def __prepare__(metacls, name, bases, **kwds):
351 return {'__annotations__': CNS()}
352 class CC(metaclass=CMeta):
353 XX: 'ANNOT'
354 self.assertEqual(CC.__annotations__['xx'], 'ANNOT')
355
356 def test_var_annot_module_semantics(self):
357 with self.assertRaises(AttributeError):
358 print(test.__annotations__)
359 self.assertEqual(ann_module.__annotations__,
360 {1: 2, 'x': int, 'y': str, 'f': typing.Tuple[int, int]})
361 self.assertEqual(ann_module.M.__annotations__,
362 {'123': 123, 'o': type})
363 self.assertEqual(ann_module2.__annotations__, {})
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700364
365 def test_var_annot_in_module(self):
366 # check that functions fail the same way when executed
367 # outside of module where they were defined
368 from test.ann_module3 import f_bad_ann, g_bad_ann, D_bad_ann
369 with self.assertRaises(NameError):
370 f_bad_ann()
371 with self.assertRaises(NameError):
372 g_bad_ann()
373 with self.assertRaises(NameError):
374 D_bad_ann(5)
375
376 def test_var_annot_simple_exec(self):
377 gns = {}; lns= {}
378 exec("'docstring'\n"
379 "__annotations__[1] = 2\n"
380 "x: int = 5\n", gns, lns)
381 self.assertEqual(lns["__annotations__"], {1: 2, 'x': int})
382 with self.assertRaises(KeyError):
383 gns['__annotations__']
384
385 def test_var_annot_custom_maps(self):
386 # tests with custom locals() and __annotations__
387 ns = {'__annotations__': CNS()}
388 exec('X: int; Z: str = "Z"; (w): complex = 1j', ns)
389 self.assertEqual(ns['__annotations__']['x'], int)
390 self.assertEqual(ns['__annotations__']['z'], str)
391 with self.assertRaises(KeyError):
392 ns['__annotations__']['w']
393 nonloc_ns = {}
394 class CNS2:
395 def __init__(self):
396 self._dct = {}
397 def __setitem__(self, item, value):
398 nonlocal nonloc_ns
399 self._dct[item] = value
400 nonloc_ns[item] = value
401 def __getitem__(self, item):
402 return self._dct[item]
403 exec('x: int = 1', {}, CNS2())
404 self.assertEqual(nonloc_ns['__annotations__']['x'], int)
405
406 def test_var_annot_refleak(self):
407 # complex case: custom locals plus custom __annotations__
408 # this was causing refleak
409 cns = CNS()
410 nonloc_ns = {'__annotations__': cns}
411 class CNS2:
412 def __init__(self):
413 self._dct = {'__annotations__': cns}
414 def __setitem__(self, item, value):
415 nonlocal nonloc_ns
416 self._dct[item] = value
417 nonloc_ns[item] = value
418 def __getitem__(self, item):
419 return self._dct[item]
420 exec('X: str', {}, CNS2())
421 self.assertEqual(nonloc_ns['__annotations__']['x'], str)
422
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500423 def test_funcdef(self):
Neal Norwitzc1505362006-12-28 06:47:50 +0000424 ### [decorators] 'def' NAME parameters ['->' test] ':' suite
425 ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
426 ### decorators: decorator+
427 ### parameters: '(' [typedargslist] ')'
428 ### typedargslist: ((tfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000429 ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000430 ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000431 ### tfpdef: NAME [':' test]
Neal Norwitzc1505362006-12-28 06:47:50 +0000432 ### varargslist: ((vfpdef ['=' test] ',')*
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000433 ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
Neal Norwitzc1505362006-12-28 06:47:50 +0000434 ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000435 ### vfpdef: NAME
Thomas Wouters89f507f2006-12-13 04:49:30 +0000436 def f1(): pass
437 f1()
438 f1(*())
439 f1(*(), **{})
440 def f2(one_argument): pass
441 def f3(two, arguments): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000442 self.assertEqual(f2.__code__.co_varnames, ('one_argument',))
443 self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments'))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000444 def a1(one_arg,): pass
445 def a2(two, args,): pass
446 def v0(*rest): pass
447 def v1(a, *rest): pass
448 def v2(a, b, *rest): pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000449
450 f1()
451 f2(1)
452 f2(1,)
453 f3(1, 2)
454 f3(1, 2,)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000455 v0()
456 v0(1)
457 v0(1,)
458 v0(1,2)
459 v0(1,2,3,4,5,6,7,8,9,0)
460 v1(1)
461 v1(1,)
462 v1(1,2)
463 v1(1,2,3)
464 v1(1,2,3,4,5,6,7,8,9,0)
465 v2(1,2)
466 v2(1,2,3)
467 v2(1,2,3,4)
468 v2(1,2,3,4,5,6,7,8,9,0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000469
Thomas Wouters89f507f2006-12-13 04:49:30 +0000470 def d01(a=1): pass
471 d01()
472 d01(1)
473 d01(*(1,))
Yury Selivanov14acf5f2015-08-05 17:54:10 -0400474 d01(*[] or [2])
475 d01(*() or (), *{} and (), **() or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000476 d01(**{'a':2})
Benjamin Petersonde12b792015-05-16 09:44:45 -0400477 d01(**{'a':2} or {})
Thomas Wouters89f507f2006-12-13 04:49:30 +0000478 def d11(a, b=1): pass
479 d11(1)
480 d11(1, 2)
481 d11(1, **{'b':2})
482 def d21(a, b, c=1): pass
483 d21(1, 2)
484 d21(1, 2, 3)
485 d21(*(1, 2, 3))
486 d21(1, *(2, 3))
487 d21(1, 2, *(3,))
488 d21(1, 2, **{'c':3})
489 def d02(a=1, b=2): pass
490 d02()
491 d02(1)
492 d02(1, 2)
493 d02(*(1, 2))
494 d02(1, *(2,))
495 d02(1, **{'b':2})
496 d02(**{'a': 1, 'b': 2})
497 def d12(a, b=1, c=2): pass
498 d12(1)
499 d12(1, 2)
500 d12(1, 2, 3)
501 def d22(a, b, c=1, d=2): pass
502 d22(1, 2)
503 d22(1, 2, 3)
504 d22(1, 2, 3, 4)
505 def d01v(a=1, *rest): pass
506 d01v()
507 d01v(1)
508 d01v(1, 2)
509 d01v(*(1, 2, 3, 4))
510 d01v(*(1,))
511 d01v(**{'a':2})
512 def d11v(a, b=1, *rest): pass
513 d11v(1)
514 d11v(1, 2)
515 d11v(1, 2, 3)
516 def d21v(a, b, c=1, *rest): pass
517 d21v(1, 2)
518 d21v(1, 2, 3)
519 d21v(1, 2, 3, 4)
520 d21v(*(1, 2, 3, 4))
521 d21v(1, 2, **{'c': 3})
522 def d02v(a=1, b=2, *rest): pass
523 d02v()
524 d02v(1)
525 d02v(1, 2)
526 d02v(1, 2, 3)
527 d02v(1, *(2, 3, 4))
528 d02v(**{'a': 1, 'b': 2})
529 def d12v(a, b=1, c=2, *rest): pass
530 d12v(1)
531 d12v(1, 2)
532 d12v(1, 2, 3)
533 d12v(1, 2, 3, 4)
534 d12v(*(1, 2, 3, 4))
535 d12v(1, 2, *(3, 4, 5))
536 d12v(1, *(2,), **{'c': 3})
537 def d22v(a, b, c=1, d=2, *rest): pass
538 d22v(1, 2)
539 d22v(1, 2, 3)
540 d22v(1, 2, 3, 4)
541 d22v(1, 2, 3, 4, 5)
542 d22v(*(1, 2, 3, 4))
543 d22v(1, 2, *(3, 4, 5))
544 d22v(1, *(2, 3), **{'d': 4})
Georg Brandld8b690f2008-05-16 17:28:50 +0000545
546 # keyword argument type tests
547 try:
548 str('x', **{b'foo':1 })
549 except TypeError:
550 pass
551 else:
552 self.fail('Bytes should not work as keyword argument names')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000553 # keyword only argument tests
554 def pos0key1(*, key): return key
555 pos0key1(key=100)
556 def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
557 pos2key2(1, 2, k1=100)
558 pos2key2(1, 2, k1=100, k2=200)
559 pos2key2(1, 2, k2=100, k1=200)
560 def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
561 pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
562 pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
563
Robert Collinsdf395992015-08-12 08:00:06 +1200564 self.assertRaises(SyntaxError, eval, "def f(*): pass")
565 self.assertRaises(SyntaxError, eval, "def f(*,): pass")
566 self.assertRaises(SyntaxError, eval, "def f(*, **kwds): pass")
567
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000568 # keyword arguments after *arglist
569 def f(*args, **kwargs):
570 return args, kwargs
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000571 self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000572 {'x':2, 'y':5}))
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400573 self.assertEqual(f(1, *(2,3), 4), ((1, 2, 3, 4), {}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000574 self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400575 self.assertEqual(f(**{'eggs':'scrambled', 'spam':'fried'}),
576 ((), {'eggs':'scrambled', 'spam':'fried'}))
577 self.assertEqual(f(spam='fried', **{'eggs':'scrambled'}),
578 ((), {'eggs':'scrambled', 'spam':'fried'}))
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000579
Serhiy Storchaka0cc99c82018-01-04 10:36:35 +0200580 # Check ast errors in *args and *kwargs
581 check_syntax_error(self, "f(*g(1=2))")
582 check_syntax_error(self, "f(**g(1=2))")
583
Neal Norwitzc1505362006-12-28 06:47:50 +0000584 # argument annotation tests
585 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000586 self.assertEqual(f.__annotations__, {'return': list})
Zachary Warece17f762015-08-01 21:55:36 -0500587 def f(x: int): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000588 self.assertEqual(f.__annotations__, {'x': int})
Zachary Warece17f762015-08-01 21:55:36 -0500589 def f(*x: str): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000590 self.assertEqual(f.__annotations__, {'x': str})
Zachary Warece17f762015-08-01 21:55:36 -0500591 def f(**x: float): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000592 self.assertEqual(f.__annotations__, {'x': float})
Zachary Warece17f762015-08-01 21:55:36 -0500593 def f(x, y: 1+2): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000594 self.assertEqual(f.__annotations__, {'y': 3})
Zachary Warece17f762015-08-01 21:55:36 -0500595 def f(a, b: 1, c: 2, d): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000596 self.assertEqual(f.__annotations__, {'b': 1, 'c': 2})
Zachary Warece17f762015-08-01 21:55:36 -0500597 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6): pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000598 self.assertEqual(f.__annotations__,
Zachary Warece17f762015-08-01 21:55:36 -0500599 {'b': 1, 'c': 2, 'e': 3, 'g': 6})
600 def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6, h: 7, i=8, j: 9 = 10,
601 **k: 11) -> 12: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000602 self.assertEqual(f.__annotations__,
Zachary Warece17f762015-08-01 21:55:36 -0500603 {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
604 'k': 11, 'return': 12})
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500605 # Check for issue #20625 -- annotations mangling
606 class Spam:
Zachary Warece17f762015-08-01 21:55:36 -0500607 def f(self, *, __kw: 1):
Yury Selivanov34ce99f2014-02-18 12:49:41 -0500608 pass
609 class Ham(Spam): pass
Benjamin Petersonbcfcfc52014-03-09 20:59:24 -0500610 self.assertEqual(Spam.f.__annotations__, {'_Spam__kw': 1})
611 self.assertEqual(Ham.f.__annotations__, {'_Spam__kw': 1})
Nick Coghlan71011e22007-04-23 11:05:01 +0000612 # Check for SF Bug #1697248 - mixing decorators and a return annotation
613 def null(x): return x
614 @null
615 def f(x) -> list: pass
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000616 self.assertEqual(f.__annotations__, {'return': list})
Nick Coghlan71011e22007-04-23 11:05:01 +0000617
Serhiy Storchaka64204de2016-06-12 17:36:24 +0300618 # test closures with a variety of opargs
Guido van Rossum0240b922007-02-26 21:23:50 +0000619 closure = 1
620 def f(): return closure
621 def f(x=1): return closure
622 def f(*, k=1): return closure
623 def f() -> int: return closure
Neal Norwitzc1505362006-12-28 06:47:50 +0000624
Robert Collinsdf395992015-08-12 08:00:06 +1200625 # Check trailing commas are permitted in funcdef argument list
626 def f(a,): pass
627 def f(*args,): pass
628 def f(**kwds,): pass
629 def f(a, *args,): pass
630 def f(a, **kwds,): pass
631 def f(*args, b,): pass
632 def f(*, b,): pass
633 def f(*args, **kwds,): pass
634 def f(a, *args, b,): pass
635 def f(a, *, b,): pass
636 def f(a, *args, **kwds,): pass
637 def f(*args, b, **kwds,): pass
638 def f(*, b, **kwds,): pass
639 def f(a, *args, b, **kwds,): pass
640 def f(a, *, b, **kwds,): pass
641
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500642 def test_lambdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000643 ### lambdef: 'lambda' [varargslist] ':' test
644 l1 = lambda : 0
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000645 self.assertEqual(l1(), 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000646 l2 = lambda : a[d] # XXX just testing the expression
Guido van Rossume2a383d2007-01-15 16:59:06 +0000647 l3 = lambda : [2 < x for x in [-1, 3, 0]]
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000648 self.assertEqual(l3(), [0, 1, 0])
Thomas Wouters89f507f2006-12-13 04:49:30 +0000649 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000650 self.assertEqual(l4(), 1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000651 l5 = lambda x, y, z=2: x + y + z
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000652 self.assertEqual(l5(1, 2), 5)
653 self.assertEqual(l5(1, 2, 3), 6)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000654 check_syntax_error(self, "lambda x: x = 2")
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000655 check_syntax_error(self, "lambda (None,): None")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000656 l6 = lambda x, y, *, k=20: x+y+k
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000657 self.assertEqual(l6(1,2), 1+2+20)
658 self.assertEqual(l6(1,2,k=10), 1+2+10)
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000659
Robert Collinsdf395992015-08-12 08:00:06 +1200660 # check that trailing commas are permitted
661 l10 = lambda a,: 0
662 l11 = lambda *args,: 0
663 l12 = lambda **kwds,: 0
664 l13 = lambda a, *args,: 0
665 l14 = lambda a, **kwds,: 0
666 l15 = lambda *args, b,: 0
667 l16 = lambda *, b,: 0
668 l17 = lambda *args, **kwds,: 0
669 l18 = lambda a, *args, b,: 0
670 l19 = lambda a, *, b,: 0
671 l20 = lambda a, *args, **kwds,: 0
672 l21 = lambda *args, b, **kwds,: 0
673 l22 = lambda *, b, **kwds,: 0
674 l23 = lambda a, *args, b, **kwds,: 0
675 l24 = lambda a, *, b, **kwds,: 0
676
Guido van Rossumb31c7f71993-11-11 10:31:23 +0000677
Thomas Wouters89f507f2006-12-13 04:49:30 +0000678 ### stmt: simple_stmt | compound_stmt
679 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000680
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500681 def test_simple_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000682 ### simple_stmt: small_stmt (';' small_stmt)* [';']
683 x = 1; pass; del x
684 def foo():
Ezio Melotti13925002011-03-16 11:05:33 +0200685 # verify statements that end with semi-colons
Thomas Wouters89f507f2006-12-13 04:49:30 +0000686 x = 1; pass; del x;
687 foo()
Georg Brandl52318d62006-09-06 07:06:08 +0000688
Guido van Rossumd8faa362007-04-27 19:54:29 +0000689 ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
Thomas Wouters89f507f2006-12-13 04:49:30 +0000690 # Tested below
Georg Brandl52318d62006-09-06 07:06:08 +0000691
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500692 def test_expr_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000693 # (exprlist '=')* exprlist
Victor Stinner15a30952016-02-08 22:45:06 +0100694 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000695 1, 2, 3
696 x = 1
697 x = 1, 2, 3
698 x = y = z = 1, 2, 3
699 x, y, z = 1, 2, 3
700 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
Guido van Rossum3bead091992-01-27 17:00:37 +0000701
Thomas Wouters89f507f2006-12-13 04:49:30 +0000702 check_syntax_error(self, "x + 1 = 1")
703 check_syntax_error(self, "a + 1 = b + 2")
Guido van Rossum3bead091992-01-27 17:00:37 +0000704
Nick Coghlan5b1fdc12014-06-16 19:48:02 +1000705 # Check the heuristic for print & exec covers significant cases
706 # As well as placing some limits on false positives
707 def test_former_statements_refer_to_builtins(self):
708 keywords = "print", "exec"
709 # Cases where we want the custom error
710 cases = [
711 "{} foo",
712 "{} {{1:foo}}",
713 "if 1: {} foo",
714 "if 1: {} {{1:foo}}",
715 "if 1:\n {} foo",
716 "if 1:\n {} {{1:foo}}",
717 ]
718 for keyword in keywords:
719 custom_msg = "call to '{}'".format(keyword)
720 for case in cases:
721 source = case.format(keyword)
722 with self.subTest(source=source):
723 with self.assertRaisesRegex(SyntaxError, custom_msg):
724 exec(source)
725 source = source.replace("foo", "(foo.)")
726 with self.subTest(source=source):
727 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
728 exec(source)
729
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500730 def test_del_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000731 # 'del' exprlist
732 abc = [1,2,3]
733 x, y, z = abc
734 xyz = x, y, z
Barry Warsaw7e3e1c12000-10-11 21:26:03 +0000735
Thomas Wouters89f507f2006-12-13 04:49:30 +0000736 del abc
737 del x, y, (z, xyz)
Barry Warsaw9182b452000-08-29 04:57:10 +0000738
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500739 def test_pass_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000740 # 'pass'
741 pass
Barry Warsaw9182b452000-08-29 04:57:10 +0000742
Thomas Wouters89f507f2006-12-13 04:49:30 +0000743 # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
744 # Tested below
Barry Warsaw9182b452000-08-29 04:57:10 +0000745
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500746 def test_break_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000747 # 'break'
748 while 1: break
Barry Warsaw9182b452000-08-29 04:57:10 +0000749
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500750 def test_continue_stmt(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000751 # 'continue'
752 i = 1
753 while i: i = 0; continue
Barry Warsaw9182b452000-08-29 04:57:10 +0000754
Thomas Wouters89f507f2006-12-13 04:49:30 +0000755 msg = ""
756 while not msg:
757 msg = "ok"
758 try:
759 continue
760 msg = "continue failed to continue inside try"
761 except:
762 msg = "continue inside try called except block"
763 if msg != "ok":
764 self.fail(msg)
Barry Warsawefc92ee2000-08-21 15:46:50 +0000765
Thomas Wouters89f507f2006-12-13 04:49:30 +0000766 msg = ""
767 while not msg:
768 msg = "finally block not called"
769 try:
770 continue
771 finally:
772 msg = "ok"
773 if msg != "ok":
774 self.fail(msg)
Guido van Rossum3bead091992-01-27 17:00:37 +0000775
Thomas Wouters89f507f2006-12-13 04:49:30 +0000776 def test_break_continue_loop(self):
777 # This test warrants an explanation. It is a test specifically for SF bugs
778 # #463359 and #462937. The bug is that a 'break' statement executed or
779 # exception raised inside a try/except inside a loop, *after* a continue
780 # statement has been executed in that loop, will cause the wrong number of
781 # arguments to be popped off the stack and the instruction pointer reset to
782 # a very small number (usually 0.) Because of this, the following test
783 # *must* written as a function, and the tracking vars *must* be function
784 # arguments with default values. Otherwise, the test will loop and loop.
Guido van Rossum3bead091992-01-27 17:00:37 +0000785
Thomas Wouters89f507f2006-12-13 04:49:30 +0000786 def test_inner(extra_burning_oil = 1, count=0):
787 big_hippo = 2
788 while big_hippo:
789 count += 1
790 try:
791 if extra_burning_oil and big_hippo == 1:
792 extra_burning_oil -= 1
793 break
794 big_hippo -= 1
795 continue
796 except:
797 raise
798 if count > 2 or big_hippo != 1:
799 self.fail("continue then break in try/except in loop broken!")
800 test_inner()
Guido van Rossum3bead091992-01-27 17:00:37 +0000801
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500802 def test_return(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000803 # 'return' [testlist]
804 def g1(): return
805 def g2(): return 1
806 g1()
807 x = g2()
808 check_syntax_error(self, "class foo:return 1")
Guido van Rossum3bead091992-01-27 17:00:37 +0000809
Serhiy Storchaka7cc42c32018-01-02 02:38:35 +0200810 def test_break_in_finally(self):
811 count = 0
812 while count < 2:
813 count += 1
814 try:
815 pass
816 finally:
817 break
818 self.assertEqual(count, 1)
819
820 count = 0
821 while count < 2:
822 count += 1
823 try:
824 continue
825 finally:
826 break
827 self.assertEqual(count, 1)
828
829 count = 0
830 while count < 2:
831 count += 1
832 try:
833 1/0
834 finally:
835 break
836 self.assertEqual(count, 1)
837
838 for count in [0, 1]:
839 self.assertEqual(count, 0)
840 try:
841 pass
842 finally:
843 break
844 self.assertEqual(count, 0)
845
846 for count in [0, 1]:
847 self.assertEqual(count, 0)
848 try:
849 continue
850 finally:
851 break
852 self.assertEqual(count, 0)
853
854 for count in [0, 1]:
855 self.assertEqual(count, 0)
856 try:
857 1/0
858 finally:
859 break
860 self.assertEqual(count, 0)
861
862 def test_return_in_finally(self):
863 def g1():
864 try:
865 pass
866 finally:
867 return 1
868 self.assertEqual(g1(), 1)
869
870 def g2():
871 try:
872 return 2
873 finally:
874 return 3
875 self.assertEqual(g2(), 3)
876
877 def g3():
878 try:
879 1/0
880 finally:
881 return 4
882 self.assertEqual(g3(), 4)
883
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500884 def test_yield(self):
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000885 # Allowed as standalone statement
886 def g(): yield 1
887 def g(): yield from ()
888 # Allowed as RHS of assignment
889 def g(): x = yield 1
890 def g(): x = yield from ()
891 # Ordinary yield accepts implicit tuples
892 def g(): yield 1, 1
893 def g(): x = yield 1, 1
894 # 'yield from' does not
895 check_syntax_error(self, "def g(): yield from (), 1")
896 check_syntax_error(self, "def g(): x = yield from (), 1")
897 # Requires parentheses as subexpression
898 def g(): 1, (yield 1)
899 def g(): 1, (yield from ())
900 check_syntax_error(self, "def g(): 1, yield 1")
901 check_syntax_error(self, "def g(): 1, yield from ()")
902 # Requires parentheses as call argument
903 def g(): f((yield 1))
904 def g(): f((yield 1), 1)
905 def g(): f((yield from ()))
906 def g(): f((yield from ()), 1)
907 check_syntax_error(self, "def g(): f(yield 1)")
908 check_syntax_error(self, "def g(): f(yield 1, 1)")
909 check_syntax_error(self, "def g(): f(yield from ())")
910 check_syntax_error(self, "def g(): f(yield from (), 1)")
911 # Not allowed at top level
912 check_syntax_error(self, "yield")
913 check_syntax_error(self, "yield from")
914 # Not allowed at class scope
Thomas Wouters89f507f2006-12-13 04:49:30 +0000915 check_syntax_error(self, "class foo:yield 1")
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000916 check_syntax_error(self, "class foo:yield from ()")
Yury Selivanovf315c1c2015-07-23 09:10:44 +0300917 # Check annotation refleak on SyntaxError
918 check_syntax_error(self, "def g(a:(yield)): pass")
Guido van Rossum3bead091992-01-27 17:00:37 +0000919
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200920 def test_yield_in_comprehensions(self):
921 # Check yield in comprehensions
922 def g(): [x for x in [(yield 1)]]
923 def g(): [x for x in [(yield from ())]]
924
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200925 check = self.check_syntax_error
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200926 check("def g(): [(yield x) for x in ()]",
927 "'yield' inside list comprehension")
928 check("def g(): [x for x in () if not (yield x)]",
929 "'yield' inside list comprehension")
930 check("def g(): [y for x in () for y in [(yield x)]]",
931 "'yield' inside list comprehension")
932 check("def g(): {(yield x) for x in ()}",
933 "'yield' inside set comprehension")
934 check("def g(): {(yield x): x for x in ()}",
935 "'yield' inside dict comprehension")
936 check("def g(): {x: (yield x) for x in ()}",
937 "'yield' inside dict comprehension")
938 check("def g(): ((yield x) for x in ())",
939 "'yield' inside generator expression")
940 check("def g(): [(yield from x) for x in ()]",
941 "'yield' inside list comprehension")
942 check("class C: [(yield x) for x in ()]",
943 "'yield' inside list comprehension")
944 check("[(yield x) for x in ()]",
945 "'yield' inside list comprehension")
946
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500947 def test_raise(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000948 # 'raise' test [',' test]
Collin Winter828f04a2007-08-31 00:04:24 +0000949 try: raise RuntimeError('just testing')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000950 except RuntimeError: pass
951 try: raise KeyboardInterrupt
952 except KeyboardInterrupt: pass
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000953
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500954 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000955 # 'import' dotted_as_names
956 import sys
957 import time, sys
958 # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
959 from time import time
960 from time import (time)
961 # not testable inside a function, but already done at top of the module
962 # from sys import *
963 from sys import path, argv
964 from sys import (path, argv)
965 from sys import (path, argv,)
Tim Peters10fb3862001-02-09 20:17:14 +0000966
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500967 def test_global(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000968 # 'global' NAME (',' NAME)*
969 global a
970 global a, b
971 global one, two, three, four, five, six, seven, eight, nine, ten
Thomas Wouters80d373c2001-09-26 12:43:39 +0000972
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500973 def test_nonlocal(self):
Benjamin Petersona933e522008-10-24 22:16:39 +0000974 # 'nonlocal' NAME (',' NAME)*
975 x = 0
976 y = 0
977 def f():
978 nonlocal x
979 nonlocal x, y
980
Benjamin Petersonc8507bf2011-05-30 10:52:48 -0500981 def test_assert(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000982 # assertTruestmt: 'assert' test [',' test]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000983 assert 1
984 assert 1, 1
985 assert lambda x:x
986 assert 1, lambda x:x+1
Ezio Melotti6cc5bf72011-12-02 18:22:52 +0200987
988 try:
989 assert True
990 except AssertionError as e:
991 self.fail("'assert True' should not have raised an AssertionError")
992
993 try:
994 assert True, 'this should always pass'
995 except AssertionError as e:
996 self.fail("'assert True, msg' should not have "
997 "raised an AssertionError")
998
999 # these tests fail if python is run with -O, so check __debug__
1000 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
1001 def testAssert2(self):
Thomas Wouters80d373c2001-09-26 12:43:39 +00001002 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001003 assert 0, "msg"
Guido van Rossumb940e112007-01-10 16:19:56 +00001004 except AssertionError as e:
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001005 self.assertEqual(e.args[0], "msg")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001006 else:
Ezio Melotti6cc5bf72011-12-02 18:22:52 +02001007 self.fail("AssertionError not raised by assert 0")
1008
1009 try:
1010 assert False
1011 except AssertionError as e:
1012 self.assertEqual(len(e.args), 0)
1013 else:
1014 self.fail("AssertionError not raised by 'assert False'")
1015
Thomas Wouters80d373c2001-09-26 12:43:39 +00001016
Thomas Wouters89f507f2006-12-13 04:49:30 +00001017 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
1018 # Tested below
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001019
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001020 def test_if(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001021 # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
1022 if 1: pass
1023 if 1: pass
1024 else: pass
1025 if 0: pass
1026 elif 0: pass
1027 if 0: pass
1028 elif 0: pass
1029 elif 0: pass
1030 elif 0: pass
1031 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001032
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001033 def test_while(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001034 # 'while' test ':' suite ['else' ':' suite]
1035 while 0: pass
1036 while 0: pass
1037 else: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001038
Christian Heimes969fe572008-01-25 11:23:10 +00001039 # Issue1920: "while 0" is optimized away,
1040 # ensure that the "else" clause is still present.
1041 x = 0
1042 while 0:
1043 x = 1
1044 else:
1045 x = 2
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001046 self.assertEqual(x, 2)
Christian Heimes969fe572008-01-25 11:23:10 +00001047
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001048 def test_for(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001049 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
1050 for i in 1, 2, 3: pass
1051 for i, j, k in (): pass
1052 else: pass
1053 class Squares:
1054 def __init__(self, max):
1055 self.max = max
1056 self.sofar = []
1057 def __len__(self): return len(self.sofar)
1058 def __getitem__(self, i):
1059 if not 0 <= i < self.max: raise IndexError
1060 n = len(self.sofar)
1061 while n <= i:
1062 self.sofar.append(n*n)
1063 n = n+1
1064 return self.sofar[i]
1065 n = 0
1066 for x in Squares(10): n = n+x
1067 if n != 285:
1068 self.fail('for over growing sequence')
Guido van Rossum3bead091992-01-27 17:00:37 +00001069
Thomas Wouters89f507f2006-12-13 04:49:30 +00001070 result = []
1071 for x, in [(1,), (2,), (3,)]:
1072 result.append(x)
1073 self.assertEqual(result, [1, 2, 3])
Guido van Rossum3bead091992-01-27 17:00:37 +00001074
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001075 def test_try(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001076 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
1077 ### | 'try' ':' suite 'finally' ':' suite
Guido van Rossumb940e112007-01-10 16:19:56 +00001078 ### except_clause: 'except' [expr ['as' expr]]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001079 try:
1080 1/0
1081 except ZeroDivisionError:
1082 pass
1083 else:
1084 pass
1085 try: 1/0
1086 except EOFError: pass
Guido van Rossumb940e112007-01-10 16:19:56 +00001087 except TypeError as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +00001088 except: pass
1089 else: pass
1090 try: 1/0
1091 except (EOFError, TypeError, ZeroDivisionError): pass
1092 try: 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +00001093 except (EOFError, TypeError, ZeroDivisionError) as msg: pass
Thomas Wouters89f507f2006-12-13 04:49:30 +00001094 try: pass
1095 finally: pass
Jeremy Hyltonf828e2d2001-02-19 15:54:52 +00001096
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001097 def test_suite(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001098 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
1099 if 1: pass
1100 if 1:
1101 pass
1102 if 1:
1103 #
1104 #
1105 #
1106 pass
1107 pass
1108 #
1109 pass
1110 #
Guido van Rossum3bead091992-01-27 17:00:37 +00001111
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001112 def test_test(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001113 ### and_test ('or' and_test)*
1114 ### and_test: not_test ('and' not_test)*
1115 ### not_test: 'not' not_test | comparison
1116 if not 1: pass
1117 if 1 and 1: pass
1118 if 1 or 1: pass
1119 if not not not 1: pass
1120 if not 1 and 1 and 1: pass
1121 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
Guido van Rossum3bead091992-01-27 17:00:37 +00001122
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001123 def test_comparison(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001124 ### comparison: expr (comp_op expr)*
1125 ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
1126 if 1: pass
1127 x = (1 == 1)
1128 if 1 == 1: pass
1129 if 1 != 1: pass
1130 if 1 < 1: pass
1131 if 1 > 1: pass
1132 if 1 <= 1: pass
1133 if 1 >= 1: pass
1134 if 1 is 1: pass
1135 if 1 is not 1: pass
1136 if 1 in (): pass
1137 if 1 not in (): pass
1138 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 +00001139
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001140 def test_binary_mask_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001141 x = 1 & 1
1142 x = 1 ^ 1
1143 x = 1 | 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001144
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001145 def test_shift_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001146 x = 1 << 1
1147 x = 1 >> 1
1148 x = 1 << 1 >> 1
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001149
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001150 def test_additive_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001151 x = 1
1152 x = 1 + 1
1153 x = 1 - 1 - 1
1154 x = 1 - 1 + 1 - 1 + 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001155
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001156 def test_multiplicative_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001157 x = 1 * 1
1158 x = 1 / 1
1159 x = 1 % 1
1160 x = 1 / 1 * 1 % 1
Guido van Rossum3bead091992-01-27 17:00:37 +00001161
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001162 def test_unary_ops(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001163 x = +1
1164 x = -1
1165 x = ~1
1166 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
1167 x = -1*1/1 + 1*1 - ---1*1
Guido van Rossum3bead091992-01-27 17:00:37 +00001168
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001169 def test_selectors(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001170 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
1171 ### subscript: expr | [expr] ':' [expr]
Guido van Rossum3bead091992-01-27 17:00:37 +00001172
Thomas Wouters89f507f2006-12-13 04:49:30 +00001173 import sys, time
1174 c = sys.path[0]
1175 x = time.time()
1176 x = sys.modules['time'].time()
1177 a = '01234'
1178 c = a[0]
1179 c = a[-1]
1180 s = a[0:5]
1181 s = a[:5]
1182 s = a[0:]
1183 s = a[:]
1184 s = a[-5:]
1185 s = a[:-1]
1186 s = a[-4:-3]
1187 # A rough test of SF bug 1333982. http://python.org/sf/1333982
1188 # The testing here is fairly incomplete.
1189 # Test cases should include: commas with 1 and 2 colons
1190 d = {}
1191 d[1] = 1
1192 d[1,] = 2
1193 d[1,2] = 3
1194 d[1,2,3] = 4
1195 L = list(d)
Serhiy Storchaka0cc99c82018-01-04 10:36:35 +02001196 L.sort(key=lambda x: (type(x).__name__, x))
Florent Xicluna9b86b9a2010-03-19 19:00:44 +00001197 self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
Guido van Rossum3bead091992-01-27 17:00:37 +00001198
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001199 def test_atoms(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001200 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
1201 ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
Guido van Rossum3bead091992-01-27 17:00:37 +00001202
Thomas Wouters89f507f2006-12-13 04:49:30 +00001203 x = (1)
1204 x = (1 or 2 or 3)
1205 x = (1 or 2 or 3, 2, 3)
Guido van Rossum3bead091992-01-27 17:00:37 +00001206
Thomas Wouters89f507f2006-12-13 04:49:30 +00001207 x = []
1208 x = [1]
1209 x = [1 or 2 or 3]
1210 x = [1 or 2 or 3, 2, 3]
1211 x = []
Guido van Rossum3bead091992-01-27 17:00:37 +00001212
Thomas Wouters89f507f2006-12-13 04:49:30 +00001213 x = {}
1214 x = {'one': 1}
1215 x = {'one': 1,}
1216 x = {'one' or 'two': 1 or 2}
1217 x = {'one': 1, 'two': 2}
1218 x = {'one': 1, 'two': 2,}
1219 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
Guido van Rossum3bead091992-01-27 17:00:37 +00001220
Thomas Wouters89f507f2006-12-13 04:49:30 +00001221 x = {'one'}
1222 x = {'one', 1,}
1223 x = {'one', 'two', 'three'}
1224 x = {2, 3, 4,}
1225
1226 x = x
1227 x = 'x'
1228 x = 123
1229
1230 ### exprlist: expr (',' expr)* [',']
1231 ### testlist: test (',' test)* [',']
1232 # These have been exercised enough above
1233
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001234 def test_classdef(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001235 # 'class' NAME ['(' [testlist] ')'] ':' suite
1236 class B: pass
1237 class B2(): pass
1238 class C1(B): pass
1239 class C2(B): pass
1240 class D(C1, C2, B): pass
1241 class C:
1242 def meth1(self): pass
1243 def meth2(self, arg): pass
1244 def meth3(self, a1, a2): pass
1245
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001246 # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
1247 # decorators: decorator+
1248 # decorated: decorators (classdef | funcdef)
1249 def class_decorator(x): return x
1250 @class_decorator
1251 class G: pass
1252
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001253 def test_dictcomps(self):
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001254 # dictorsetmaker: ( (test ':' test (comp_for |
1255 # (',' test ':' test)* [','])) |
1256 # (test (comp_for | (',' test)* [','])) )
1257 nums = [1, 2, 3]
1258 self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
1259
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001260 def test_listcomps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001261 # list comprehension tests
1262 nums = [1, 2, 3, 4, 5]
1263 strs = ["Apple", "Banana", "Coconut"]
1264 spcs = [" Apple", " Banana ", "Coco nut "]
1265
1266 self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
1267 self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
1268 self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
1269 self.assertEqual([(i, s) for i in nums for s in strs],
1270 [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
1271 (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
1272 (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
1273 (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
1274 (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
1275 self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
1276 [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
1277 (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
1278 (5, 'Banana'), (5, 'Coconut')])
1279 self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
1280 [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
1281
1282 def test_in_func(l):
1283 return [0 < x < 3 for x in l if x > 2]
1284
1285 self.assertEqual(test_in_func(nums), [False, False, False])
1286
1287 def test_nested_front():
1288 self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
1289 [[1, 2], [3, 4], [5, 6]])
1290
1291 test_nested_front()
1292
1293 check_syntax_error(self, "[i, s for i in nums for s in strs]")
1294 check_syntax_error(self, "[x if y]")
1295
1296 suppliers = [
1297 (1, "Boeing"),
1298 (2, "Ford"),
1299 (3, "Macdonalds")
1300 ]
1301
1302 parts = [
1303 (10, "Airliner"),
1304 (20, "Engine"),
1305 (30, "Cheeseburger")
1306 ]
1307
1308 suppart = [
1309 (1, 10), (1, 20), (2, 20), (3, 30)
1310 ]
1311
1312 x = [
1313 (sname, pname)
1314 for (sno, sname) in suppliers
1315 for (pno, pname) in parts
1316 for (sp_sno, sp_pno) in suppart
1317 if sno == sp_sno and pno == sp_pno
1318 ]
1319
1320 self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
1321 ('Macdonalds', 'Cheeseburger')])
1322
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001323 def test_genexps(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001324 # generator expression tests
1325 g = ([x for x in range(10)] for x in range(1))
Georg Brandla18af4e2007-04-21 15:47:16 +00001326 self.assertEqual(next(g), [x for x in range(10)])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001327 try:
Georg Brandla18af4e2007-04-21 15:47:16 +00001328 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001329 self.fail('should produce StopIteration exception')
1330 except StopIteration:
1331 pass
1332
1333 a = 1
1334 try:
1335 g = (a for d in a)
Georg Brandla18af4e2007-04-21 15:47:16 +00001336 next(g)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001337 self.fail('should produce TypeError')
1338 except TypeError:
1339 pass
1340
1341 self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
1342 self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
1343
1344 a = [x for x in range(10)]
1345 b = (x for x in (y for y in a))
1346 self.assertEqual(sum(b), sum([x for x in range(10)]))
1347
1348 self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
1349 self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
1350 self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
1351 self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
1352 self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
1353 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)]))
1354 self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
1355 check_syntax_error(self, "foo(x for x in range(10), 100)")
1356 check_syntax_error(self, "foo(100, x for x in range(10))")
1357
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001358 def test_comprehension_specials(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001359 # test for outmost iterable precomputation
1360 x = 10; g = (i for i in range(x)); x = 5
1361 self.assertEqual(len(list(g)), 10)
1362
1363 # This should hold, since we're only precomputing outmost iterable.
1364 x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
1365 x = 5; t = True;
1366 self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
1367
1368 # Grammar allows multiple adjacent 'if's in listcomps and genexps,
1369 # even though it's silly. Make sure it works (ifelse broke this.)
1370 self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
1371 self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
1372
1373 # verify unpacking single element tuples in listcomp/genexp.
1374 self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
1375 self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
1376
Benjamin Petersonf17ab892009-05-29 21:55:57 +00001377 def test_with_statement(self):
1378 class manager(object):
1379 def __enter__(self):
1380 return (1, 2)
1381 def __exit__(self, *args):
1382 pass
1383
1384 with manager():
1385 pass
1386 with manager() as x:
1387 pass
1388 with manager() as (x, y):
1389 pass
1390 with manager(), manager():
1391 pass
1392 with manager() as x, manager() as y:
1393 pass
1394 with manager() as x, manager():
1395 pass
1396
Benjamin Petersonc8507bf2011-05-30 10:52:48 -05001397 def test_if_else_expr(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +00001398 # Test ifelse expressions in various cases
1399 def _checkeval(msg, ret):
1400 "helper to check that evaluation of expressions is done correctly"
Victor Stinnerc6ec54d2016-04-12 18:33:41 +02001401 print(msg)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001402 return ret
1403
Nick Coghlan650f0d02007-04-15 12:05:43 +00001404 # the next line is not allowed anymore
1405 #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
Thomas Wouters89f507f2006-12-13 04:49:30 +00001406 self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
1407 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])
1408 self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
1409 self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
1410 self.assertEqual((5 and 6 if 0 else 1), 1)
1411 self.assertEqual(((5 and 6) if 0 else 1), 1)
1412 self.assertEqual((5 and (6 if 1 else 1)), 6)
1413 self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
1414 self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
1415 self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
1416 self.assertEqual((not 5 if 1 else 1), False)
1417 self.assertEqual((not 5 if 0 else 1), 1)
1418 self.assertEqual((6 + 1 if 1 else 2), 7)
1419 self.assertEqual((6 - 1 if 1 else 2), 5)
1420 self.assertEqual((6 * 2 if 1 else 4), 12)
1421 self.assertEqual((6 / 2 if 1 else 3), 3)
1422 self.assertEqual((6 < 4 if 0 else 2), 2)
Jeremy Hylton7b03bad2006-02-28 17:46:23 +00001423
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001424 def test_paren_evaluation(self):
1425 self.assertEqual(16 // (4 // 2), 8)
1426 self.assertEqual((16 // 4) // 2, 2)
1427 self.assertEqual(16 // 4 // 2, 2)
1428 self.assertTrue(False is (2 is 3))
1429 self.assertFalse((False is 2) is 3)
1430 self.assertFalse(False is 2 is 3)
1431
Benjamin Petersond51374e2014-04-09 23:55:56 -04001432 def test_matrix_mul(self):
1433 # This is not intended to be a comprehensive test, rather just to be few
1434 # samples of the @ operator in test_grammar.py.
1435 class M:
1436 def __matmul__(self, o):
1437 return 4
1438 def __imatmul__(self, o):
1439 self.other = o
1440 return self
1441 m = M()
1442 self.assertEqual(m @ m, 4)
1443 m @= 42
1444 self.assertEqual(m.other, 42)
1445
Yury Selivanov75445082015-05-11 22:57:16 -04001446 def test_async_await(self):
Yury Selivanov75445082015-05-11 22:57:16 -04001447 async def test():
1448 def sum():
Yury Selivanov8fb307c2015-07-22 13:33:45 +03001449 pass
Yury Selivanov75445082015-05-11 22:57:16 -04001450 if 1:
1451 await someobj()
1452
1453 self.assertEqual(test.__name__, 'test')
1454 self.assertTrue(bool(test.__code__.co_flags & inspect.CO_COROUTINE))
1455
1456 def decorator(func):
1457 setattr(func, '_marked', True)
1458 return func
1459
1460 @decorator
1461 async def test2():
1462 return 22
1463 self.assertTrue(test2._marked)
1464 self.assertEqual(test2.__name__, 'test2')
1465 self.assertTrue(bool(test2.__code__.co_flags & inspect.CO_COROUTINE))
1466
1467 def test_async_for(self):
1468 class Done(Exception): pass
1469
1470 class AIter:
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001471 def __aiter__(self):
Yury Selivanov75445082015-05-11 22:57:16 -04001472 return self
1473 async def __anext__(self):
1474 raise StopAsyncIteration
1475
1476 async def foo():
1477 async for i in AIter():
1478 pass
1479 async for i, j in AIter():
1480 pass
1481 async for i in AIter():
1482 pass
1483 else:
1484 pass
1485 raise Done
1486
1487 with self.assertRaises(Done):
1488 foo().send(None)
1489
1490 def test_async_with(self):
1491 class Done(Exception): pass
1492
1493 class manager:
1494 async def __aenter__(self):
1495 return (1, 2)
1496 async def __aexit__(self, *exc):
1497 return False
1498
1499 async def foo():
1500 async with manager():
1501 pass
1502 async with manager() as x:
1503 pass
1504 async with manager() as (x, y):
1505 pass
1506 async with manager(), manager():
1507 pass
1508 async with manager() as x, manager() as y:
1509 pass
1510 async with manager() as x, manager():
1511 pass
1512 raise Done
1513
1514 with self.assertRaises(Done):
1515 foo().send(None)
1516
Guido van Rossum3bead091992-01-27 17:00:37 +00001517
Thomas Wouters89f507f2006-12-13 04:49:30 +00001518if __name__ == '__main__':
Zachary Ware38c707e2015-04-13 15:00:43 -05001519 unittest.main()