Debian Codegraph @

tests/test_context.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 ``astroid.context.InferenceContext``.
6
7 The hot-path ``clone()`` implementation bypasses ``__init__`` and writes
8 slots directly. These tests pin down each field's clone semantics so a
9 future refactor of either ``__init__`` or ``clone()`` can't silently
10 diverge them.
11 """
12
13 from __future__ import annotations
14
15 import pytest
16
17 from astroid import extract_node, nodes
18 from astroid.context import CallContext, InferenceContext
19
20
21 def _populated_context() -> InferenceContext:
22 """Return a context with every clonable slot set to a distinctive value."""
23 node = extract_node("x = 1; x #@")
24 ctx = InferenceContext()
25 ctx.path.add((node, "x"))
26 ctx.lookupname = "x"
27 ctx.callcontext = CallContext(args=[node])
28 ctx.boundnode = node
29 ctx.extra_context = {node: InferenceContext()}
30 # ``_nodes_inferred`` is a 1-element list used as a mutable counter
31 # shared across clones, so put a recognizable value in it.
32 ctx._nodes_inferred[0] = 7
33 return ctx
34
35
36 class TestInferenceContextInit:
37 """``__init__`` slow path — no longer exercised by ``clone()``."""
38
39 def test_init_with_explicit_nodes_inferred(self) -> None:
40 """An explicitly passed counter cell is adopted, not copied.
41
42 The old ``clone()`` used this parameter to share the counter;
43 the fast path writes the slot directly, so this keeps the
44 ``__init__`` contract covered for external callers.
45 """
46 cell = [7]
47 ctx = InferenceContext(nodes_inferred=cell)
48 assert ctx._nodes_inferred is cell
49 assert ctx.nodes_inferred == 7
50 ctx.nodes_inferred = 42
51 assert cell[0] == 42
52
53 def test_init_default_nodes_inferred(self) -> None:
54 """Without the parameter, each context gets its own zeroed cell."""
55 ctx = InferenceContext()
56 other = InferenceContext()
57 assert ctx.nodes_inferred == 0
58 assert ctx._nodes_inferred is not other._nodes_inferred
59
60
61 class TestInferenceContextClone:
62 """The clone() fast-path must preserve the semantics of the slow path."""
63
64 def test_clone_path_is_independent_copy(self) -> None:
65 """``path`` is copied — mutating the clone's path must not affect the original."""
66 original = _populated_context()
67 clone = original.clone()
68 assert clone.path == original.path
69 assert clone.path is not original.path
70 clone.path.clear()
71 assert original.path, "clearing the clone leaked back to the original"
72
73 def test_clone_lookupname_is_reset(self) -> None:
74 """``clone()`` deliberately drops the original's ``lookupname``."""
75 original = _populated_context()
76 assert original.lookupname == "x"
77 clone = original.clone()
78 assert clone.lookupname is None
79
80 def test_clone_shares_nodes_inferred_counter(self) -> None:
81 """``_nodes_inferred`` is a mutable cell shared across the clone family.
82
83 Otherwise the per-inference budget enforced by ``max_inferred``
84 would reset on every clone and the ``nodes_inferred`` property
85 would not see writes made through the clone.
86 """
87 original = _populated_context()
88 clone = original.clone()
89 assert clone._nodes_inferred is original._nodes_inferred
90 clone.nodes_inferred = 42
91 assert original.nodes_inferred == 42
92
93 def test_clone_propagates_callcontext_and_boundnode(self) -> None:
94 """Call-site state and bound node are passed through by identity."""
95 original = _populated_context()
96 clone = original.clone()
97 assert clone.callcontext is original.callcontext
98 assert clone.boundnode is original.boundnode
99 assert clone.extra_context is original.extra_context
100
101 def test_clone_constraints_is_independent_copy(self) -> None:
102 """Constraints dict is shallow-copied so per-branch state can diverge."""
103 node = extract_node("if x: pass #@")
104 original = InferenceContext()
105 original.constraints["x"] = {node: set()}
106 clone = original.clone()
107 assert clone.constraints == original.constraints
108 assert clone.constraints is not original.constraints
109 clone.constraints["y"] = {}
110 assert "y" not in original.constraints
111
112 def test_clone_skips_init(self) -> None:
113 """The fast path goes through ``__new__``, not ``__init__``.
114
115 Subclasses that override ``__init__`` for side effects (none today,
116 but plausible) would notice this, and so would profilers — the
117 whole point of the change is to avoid the ``__init__`` body.
118 """
119 # The patch/restore dance below trips ``redefined-variable-type``
120 # because ``__init__`` flips between a plain function and a bound
121 # method. That's the whole point of the test.
122 # pylint: disable=redefined-variable-type
123 called = []
124
125 original_init = InferenceContext.__init__
126
127 def tracking_init(self, *args, **kwargs):
128 called.append((args, kwargs))
129 original_init(self, *args, **kwargs)
130
131 InferenceContext.__init__ = tracking_init
132 try:
133 ctx = InferenceContext()
134 assert called, "sanity check: instantiation should call __init__"
135 called.clear()
136 ctx.clone()
137 assert not called, f"clone() must bypass __init__; got calls: {called!r}"
138 finally:
139 InferenceContext.__init__ = original_init
140
141 def test_clone_returns_inference_context_instance(self) -> None:
142 """Type identity is preserved (regression guard against ``__new__`` misuse)."""
143 ctx = InferenceContext()
144 clone = ctx.clone()
145 # We deliberately want exact-type identity here, not ``isinstance``,
146 # because ``__new__`` mis-applied to a subclass would yield a wrong
147 # concrete type that ``isinstance`` would still accept.
148 assert type(clone) is InferenceContext # pylint: disable=unidiomatic-typecheck
149
150 def test_clone_is_not_is_empty_when_seeded(self) -> None:
151 """End-to-end check: a populated clone still reports as non-empty."""
152 original = _populated_context()
153 clone = original.clone()
154 # ``lookupname`` is reset and ``nodes_inferred`` would be cleared,
155 # but ``path`` / ``callcontext`` / ``boundnode`` carry over and
156 # keep the clone non-empty.
157 assert not clone.is_empty()
158
159
160 @pytest.mark.parametrize(
161 "node_source",
162 [
163 "x = 1\nx #@",
164 "def f(): return 1\nf() #@",
165 ],
166 )
167 def test_clone_keeps_inference_working(node_source: str) -> None:
168 """End-to-end sanity: inference through a cloned context still resolves."""
169 node = extract_node(node_source)
170 ctx = InferenceContext()
171 clone = ctx.clone()
172 inferred = next(node.infer(context=clone))
173 assert isinstance(inferred, (nodes.Const, nodes.FunctionDef, nodes.NodeNG))