|
14 | 14 | from importlib.machinery import ModuleSpec |
15 | 15 | from importlib.util import find_spec |
16 | 16 | from pathlib import Path |
| 17 | +from typing import Any |
17 | 18 |
|
18 | 19 | import pytest |
19 | 20 |
|
@@ -79,6 +80,7 @@ def _clear_call_graph_caches() -> None: |
79 | 80 | "_resolve_function_target", |
80 | 81 | "_resolve_module_source", |
81 | 82 | "_safe_call_graph_entrypoints", |
| 83 | + "_iter_call_nodes", |
82 | 84 | "_collect_function_import_aliases", |
83 | 85 | "_parameter_controlled_names", |
84 | 86 | "_split_function_name", |
@@ -140,6 +142,37 @@ def _env_without_pythonpath() -> dict[str, str]: |
140 | 142 | return {key: value for key, value in os.environ.items() if key != "PYTHONPATH"} |
141 | 143 |
|
142 | 144 |
|
| 145 | +def test_iter_call_nodes_reuses_cached_walk(monkeypatch: pytest.MonkeyPatch) -> None: |
| 146 | + module = ast.parse( |
| 147 | + """ |
| 148 | +def bridge(target, command): |
| 149 | + callback = getattr(target, command) |
| 150 | + callback(command) |
| 151 | +""" |
| 152 | + ) |
| 153 | + bridge = module.body[0] |
| 154 | + assert isinstance(bridge, ast.FunctionDef) |
| 155 | + |
| 156 | + visits = 0 |
| 157 | + original_visit = ast.NodeVisitor.visit |
| 158 | + |
| 159 | + def counting_visit(self: ast.NodeVisitor, node: ast.AST) -> Any: |
| 160 | + nonlocal visits |
| 161 | + visits += 1 |
| 162 | + return original_visit(self, node) |
| 163 | + |
| 164 | + monkeypatch.setattr(ast.NodeVisitor, "visit", counting_visit) |
| 165 | + call_graph._iter_call_nodes.cache_clear() |
| 166 | + |
| 167 | + first = call_graph._iter_call_nodes(bridge) |
| 168 | + first_visit_count = visits |
| 169 | + second = call_graph._iter_call_nodes(bridge) |
| 170 | + |
| 171 | + assert first == second |
| 172 | + assert first_visit_count > 0 |
| 173 | + assert visits == first_visit_count |
| 174 | + |
| 175 | + |
143 | 176 | def test_collect_function_import_aliases_reuses_cached_walk(monkeypatch: pytest.MonkeyPatch) -> None: |
144 | 177 | module = ast.parse( |
145 | 178 | """ |
|
0 commit comments