Debian Codegraph @

tests/test_nodes.py

raw
1 # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
2 # For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
3 # Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
4
5 """Tests for specific behaviour of astroid nodes."""
6
7 from __future__ import annotations
8
9 import copy
10 import inspect
11 import os
12 import random
13 import sys
14 import textwrap
15 import unittest
16 import warnings
17 from typing import Any
18
19 import pytest
20
21 import astroid
22 from astroid import (
23 Uninferable,
24 bases,
25 builder,
26 extract_node,
27 nodes,
28 parse,
29 transforms,
30 util,
31 )
32 from astroid.const import (
33 IS_PYPY,
34 PY311_PLUS,
35 PY312_PLUS,
36 PY313_PLUS,
37 PY314_PLUS,
38 PY315_PLUS,
39 Context,
40 )
41 from astroid.context import InferenceContext
42 from astroid.exceptions import (
43 AstroidBuildingError,
44 AstroidSyntaxError,
45 AstroidTypeError,
46 AttributeInferenceError,
47 StatementMissing,
48 )
49 from astroid.nodes.node_classes import UNATTACHED_UNKNOWN
50 from astroid.nodes.scoped_nodes import SYNTHETIC_ROOT
51 from tests.testdata.python3.recursion_error import LONG_CHAINED_METHOD_CALL
52
53 from . import resources
54
55 abuilder = builder.AstroidBuilder(astroid.MANAGER)
56
57
58 class AsStringTest(resources.SysPathSetup, unittest.TestCase):
59 def test_tuple_as_string(self) -> None:
60 def build(string: str) -> nodes.Tuple:
61 return abuilder.string_build(string).body[0].value
62
63 self.assertEqual(build("1,").as_string(), "(1, )")
64 self.assertEqual(build("1, 2, 3").as_string(), "(1, 2, 3)")
65 self.assertEqual(build("(1, )").as_string(), "(1, )")
66 self.assertEqual(build("1, 2, 3").as_string(), "(1, 2, 3)")
67
68 def test_func_signature_issue_185(self) -> None:
69 code = textwrap.dedent("""
70 def test(a, b, c=42, *, x=42, **kwargs):
71 print(a, b, c, args)
72 """)
73 node = parse(code)
74 self.assertEqual(node.as_string().strip(), code.strip())
75
76 def test_as_string_for_list_containing_uninferable(self) -> None:
77 node = builder.extract_node("""
78 def foo():
79 bar = [arg] * 1
80 """)
81 binop = node.body[0].value
82 inferred = next(binop.infer())
83 self.assertEqual(inferred.as_string(), "[Uninferable]")
84 self.assertEqual(binop.as_string(), "[arg] * 1")
85
86 def test_frozenset_as_string(self) -> None:
87 ast_nodes = builder.extract_node("""
88 frozenset((1, 2, 3)) #@
89 frozenset({1, 2, 3}) #@
90 frozenset([1, 2, 3,]) #@
91
92 frozenset(None) #@
93 frozenset(1) #@
94 """)
95 ast_nodes = [next(node.infer()) for node in ast_nodes]
96 assert isinstance(ast_nodes, list)
97 self.assertEqual(ast_nodes[0].as_string(), "frozenset((1, 2, 3))")
98 self.assertEqual(ast_nodes[1].as_string(), "frozenset({1, 2, 3})")
99 self.assertEqual(ast_nodes[2].as_string(), "frozenset([1, 2, 3])")
100
101 self.assertNotEqual(ast_nodes[3].as_string(), "frozenset(None)")
102 self.assertNotEqual(ast_nodes[4].as_string(), "frozenset(1)")
103
104 def test_varargs_kwargs_as_string(self) -> None:
105 ast = abuilder.string_build("raise_string(*args, **kwargs)").body[0]
106 self.assertEqual(ast.as_string(), "raise_string(*args, **kwargs)")
107
108 @pytest.mark.skipif(PY314_PLUS, reason="return in finally is now a syntax error")
109 def test_module_as_string_pre_3_14(self) -> None:
110 """Check as_string on a whole module prepared to be returned identically for py < 3.14."""
111 self.maxDiff = None
112 module = resources.build_file("data/module.py", "data.module")
113 with open(resources.find("data/module.py"), encoding="utf-8") as fobj:
114 # Ignore comments in python file
115 data_str = "\n".join(
116 [s for s in fobj.read().split("\n") if not s.lstrip().startswith("# ")]
117 )
118 self.assertMultiLineEqual(module.as_string(), data_str)
119
120 @pytest.mark.skipif(
121 not PY314_PLUS, reason="return in finally is now a syntax error"
122 )
123 def test_module_as_string(self) -> None:
124 """Check as_string on a whole module prepared to be returned identically for py > 3.14."""
125 self.maxDiff = None
126 module = resources.build_file("data/module3.14.py", "data.module3.14")
127 with open(resources.find("data/module3.14.py"), encoding="utf-8") as fobj:
128 # Ignore comments in python file
129 data_str = "\n".join(
130 [s for s in fobj.read().split("\n") if not s.lstrip().startswith("# ")]
131 )
132 self.assertMultiLineEqual(module.as_string(), data_str)
133
134 def test_module2_as_string(self) -> None:
135 """Check as_string on a whole module prepared to be returned identically."""
136 module2 = resources.build_file("data/module2.py", "data.module2")
137 with open(resources.find("data/module2.py"), encoding="utf-8") as fobj:
138 self.assertMultiLineEqual(module2.as_string(), fobj.read())
139
140 def test_as_string(self) -> None:
141 """Check as_string for python syntax >= 2.7."""
142 code = """one_two = {1, 2}
143 b = {v: k for (k, v) in enumerate('string')}
144 cdd = {k for k in b}\n\n"""
145 ast = abuilder.string_build(code)
146 self.assertMultiLineEqual(ast.as_string(), code)
147
148 def test_3k_as_string(self) -> None:
149 """Check as_string for python 3k syntax."""
150 code = """print()
151
152 def function(var):
153 nonlocal counter
154 try:
155 hello
156 except NameError as nexc:
157 (*hell, o) = b'hello'
158 raise AttributeError from nexc
159 \n"""
160 ast = abuilder.string_build(code)
161 self.assertEqual(ast.as_string(), code)
162
163 def test_3k_annotations_and_metaclass(self) -> None:
164 code = '''
165 def function(var: int):
166 nonlocal counter
167
168 class Language(metaclass=Natural):
169 """natural language"""
170 '''
171
172 code_annotations = textwrap.dedent(code)
173 expected = '''\
174 def function(var: int):
175 nonlocal counter
176
177
178 class Language(metaclass=Natural):
179 """natural language"""'''
180 ast = abuilder.string_build(code_annotations)
181 self.assertEqual(ast.as_string().strip(), expected)
182
183 def test_ellipsis(self) -> None:
184 ast = abuilder.string_build("a[...]").body[0]
185 self.assertEqual(ast.as_string(), "a[...]")
186
187 def test_slices(self) -> None:
188 for code in (
189 "a[0]",
190 "a[1:3]",
191 "a[:-1:step]",
192 "a[:, newaxis]",
193 "a[newaxis, :]",
194 "del L[::2]",
195 "del A[1]",
196 "del Br[:]",
197 ):
198 ast = abuilder.string_build(code).body[0]
199 self.assertEqual(ast.as_string(), code)
200
201 def test_slice_and_subscripts(self) -> None:
202 code = """a[:1] = bord[2:]
203 a[:1] = bord[2:]
204 del bree[3:d]
205 bord[2:]
206 del av[d::f], a[df:]
207 a[:1] = bord[2:]
208 del SRC[::1, newaxis, 1:]
209 tous[vals] = 1010
210 del thousand[key]
211 del a[::2], a[:-1:step]
212 del Fee.form[left:]
213 aout.vals = miles.of_stuff
214 del (ccok, (name.thing, foo.attrib.value)), Fee.form[left:]
215 if all[1] == bord[0:]:
216 pass\n\n"""
217 ast = abuilder.string_build(code)
218 self.assertEqual(ast.as_string(), code)
219
220 def test_int_attribute(self) -> None:
221 code = """
222 x = (-3).real
223 y = (3).imag
224 """
225 ast = abuilder.string_build(code)
226 self.assertEqual(ast.as_string().strip(), code.strip())
227
228 def test_operator_precedence(self) -> None:
229 with open(resources.find("data/operator_precedence.py"), encoding="utf-8") as f:
230 for code in f:
231 self.check_as_string_ast_equality(code)
232
233 @staticmethod
234 def check_as_string_ast_equality(code: str) -> None:
235 """
236 Check that as_string produces source code with exactly the same
237 semantics as the source it was originally parsed from.
238 """
239 pre = builder.parse(code)
240 post = builder.parse(pre.as_string())
241
242 pre_repr = pre.repr_tree()
243 post_repr = post.repr_tree()
244
245 assert pre_repr == post_repr
246 assert pre.as_string().strip() == code.strip()
247
248 def test_class_def(self) -> None:
249 code = """
250 import abc
251 from typing import Tuple
252
253
254 class A:
255 pass
256
257
258
259 class B(metaclass=A, x=1):
260 pass
261
262
263
264 class C(B):
265 pass
266
267
268
269 class D(metaclass=abc.ABCMeta):
270 pass
271
272
273 def func(param: Tuple):
274 pass
275 """
276 ast = abuilder.string_build(code)
277 self.assertEqual(ast.as_string().strip(), code.strip())
278
279 def test_f_strings(self):
280 code = r'''
281 a = f"{'a'}"
282 b = f'{{b}}'
283 c = f""" "{'c'}" """
284 d = f'{d!r} {d!s} {d!a}'
285 e = f'{e:.3}'
286 f = f'{f:{x}.{y}}'
287 n = f'\n'
288 everything = f""" " \' \r \t \\ {{ }} {'x' + x!r:a} {["'"]!s:{a}}"""
289 '''
290 ast = abuilder.string_build(code)
291 self.assertEqual(ast.as_string().strip(), code.strip())
292
293 @staticmethod
294 def test_as_string_unknown() -> None:
295 unknown1 = nodes.Unknown(parent=SYNTHETIC_ROOT)
296 unknown2 = nodes.Unknown(lineno=1, col_offset=0, parent=SYNTHETIC_ROOT)
297 assert unknown1.as_string() == "Unknown.Unknown()"
298 assert unknown2.as_string() == "Unknown.Unknown()"
299
300 @staticmethod
301 @pytest.mark.skipif(
302 IS_PYPY,
303 reason="Test requires manipulating the recursion limit, which cannot "
304 "be undone in a finally block without polluting other tests on PyPy.",
305 )
306 def test_recursion_error_trapped() -> None:
307 with pytest.warns(UserWarning, match="unable to transform"):
308 ast = abuilder.string_build(LONG_CHAINED_METHOD_CALL)
309
310 attribute = ast.body[1].value.func
311 with pytest.raises(UserWarning):
312 attribute.as_string()
313
314
315 @pytest.mark.skipif(not PY312_PLUS, reason="Uses 3.12 type param nodes")
316 class AsStringTypeParamNodes(unittest.TestCase):
317 @staticmethod
318 def test_as_string_type_alias() -> None:
319 ast1 = abuilder.string_build("type Point = tuple[float, float]")
320 type_alias1 = ast1.body[0]
321 assert type_alias1.as_string().strip() == "type Point = tuple[float, float]"
322 ast2 = abuilder.string_build(
323 "type Point[T, **P] = tuple[float, T, Callable[P, None]]"
324 )
325 type_alias2 = ast2.body[0]
326 assert (
327 type_alias2.as_string().strip()
328 == "type Point[T, **P] = tuple[float, T, Callable[P, None]]"
329 )
330
331 @staticmethod
332 def test_as_string_type_var() -> None:
333 ast = abuilder.string_build("type Point[T: int | str] = tuple[float, float]")
334 type_var = ast.body[0].type_params[0]
335 assert type_var.as_string().strip() == "T: int | str"
336
337 @staticmethod
338 @pytest.mark.skipif(
339 not PY313_PLUS, reason="Type parameter defaults were added in 313"
340 )
341 def test_as_string_type_var_default() -> None:
342 ast = abuilder.string_build(
343 "type Point[T: int | str = int] = tuple[float, float]"
344 )
345 type_var = ast.body[0].type_params[0]
346 assert type_var.as_string().strip() == "T: int | str = int"
347
348 @staticmethod
349 def test_as_string_type_var_tuple() -> None:
350 ast = abuilder.string_build("type Alias[*Ts] = tuple[*Ts]")
351 type_var_tuple = ast.body[0].type_params[0]
352 assert type_var_tuple.as_string().strip() == "*Ts"
353
354 @staticmethod
355 @pytest.mark.skipif(
356 not PY313_PLUS, reason="Type parameter defaults were added in 313"
357 )
358 def test_as_string_type_var_tuple_defaults() -> None:
359 ast = abuilder.string_build("type Alias[*Ts = tuple[int, str]] = tuple[*Ts]")
360 type_var_tuple = ast.body[0].type_params[0]
361 assert type_var_tuple.as_string().strip() == "*Ts = tuple[int, str]"
362
363 @staticmethod
364 def test_as_string_param_spec() -> None:
365 ast = abuilder.string_build("type Alias[**P] = Callable[P, int]")
366 param_spec = ast.body[0].type_params[0]
367 assert param_spec.as_string().strip() == "**P"
368
369 @staticmethod
370 @pytest.mark.skipif(
371 not PY313_PLUS, reason="Type parameter defaults were added in 313"
372 )
373 def test_as_string_param_spec_defaults() -> None:
374 ast = abuilder.string_build("type Alias[**P = [str, int]] = Callable[P, int]")
375 param_spec = ast.body[0].type_params[0]
376 assert param_spec.as_string().strip() == "**P = [str, int]"
377
378 @staticmethod
379 def test_as_string_class_type_params() -> None:
380 code = abuilder.string_build("class A[T, **P]: ...")
381 cls_node = code.body[0]
382 assert cls_node.as_string().strip() == "class A[T, **P]:\n ..."
383
384 @staticmethod
385 def test_as_string_function_type_params() -> None:
386 code = abuilder.string_build("def func[T, **P](): ...")
387 func_node = code.body[0]
388 assert func_node.as_string().strip() == "def func[T, **P]():\n ..."
389
390
391 class _NodeTest(unittest.TestCase):
392 """Test transformation of If Node."""
393
394 CODE = ""
395
396 @property
397 def astroid(self) -> nodes.Module:
398 try:
399 return self.__class__.__dict__["CODE_Astroid"]
400 except KeyError:
401 module = builder.parse(self.CODE)
402 self.__class__.CODE_Astroid = module
403 return module
404
405
406 class IfNodeTest(_NodeTest):
407 """Test transformation of If Node."""
408
409 CODE = """
410 if 0:
411 print()
412
413 if True:
414 print()
415 else:
416 pass
417
418 if "":
419 print()
420 elif []:
421 raise
422
423 if 1:
424 print()
425 elif True:
426 print()
427 elif func():
428 pass
429 else:
430 raise
431
432 if 1:
433 print()
434 elif (
435 2
436 and 3
437 ):
438 print()
439 else:
440 # This is using else in a comment
441 raise
442 """
443
444 def test_if_elif_else_node(self) -> None:
445 """Test transformation for If node."""
446 self.assertEqual(len(self.astroid.body), 5)
447 for stmt in self.astroid.body:
448 self.assertIsInstance(stmt, nodes.If)
449 self.assertFalse(self.astroid.body[0].orelse) # simple If
450 self.assertIsInstance(self.astroid.body[1].orelse[0], nodes.Pass) # If / else
451 self.assertIsInstance(self.astroid.body[2].orelse[0], nodes.If) # If / elif
452 self.assertIsInstance(self.astroid.body[3].orelse[0].orelse[0], nodes.If)
453
454 def test_block_range(self) -> None:
455 """Test block_range of various scope constructs"""
456 # Module
457 self.assertEqual(self.astroid.block_range(1), (0, 33))
458 # NOTE: Module does not consider the lineno argument. It would be more consistent to make
459 # this return (10, 33) but without a use case it seems better to not change behaviour.
460 self.assertEqual(self.astroid.block_range(10), (0, 33))
461
462 # if
463 self.assertEqual(self.astroid.body[0].block_range(2), (2, 3))
464 self.assertEqual(self.astroid.body[0].block_range(3), (3, 3))
465
466 # if ... else
467 self.assertEqual(self.astroid.body[1].block_range(5), (5, 6))
468 self.assertEqual(self.astroid.body[1].block_range(6), (6, 6))
469 self.assertEqual(self.astroid.body[1].block_range(7), (7, 8))
470 self.assertEqual(self.astroid.body[1].block_range(8), (8, 8))
471
472 # if ... elif
473 self.assertEqual(self.astroid.body[2].block_range(10), (10, 11))
474 self.assertEqual(self.astroid.body[2].block_range(11), (11, 11))
475 self.assertEqual(self.astroid.body[2].block_range(12), (12, 13))
476 self.assertEqual(self.astroid.body[2].block_range(13), (13, 13))
477
478 # if ... elif ... elif ... else
479 self.assertEqual(self.astroid.body[3].block_range(15), (15, 16))
480 self.assertEqual(self.astroid.body[3].block_range(16), (16, 16))
481 self.assertEqual(self.astroid.body[3].block_range(17), (17, 18))
482 self.assertEqual(self.astroid.body[3].block_range(18), (18, 18))
483 self.assertEqual(self.astroid.body[3].block_range(19), (19, 20))
484 self.assertEqual(self.astroid.body[3].block_range(20), (20, 20))
485 self.assertEqual(self.astroid.body[3].block_range(21), (21, 22))
486 self.assertEqual(self.astroid.body[3].block_range(22), (22, 22))
487
488 # if ... elif ... else
489 self.assertEqual(self.astroid.body[4].block_range(24), (24, 25))
490 self.assertEqual(self.astroid.body[4].block_range(25), (25, 25))
491 self.assertEqual(self.astroid.body[4].block_range(26), (26, 30))
492 self.assertEqual(self.astroid.body[4].block_range(27), (27, 30))
493 self.assertEqual(self.astroid.body[4].block_range(28), (28, 30))
494 self.assertEqual(self.astroid.body[4].block_range(29), (29, 30))
495 self.assertEqual(self.astroid.body[4].block_range(30), (30, 30))
496 self.assertEqual(self.astroid.body[4].block_range(31), (31, 33))
497 self.assertEqual(self.astroid.body[4].block_range(32), (32, 33))
498 self.assertEqual(self.astroid.body[4].block_range(33), (33, 33))
499
500
501 class TryNodeTest(_NodeTest):
502 CODE = """
503 try: # L2
504 print("Hello")
505 except IOError:
506 pass
507 except UnicodeError:
508 pass
509 else:
510 print()
511 finally:
512 print()
513 """
514
515 def test_block_range(self) -> None:
516 try_node = self.astroid.body[0]
517 assert try_node.block_range(1) == (1, 11)
518 assert try_node.block_range(2) == (2, 3)
519 assert try_node.block_range(3) == (3, 3)
520 assert try_node.block_range(4) == (4, 5)
521 assert try_node.block_range(5) == (5, 5)
522 assert try_node.block_range(6) == (6, 7)
523 assert try_node.block_range(7) == (7, 7)
524 assert try_node.block_range(8) == (8, 9)
525 assert try_node.block_range(9) == (9, 9)
526 assert try_node.block_range(10) == (10, 11)
527 assert try_node.block_range(11) == (11, 11)
528
529
530 class ImportNodeTest(resources.SysPathSetup, unittest.TestCase):
531 def setUp(self) -> None:
532 super().setUp()
533 self.module = resources.build_file("data/module.py", "data.module")
534 self.module2 = resources.build_file("data/module2.py", "data.module2")
535
536 @pytest.mark.skipif(not PY315_PLUS, reason="PEP 810 lazy imports, new in 3.15")
537 def test_lazy_import(self) -> None:
538 node = extract_node("lazy import json")
539 assert isinstance(node, nodes.Import)
540 assert node.is_lazy == 1
541 self.assertEqual(node.as_string(), "lazy import json")
542
543 @pytest.mark.skipif(not PY315_PLUS, reason="PEP 810 lazy imports, new in 3.15")
544 def test_lazy_import_from(self) -> None:
545 node = extract_node("lazy from pathlib import Path")
546 assert isinstance(node, nodes.ImportFrom)
547 assert node.is_lazy == 1
548 self.assertEqual(node.as_string(), "lazy from pathlib import Path")
549
550 def test_eager_import_is_not_lazy(self) -> None:
551 # The ``is_lazy`` flag defaults to 0 on every supported version.
552 assert extract_node("import json").is_lazy == 0
553 assert extract_node("from pathlib import Path").is_lazy == 0
554
555 def test_import_self_resolve(self) -> None:
556 myos = next(self.module2.igetattr("myos"))
557 self.assertTrue(isinstance(myos, nodes.Module), myos)
558 self.assertEqual(myos.name, "os")
559 self.assertEqual(myos.qname(), "os")
560 self.assertEqual(myos.pytype(), "builtins.module")
561
562 def test_from_self_resolve(self) -> None:
563 namenode = next(self.module.igetattr("NameNode"))
564 self.assertTrue(isinstance(namenode, nodes.ClassDef), namenode)
565 self.assertEqual(namenode.root().name, "astroid.nodes.node_classes")
566 self.assertEqual(namenode.qname(), "astroid.nodes.node_classes.Name")
567 self.assertEqual(namenode.pytype(), "builtins.type")
568 abspath = next(self.module2.igetattr("abspath"))
569 self.assertTrue(isinstance(abspath, nodes.FunctionDef), abspath)
570 self.assertEqual(abspath.root().name, "os.path")
571 self.assertEqual(abspath.pytype(), "builtins.function")
572 if sys.platform != "win32":
573 # Not sure what is causing this check to fail on Windows.
574 # For some reason the abspath() inference returns a different
575 # path than expected:
576 # AssertionError: 'os.path._abspath_fallback' != 'os.path.abspath'
577 self.assertEqual(abspath.qname(), "os.path.abspath")
578
579 def test_real_name(self) -> None:
580 from_ = self.module["NameNode"]
581 self.assertEqual(from_.real_name("NameNode"), "Name")
582 imp_ = self.module["os"]
583 self.assertEqual(imp_.real_name("os"), "os")
584 self.assertRaises(AttributeInferenceError, imp_.real_name, "os.path")
585 imp_ = self.module["NameNode"]
586 self.assertEqual(imp_.real_name("NameNode"), "Name")
587 self.assertRaises(AttributeInferenceError, imp_.real_name, "Name")
588 imp_ = self.module2["YO"]
589 self.assertEqual(imp_.real_name("YO"), "YO")
590 self.assertRaises(AttributeInferenceError, imp_.real_name, "data")
591
592 def test_as_string(self) -> None:
593 ast = self.module["modutils"]
594 self.assertEqual(ast.as_string(), "from astroid import modutils")
595 ast = self.module["NameNode"]
596 self.assertEqual(ast.as_string(), "from astroid.nodes import Name as NameNode")
597 ast = self.module["os"]
598 self.assertEqual(ast.as_string(), "import os.path")
599 code = """from . import here
600 from .. import door
601 from .store import bread
602 from ..cave import wine\n\n"""
603 ast = abuilder.string_build(code)
604 self.assertMultiLineEqual(ast.as_string(), code)
605
606 def test_bad_import_inference(self) -> None:
607 # Explication of bug
608 """When we import PickleError from nonexistent, a call to the infer
609 method of this From node will be made by unpack_infer.
610 inference.infer_from will try to import this module, which will fail and
611 raise a InferenceException (by ImportNode.do_import_module). The infer_name
612 will catch this exception and yield and Uninferable instead.
613 """
614
615 code = """
616 try:
617 from pickle import PickleError
618 except ImportError:
619 from nonexistent import PickleError
620
621 try:
622 pass
623 except PickleError:
624 pass
625 """
626 module = builder.parse(code)
627 handler_type = module.body[1].handlers[0].type
628
629 excs = list(nodes.unpack_infer(handler_type))
630 # The number of returned object can differ on Python 2
631 # and Python 3. In one version, an additional item will
632 # be returned, from the _pickle module, which is not
633 # present in the other version.
634 self.assertIsInstance(excs[0], nodes.ClassDef)
635 self.assertEqual(excs[0].name, "PickleError")
636 self.assertIs(excs[-1], util.Uninferable)
637
638 def test_absolute_import(self) -> None:
639 module = resources.build_file("data/absimport.py")
640 ctx = InferenceContext()
641 # will fail if absolute import failed
642 ctx.lookupname = "message"
643 next(module["message"].infer(ctx))
644 ctx.lookupname = "email"
645 m = next(module["email"].infer(ctx))
646 self.assertFalse(m.file.startswith(os.path.join("data", "email.py")))
647
648 def test_more_absolute_import(self) -> None:
649 module = resources.build_file("data/module1abs/__init__.py", "data.module1abs")
650 self.assertIn("sys", module.locals)
651
652 _pickle_names = ("dump",) # "dumps", "load", "loads")
653
654 def test_conditional(self) -> None:
655 module = resources.build_file("data/conditional_import/__init__.py")
656 ctx = InferenceContext()
657
658 for name in self._pickle_names:
659 ctx.lookupname = name
660 some = list(module[name].infer(ctx))
661 assert Uninferable not in some, name
662
663 def test_conditional_import(self) -> None:
664 module = resources.build_file("data/conditional.py")
665 ctx = InferenceContext()
666
667 for name in self._pickle_names:
668 ctx.lookupname = name
669 some = list(module[name].infer(ctx))
670 assert Uninferable not in some, name
671
672
673 class CmpNodeTest(unittest.TestCase):
674 def test_as_string(self) -> None:
675 ast = abuilder.string_build("a == 2").body[0]
676 self.assertEqual(ast.as_string(), "a == 2")
677
678
679 class ConstNodeTest(unittest.TestCase):
680 def _test(self, value: Any) -> None:
681 node = nodes.const_factory(value)
682 self.assertIsInstance(node._proxied, nodes.ClassDef)
683 self.assertEqual(node._proxied.name, value.__class__.__name__)
684 self.assertIs(node.value, value)
685 self.assertTrue(node._proxied.parent)
686 self.assertEqual(node._proxied.root().name, value.__class__.__module__)
687 with self.assertRaises(StatementMissing):
688 node.statement()
689 assert node.frame() is SYNTHETIC_ROOT
690
691 def test_none(self) -> None:
692 self._test(None)
693
694 def test_bool(self) -> None:
695 self._test(True)
696
697 def test_int(self) -> None:
698 self._test(1)
699
700 def test_float(self) -> None:
701 self._test(1.0)
702
703 def test_complex(self) -> None:
704 self._test(1.0j)
705
706 def test_str(self) -> None:
707 self._test("a")
708
709 def test_unicode(self) -> None:
710 self._test("a")
711
712 def test_str_kind(self):
713 node = builder.extract_node("""
714 const = u"foo"
715 """)
716 assert isinstance(node.value, nodes.Const)
717 assert node.value.value == "foo"
718 assert node.value.kind, "u"
719
720 def test_copy(self) -> None:
721 """Make sure copying a Const object doesn't result in infinite recursion."""
722 const = copy.copy(nodes.Const(1))
723 assert const.value == 1
724
725
726 class NameNodeTest(unittest.TestCase):
727 def test_assign_to_true(self) -> None:
728 """Test that True and False assignments don't crash."""
729 code = """
730 True = False
731 def hello(False):
732 pass
733 del True
734 """
735 with self.assertRaises(AstroidBuildingError):
736 builder.parse(code)
737
738
739 class TestNamedExprNode:
740 """Tests for the NamedExpr node."""
741
742 @staticmethod
743 def test_frame() -> None:
744 """Test if the frame of NamedExpr is correctly set for certain types
745 of parent nodes.
746 """
747 module = builder.parse("""
748 def func(var_1):
749 pass
750
751 def func_two(var_2, var_2 = (named_expr_1 := "walrus")):
752 pass
753
754 class MyBaseClass:
755 pass
756
757 class MyInheritedClass(MyBaseClass, var_3=(named_expr_2 := "walrus")):
758 pass
759
760 VAR = lambda y = (named_expr_3 := "walrus"): print(y)
761
762 def func_with_lambda(
763 var_5 = (
764 named_expr_4 := lambda y = (named_expr_5 := "walrus"): y
765 )
766 ):
767 pass
768
769 COMPREHENSION = [y for i in (1, 2) if (y := i ** 2)]
770 """)
771 function = module.body[0]
772 assert function.args.frame() == function
773 assert function.args.frame() == function
774
775 function_two = module.body[1]
776 assert function_two.args.args[0].frame() == function_two
777 assert function_two.args.args[0].frame() == function_two
778 assert function_two.args.args[1].frame() == function_two
779 assert function_two.args.args[1].frame() == function_two
780 assert function_two.args.defaults[0].frame() == module
781 assert function_two.args.defaults[0].frame() == module
782
783 inherited_class = module.body[3]
784 assert inherited_class.keywords[0].frame() == inherited_class
785 assert inherited_class.keywords[0].frame() == inherited_class
786 assert inherited_class.keywords[0].value.frame() == module
787 assert inherited_class.keywords[0].value.frame() == module
788
789 lambda_assignment = module.body[4].value
790 assert lambda_assignment.args.args[0].frame() == lambda_assignment
791 assert lambda_assignment.args.args[0].frame() == lambda_assignment
792 assert lambda_assignment.args.defaults[0].frame() == module
793 assert lambda_assignment.args.defaults[0].frame() == module
794
795 lambda_named_expr = module.body[5].args.defaults[0]
796 assert lambda_named_expr.value.args.defaults[0].frame() == module
797 assert lambda_named_expr.value.args.defaults[0].frame() == module
798
799 comprehension = module.body[6].value
800 assert comprehension.generators[0].ifs[0].frame() == module
801 assert comprehension.generators[0].ifs[0].frame() == module
802
803 @staticmethod
804 def test_scope() -> None:
805 """Test if the scope of NamedExpr is correctly set for certain types
806 of parent nodes.
807 """
808 module = builder.parse("""
809 def func(var_1):
810 pass
811
812 def func_two(var_2, var_2 = (named_expr_1 := "walrus")):
813 pass
814
815 class MyBaseClass:
816 pass
817
818 class MyInheritedClass(MyBaseClass, var_3=(named_expr_2 := "walrus")):
819 pass
820
821 VAR = lambda y = (named_expr_3 := "walrus"): print(y)
822
823 def func_with_lambda(
824 var_5 = (
825 named_expr_4 := lambda y = (named_expr_5 := "walrus"): y
826 )
827 ):
828 pass
829
830 COMPREHENSION = [y for i in (1, 2) if (y := i ** 2)]
831 """)
832 function = module.body[0]
833 assert function.args.scope() == function
834
835 function_two = module.body[1]
836 assert function_two.args.args[0].scope() == function_two
837 assert function_two.args.args[1].scope() == function_two
838 assert function_two.args.defaults[0].scope() == module
839
840 inherited_class = module.body[3]
841 assert inherited_class.keywords[0].scope() == inherited_class
842 assert inherited_class.keywords[0].value.scope() == module
843
844 lambda_assignment = module.body[4].value
845 assert lambda_assignment.args.args[0].scope() == lambda_assignment
846 assert lambda_assignment.args.defaults[0].scope()
847
848 lambda_named_expr = module.body[5].args.defaults[0]
849 assert lambda_named_expr.value.args.defaults[0].scope() == module
850
851 comprehension = module.body[6].value
852 assert comprehension.generators[0].ifs[0].scope() == module
853
854
855 class AnnAssignNodeTest(unittest.TestCase):
856 def test_primitive(self) -> None:
857 code = textwrap.dedent("""
858 test: int = 5
859 """)
860 assign = builder.extract_node(code)
861 self.assertIsInstance(assign, nodes.AnnAssign)
862 self.assertEqual(assign.target.name, "test")
863 self.assertEqual(assign.annotation.name, "int")
864 self.assertEqual(assign.value.value, 5)
865 self.assertEqual(assign.simple, 1)
866
867 def test_primitive_without_initial_value(self) -> None:
868 code = textwrap.dedent("""
869 test: str
870 """)
871 assign = builder.extract_node(code)
872 self.assertIsInstance(assign, nodes.AnnAssign)
873 self.assertEqual(assign.target.name, "test")
874 self.assertEqual(assign.annotation.name, "str")
875 self.assertEqual(assign.value, None)
876
877 def test_complex(self) -> None:
878 code = textwrap.dedent("""
879 test: Dict[List[str]] = {}
880 """)
881 assign = builder.extract_node(code)
882 self.assertIsInstance(assign, nodes.AnnAssign)
883 self.assertEqual(assign.target.name, "test")
884 self.assertIsInstance(assign.annotation, nodes.Subscript)
885 self.assertIsInstance(assign.value, nodes.Dict)
886
887 def test_as_string(self) -> None:
888 code = textwrap.dedent("""
889 print()
890 test: int = 5
891 test2: str
892 test3: List[Dict[str, str]] = []
893 """)
894 ast = abuilder.string_build(code)
895 self.assertEqual(ast.as_string().strip(), code.strip())
896
897
898 class ArgumentsNodeTC(unittest.TestCase):
899 def test_linenumbering(self) -> None:
900 ast = builder.parse("""
901 def func(a,
902 b): pass
903 x = lambda x: None
904 """)
905 self.assertEqual(ast["func"].args.fromlineno, 2)
906 self.assertFalse(ast["func"].args.is_statement)
907 xlambda = next(ast["x"].infer())
908 self.assertEqual(xlambda.args.fromlineno, 4)
909 self.assertEqual(xlambda.args.tolineno, 4)
910 self.assertFalse(xlambda.args.is_statement)
911
912 def test_kwoargs(self) -> None:
913 ast = builder.parse("""
914 def func(*, x):
915 pass
916 """)
917 args = ast["func"].args
918 assert isinstance(args, nodes.Arguments)
919 assert args.is_argument("x")
920 assert args.kw_defaults == [None]
921
922 ast = builder.parse("""
923 def func(*, x = "default"):
924 pass
925 """)
926 args = ast["func"].args
927 assert isinstance(args, nodes.Arguments)
928 assert args.is_argument("x")
929 assert len(args.kw_defaults) == 1
930 assert isinstance(args.kw_defaults[0], nodes.Const)
931 assert args.kw_defaults[0].value == "default"
932
933 def test_positional_only(self):
934 ast = builder.parse("""
935 def func(x, /, y):
936 pass
937 """)
938 args = ast["func"].args
939 self.assertTrue(args.is_argument("x"))
940 self.assertTrue(args.is_argument("y"))
941 index, node = args.find_argname("x")
942 self.assertEqual(index, 0)
943 self.assertIsNotNone(node)
944
945
946 class UnboundMethodNodeTest(unittest.TestCase):
947 def test_no_super_getattr(self) -> None:
948 # This is a test for issue
949 # https://bitbucket.org/logilab/astroid/issue/91, which tests
950 # that UnboundMethod doesn't call super when doing .getattr.
951
952 ast = builder.parse("""
953 class A(object):
954 def test(self):
955 pass
956 meth = A.test
957 """)
958 node = next(ast["meth"].infer())
959 with self.assertRaises(AttributeInferenceError):
960 node.getattr("__missssing__")
961 name = node.getattr("__name__")[0]
962 self.assertIsInstance(name, nodes.Const)
963 self.assertEqual(name.value, "test")
964
965
966 class BoundMethodNodeTest(unittest.TestCase):
967 def _is_property(self, ast: nodes.Module, prop: str) -> None:
968 inferred = next(ast[prop].infer())
969 self.assertIsInstance(inferred, nodes.Const, prop)
970 self.assertEqual(inferred.value, 42, prop)
971
972 def test_is_standard_property(self) -> None:
973 # Test to make sure the Python-provided property decorators
974 # are properly interpreted as properties
975 ast = builder.parse("""
976 import abc
977 import functools
978
979 class A(object):
980 @property
981 def builtin_property(self): return 42
982
983 @abc.abstractproperty
984 def abc_property(self): return 42
985
986 @property
987 @abc.abstractmethod
988 def abstractmethod_property(self): return 42
989
990 @functools.cached_property
991 def functools_property(self): return 42
992
993 cls = A()
994 builtin_p = cls.builtin_property
995 abc_p = cls.abc_property
996 abstractmethod_p = cls.abstractmethod_property
997 functools_p = cls.functools_property
998 """)
999 for prop in (
1000 "builtin_p",
1001 "abc_p",
1002 "abstractmethod_p",
1003 "functools_p",
1004 ):
1005 self._is_property(ast, prop)
1006
1007 @pytest.mark.skipif(not PY311_PLUS, reason="Uses enum.property introduced in 3.11")
1008 def test_is_standard_property_py311(self) -> None:
1009 # Test to make sure the Python-provided property decorators
1010 # are properly interpreted as properties
1011 ast = builder.parse("""
1012 import enum
1013
1014 class A(object):
1015 @enum.property
1016 def enum_property(self): return 42
1017
1018 cls = A()
1019 enum_p = cls.enum_property
1020 """)
1021 self._is_property(ast, "enum_p")
1022
1023 def test_is_possible_property(self) -> None:
1024 # Test to make sure that decorators with POSSIBLE_PROPERTIES names
1025 # are properly interpreted as properties
1026 ast = builder.parse("""
1027 # Not real decorators, but we don't care
1028 def cachedproperty(): pass
1029 def cached_property(): pass
1030 def reify(): pass
1031 def lazy_property(): pass
1032 def lazyproperty(): pass
1033 def lazy(): pass
1034 def lazyattribute(): pass
1035 def lazy_attribute(): pass
1036 def LazyProperty(): pass
1037 def DynamicClassAttribute(): pass
1038
1039 class A(object):
1040 @cachedproperty
1041 def cachedproperty(self): return 42
1042
1043 @cached_property
1044 def cached_property(self): return 42
1045
1046 @reify
1047 def reified(self): return 42
1048
1049 @lazy_property
1050 def lazy_prop(self): return 42
1051
1052 @lazyproperty
1053 def lazyprop(self): return 42
1054
1055 @lazy
1056 def decorated_with_lazy(self): return 42
1057
1058 @lazyattribute
1059 def lazyattribute(self): return 42
1060
1061 @lazy_attribute
1062 def lazy_attribute(self): return 42
1063
1064 @LazyProperty
1065 def LazyProperty(self): return 42
1066
1067 @DynamicClassAttribute
1068 def DynamicClassAttribute(self): return 42
1069
1070 cls = A()
1071 cachedp = cls.cachedproperty
1072 cached_p = cls.cached_property
1073 reified = cls.reified
1074 lazy_prop = cls.lazy_prop
1075 lazyprop = cls.lazyprop
1076 decorated_with_lazy = cls.decorated_with_lazy
1077 lazya = cls.lazyattribute
1078 lazy_a = cls.lazy_attribute
1079 LazyP = cls.LazyProperty
1080 DynamicClassA = cls.DynamicClassAttribute
1081 """)
1082 for prop in (
1083 "cachedp",
1084 "cached_p",
1085 "reified",
1086 "lazy_prop",
1087 "lazyprop",
1088 "decorated_with_lazy",
1089 "lazya",
1090 "lazy_a",
1091 "LazyP",
1092 "DynamicClassA",
1093 ):
1094 self._is_property(ast, prop)
1095
1096 def test_is_standard_property_subclass(self) -> None:
1097 # Test to make sure that subclasses of the Python-provided property decorators
1098 # are properly interpreted as properties
1099 ast = builder.parse("""
1100 import abc
1101 import functools
1102 from typing import Generic, TypeVar
1103
1104 class user_property(property): pass
1105 class user_abc_property(abc.abstractproperty): pass
1106 class user_functools_property(functools.cached_property): pass
1107 T = TypeVar('T')
1108 class annotated_user_functools_property(functools.cached_property[T], Generic[T]): pass
1109
1110 class A(object):
1111 @user_property
1112 def user_property(self): return 42
1113
1114 @user_abc_property
1115 def user_abc_property(self): return 42
1116
1117 @user_functools_property
1118 def user_functools_property(self): return 42
1119
1120 @annotated_user_functools_property
1121 def annotated_user_functools_property(self): return 42
1122
1123 cls = A()
1124 user_p = cls.user_property
1125 user_abc_p = cls.user_abc_property
1126 user_functools_p = cls.user_functools_property
1127 annotated_user_functools_p = cls.annotated_user_functools_property
1128 """)
1129 for prop in (
1130 "user_p",
1131 "user_abc_p",
1132 "user_functools_p",
1133 "annotated_user_functools_p",
1134 ):
1135 self._is_property(ast, prop)
1136
1137 @pytest.mark.skipif(not PY311_PLUS, reason="Uses enum.property introduced in 3.11")
1138 def test_is_standard_property_subclass_py311(self) -> None:
1139 # Test to make sure that subclasses of the Python-provided property decorators
1140 # are properly interpreted as properties
1141 ast = builder.parse("""
1142 import enum
1143
1144 class user_enum_property(enum.property): pass
1145
1146 class A(object):
1147 @user_enum_property
1148 def user_enum_property(self): return 42
1149
1150 cls = A()
1151 user_enum_p = cls.user_enum_property
1152 """)
1153 self._is_property(ast, "user_enum_p")
1154
1155 @pytest.mark.skipif(not PY312_PLUS, reason="Uses 3.12 generic typing syntax")
1156 def test_is_standard_property_subclass_py312(self) -> None:
1157 ast = builder.parse("""
1158 from functools import cached_property
1159
1160 class annotated_user_cached_property[T](cached_property[T]):
1161 pass
1162
1163 class A(object):
1164 @annotated_user_cached_property
1165 def annotated_user_cached_property(self): return 42
1166
1167 cls = A()
1168 annotated_user_cached_p = cls.annotated_user_cached_property
1169 """)
1170 self._is_property(ast, "annotated_user_cached_p")
1171
1172 def test_is_not_property(self) -> None:
1173 ast = builder.parse("""
1174 from collections.abc import Iterator
1175
1176 class cached_property: pass
1177 # If a decorator is named cached_property, we will accept it as a property,
1178 # even if it isn't functools.cached_property.
1179 # However, do not extend the same leniency to superclasses of decorators.
1180 class wrong_superclass_type1(cached_property): pass
1181 class wrong_superclass_type2(cached_property[float]): pass
1182 cachedproperty = { float: int }
1183 class wrong_superclass_type3(cachedproperty[float]): pass
1184 class wrong_superclass_type4(Iterator[float]): pass
1185
1186 class A(object):
1187 def no_decorator(self): return 42
1188
1189 def property(self): return 42
1190
1191 @wrong_superclass_type1
1192 def wrong_superclass_type1(self): return 42
1193
1194 @wrong_superclass_type2
1195 def wrong_superclass_type2(self): return 42
1196
1197 @wrong_superclass_type3
1198 def wrong_superclass_type3(self): return 42
1199
1200 @wrong_superclass_type4
1201 def wrong_superclass_type4(self): return 42
1202
1203 cls = A()
1204 no_decorator = cls.no_decorator
1205 not_prop = cls.property
1206 bad_superclass1 = cls.wrong_superclass_type1
1207 bad_superclass2 = cls.wrong_superclass_type2
1208 bad_superclass3 = cls.wrong_superclass_type3
1209 bad_superclass4 = cls.wrong_superclass_type4
1210 """)
1211 for prop in (
1212 "no_decorator",
1213 "not_prop",
1214 "bad_superclass1",
1215 "bad_superclass2",
1216 "bad_superclass3",
1217 "bad_superclass4",
1218 ):
1219 inferred = next(ast[prop].infer())
1220 self.assertIsInstance(inferred, bases.BoundMethod)
1221
1222
1223 class AliasesTest(unittest.TestCase):
1224 def setUp(self) -> None:
1225 self.transformer = transforms.TransformVisitor()
1226
1227 def parse_transform(self, code: str) -> nodes.Module:
1228 module = parse(code, apply_transforms=False)
1229 return self.transformer.visit(module)
1230
1231 def test_aliases(self) -> None:
1232 def test_from(node: nodes.ImportFrom) -> nodes.ImportFrom:
1233 node.names = [*node.names, ("absolute_import", None)]
1234 return node
1235
1236 def test_class(node: nodes.ClassDef) -> nodes.ClassDef:
1237 node.name = "Bar"
1238 return node
1239
1240 def test_function(node: nodes.FunctionDef) -> nodes.FunctionDef:
1241 node.name = "another_test"
1242 return node
1243
1244 def test_callfunc(node: nodes.Call) -> nodes.Call | None:
1245 if node.func.name == "Foo":
1246 node.func.name = "Bar"
1247 return node
1248 return None
1249
1250 def test_assname(node: nodes.AssignName) -> nodes.AssignName | None:
1251 if node.name == "foo":
1252 return nodes.AssignName(
1253 "bar",
1254 node.lineno,
1255 node.col_offset,
1256 node.parent,
1257 end_lineno=node.end_lineno,
1258 end_col_offset=node.end_col_offset,
1259 )
1260 return None
1261
1262 def test_assattr(node: nodes.AssignAttr) -> nodes.AssignAttr:
1263 if node.attrname == "a":
1264 node.attrname = "b"
1265 return node
1266 return None
1267
1268 def test_getattr(node: nodes.Attribute) -> nodes.Attribute:
1269 if node.attrname == "a":
1270 node.attrname = "b"
1271 return node
1272 return None
1273
1274 def test_genexpr(node: nodes.GeneratorExp) -> nodes.GeneratorExp:
1275 if node.elt.value == 1:
1276 node.elt = nodes.Const(2, node.lineno, node.col_offset, node.parent)
1277 return node
1278 return None
1279
1280 self.transformer.register_transform(nodes.ImportFrom, test_from)
1281 self.transformer.register_transform(nodes.ClassDef, test_class)
1282 self.transformer.register_transform(nodes.FunctionDef, test_function)
1283 self.transformer.register_transform(nodes.Call, test_callfunc)
1284 self.transformer.register_transform(nodes.AssignName, test_assname)
1285 self.transformer.register_transform(nodes.AssignAttr, test_assattr)
1286 self.transformer.register_transform(nodes.Attribute, test_getattr)
1287 self.transformer.register_transform(nodes.GeneratorExp, test_genexpr)
1288
1289 string = """
1290 from __future__ import print_function
1291
1292 class Foo: pass
1293
1294 def test(a): return a
1295
1296 foo = Foo()
1297 foo.a = test(42)
1298 foo.a
1299 (1 for _ in range(0, 42))
1300 """
1301
1302 module = self.parse_transform(string)
1303
1304 self.assertEqual(len(module.body[0].names), 2)
1305 self.assertIsInstance(module.body[0], nodes.ImportFrom)
1306 self.assertEqual(module.body[1].name, "Bar")
1307 self.assertIsInstance(module.body[1], nodes.ClassDef)
1308 self.assertEqual(module.body[2].name, "another_test")
1309 self.assertIsInstance(module.body[2], nodes.FunctionDef)
1310 self.assertEqual(module.body[3].targets[0].name, "bar")
1311 self.assertIsInstance(module.body[3].targets[0], nodes.AssignName)
1312 self.assertEqual(module.body[3].value.func.name, "Bar")
1313 self.assertIsInstance(module.body[3].value, nodes.Call)
1314 self.assertEqual(module.body[4].targets[0].attrname, "b")
1315 self.assertIsInstance(module.body[4].targets[0], nodes.AssignAttr)
1316 self.assertIsInstance(module.body[5], nodes.Expr)
1317 self.assertEqual(module.body[5].value.attrname, "b")
1318 self.assertIsInstance(module.body[5].value, nodes.Attribute)
1319 self.assertEqual(module.body[6].value.elt.value, 2)
1320 self.assertIsInstance(module.body[6].value, nodes.GeneratorExp)
1321
1322
1323 class Python35AsyncTest(unittest.TestCase):
1324 def test_async_await_keywords(self) -> None:
1325 (
1326 async_def,
1327 async_for,
1328 async_with,
1329 async_for2,
1330 async_with2,
1331 await_node,
1332 ) = builder.extract_node(
1333 """
1334 async def func(): #@
1335 async for i in range(10): #@
1336 f = __(await i)
1337 async with test(): #@
1338 pass
1339 async for i \
1340 in range(10): #@
1341 pass
1342 async with test(), \
1343 test2(): #@
1344 pass
1345 """
1346 )
1347 assert isinstance(async_def, nodes.AsyncFunctionDef)
1348 assert async_def.lineno == 2
1349 assert async_def.col_offset == 0
1350
1351 assert isinstance(async_for, nodes.AsyncFor)
1352 assert async_for.lineno == 3
1353 assert async_for.col_offset == 4
1354
1355 assert isinstance(async_with, nodes.AsyncWith)
1356 assert async_with.lineno == 5
1357 assert async_with.col_offset == 4
1358
1359 assert isinstance(async_for2, nodes.AsyncFor)
1360 assert async_for2.lineno == 7
1361 assert async_for2.col_offset == 4
1362
1363 assert isinstance(async_with2, nodes.AsyncWith)
1364 assert async_with2.lineno == 9
1365 assert async_with2.col_offset == 4
1366
1367 assert isinstance(await_node, nodes.Await)
1368 assert isinstance(await_node.value, nodes.Name)
1369 assert await_node.lineno == 4
1370 assert await_node.col_offset == 15
1371
1372 def _test_await_async_as_string(self, code: str) -> None:
1373 ast_node = parse(code)
1374 self.assertEqual(ast_node.as_string().strip(), code.strip())
1375
1376 def test_await_as_string(self) -> None:
1377 code = textwrap.dedent("""
1378 async def function():
1379 await 42
1380 await x[0]
1381 (await x)[0]
1382 await (x + y)[0]
1383 """)
1384 self._test_await_async_as_string(code)
1385
1386 def test_asyncwith_as_string(self) -> None:
1387 code = textwrap.dedent("""
1388 async def function():
1389 async with 42:
1390 pass
1391 """)
1392 self._test_await_async_as_string(code)
1393
1394 def test_asyncfor_as_string(self) -> None:
1395 code = textwrap.dedent("""
1396 async def function():
1397 async for i in range(10):
1398 await 42
1399 """)
1400 self._test_await_async_as_string(code)
1401
1402 def test_decorated_async_def_as_string(self) -> None:
1403 code = textwrap.dedent("""
1404 @decorator
1405 async def function():
1406 async for i in range(10):
1407 await 42
1408 """)
1409 self._test_await_async_as_string(code)
1410
1411
1412 class ContextTest(unittest.TestCase):
1413 def test_subscript_load(self) -> None:
1414 node = builder.extract_node("f[1]")
1415 self.assertIs(node.ctx, Context.Load)
1416
1417 def test_subscript_del(self) -> None:
1418 node = builder.extract_node("del f[1]")
1419 self.assertIs(node.targets[0].ctx, Context.Del)
1420
1421 def test_subscript_store(self) -> None:
1422 node = builder.extract_node("f[1] = 2")
1423 subscript = node.targets[0]
1424 self.assertIs(subscript.ctx, Context.Store)
1425
1426 def test_list_load(self) -> None:
1427 node = builder.extract_node("[]")
1428 self.assertIs(node.ctx, Context.Load)
1429
1430 def test_list_del(self) -> None:
1431 node = builder.extract_node("del []")
1432 self.assertIs(node.targets[0].ctx, Context.Del)
1433
1434 def test_list_store(self) -> None:
1435 with self.assertRaises(AstroidSyntaxError):
1436 builder.extract_node("[0] = 2")
1437
1438 def test_tuple_load(self) -> None:
1439 node = builder.extract_node("(1, )")
1440 self.assertIs(node.ctx, Context.Load)
1441
1442 def test_tuple_store(self) -> None:
1443 with self.assertRaises(AstroidSyntaxError):
1444 builder.extract_node("(1, ) = 3")
1445
1446 def test_starred_load(self) -> None:
1447 node = builder.extract_node("a = *b")
1448 starred = node.value
1449 self.assertIs(starred.ctx, Context.Load)
1450
1451 def test_starred_store(self) -> None:
1452 node = builder.extract_node("a, *b = 1, 2")
1453 starred = node.targets[0].elts[1]
1454 self.assertIs(starred.ctx, Context.Store)
1455
1456
1457 def test_unknown() -> None:
1458 """Test Unknown node."""
1459 assert isinstance(next(UNATTACHED_UNKNOWN.infer()), type(util.Uninferable))
1460 assert isinstance(UNATTACHED_UNKNOWN.name, str)
1461 assert isinstance(UNATTACHED_UNKNOWN.qname(), str)
1462
1463
1464 def test_type_comments_with() -> None:
1465 module = builder.parse("""
1466 with a as b: # type: int
1467 pass
1468 with a as b: # type: ignore[name-defined]
1469 pass
1470 """)
1471 node = module.body[0]
1472 ignored_node = module.body[1]
1473 assert isinstance(node.type_annotation, nodes.Name)
1474
1475 assert ignored_node.type_annotation is None
1476
1477
1478 def test_type_comments_for() -> None:
1479 module = builder.parse("""
1480 for a, b in [1, 2, 3]: # type: List[int]
1481 pass
1482 for a, b in [1, 2, 3]: # type: ignore[name-defined]
1483 pass
1484 """)
1485 node = module.body[0]
1486 ignored_node = module.body[1]
1487 assert isinstance(node.type_annotation, nodes.Subscript)
1488 assert node.type_annotation.as_string() == "List[int]"
1489
1490 assert ignored_node.type_annotation is None
1491
1492
1493 def test_type_coments_assign() -> None:
1494 module = builder.parse("""
1495 a, b = [1, 2, 3] # type: List[int]
1496 a, b = [1, 2, 3] # type: ignore[name-defined]
1497 """)
1498 node = module.body[0]
1499 ignored_node = module.body[1]
1500 assert isinstance(node.type_annotation, nodes.Subscript)
1501 assert node.type_annotation.as_string() == "List[int]"
1502
1503 assert ignored_node.type_annotation is None
1504
1505
1506 def test_type_comments_invalid_expression() -> None:
1507 module = builder.parse("""
1508 a, b = [1, 2, 3] # type: something completely invalid
1509 a, b = [1, 2, 3] # typeee: 2*+4
1510 a, b = [1, 2, 3] # type: List[int
1511 """)
1512 for node in module.body:
1513 assert node.type_annotation is None
1514
1515
1516 def test_type_comments_invalid_function_comments() -> None:
1517 module = builder.parse("""
1518 def func(
1519 # type: () -> int # inside parentheses
1520 ):
1521 pass
1522 def func():
1523 # type: something completely invalid
1524 pass
1525 def func1():
1526 # typeee: 2*+4
1527 pass
1528 def func2():
1529 # type: List[int
1530 pass
1531 """)
1532 for node in module.body:
1533 assert node.type_comment_returns is None
1534 assert node.type_comment_args is None
1535
1536
1537 def test_type_comments_pathological_assign() -> None:
1538 """Regression test for issue #2993.
1539
1540 A type comment with deeply nested braces causes ``ast.parse`` to raise
1541 ``MemoryError`` (or ``ValueError`` on some interpreters). astroid should
1542 treat the type comment as invalid instead of crashing.
1543 """
1544 code = "a = b # type:i" + "{" * 200
1545 module = builder.parse(code)
1546 assert module.body[0].type_annotation is None
1547
1548
1549 def test_type_comments_pathological_function() -> None:
1550 """Regression test for issue #2993 covering function type comments."""
1551 code = "def func():\n # type: i" + "{" * 200 + "\n pass\n"
1552 module = builder.parse(code)
1553 assert module.body[0].type_comment_returns is None
1554 assert module.body[0].type_comment_args is None
1555
1556
1557 def test_type_comments_function() -> None:
1558 module = builder.parse("""
1559 def func():
1560 # type: (int) -> str
1561 pass
1562 def func1():
1563 # type: (int, int, int) -> (str, str)
1564 pass
1565 def func2():
1566 # type: (int, int, str, List[int]) -> List[int]
1567 pass
1568 """)
1569 expected_annotations = [
1570 (["int"], nodes.Name, "str"),
1571 (["int", "int", "int"], nodes.Tuple, "(str, str)"),
1572 (["int", "int", "str", "List[int]"], nodes.Subscript, "List[int]"),
1573 ]
1574 for node, (expected_args, expected_returns_type, expected_returns_string) in zip(
1575 module.body, expected_annotations
1576 ):
1577 assert node.type_comment_returns is not None
1578 assert node.type_comment_args is not None
1579 for expected_arg, actual_arg in zip(expected_args, node.type_comment_args):
1580 assert actual_arg.as_string() == expected_arg
1581 assert isinstance(node.type_comment_returns, expected_returns_type)
1582 assert node.type_comment_returns.as_string() == expected_returns_string
1583
1584
1585 def test_type_comments_arguments() -> None:
1586 module = builder.parse("""
1587 def func(
1588 a, # type: int
1589 ):
1590 # type: (...) -> str
1591 pass
1592 def func1(
1593 a, # type: int
1594 b, # type: int
1595 c, # type: int
1596 ):
1597 # type: (...) -> (str, str)
1598 pass
1599 def func2(
1600 a, # type: int
1601 b, # type: int
1602 c, # type: str
1603 d, # type: List[int]
1604 ):
1605 # type: (...) -> List[int]
1606 pass
1607 """)
1608 expected_annotations = [
1609 ["int"],
1610 ["int", "int", "int"],
1611 ["int", "int", "str", "List[int]"],
1612 ]
1613 for node, expected_args in zip(module.body, expected_annotations):
1614 assert len(node.type_comment_args) == 1
1615 assert isinstance(node.type_comment_args[0], nodes.Const)
1616 assert node.type_comment_args[0].value == Ellipsis
1617 assert len(node.args.type_comment_args) == len(expected_args)
1618 for expected_arg, actual_arg in zip(expected_args, node.args.type_comment_args):
1619 assert actual_arg.as_string() == expected_arg
1620
1621
1622 def test_type_comments_posonly_arguments() -> None:
1623 module = builder.parse("""
1624 def f_arg_comment(
1625 a, # type: int
1626 b, # type: int
1627 /,
1628 c, # type: Optional[int]
1629 d, # type: Optional[int]
1630 *,
1631 e, # type: float
1632 f, # type: float
1633 ):
1634 # type: (...) -> None
1635 pass
1636 """)
1637 expected_annotations = [
1638 [["int", "int"], ["Optional[int]", "Optional[int]"], ["float", "float"]]
1639 ]
1640 for node, expected_types in zip(module.body, expected_annotations):
1641 assert len(node.type_comment_args) == 1
1642 assert isinstance(node.type_comment_args[0], nodes.Const)
1643 assert node.type_comment_args[0].value == Ellipsis
1644 type_comments = [
1645 node.args.type_comment_posonlyargs,
1646 node.args.type_comment_args,
1647 node.args.type_comment_kwonlyargs,
1648 ]
1649 for expected_args, actual_args in zip(expected_types, type_comments):
1650 assert len(expected_args) == len(actual_args)
1651 for expected_arg, actual_arg in zip(expected_args, actual_args):
1652 assert actual_arg.as_string() == expected_arg
1653
1654
1655 def test_correct_function_type_comment_parent() -> None:
1656 data = """
1657 def f(a):
1658 # type: (A) -> A
1659 pass
1660 """
1661 parsed_data = builder.parse(data)
1662 f = parsed_data.body[0]
1663 assert f.type_comment_args[0].parent is f
1664 assert f.type_comment_returns.parent is f
1665
1666
1667 def test_is_generator_for_yield_assignments() -> None:
1668 node = astroid.extract_node("""
1669 class A:
1670 def test(self):
1671 a = yield
1672 while True:
1673 print(a)
1674 yield a
1675 a = A()
1676 a.test
1677 """)
1678 inferred = next(node.infer())
1679 assert isinstance(inferred, astroid.BoundMethod)
1680 assert bool(inferred.is_generator())
1681
1682
1683 class AsyncGeneratorTest(unittest.TestCase):
1684 def test_async_generator(self):
1685 node = astroid.extract_node("""
1686 async def a_iter(n):
1687 for i in range(1, n + 1):
1688 yield i
1689 await asyncio.sleep(1)
1690 a_iter(2) #@
1691 """)
1692 inferred = next(node.infer())
1693 assert isinstance(inferred, bases.AsyncGenerator)
1694 assert inferred.getattr("__aiter__")
1695 assert inferred.getattr("__anext__")
1696 assert inferred.pytype() == "builtins.async_generator"
1697 assert inferred.display_type() == "AsyncGenerator"
1698
1699
1700 def test_f_string_correct_line_numbering() -> None:
1701 """Test that we generate correct line numbers for f-strings."""
1702 node = astroid.extract_node("""
1703 def func_foo(arg_bar, arg_foo):
1704 dict_foo = {}
1705
1706 f'{arg_bar.attr_bar}' #@
1707 """)
1708 assert node.lineno == 5
1709 assert node.last_child().lineno == 5
1710 assert node.last_child().last_child().lineno == 5
1711
1712
1713 def test_assignment_expression() -> None:
1714 code = """
1715 if __(a := 1):
1716 pass
1717 if __(b := test):
1718 pass
1719 """
1720 first, second = astroid.extract_node(code)
1721
1722 assert isinstance(first.target, nodes.AssignName)
1723 assert first.target.name == "a"
1724 assert isinstance(first.value, nodes.Const)
1725 assert first.value.value == 1
1726 assert first.as_string() == "(a := 1)"
1727
1728 assert isinstance(second.target, nodes.AssignName)
1729 assert second.target.name == "b"
1730 assert isinstance(second.value, nodes.Name)
1731 assert second.value.name == "test"
1732 assert second.as_string() == "(b := test)"
1733
1734
1735 def test_assignment_expression_as_string() -> None:
1736 """Regression test for https://github.com/pylint-dev/astroid/issues/2668."""
1737 code = "if attn_output.size() != (size := (1, 2, 3, 4)):\n pass"
1738 rendered = astroid.extract_node(code).as_string()
1739 assert "(size := (1, 2, 3, 4))" in rendered
1740 compile(rendered, "<astroid-as-string>", "exec")
1741
1742
1743 def test_assignment_expression_compare_operands_as_string() -> None:
1744 """NamedExpr operands always render with their own parens."""
1745 compare = astroid.parse("if (a := 10) != (a := 10):\n pass").body[0].test
1746
1747 assert isinstance(compare, nodes.Compare)
1748 assert compare.left.as_string() == "a := 10"
1749 assert compare.ops[0][1].as_string() == "a := 10"
1750 assert compare.as_string() == "(a := 10) != (a := 10)"
1751
1752
1753 def test_assignment_expression_in_functiondef() -> None:
1754 code = """
1755 def function(param = (assignment := "walrus")):
1756 def inner_function(inner_param = (inner_assign := "walrus")):
1757 pass
1758 pass
1759
1760 class MyClass(attr = (assignment_two := "walrus")):
1761 pass
1762
1763 VAR = lambda y = (assignment_three := "walrus"): print(y)
1764
1765 def func_with_lambda(
1766 param=(named_expr_four := lambda y=(assignment_four := "walrus"): y),
1767 ):
1768 pass
1769
1770 COMPREHENSION = [y for i in (1, 2) if (assignment_five := i ** 2)]
1771
1772 def func():
1773 var = lambda y = (assignment_six := 2): print(y)
1774
1775 VAR_TWO = [
1776 func(assignment_seven := 2)
1777 for _ in (1,)
1778 ]
1779
1780 LAMBDA = lambda x: print(assignment_eight := x ** 2)
1781
1782 class SomeClass:
1783 (assignment_nine := 2**2)
1784 """
1785 module = astroid.parse(code)
1786
1787 assert "assignment" in module.locals
1788 assert isinstance(module.locals.get("assignment")[0], nodes.AssignName)
1789 function = module.body[0]
1790 assert "inner_assign" in function.locals
1791 assert "inner_assign" not in module.locals
1792 assert isinstance(function.locals.get("inner_assign")[0], nodes.AssignName)
1793
1794 assert "assignment_two" in module.locals
1795 assert isinstance(module.locals.get("assignment_two")[0], nodes.AssignName)
1796
1797 assert "assignment_three" in module.locals
1798 assert isinstance(module.locals.get("assignment_three")[0], nodes.AssignName)
1799
1800 assert "assignment_four" in module.locals
1801 assert isinstance(module.locals.get("assignment_four")[0], nodes.AssignName)
1802
1803 assert "assignment_five" in module.locals
1804 assert isinstance(module.locals.get("assignment_five")[0], nodes.AssignName)
1805
1806 func = module.body[5]
1807 assert "assignment_six" in func.locals
1808 assert "assignment_six" not in module.locals
1809 assert isinstance(func.locals.get("assignment_six")[0], nodes.AssignName)
1810
1811 assert "assignment_seven" in module.locals
1812 assert isinstance(module.locals.get("assignment_seven")[0], nodes.AssignName)
1813
1814 lambda_assign = module.body[7]
1815 assert "assignment_eight" in lambda_assign.value.locals
1816 assert "assignment_eight" not in module.locals
1817 assert isinstance(
1818 lambda_assign.value.locals.get("assignment_eight")[0], nodes.AssignName
1819 )
1820
1821 class_assign = module.body[8]
1822 assert "assignment_nine" in class_assign.locals
1823 assert "assignment_nine" not in module.locals
1824 assert isinstance(class_assign.locals.get("assignment_nine")[0], nodes.AssignName)
1825
1826
1827 def test_get_doc() -> None:
1828 code = textwrap.dedent("""\
1829 def func():
1830 "Docstring"
1831 return 1
1832 """)
1833 node: nodes.FunctionDef = astroid.extract_node(code) # type: ignore[assignment]
1834 assert isinstance(node.doc_node, nodes.Const)
1835 assert node.doc_node.value == "Docstring"
1836 assert node.doc_node.lineno == 2
1837 assert node.doc_node.col_offset == 4
1838 assert node.doc_node.end_lineno == 2
1839 assert node.doc_node.end_col_offset == 15
1840
1841 code = textwrap.dedent("""\
1842 def func():
1843 ...
1844 return 1
1845 """)
1846 node = astroid.extract_node(code)
1847 assert node.doc_node is None
1848
1849
1850 def test_parse_fstring_debug_mode() -> None:
1851 node = astroid.extract_node('f"{3=}"')
1852 assert isinstance(node, nodes.JoinedStr)
1853 assert node.as_string() == "f'3={3!r}'"
1854
1855
1856 def test_parse_type_comments_with_proper_parent() -> None:
1857 code = """
1858 class D: #@
1859 @staticmethod
1860 def g(
1861 x # type: np.array
1862 ):
1863 pass
1864 """
1865 node = astroid.extract_node(code)
1866 func = node.getattr("g")[0]
1867 type_comments = func.args.type_comment_args
1868 assert len(type_comments) == 1
1869
1870 type_comment = type_comments[0]
1871 assert isinstance(type_comment, nodes.Attribute)
1872 assert isinstance(type_comment.parent, nodes.Expr)
1873 assert isinstance(type_comment.parent.parent, nodes.Arguments)
1874
1875
1876 def test_const_itered() -> None:
1877 code = 'a = "string"'
1878 node = astroid.extract_node(code).value
1879 assert isinstance(node, nodes.Const)
1880 itered = node.itered()
1881 assert len(itered) == 6
1882 assert [elem.value for elem in itered] == list("string")
1883
1884
1885 def test_is_generator_for_yield_in_while() -> None:
1886 code = """
1887 def paused_iter(iterable):
1888 while True:
1889 # Continue to yield the same item until `next(i)` or `i.send(False)`
1890 while (yield value):
1891 pass
1892 """
1893 node = astroid.extract_node(code)
1894 assert bool(node.is_generator())
1895
1896
1897 def test_is_generator_for_yield_in_if() -> None:
1898 code = """
1899 import asyncio
1900
1901 def paused_iter(iterable):
1902 if (yield from asyncio.sleep(0.01)):
1903 pass
1904 return
1905 """
1906 node = astroid.extract_node(code)
1907 assert bool(node.is_generator())
1908
1909
1910 def test_is_generator_for_yield_in_aug_assign() -> None:
1911 code = """
1912 def test():
1913 buf = ''
1914 while True:
1915 buf += yield
1916 """
1917 node = astroid.extract_node(code)
1918 assert bool(node.is_generator())
1919
1920
1921 class TestPatternMatching:
1922 @staticmethod
1923 def test_match_simple():
1924 code = textwrap.dedent("""
1925 match status:
1926 case 200:
1927 pass
1928 case 401 | 402 | 403:
1929 pass
1930 case None:
1931 pass
1932 case _:
1933 pass
1934 """).strip()
1935 node = builder.extract_node(code)
1936 assert node.as_string() == code
1937 assert isinstance(node, nodes.Match)
1938 assert isinstance(node.subject, nodes.Name)
1939 assert node.subject.name == "status"
1940 assert isinstance(node.cases, list) and len(node.cases) == 4
1941 case0, case1, case2, case3 = node.cases
1942 assert list(node.get_children()) == [node.subject, *node.cases]
1943
1944 assert isinstance(case0.pattern, nodes.MatchValue)
1945 assert (
1946 isinstance(case0.pattern.value, nodes.Const)
1947 and case0.pattern.value.value == 200
1948 )
1949 assert list(case0.pattern.get_children()) == [case0.pattern.value]
1950 assert case0.guard is None
1951 assert isinstance(case0.body[0], nodes.Pass)
1952 assert list(case0.get_children()) == [case0.pattern, case0.body[0]]
1953
1954 assert isinstance(case1.pattern, nodes.MatchOr)
1955 assert (
1956 isinstance(case1.pattern.patterns, list)
1957 and len(case1.pattern.patterns) == 3
1958 )
1959 for i in range(3):
1960 match_value = case1.pattern.patterns[i]
1961 assert isinstance(match_value, nodes.MatchValue)
1962 assert isinstance(match_value.value, nodes.Const)
1963 assert match_value.value.value == (401, 402, 403)[i]
1964 assert list(case1.pattern.get_children()) == case1.pattern.patterns
1965
1966 assert isinstance(case2.pattern, nodes.MatchSingleton)
1967 assert case2.pattern.value is None
1968 assert not list(case2.pattern.get_children())
1969
1970 assert isinstance(case3.pattern, nodes.MatchAs)
1971 assert case3.pattern.name is None
1972 assert case3.pattern.pattern is None
1973 assert not list(case3.pattern.get_children())
1974
1975 @staticmethod
1976 def test_match_sequence():
1977 code = textwrap.dedent("""
1978 match status:
1979 case [x, 2, _, *rest] as y if x > 2:
1980 pass
1981 """).strip()
1982 node = builder.extract_node(code)
1983 assert node.as_string() == code
1984 assert isinstance(node, nodes.Match)
1985 assert isinstance(node.cases, list) and len(node.cases) == 1
1986 case = node.cases[0]
1987
1988 assert isinstance(case.pattern, nodes.MatchAs)
1989 assert isinstance(case.pattern.name, nodes.AssignName)
1990 assert case.pattern.name.name == "y"
1991 assert list(case.pattern.get_children()) == [
1992 case.pattern.pattern,
1993 case.pattern.name,
1994 ]
1995 assert isinstance(case.guard, nodes.Compare)
1996 assert isinstance(case.body[0], nodes.Pass)
1997 assert list(case.get_children()) == [case.pattern, case.guard, case.body[0]]
1998
1999 pattern_seq = case.pattern.pattern
2000 assert isinstance(pattern_seq, nodes.MatchSequence)
2001 assert isinstance(pattern_seq.patterns, list) and len(pattern_seq.patterns) == 4
2002 assert (
2003 isinstance(pattern_seq.patterns[0], nodes.MatchAs)
2004 and isinstance(pattern_seq.patterns[0].name, nodes.AssignName)
2005 and pattern_seq.patterns[0].name.name == "x"
2006 and pattern_seq.patterns[0].pattern is None
2007 )
2008 assert (
2009 isinstance(pattern_seq.patterns[1], nodes.MatchValue)
2010 and isinstance(pattern_seq.patterns[1].value, nodes.Const)
2011 and pattern_seq.patterns[1].value.value == 2
2012 )
2013 assert (
2014 isinstance(pattern_seq.patterns[2], nodes.MatchAs)
2015 and pattern_seq.patterns[2].name is None
2016 )
2017 assert (
2018 isinstance(pattern_seq.patterns[3], nodes.MatchStar)
2019 and isinstance(pattern_seq.patterns[3].name, nodes.AssignName)
2020 and pattern_seq.patterns[3].name.name == "rest"
2021 )
2022 assert list(pattern_seq.patterns[3].get_children()) == [
2023 pattern_seq.patterns[3].name
2024 ]
2025 assert list(pattern_seq.get_children()) == pattern_seq.patterns
2026
2027 @staticmethod
2028 def test_match_mapping():
2029 code = textwrap.dedent("""
2030 match status:
2031 case {0: x, 1: _}:
2032 pass
2033 case {**rest}:
2034 pass
2035 """).strip()
2036 node = builder.extract_node(code)
2037 assert node.as_string() == code
2038 assert isinstance(node, nodes.Match)
2039 assert isinstance(node.cases, list) and len(node.cases) == 2
2040 case0, case1 = node.cases
2041
2042 assert isinstance(case0.pattern, nodes.MatchMapping)
2043 assert case0.pattern.rest is None
2044 assert isinstance(case0.pattern.keys, list) and len(case0.pattern.keys) == 2
2045 assert (
2046 isinstance(case0.pattern.patterns, list)
2047 and len(case0.pattern.patterns) == 2
2048 )
2049 for i in range(2):
2050 key = case0.pattern.keys[i]
2051 assert isinstance(key, nodes.Const)
2052 assert key.value == i
2053 pattern = case0.pattern.patterns[i]
2054 assert isinstance(pattern, nodes.MatchAs)
2055 if i == 0:
2056 assert isinstance(pattern.name, nodes.AssignName)
2057 assert pattern.name.name == "x"
2058 elif i == 1:
2059 assert pattern.name is None
2060 assert list(case0.pattern.get_children()) == [
2061 *case0.pattern.keys,
2062 *case0.pattern.patterns,
2063 ]
2064
2065 assert isinstance(case1.pattern, nodes.MatchMapping)
2066 assert isinstance(case1.pattern.rest, nodes.AssignName)
2067 assert case1.pattern.rest.name == "rest"
2068 assert isinstance(case1.pattern.keys, list) and len(case1.pattern.keys) == 0
2069 assert (
2070 isinstance(case1.pattern.patterns, list)
2071 and len(case1.pattern.patterns) == 0
2072 )
2073 assert list(case1.pattern.get_children()) == [case1.pattern.rest]
2074
2075 @staticmethod
2076 def test_match_class():
2077 code = textwrap.dedent("""
2078 match x:
2079 case Point2D(0, a):
2080 pass
2081 case Point3D(x=0, y=1, z=b):
2082 pass
2083 """).strip()
2084 node = builder.extract_node(code)
2085 assert node.as_string() == code
2086 assert isinstance(node, nodes.Match)
2087 assert isinstance(node.cases, list) and len(node.cases) == 2
2088 case0, case1 = node.cases
2089
2090 assert isinstance(case0.pattern, nodes.MatchClass)
2091 assert isinstance(case0.pattern.cls, nodes.Name)
2092 assert case0.pattern.cls.name == "Point2D"
2093 assert (
2094 isinstance(case0.pattern.patterns, list)
2095 and len(case0.pattern.patterns) == 2
2096 )
2097 match_value = case0.pattern.patterns[0]
2098 assert (
2099 isinstance(match_value, nodes.MatchValue)
2100 and isinstance(match_value.value, nodes.Const)
2101 and match_value.value.value == 0
2102 )
2103 match_as = case0.pattern.patterns[1]
2104 assert (
2105 isinstance(match_as, nodes.MatchAs)
2106 and match_as.pattern is None
2107 and isinstance(match_as.name, nodes.AssignName)
2108 and match_as.name.name == "a"
2109 )
2110 assert list(case0.pattern.get_children()) == [
2111 case0.pattern.cls,
2112 *case0.pattern.patterns,
2113 ]
2114
2115 assert isinstance(case1.pattern, nodes.MatchClass)
2116 assert isinstance(case1.pattern.cls, nodes.Name)
2117 assert case1.pattern.cls.name == "Point3D"
2118 assert (
2119 isinstance(case1.pattern.patterns, list)
2120 and len(case1.pattern.patterns) == 0
2121 )
2122 assert (
2123 isinstance(case1.pattern.kwd_attrs, list)
2124 and len(case1.pattern.kwd_attrs) == 3
2125 )
2126 assert (
2127 isinstance(case1.pattern.kwd_patterns, list)
2128 and len(case1.pattern.kwd_patterns) == 3
2129 )
2130 for i in range(2):
2131 assert case1.pattern.kwd_attrs[i] == ("x", "y")[i]
2132 kwd_pattern = case1.pattern.kwd_patterns[i]
2133 assert isinstance(kwd_pattern, nodes.MatchValue)
2134 assert isinstance(kwd_pattern.value, nodes.Const)
2135 assert kwd_pattern.value.value == i
2136 assert case1.pattern.kwd_attrs[2] == "z"
2137 kwd_pattern = case1.pattern.kwd_patterns[2]
2138 assert (
2139 isinstance(kwd_pattern, nodes.MatchAs)
2140 and kwd_pattern.pattern is None
2141 and isinstance(kwd_pattern.name, nodes.AssignName)
2142 and kwd_pattern.name.name == "b"
2143 )
2144 assert list(case1.pattern.get_children()) == [
2145 case1.pattern.cls,
2146 *case1.pattern.kwd_patterns,
2147 ]
2148
2149 @staticmethod
2150 def test_return_from_match():
2151 code = textwrap.dedent("""
2152 def return_from_match(x):
2153 match x:
2154 case 10:
2155 return 10
2156 case _:
2157 return -1
2158
2159 return_from_match(10) #@
2160 """).strip()
2161 node = builder.extract_node(code)
2162 inferred = node.inferred()
2163 assert len(inferred) == 2
2164 assert [inf.value for inf in inferred] == [10, -1]
2165
2166
2167 @pytest.mark.skipif(not PY314_PLUS, reason="TemplateStr was added in PY314")
2168 class TestTemplateString:
2169 @staticmethod
2170 def test_template_string_simple() -> None:
2171 code = textwrap.dedent("""
2172 name = "Foo"
2173 place = 3
2174 t"{name} finished {place!r:ordinal}" #@
2175 """).strip()
2176 node = builder.extract_node(code)
2177 assert node.as_string() == "t'{name} finished {place!r:ordinal}'"
2178 assert isinstance(node, nodes.TemplateStr)
2179 assert len(node.values) == 3
2180 value = node.values[0]
2181 assert isinstance(value, nodes.Interpolation)
2182 assert isinstance(value.value, nodes.Name)
2183 assert value.value.name == "name"
2184 assert value.str == "name"
2185 assert value.conversion == -1
2186 assert value.format_spec is None
2187 value = node.values[1]
2188 assert isinstance(value, nodes.Const)
2189 assert value.pytype() == "builtins.str"
2190 assert value.value == " finished "
2191 value = node.values[2]
2192 assert isinstance(value, nodes.Interpolation)
2193 assert isinstance(value.value, nodes.Name)
2194 assert value.value.name == "place"
2195 assert value.str == "place"
2196 assert value.conversion == ord("r")
2197 assert isinstance(value.format_spec, nodes.JoinedStr)
2198
2199
2200 @pytest.mark.parametrize(
2201 "node",
2202 [
2203 node
2204 for node in astroid.nodes.ALL_NODE_CLASSES
2205 if node.__name__ not in ["BaseContainer", "NodeNG", "const_factory"]
2206 ],
2207 )
2208 @pytest.mark.filterwarnings("error")
2209 def test_str_repr_no_warnings(node):
2210 parameters = inspect.signature(node.__init__).parameters
2211
2212 args = {}
2213 for name, param_type in parameters.items():
2214 if name == "self":
2215 continue
2216
2217 if name == "parent" and "NodeNG" in param_type.annotation:
2218 args[name] = SYNTHETIC_ROOT
2219 elif "int" in param_type.annotation:
2220 args[name] = random.randint(0, 50)
2221 elif (
2222 "NodeNG" in param_type.annotation
2223 or "SuccessfulInferenceResult" in param_type.annotation
2224 ):
2225 args[name] = UNATTACHED_UNKNOWN
2226 elif "str" in param_type.annotation:
2227 args[name] = ""
2228 else:
2229 args[name] = None
2230
2231 test_node = node(**args)
2232 str(test_node)
2233 repr(test_node)
2234
2235
2236 def test_arguments_contains_all():
2237 """Ensure Arguments.arguments actually returns all available arguments"""
2238
2239 def manually_get_args(arg_node) -> set:
2240 names = set()
2241 if arg_node.args.vararg:
2242 names.add(arg_node.args.vararg)
2243 if arg_node.args.kwarg:
2244 names.add(arg_node.args.kwarg)
2245
2246 names.update([x.name for x in arg_node.args.args])
2247 names.update([x.name for x in arg_node.args.kwonlyargs])
2248
2249 return names
2250
2251 node = extract_node("""def a(fruit: str, *args, b=None, c=None, **kwargs): ...""")
2252 assert manually_get_args(node) == {x.name for x in node.args.arguments}
2253
2254 node = extract_node("""def a(mango: int, b="banana", c=None, **kwargs): ...""")
2255 assert manually_get_args(node) == {x.name for x in node.args.arguments}
2256
2257 node = extract_node("""def a(self, num = 10, *args): ...""")
2258 assert manually_get_args(node) == {x.name for x in node.args.arguments}
2259
2260
2261 def test_arguments_default_value():
2262 node = extract_node(
2263 "def fruit(eat='please', *, peel='no', trim='yes', **kwargs): ..."
2264 )
2265 assert node.args.default_value("eat").value == "please"
2266
2267 node = extract_node("def fruit(seeds, flavor='good', *, peel='maybe'): ...")
2268 assert node.args.default_value("flavor").value == "good"
2269
2270
2271 def test_arguments_annotations():
2272 node = extract_node(
2273 "def fruit(eat: str, /, peel: bool, *args: int, trim: float, **kwargs: bytes): ..."
2274 )
2275 assert isinstance(node.args, nodes.Arguments)
2276 annotation_names = [
2277 ann.name for ann in node.args.get_annotations() if isinstance(ann, nodes.Name)
2278 ]
2279 assert all(
2280 name in annotation_names for name in ("str", "bool", "int", "float", "bytes")
2281 )
2282
2283
2284 def test_deprecated_nodes_import_from_toplevel():
2285 # pylint: disable=import-outside-toplevel,no-name-in-module
2286 with pytest.raises(
2287 DeprecationWarning, match="importing 'For' from 'astroid' is deprecated"
2288 ):
2289 from astroid import For
2290
2291 with warnings.catch_warnings():
2292 warnings.simplefilter("ignore", DeprecationWarning)
2293 from astroid import For
2294
2295 assert For is nodes.For
2296
2297 # This should not raise a DeprecationWarning
2298 # pylint: disable-next=unused-import
2299 from astroid import builtin_lookup
2300
2301
2302 def test_str_long_name_no_crash() -> None:
2303 """str() should not crash with ValueError on nodes with long names.
2304
2305 Regression test for https://github.com/pylint-dev/astroid/issues/2764
2306 """
2307 long_name = "a" * 200
2308 code = f"class {long_name}:\n pass"
2309 module = parse(code)
2310 # This should not raise ValueError('width must be != 0')
2311 result = str(module.body[0])
2312 assert long_name in result
2313
2314
2315 def test_str_large_int_no_crash() -> None:
2316 """str() should not crash with ValueError on nodes with large integer values.
2317
2318 Regression test for https://github.com/pylint-dev/astroid/issues/2785
2319 """
2320 code = "x = 10 ** 5000"
2321 module = parse(code)
2322 # Infer the BinOp to get a Const with a huge int value
2323 inferred = next(module.body[0].value.infer())
2324 assert isinstance(inferred.value, int)
2325 # This should not raise ValueError about integer string conversion limit
2326 result = str(inferred)
2327 assert "int" in result
2328
2329
2330 def test_str_large_int_getitem_no_crash() -> None:
2331 """getitem error message should not crash with large integer values."""
2332 code = "x = 10 ** 5000"
2333 module = parse(code)
2334 inferred = next(module.body[0].value.infer())
2335 assert isinstance(inferred.value, int)
2336 # Trigger the error path that formats the value
2337 with pytest.raises(AstroidTypeError, match=r"too large to display|int"):
2338 inferred.getitem(nodes.Const(0))
2339
2340
2341 def test_slice_qname() -> None:
2342 """Test that Slice node has a qname method returning 'builtins.slice'."""
2343 node = extract_node("f[1:2]")
2344 assert isinstance(node, nodes.Subscript)
2345 assert isinstance(node.slice, nodes.Slice)
2346 assert node.slice.qname() == "builtins.slice"
2347
2348
2349 @pytest.mark.skipif(not PY312_PLUS, reason="Uses 3.12 type param nodes")
2350 @pytest.mark.parametrize(
2351 "source,node_type,qname",
2352 [
2353 ("class Basket[T]: pass", nodes.TypeVar, "typing.TypeVar"),
2354 ("def peel[**P](): pass", nodes.ParamSpec, "typing.ParamSpec"),
2355 ("def peel[*Ts](): pass", nodes.TypeVarTuple, "typing.TypeVarTuple"),
2356 ],
2357 )
2358 def test_type_param_qname(
2359 source: str, node_type: type[nodes.NodeNG], qname: str
2360 ) -> None:
2361 """Type parameters are inferred as themselves, so they need a qname."""
2362 node = extract_node(source)
2363 type_param = node.type_params[0]
2364 assert isinstance(type_param, node_type)
2365 assert next(type_param.infer()) is type_param
2366 assert type_param.qname() == qname
2367 assert type_param.pytype() == qname
2368
2369
2370 @pytest.mark.skipif(not PY312_PLUS, reason="Uses 3.12 type alias nodes")
2371 def test_type_alias_qname() -> None:
2372 """A type alias is inferred as itself, so it needs a qname."""
2373 node = extract_node("type Basket = int")
2374 assert isinstance(node, nodes.TypeAlias)
2375 assert next(node.infer()) is node
2376 assert node.qname() == "typing.TypeAliasType"
2377 assert node.pytype() == "typing.TypeAliasType"
2378
2379
2380 def test_self_inferring_nodes_have_a_type() -> None:
2381 """A node inferred as itself is a value, so callers ask it for its type.
2382
2383 Without ``qname()`` and ``pytype()`` they crash with an ``AttributeError``
2384 instead, as ``FunctionDef.decoratornames()`` used to for ``@T``. Nodes are
2385 found by their ``_infer`` return annotation, so this only covers the usual
2386 spelling, ``Iterator[TheNodeClass]``.
2387 """
2388 node_classes = set()
2389 to_visit = [nodes.NodeNG]
2390 while to_visit:
2391 for subclass in to_visit.pop().__subclasses__():
2392 if subclass not in node_classes:
2393 node_classes.add(subclass)
2394 to_visit.append(subclass)
2395
2396 missing = []
2397 for node_class in node_classes:
2398 infer = node_class.__dict__.get("_infer")
2399 if infer is None:
2400 continue
2401 returns = str(infer.__annotations__.get("return", ""))
2402 if returns not in (f"Iterator[{node_class.__name__}]", "Iterator[Self]"):
2403 continue
2404 if issubclass(node_class, bases.Proxy):
2405 # Proxies answer both from the class they proxy, e.g. Const.
2406 continue
2407 missing += [
2408 f"{node_class.__name__}.{name}"
2409 for name in ("qname", "pytype")
2410 if not hasattr(node_class, name)
2411 ]
2412
2413 assert not missing