Debian Codegraph @

lib-python/3/test/test_future_stmt/test_future.py

raw symbols SCIP
1 # Test various flavors of legal and illegal future statements
2
3 import __future__
4 import ast
5 import unittest
6 from test import support
7 from test.support import import_helper
8 from textwrap import dedent
9 import os
10 import re
11 import sys
12
13 rx = re.compile(r'\((\S+).py, line (\d+)')
14
15 def get_error_location(msg):
16 mo = rx.search(str(msg))
17 return mo.group(1, 2)
18
19 class FutureTest(unittest.TestCase):
20
21 def check_syntax_error(self, err, basename, lineno, offset=1):
22 #PyPy change: PyPy may format multi-line spans as "lines X-Y" instead of "line X"
23 err_str = str(err)
24 self.assertTrue(
25 '%s.py, line %d' % (basename, lineno) in err_str or
26 '%s.py, lines %d-' % (basename, lineno) in err_str,
27 '%r not found in %r' % ('%s.py, line(s) %d' % (basename, lineno), err_str)
28 )
29 self.assertEqual(os.path.basename(err.filename), basename + '.py')
30 self.assertEqual(err.lineno, lineno)
31 self.assertEqual(err.offset, offset)
32
33 def test_future1(self):
34 with import_helper.CleanImport('test.test_future_stmt.future_test1'):
35 from test.test_future_stmt import future_test1
36 self.assertEqual(future_test1.result, 6)
37
38 def test_future2(self):
39 with import_helper.CleanImport('test.test_future_stmt.future_test2'):
40 from test.test_future_stmt import future_test2
41 self.assertEqual(future_test2.result, 6)
42
43 def test_future_single_import(self):
44 with import_helper.CleanImport(
45 'test.test_future_stmt.test_future_single_import',
46 ):
47 from test.test_future_stmt import test_future_single_import
48
49 def test_future_multiple_imports(self):
50 with import_helper.CleanImport(
51 'test.test_future_stmt.test_future_multiple_imports',
52 ):
53 from test.test_future_stmt import test_future_multiple_imports
54
55 def test_future_multiple_features(self):
56 with import_helper.CleanImport(
57 "test.test_future_stmt.test_future_multiple_features",
58 ):
59 from test.test_future_stmt import test_future_multiple_features
60
61 def test_badfuture3(self):
62 with self.assertRaises(SyntaxError) as cm:
63 from test.test_future_stmt import badsyntax_future3
64 self.check_syntax_error(cm.exception, "badsyntax_future3", 3)
65
66 def test_badfuture4(self):
67 with self.assertRaises(SyntaxError) as cm:
68 from test.test_future_stmt import badsyntax_future4
69 self.check_syntax_error(cm.exception, "badsyntax_future4", 3)
70
71 def test_badfuture5(self):
72 with self.assertRaises(SyntaxError) as cm:
73 from test.test_future_stmt import badsyntax_future5
74 self.check_syntax_error(cm.exception, "badsyntax_future5", 4)
75
76 def test_badfuture6(self):
77 with self.assertRaises(SyntaxError) as cm:
78 from test.test_future_stmt import badsyntax_future6
79 self.check_syntax_error(cm.exception, "badsyntax_future6", 3)
80
81 def test_badfuture7(self):
82 with self.assertRaises(SyntaxError) as cm:
83 from test.test_future_stmt import badsyntax_future7
84 #PyPy change: PyPy (like CPython 3.12+) reports offset 54 here; CPython 3.11 reported 53
85 offset = 54 if sys.implementation.name == 'pypy' else 53
86 self.check_syntax_error(cm.exception, "badsyntax_future7", 3, offset)
87
88 def test_badfuture8(self):
89 with self.assertRaises(SyntaxError) as cm:
90 from test.test_future_stmt import badsyntax_future8
91 self.check_syntax_error(cm.exception, "badsyntax_future8", 3)
92
93 def test_badfuture9(self):
94 with self.assertRaises(SyntaxError) as cm:
95 from test.test_future_stmt import badsyntax_future9
96 self.check_syntax_error(cm.exception, "badsyntax_future9", 3)
97
98 def test_badfuture10(self):
99 with self.assertRaises(SyntaxError) as cm:
100 from test.test_future_stmt import badsyntax_future10
101 self.check_syntax_error(cm.exception, "badsyntax_future10", 3)
102
103 def test_ensure_flags_dont_clash(self):
104 # bpo-39562: test that future flags and compiler flags doesn't clash
105
106 # obtain future flags (CO_FUTURE_***) from the __future__ module
107 flags = {
108 f"CO_FUTURE_{future.upper()}": getattr(__future__, future).compiler_flag
109 for future in __future__.all_feature_names
110 }
111 # obtain some of the exported compiler flags (PyCF_***) from the ast module
112 flags |= {
113 flag: getattr(ast, flag)
114 for flag in dir(ast) if flag.startswith("PyCF_")
115 }
116 self.assertCountEqual(set(flags.values()), flags.values())
117
118 def test_parserhack(self):
119 # test that the parser.c::future_hack function works as expected
120 # Note: although this test must pass, it's not testing the original
121 # bug as of 2.6 since the with statement is not optional and
122 # the parser hack disabled. If a new keyword is introduced in
123 # 2.6, change this to refer to the new future import.
124 try:
125 exec("from __future__ import print_function; print 0")
126 except SyntaxError:
127 pass
128 else:
129 self.fail("syntax error didn't occur")
130
131 try:
132 exec("from __future__ import (print_function); print 0")
133 except SyntaxError:
134 pass
135 else:
136 self.fail("syntax error didn't occur")
137
138 def test_unicode_literals_exec(self):
139 scope = {}
140 exec("from __future__ import unicode_literals; x = ''", {}, scope)
141 self.assertIsInstance(scope["x"], str)
142
143 class AnnotationsFutureTestCase(unittest.TestCase):
144 template = dedent(
145 """
146 from __future__ import annotations
147 def f() -> {ann}:
148 ...
149 def g(arg: {ann}) -> None:
150 ...
151 async def f2() -> {ann}:
152 ...
153 async def g2(arg: {ann}) -> None:
154 ...
155 class H:
156 var: {ann}
157 object.attr: {ann}
158 var: {ann}
159 var2: {ann} = None
160 object.attr: {ann}
161 """
162 )
163
164 def getActual(self, annotation):
165 scope = {}
166 exec(self.template.format(ann=annotation), {}, scope)
167 func_ret_ann = scope['f'].__annotations__['return']
168 func_arg_ann = scope['g'].__annotations__['arg']
169 async_func_ret_ann = scope['f2'].__annotations__['return']
170 async_func_arg_ann = scope['g2'].__annotations__['arg']
171 var_ann1 = scope['__annotations__']['var']
172 var_ann2 = scope['__annotations__']['var2']
173 self.assertEqual(func_ret_ann, func_arg_ann)
174 self.assertEqual(func_ret_ann, async_func_ret_ann)
175 self.assertEqual(func_ret_ann, async_func_arg_ann)
176 self.assertEqual(func_ret_ann, var_ann1)
177 self.assertEqual(func_ret_ann, var_ann2)
178 return func_ret_ann
179
180 def assertAnnotationEqual(
181 self, annotation, expected=None, drop_parens=False, is_tuple=False,
182 ):
183 actual = self.getActual(annotation)
184 if expected is None:
185 expected = annotation if not is_tuple else annotation[1:-1]
186 if drop_parens:
187 self.assertNotEqual(actual, expected)
188 actual = actual.replace("(", "").replace(")", "")
189
190 self.assertEqual(actual, expected)
191
192 def _exec_future(self, code):
193 scope = {}
194 exec(
195 "from __future__ import annotations\n"
196 + code, scope
197 )
198 return scope
199
200 def test_annotations(self):
201 eq = self.assertAnnotationEqual
202 eq('...')
203 eq("'some_string'")
204 eq("u'some_string'")
205 eq("b'\\xa3'")
206 eq('Name')
207 eq('None')
208 eq('True')
209 eq('False')
210 eq('1')
211 eq('1.0')
212 eq('1j')
213 eq('True or False')
214 eq('True or False or None')
215 eq('True and False')
216 eq('True and False and None')
217 eq('Name1 and Name2 or Name3')
218 eq('Name1 and (Name2 or Name3)')
219 eq('Name1 or Name2 and Name3')
220 eq('(Name1 or Name2) and Name3')
221 eq('Name1 and Name2 or Name3 and Name4')
222 eq('Name1 or Name2 and Name3 or Name4')
223 eq('a + b + (c + d)')
224 eq('a * b * (c * d)')
225 eq('(a ** b) ** c ** d')
226 eq('v1 << 2')
227 eq('1 >> v2')
228 eq('1 % finished')
229 eq('1 + v2 - v3 * 4 ^ 5 ** v6 / 7 // 8')
230 eq('not great')
231 eq('not not great')
232 eq('~great')
233 eq('+value')
234 eq('++value')
235 eq('-1')
236 eq('~int and not v1 ^ 123 + v2 | True')
237 eq('a + (not b)')
238 eq('lambda: None')
239 eq('lambda arg: None')
240 eq('lambda a=True: a')
241 eq('lambda a, b, c=True: a')
242 eq("lambda a, b, c=True, *, d=1 << v2, e='str': a")
243 eq("lambda a, b, c=True, *vararg, d, e='str', **kwargs: a + b")
244 eq("lambda a, /, b, c=True, *vararg, d, e='str', **kwargs: a + b")
245 eq('lambda x, /: x')
246 eq('lambda x=1, /: x')
247 eq('lambda x, /, y: x + y')
248 eq('lambda x=1, /, y=2: x + y')
249 eq('lambda x, /, y=1: x + y')
250 eq('lambda x, /, y=1, *, z=3: x + y + z')
251 eq('lambda x=1, /, y=2, *, z=3: x + y + z')
252 eq('lambda x=1, /, y=2, *, z: x + y + z')
253 eq('lambda x=1, y=2, z=3, /, w=4, *, l, l2: x + y + z + w + l + l2')
254 eq('lambda x=1, y=2, z=3, /, w=4, *, l, l2, **kwargs: x + y + z + w + l + l2')
255 eq('lambda x, /, y=1, *, z: x + y + z')
256 eq('lambda x: lambda y: x + y')
257 eq('1 if True else 2')
258 eq('str or None if int or True else str or bytes or None')
259 eq('str or None if (1 if True else 2) else str or bytes or None')
260 eq("0 if not x else 1 if x > 0 else -1")
261 eq("(1 if x > 0 else -1) if x else 0")
262 eq("{'2.7': dead, '3.7': long_live or die_hard}")
263 eq("{'2.7': dead, '3.7': long_live or die_hard, **{'3.6': verygood}}")
264 eq("{**a, **b, **c}")
265 eq("{'2.7', '3.6', '3.7', '3.8', '3.9', '4.0' if gilectomy else '3.10'}")
266 eq("{*a, *b, *c}")
267 eq("({'a': 'b'}, True or False, +value, 'string', b'bytes') or None")
268 eq("()")
269 eq("(a,)")
270 eq("(a, b)")
271 eq("(a, b, c)")
272 eq("(*a, *b, *c)")
273 eq("[]")
274 eq("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10 or A, 11 or B, 12 or C]")
275 eq("[*a, *b, *c]")
276 eq("{i for i in (1, 2, 3)}")
277 eq("{i ** 2 for i in (1, 2, 3)}")
278 eq("{i ** 2 for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))}")
279 eq("{i ** 2 + j for i in (1, 2, 3) for j in (1, 2, 3)}")
280 eq("[i for i in (1, 2, 3)]")
281 eq("[i ** 2 for i in (1, 2, 3)]")
282 eq("[i ** 2 for i, _ in ((1, 'a'), (2, 'b'), (3, 'c'))]")
283 eq("[i ** 2 + j for i in (1, 2, 3) for j in (1, 2, 3)]")
284 eq("(i for i in (1, 2, 3))")
285 eq("(i ** 2 for i in (1, 2, 3))")
286 eq("(i ** 2 for i, _ in ((1, 'a'), (2, 'b'), (3, 'c')))")
287 eq("(i ** 2 + j for i in (1, 2, 3) for j in (1, 2, 3))")
288 eq("{i: 0 for i in (1, 2, 3)}")
289 eq("{i: j for i, j in ((1, 'a'), (2, 'b'), (3, 'c'))}")
290 eq("[(x, y) for x, y in (a, b)]")
291 eq("[(x,) for x, in (a,)]")
292 eq("Python3 > Python2 > COBOL")
293 eq("Life is Life")
294 eq("call()")
295 eq("call(arg)")
296 eq("call(kwarg='hey')")
297 eq("call(arg, kwarg='hey')")
298 eq("call(arg, *args, another, kwarg='hey')")
299 eq("call(arg, another, kwarg='hey', **kwargs, kwarg2='ho')")
300 eq("lukasz.langa.pl")
301 eq("call.me(maybe)")
302 eq("1 .real")
303 eq("1.0.real")
304 eq("....__class__")
305 eq("list[str]")
306 eq("dict[str, int]")
307 eq("set[str,]")
308 eq("tuple[()]")
309 eq("tuple[str, ...]")
310 eq("tuple[str, *types]")
311 eq("tuple[str, int, (str, int)]")
312 eq("tuple[*int, str, str, (str, int)]")
313 eq("tuple[str, int, float, dict[str, int]]")
314 eq("slice[0]")
315 eq("slice[0:1]")
316 eq("slice[0:1:2]")
317 eq("slice[:]")
318 eq("slice[:-1]")
319 eq("slice[1:]")
320 eq("slice[::-1]")
321 eq("slice[:,]")
322 eq("slice[1:2,]")
323 eq("slice[1:2:3,]")
324 eq("slice[1:2, 1]")
325 eq("slice[1:2, 2, 3]")
326 eq("slice[()]")
327 # Note that `slice[*Ts]`, `slice[*Ts,]`, and `slice[(*Ts,)]` all have
328 # the same AST, but only `slice[*Ts,]` passes this test, because that's
329 # what the unparser produces.
330 eq("slice[*Ts,]")
331 eq("slice[1, *Ts]")
332 eq("slice[*Ts, 2]")
333 eq("slice[1, *Ts, 2]")
334 eq("slice[*Ts, *Ts]")
335 eq("slice[1, *Ts, *Ts]")
336 eq("slice[*Ts, 1, *Ts]")
337 eq("slice[*Ts, *Ts, 1]")
338 eq("slice[1, *Ts, *Ts, 2]")
339 eq("slice[1:2, *Ts]")
340 eq("slice[*Ts, 1:2]")
341 eq("slice[1:2, *Ts, 3:4]")
342 eq("slice[a, b:c, d:e:f]")
343 eq("slice[(x for x in a)]")
344 eq('str or None if sys.version_info[0] > (3,) else str or bytes or None')
345 eq("f'f-string without formatted values is just a string'")
346 eq("f'{{NOT a formatted value}}'")
347 eq("f'some f-string with {a} {few():.2f} {formatted.values!r}'")
348 eq('''f"{f'{nested} inner'} outer"''')
349 eq("f'space between opening braces: { {a for a in (1, 2, 3)}}'")
350 eq("f'{(lambda x: x)}'")
351 eq("f'{(None if a else lambda x: x)}'")
352 eq("f'{x}'")
353 eq("f'{x!r}'")
354 eq("f'{x!a}'")
355 eq('[x for x in (a if b else c)]')
356 eq('[x for x in a if (b if c else d)]')
357 eq('f(x for x in a)')
358 eq('f(1, (x for x in a))')
359 eq('f((x for x in a), 2)')
360 eq('(((a)))', 'a')
361 eq('(((a, b)))', '(a, b)')
362 eq("1 + 2 + 3")
363
364 def test_fstring_debug_annotations(self):
365 # f-strings with '=' don't round trip very well, so set the expected
366 # result explicitly.
367 self.assertAnnotationEqual("f'{x=!r}'", expected="f'x={x!r}'")
368 self.assertAnnotationEqual("f'{x=:}'", expected="f'x={x:}'")
369 self.assertAnnotationEqual("f'{x=:.2f}'", expected="f'x={x:.2f}'")
370 self.assertAnnotationEqual("f'{x=!r}'", expected="f'x={x!r}'")
371 self.assertAnnotationEqual("f'{x=!a}'", expected="f'x={x!a}'")
372 self.assertAnnotationEqual("f'{x=!s:*^20}'", expected="f'x={x!s:*^20}'")
373
374 def test_infinity_numbers(self):
375 inf = "1e" + repr(sys.float_info.max_10_exp + 1)
376 infj = f"{inf}j"
377 self.assertAnnotationEqual("1e1000", expected=inf)
378 self.assertAnnotationEqual("1e1000j", expected=infj)
379 self.assertAnnotationEqual("-1e1000", expected=f"-{inf}")
380 self.assertAnnotationEqual("3+1e1000j", expected=f"3 + {infj}")
381 self.assertAnnotationEqual("(1e1000, 1e1000j)", expected=f"({inf}, {infj})")
382 self.assertAnnotationEqual("'inf'")
383 self.assertAnnotationEqual("('inf', 1e1000, 'infxxx', 1e1000j)", expected=f"('inf', {inf}, 'infxxx', {infj})")
384 self.assertAnnotationEqual("(1e1000, (1e1000j,))", expected=f"({inf}, ({infj},))")
385
386 def test_annotation_with_complex_target(self):
387 with self.assertRaises(SyntaxError):
388 exec(
389 "from __future__ import annotations\n"
390 "object.__debug__: int"
391 )
392
393 def test_annotations_symbol_table_pass(self):
394 namespace = self._exec_future(dedent("""
395 from __future__ import annotations
396
397 def foo():
398 outer = 1
399 def bar():
400 inner: outer = 1
401 return bar
402 """))
403
404 foo = namespace.pop("foo")
405 self.assertIsNone(foo().__closure__)
406 self.assertEqual(foo.__code__.co_cellvars, ())
407 self.assertEqual(foo().__code__.co_freevars, ())
408
409 def test_annotations_forbidden(self):
410 with self.assertRaises(SyntaxError):
411 self._exec_future("test: (yield)")
412
413 with self.assertRaises(SyntaxError):
414 self._exec_future("test.test: (yield a + b)")
415
416 with self.assertRaises(SyntaxError):
417 self._exec_future("test[something]: (yield from x)")
418
419 with self.assertRaises(SyntaxError):
420 self._exec_future("def func(test: (yield from outside_of_generator)): pass")
421
422 with self.assertRaises(SyntaxError):
423 self._exec_future("def test() -> (await y): pass")
424
425 with self.assertRaises(SyntaxError):
426 self._exec_future("async def test() -> something((a := b)): pass")
427
428 with self.assertRaises(SyntaxError):
429 self._exec_future("test: await some.complicated[0].call(with_args=True or 1 is not 1)")
430
431 with self.assertRaises(SyntaxError):
432 self._exec_future("test: f'{(x := 10):=10}'")
433
434 with self.assertRaises(SyntaxError):
435 self._exec_future(dedent("""\
436 def foo():
437 def bar(arg: (yield)): pass
438 """))
439
440 def test_get_type_hints_on_func_with_variadic_arg(self):
441 # `typing.get_type_hints` might break on a function with a variadic
442 # annotation (e.g. `f(*args: *Ts)`) if `from __future__ import
443 # annotations`, because it could try to evaluate `*Ts` as an expression,
444 # which on its own isn't value syntax.
445 namespace = self._exec_future(dedent("""\
446 class StarredC: pass
447 class C:
448 def __iter__(self):
449 yield StarredC()
450 c = C()
451 def f(*args: *c): pass
452 import typing
453 hints = typing.get_type_hints(f)
454 """))
455
456 hints = namespace.pop('hints')
457 self.assertIsInstance(hints['args'], namespace['StarredC'])
458
459
460 if __name__ == "__main__":
461 unittest.main()