Debian Codegraph @

tests/test_protocols.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 from __future__ import annotations
6
7 import contextlib
8 import unittest
9 from collections.abc import Callable, Iterator
10 from typing import Any
11
12 import pytest
13
14 import astroid
15 from astroid import extract_node, nodes
16 from astroid.const import PY312_PLUS
17 from astroid.context import InferenceContext
18 from astroid.exceptions import InferenceError
19 from astroid.manager import AstroidManager
20 from astroid.util import Uninferable, UninferableBase
21
22
23 @contextlib.contextmanager
24 def _add_transform(
25 manager: AstroidManager,
26 node: type,
27 transform: Callable,
28 predicate: Any | None = None,
29 ) -> Iterator:
30 manager.register_transform(node, transform, predicate)
31 try:
32 yield
33 finally:
34 manager.unregister_transform(node, transform, predicate)
35
36
37 class ProtocolTests(unittest.TestCase):
38 def assertConstNodesEqual(
39 self, nodes_list_expected: list[int], nodes_list_got: list[nodes.Const]
40 ) -> None:
41 self.assertEqual(len(nodes_list_expected), len(nodes_list_got))
42 for node in nodes_list_got:
43 self.assertIsInstance(node, nodes.Const)
44 for node, expected_value in zip(nodes_list_got, nodes_list_expected):
45 self.assertEqual(expected_value, node.value)
46
47 def assertNameNodesEqual(
48 self, nodes_list_expected: list[str], nodes_list_got: list[nodes.Name]
49 ) -> None:
50 self.assertEqual(len(nodes_list_expected), len(nodes_list_got))
51 for node in nodes_list_got:
52 self.assertIsInstance(node, nodes.Name)
53 for node, expected_name in zip(nodes_list_got, nodes_list_expected):
54 self.assertEqual(expected_name, node.name)
55
56 def test_assigned_stmts_simple_for(self) -> None:
57 assign_stmts = extract_node("""
58 for a in (1, 2, 3): #@
59 pass
60
61 for b in range(3): #@
62 pass
63 """)
64
65 for1_assnode = next(assign_stmts[0].nodes_of_class(nodes.AssignName))
66 assigned = list(for1_assnode.assigned_stmts())
67 self.assertConstNodesEqual([1, 2, 3], assigned)
68
69 for2_assnode = next(assign_stmts[1].nodes_of_class(nodes.AssignName))
70 self.assertRaises(InferenceError, list, for2_assnode.assigned_stmts())
71
72 def test_assigned_stmts_arguments_without_context(self) -> None:
73 # Regression: the Arguments assigned_stmts protocol may be called
74 # without an inference context (the public ``assigned_stmts`` API
75 # defaults it to None). Resolving a function's first parameter that way
76 # used to crash with ``AttributeError: 'NoneType' object has no
77 # attribute 'boundnode'``; it should degrade to Uninferable instead.
78 args = extract_node("""
79 def f(x, y): #@
80 return x
81 """).args
82 assigned = list(args.assigned_stmts(node=args.args[0]))
83 self.assertEqual(assigned, [Uninferable])
84
85 def test_assigned_stmts_nested_for_tuple(self) -> None:
86 assign_stmts = extract_node("""
87 for a, (b, c) in [(1, (2, 3))]: #@
88 pass
89 """)
90
91 assign_nodes = assign_stmts.nodes_of_class(nodes.AssignName)
92
93 for1_assnode = next(assign_nodes)
94 assigned = list(for1_assnode.assigned_stmts())
95 self.assertConstNodesEqual([1], assigned)
96
97 for2_assnode = next(assign_nodes)
98 assigned2 = list(for2_assnode.assigned_stmts())
99 self.assertConstNodesEqual([2], assigned2)
100
101 def test_assigned_stmts_nested_for_dict(self) -> None:
102 assign_stmts = extract_node("""
103 for a, (b, c) in {1: ("a", str), 2: ("b", bytes)}.items(): #@
104 pass
105 """)
106 assign_nodes = assign_stmts.nodes_of_class(nodes.AssignName)
107
108 # assigned: [1, 2]
109 for1_assnode = next(assign_nodes)
110 assigned = list(for1_assnode.assigned_stmts())
111 self.assertConstNodesEqual([1, 2], assigned)
112
113 # assigned2: ["a", "b"]
114 for2_assnode = next(assign_nodes)
115 assigned2 = list(for2_assnode.assigned_stmts())
116 self.assertConstNodesEqual(["a", "b"], assigned2)
117
118 # assigned3: [str, bytes]
119 for3_assnode = next(assign_nodes)
120 assigned3 = list(for3_assnode.assigned_stmts())
121 self.assertNameNodesEqual(["str", "bytes"], assigned3)
122
123 def test_assigned_stmts_starred_for(self) -> None:
124 assign_stmts = extract_node("""
125 for *a, b in ((1, 2, 3), (4, 5, 6, 7)): #@
126 pass
127 """)
128
129 for1_starred = next(assign_stmts.nodes_of_class(nodes.Starred))
130 assigned = next(for1_starred.assigned_stmts())
131 assert isinstance(assigned, nodes.List)
132 assert assigned.as_string() == "[1, 2]"
133
134 def test_assigned_stmts_starred_for_not_last(self) -> None:
135 """A starred target that isn't last must not truncate to its own arity."""
136 assign_stmts = extract_node("""
137 for a, *b, c in ((1, 2, 3, 4),): #@
138 pass
139 """)
140
141 starred = next(assign_stmts.nodes_of_class(nodes.Starred))
142 assigned = next(starred.assigned_stmts())
143 assert isinstance(assigned, nodes.List)
144 assert assigned.as_string() == "[2, 3]"
145
146 def _get_starred_stmts(self, code: str) -> list | UninferableBase:
147 assign_stmt = extract_node(f"{code} #@")
148 starred = next(assign_stmt.nodes_of_class(nodes.Starred))
149 return next(starred.assigned_stmts())
150
151 def _helper_starred_expected_const(self, code: str, expected: list[int]) -> None:
152 stmts = self._get_starred_stmts(code)
153 self.assertIsInstance(stmts, nodes.List)
154 stmts = stmts.elts
155 self.assertConstNodesEqual(expected, stmts)
156
157 def _helper_starred_expected(self, code: str, expected: UninferableBase) -> None:
158 stmts = self._get_starred_stmts(code)
159 self.assertEqual(expected, stmts)
160
161 def _helper_starred_inference_error(self, code: str) -> None:
162 assign_stmt = extract_node(f"{code} #@")
163 starred = next(assign_stmt.nodes_of_class(nodes.Starred))
164 self.assertRaises(InferenceError, list, starred.assigned_stmts())
165
166 def test_assigned_stmts_starred_assnames(self) -> None:
167 self._helper_starred_expected_const("a, *b = (1, 2, 3, 4) #@", [2, 3, 4])
168 self._helper_starred_expected_const("*a, b = (1, 2, 3) #@", [1, 2])
169 self._helper_starred_expected_const("a, *b, c = (1, 2, 3, 4, 5) #@", [2, 3, 4])
170 self._helper_starred_expected_const("a, *b = (1, 2) #@", [2])
171 self._helper_starred_expected_const("*b, a = (1, 2) #@", [1])
172 self._helper_starred_expected_const("[*b] = (1, 2) #@", [1, 2])
173
174 def test_assigned_stmts_starred_yes(self) -> None:
175 # Not something iterable and known
176 self._helper_starred_expected("a, *b = range(3) #@", Uninferable)
177 # Not something inferable
178 self._helper_starred_expected("a, *b = balou() #@", Uninferable)
179 # In function, unknown.
180 self._helper_starred_expected(
181 """
182 def test(arg):
183 head, *tail = arg #@""",
184 Uninferable,
185 )
186 # These cases aren't worth supporting.
187 self._helper_starred_expected(
188 "a, (*b, c), d = (1, (2, 3, 4), 5) #@", Uninferable
189 )
190
191 def test_assigned_stmts_starred_inside_call(self) -> None:
192 """Regression test for https://github.com/pylint-dev/pylint/issues/6372."""
193 code = "string_twos = ''.join(str(*y) for _, *y in [[1, 2], [1, 2]]) #@"
194 stmt = extract_node(code)
195 starred = next(stmt.nodes_of_class(nodes.Starred))
196 starred_stmts = starred.assigned_stmts()
197 self.assertIs(next(starred_stmts), Uninferable)
198 # Generator exhausted after one call
199 with self.assertRaises(StopIteration):
200 next(starred_stmts)
201
202 def test_assigned_stmts_starred_assignattr(self) -> None:
203 """Regression test for https://github.com/pylint-dev/astroid/issues/2646.
204
205 Starred with an AssignAttr target crashed on ``.value.name``.
206 """
207 code = """
208 for *o.attr, (*t,) in (): #@
209 pass
210 """
211 assign_stmts = extract_node(code)
212 # Both starred nodes must be reachable without AttributeError
213 starred_nodes = list(assign_stmts.nodes_of_class(nodes.Starred))
214 assert len(starred_nodes) == 2
215 for starred in starred_nodes:
216 self.assertIs(next(starred.assigned_stmts()), Uninferable)
217
218 def test_assigned_stmts_starred_subscript_target(self) -> None:
219 """Starred with a Subscript target must not crash on ``.value.name``."""
220 code = """
221 for *d[0], (*t,) in (): #@
222 pass
223 """
224 assign_stmts = extract_node(code)
225 starred_nodes = list(assign_stmts.nodes_of_class(nodes.Starred))
226 assert len(starred_nodes) == 2
227 for starred in starred_nodes:
228 self.assertIs(next(starred.assigned_stmts()), Uninferable)
229
230 def test_assigned_stmts_starred_same_name_identity(self) -> None:
231 """Node identity distinguishes starred nodes that share a name."""
232 code = """
233 for *a, (*a,) in [(1, 2, (3,))]: #@
234 pass
235 """
236 assign_stmts = extract_node(code)
237 starred_nodes = list(assign_stmts.nodes_of_class(nodes.Starred))
238 assert len(starred_nodes) == 2
239 # Each starred node should resolve independently, not match the other
240 for starred in starred_nodes:
241 result = next(starred.assigned_stmts())
242 assert not isinstance(result, Exception)
243
244 def test_assign_stmts_starred_fails(self) -> None:
245 # Too many starred
246 self._helper_starred_inference_error("a, *b, *c = (1, 2, 3) #@")
247 # This could be solved properly, but it complicates needlessly the
248 # code for assigned_stmts, without offering real benefit.
249 self._helper_starred_inference_error(
250 "(*a, b), (c, *d) = (1, 2, 3), (4, 5, 6) #@"
251 )
252
253 def test_assigned_stmts_assignments(self) -> None:
254 assign_stmts = extract_node("""
255 c = a #@
256
257 d, e = b, c #@
258 """)
259
260 simple_assnode = next(assign_stmts[0].nodes_of_class(nodes.AssignName))
261 assigned = list(simple_assnode.assigned_stmts())
262 self.assertNameNodesEqual(["a"], assigned)
263
264 assnames = assign_stmts[1].nodes_of_class(nodes.AssignName)
265 simple_mul_assnode_1 = next(assnames)
266 assigned = list(simple_mul_assnode_1.assigned_stmts())
267 self.assertNameNodesEqual(["b"], assigned)
268 simple_mul_assnode_2 = next(assnames)
269 assigned = list(simple_mul_assnode_2.assigned_stmts())
270 self.assertNameNodesEqual(["c"], assigned)
271
272 def test_assigned_stmts_annassignments(self) -> None:
273 annassign_stmts = extract_node("""
274 a: str = "abc" #@
275 b: str #@
276 """)
277 simple_annassign_node = next(
278 annassign_stmts[0].nodes_of_class(nodes.AssignName)
279 )
280 assigned = list(simple_annassign_node.assigned_stmts())
281 self.assertEqual(1, len(assigned))
282 self.assertIsInstance(assigned[0], nodes.Const)
283 self.assertEqual(assigned[0].value, "abc")
284
285 empty_annassign_node = next(annassign_stmts[1].nodes_of_class(nodes.AssignName))
286 assigned = list(empty_annassign_node.assigned_stmts())
287 self.assertEqual(1, len(assigned))
288 self.assertIs(assigned[0], Uninferable)
289
290 def test_sequence_assigned_stmts_not_accepting_empty_node(self) -> None:
291 def transform(node: nodes.Assign) -> None:
292 node.root().locals["__all__"] = [node.value]
293
294 manager = astroid.MANAGER
295 with _add_transform(manager, nodes.Assign, transform):
296 module = astroid.parse("""
297 __all__ = ['a']
298 """)
299 module.wildcard_import_names()
300
301 def test_not_passing_uninferable_in_seq_inference(self) -> None:
302 class Visitor:
303 def visit(self, node: nodes.Assign | nodes.BinOp | nodes.List) -> Any:
304 for child in node.get_children():
305 child.accept(self)
306
307 visit_module = visit
308 visit_assign = visit
309 visit_binop = visit
310 visit_list = visit
311 visit_const = visit
312 visit_name = visit
313
314 def visit_assignname(self, node: nodes.AssignName) -> None:
315 for _ in node.infer():
316 pass
317
318 parsed = extract_node("""
319 a = []
320 x = [a*2, a]*2*2
321 """)
322 parsed.accept(Visitor())
323
324 @staticmethod
325 def test_uninferable_exponents() -> None:
326 """Attempting to calculate the result is prohibitively expensive."""
327 parsed = extract_node("15 ** 20220609")
328 assert parsed.inferred() == [Uninferable]
329
330 # Test a pathological case (more realistic: None as naive inference result)
331 parsed = extract_node("None ** 2")
332 assert parsed.inferred() == [Uninferable]
333
334 @staticmethod
335 def test_uninferable_list_multiplication() -> None:
336 """Attempting to calculate the result is prohibitively expensive."""
337 parsed = extract_node("[0] * 123456789")
338 element = parsed.inferred()[0].elts[0]
339 assert element.value is Uninferable
340
341 @staticmethod
342 def test_uninferable_list_multiplication_with_multiple_operands() -> None:
343 """Attempting to calculate the result is prohibitively expensive."""
344 parsed = extract_node("[0] * 825 * 16547118")
345 element = parsed.inferred()[0].elts[0]
346 assert element.value is Uninferable
347
348 @staticmethod
349 def test_list_multiplication_with_empty_list_and_overflowing_multiplier() -> None:
350 parsed = extract_node("[] * 1163845194457646539560")
351 assert parsed.inferred()[0].elts == []
352
353 @staticmethod
354 def test_list_multiplication_with_zero_multiplier() -> None:
355 parsed = extract_node("[0] * 0")
356 assert parsed.inferred()[0].elts == []
357
358 @staticmethod
359 def test_list_multiplication_with_negative_overflowing_multiplier() -> None:
360 parsed = extract_node("[0] * -9223372036854775809")
361 assert parsed.inferred()[0].elts == []
362
363 @staticmethod
364 def test_uninferable_string_multiplication() -> None:
365 """Building the repeated string would be prohibitively expensive."""
366 parsed = extract_node('"abc" * 123456789')
367 assert parsed.inferred() == [Uninferable]
368
369 # The reflected form (int * str) must be bounded too.
370 parsed = extract_node('123456789 * "abc"')
371 assert parsed.inferred() == [Uninferable]
372
373 @staticmethod
374 def test_uninferable_bytes_multiplication() -> None:
375 """Building the repeated bytes would be prohibitively expensive."""
376 parsed = extract_node('b"abc" * 123456789')
377 assert parsed.inferred() == [Uninferable]
378
379 @staticmethod
380 def test_string_multiplication_with_zero_multiplier() -> None:
381 parsed = extract_node('"abc" * 0')
382 assert parsed.inferred()[0].value == ""
383
384 @staticmethod
385 def test_uninferable_left_shift() -> None:
386 """The shifted integer would be prohibitively expensive to build."""
387 parsed = extract_node("1 << 123456789")
388 assert parsed.inferred() == [Uninferable]
389
390 @staticmethod
391 def test_uninferable_string_concatenation() -> None:
392 """The concatenated string would be prohibitively expensive to build."""
393 parsed = extract_node('("a" * 60000000) + ("b" * 60000000)')
394 assert parsed.inferred() == [Uninferable]
395
396 @staticmethod
397 def test_uninferable_bytes_concatenation() -> None:
398 parsed = extract_node('(b"a" * 60000000) + (b"b" * 60000000)')
399 assert parsed.inferred() == [Uninferable]
400
401 @staticmethod
402 def test_string_concatenation_small_still_infers() -> None:
403 parsed = extract_node('"ab" + "cd"')
404 assert parsed.inferred()[0].value == "abcd"
405
406 @staticmethod
407 def test_uninferable_list_concatenation() -> None:
408 """The concatenated list would be prohibitively expensive to build."""
409 parsed = extract_node("([1] * 50000001) + ([1] * 50000001)")
410 assert parsed.inferred() == [Uninferable]
411
412 @staticmethod
413 def test_uninferable_oversized_percent_formatting() -> None:
414 """The % guard in const_infer_binary_op backs up the dedicated handler.
415
416 Normal inference routes str/bytes % through
417 _infer_old_style_string_formatting, so invoke the protocol directly.
418 """
419 parsed = extract_node('"%1000000000d" % 1')
420 result = parsed.left.infer_binary_op(
421 parsed, "%", parsed.right, InferenceContext(), None
422 )
423 assert list(result) == [Uninferable]
424
425
426 def test_named_expr_inference() -> None:
427 code = """
428 if (a := 2) == 2:
429 a #@
430
431
432 # Test a function call
433 def test():
434 return 24
435
436 if (a := test()):
437 a #@
438
439 # Normal assignments in sequences
440 { (a:= 4) } #@
441 [ (a:= 5) ] #@
442
443 # Something more complicated
444 def test(value=(p := 24)): return p
445 [ y:= test()] #@
446
447 # Priority assignment
448 (x := 1, 2)
449 x #@
450 """
451 ast_nodes = extract_node(code)
452 assert isinstance(ast_nodes, list)
453 node = next(ast_nodes[0].infer())
454 assert isinstance(node, nodes.Const)
455 assert node.value == 2
456
457 node = next(ast_nodes[1].infer())
458 assert isinstance(node, nodes.Const)
459 assert node.value == 24
460
461 node = next(ast_nodes[2].infer())
462 assert isinstance(node, nodes.Set)
463 assert isinstance(node.elts[0], nodes.Const)
464 assert node.elts[0].value == 4
465
466 node = next(ast_nodes[3].infer())
467 assert isinstance(node, nodes.List)
468 assert isinstance(node.elts[0], nodes.Const)
469 assert node.elts[0].value == 5
470
471 node = next(ast_nodes[4].infer())
472 assert isinstance(node, nodes.List)
473 assert isinstance(node.elts[0], nodes.Const)
474 assert node.elts[0].value == 24
475
476 node = next(ast_nodes[5].infer())
477 assert isinstance(node, nodes.Const)
478 assert node.value == 1
479
480
481 class TestPatternMatching:
482 @staticmethod
483 def test_assigned_stmts_match_mapping():
484 """Assigned_stmts for MatchMapping not yet implemented.
485
486 Test the result is 'Uninferable' and no exception is raised.
487 """
488 assign_stmts = extract_node("""
489 var = {1: "Hello", 2: "World"}
490 match var:
491 case {**rest}: #@
492 pass
493 """)
494 match_mapping: nodes.MatchMapping = assign_stmts.pattern # type: ignore[union-attr]
495 assert match_mapping.rest
496 assigned = next(match_mapping.rest.assigned_stmts())
497 assert assigned == Uninferable
498
499 @staticmethod
500 def test_assigned_stmts_match_star():
501 """Assigned_stmts for MatchStar not yet implemented.
502
503 Test the result is 'Uninferable' and no exception is raised.
504 """
505 assign_stmts = extract_node("""
506 var = (0, 1, 2)
507 match var:
508 case (0, 1, *rest): #@
509 pass
510 """)
511 match_sequence: nodes.MatchSequence = assign_stmts.pattern # type: ignore[union-attr]
512 match_star = match_sequence.patterns[2]
513 assert isinstance(match_star, nodes.MatchStar) and match_star.name
514 assigned = next(match_star.name.assigned_stmts())
515 assert assigned == Uninferable
516
517 @staticmethod
518 def test_assigned_stmts_match_as():
519 """Assigned_stmts for MatchAs only implemented for the most basic case (y)."""
520 assign_stmts = extract_node("""
521 var = 42
522 match var: #@
523 case 2 | x: #@
524 pass
525 case (1, 2) as y: #@
526 pass
527 case z: #@
528 pass
529 """)
530 subject: nodes.Const = assign_stmts[0].subject # type: ignore[index,union-attr]
531 match_or: nodes.MatchOr = assign_stmts[1].pattern # type: ignore[index,union-attr]
532 match_as_with_pattern: nodes.MatchAs = assign_stmts[2].pattern # type: ignore[index,union-attr]
533 match_as: nodes.MatchAs = assign_stmts[3].pattern # type: ignore[index,union-attr]
534
535 match_or_1 = match_or.patterns[1]
536 assert isinstance(match_or_1, nodes.MatchAs) and match_or_1.name
537 assigned_match_or_1 = next(match_or_1.name.assigned_stmts())
538 assert assigned_match_or_1 == Uninferable
539
540 assert match_as_with_pattern.name and match_as_with_pattern.pattern
541 assigned_match_as_pattern = next(match_as_with_pattern.name.assigned_stmts())
542 assert assigned_match_as_pattern == Uninferable
543
544 assert match_as.name
545 assigned_match_as = next(match_as.name.assigned_stmts())
546 assert assigned_match_as == subject
547
548
549 @pytest.mark.skipif(not PY312_PLUS, reason="Generic typing syntax requires python 3.12")
550 class TestGenericTypeSyntax:
551 @staticmethod
552 def test_assigned_stmts_type_var():
553 """The assigned statement is the TypeVar node itself."""
554 assign_stmts = extract_node("type Point[T] = tuple[float, float]")
555 type_var: nodes.TypeVar = assign_stmts.type_params[0]
556 assigned = next(type_var.name.assigned_stmts())
557 assert isinstance(assigned, nodes.TypeVar)
558 assert assigned is type_var
559
560 @staticmethod
561 def test_assigned_stmts_type_var_tuple():
562 """The assigned statement is the TypeVarTuple node itself."""
563 assign_stmts = extract_node("type Alias[*Ts] = tuple[*Ts]")
564 type_var_tuple: nodes.TypeVarTuple = assign_stmts.type_params[0]
565 assigned = next(type_var_tuple.name.assigned_stmts())
566 assert isinstance(assigned, nodes.TypeVarTuple)
567 assert assigned is type_var_tuple
568
569 @staticmethod
570 def test_assigned_stmts_param_spec():
571 """The assigned statement is the ParamSpec node itself."""
572 assign_stmts = extract_node("type Alias[**P] = Callable[P, int]")
573 param_spec: nodes.ParamSpec = assign_stmts.type_params[0]
574 assigned = next(param_spec.name.assigned_stmts())
575 assert isinstance(assigned, nodes.ParamSpec)
576 assert assigned is param_spec