|
11 | 11 | The edge is kept — the type dependency is real for "what references this |
12 | 12 | type" — stamped `type_only`, and `find_import_cycles` excludes it the way |
13 | 13 | it already excludes deferred `import(...)` (#1241). |
| 14 | +
|
| 15 | +Python's `if TYPE_CHECKING:` imports never execute either and get the same |
| 16 | +stamp (#3159). Merging two edges of one file pair keeps an attribute from |
| 17 | +either, so the merged edge is `type_only` only if every import folded into it |
| 18 | +is: a runtime import next to a type-only one keeps its cycle. |
14 | 19 | """ |
15 | 20 | from __future__ import annotations |
16 | 21 |
|
17 | 22 | import tempfile |
18 | 23 | from pathlib import Path |
19 | 24 |
|
| 25 | +import pytest |
| 26 | + |
20 | 27 | from graphify.analyze import find_import_cycles |
21 | | -from graphify.build import build_from_json |
| 28 | +from graphify.build import build_from_json, dedupe_edges |
22 | 29 | from graphify.extract import extract |
23 | 30 |
|
24 | 31 |
|
@@ -94,13 +101,16 @@ def test_plain_imports_are_untouched(tmp_path): |
94 | 101 | # The cycles — the reporter's minimal repro |
95 | 102 | # --------------------------------------------------------------------------- |
96 | 103 |
|
97 | | -def _cycles(tmp_path, files): |
| 104 | +def _cycles(tmp_path, files, directed=True, raw=False): |
98 | 105 | r = _extract(tmp_path, files) |
99 | 106 | # directed=True mirrors a --directed build; in the default undirected |
100 | 107 | # graph two module edges between one file pair collapse to a single |
101 | 108 | # stored edge, so a synthetic 2-cycle needs distinct endpoints anyway. |
102 | | - G = build_from_json({"nodes": r["nodes"], "edges": r["edges"], "hyperedges": []}, |
103 | | - root=str(tmp_path), directed=True) |
| 109 | + # raw=True takes the `update --no-cluster` route: edges are deduplicated |
| 110 | + # before the graph is built from that graph.json (`cluster-only`). |
| 111 | + edges = dedupe_edges(r["edges"]) if raw else r["edges"] |
| 112 | + G = build_from_json({"nodes": r["nodes"], "edges": edges, "hyperedges": []}, |
| 113 | + root=str(tmp_path), directed=directed) |
104 | 114 | return find_import_cycles(G) |
105 | 115 |
|
106 | 116 |
|
@@ -131,3 +141,181 @@ def test_a_cycle_with_one_type_only_leg_is_not_a_cycle(tmp_path): |
131 | 141 | "b.ts": 'import type { AT } from "./a.js";\nexport const b = 2;\n', |
132 | 142 | }) |
133 | 143 | assert cycles == [], cycles |
| 144 | + |
| 145 | + |
| 146 | +def test_undirected_graph_keeps_the_marker_when_the_reverse_import_is_dropped(tmp_path): |
| 147 | + """Default undirected graph: b imports a at runtime, a only `import type`s b. |
| 148 | + The pair keeps one edge (#1061); a's type-only import must not become a |
| 149 | + runtime leg closing a -> b -> c -> a.""" |
| 150 | + cycles = _cycles(tmp_path, { |
| 151 | + "a.ts": "import type { B } from './b';\nexport class A { b?: B; }\n", |
| 152 | + "b.ts": ("import { A } from './a';\nimport { C } from './c';\n" |
| 153 | + "export class B { a = new A(); c = new C(); }\n"), |
| 154 | + "c.ts": "import { A } from './a';\nexport class C { a = new A(); }\n", |
| 155 | + }, directed=False) |
| 156 | + assert cycles == [], cycles |
| 157 | + |
| 158 | + |
| 159 | +# --------------------------------------------------------------------------- |
| 160 | +# Python: imports under `if TYPE_CHECKING:` (#3159) |
| 161 | +# --------------------------------------------------------------------------- |
| 162 | + |
| 163 | +def _stamped_by_line(result, importer): |
| 164 | + """{line: some edge of that import statement is stamped} for one file.""" |
| 165 | + out: dict[int, bool] = {} |
| 166 | + for e in result["edges"]: |
| 167 | + if e["source_file"].endswith(importer) and e["relation"] in ("imports", "imports_from"): |
| 168 | + line = int(e["source_location"][1:]) |
| 169 | + out[line] = out.get(line, False) or bool(e.get("type_only")) |
| 170 | + return out |
| 171 | + |
| 172 | + |
| 173 | +def _names(cycles): |
| 174 | + return sorted(sorted(Path(f).name for f in c["cycle"]) for c in cycles) |
| 175 | + |
| 176 | + |
| 177 | +def test_python_imports_under_type_checking_are_stamped(tmp_path): |
| 178 | + r = _extract(tmp_path, { |
| 179 | + "pkg/__init__.py": "", |
| 180 | + "pkg/models.py": "class Item: ...\n", |
| 181 | + "pkg/service.py": ( |
| 182 | + "import sys\n" # 1 |
| 183 | + "import typing\n" # 2 |
| 184 | + "from typing import TYPE_CHECKING\n" # 3 |
| 185 | + "\n" # 4 |
| 186 | + "if TYPE_CHECKING:\n" # 5 |
| 187 | + " from pkg.models import Item\n" # 6 |
| 188 | + " import pkg.models\n" # 7 |
| 189 | + " from .models import Item as Rel\n" # 8 |
| 190 | + " if sys.version_info >= (3, 11):\n" # 9 |
| 191 | + " from pkg.models import Item as Nested\n" # 10 |
| 192 | + "if typing.TYPE_CHECKING:\n" # 11 |
| 193 | + " from pkg.models import Item as Attr\n" # 12 |
| 194 | + ), |
| 195 | + }) |
| 196 | + stamped = _stamped_by_line(r, "service.py") |
| 197 | + assert [line for line, flag in stamped.items() if flag] == [6, 7, 8, 10, 12] |
| 198 | + |
| 199 | + |
| 200 | +def test_python_imports_that_run_are_not_stamped(tmp_path): |
| 201 | + """The `else:` of the guard and `if not TYPE_CHECKING:` run at import time.""" |
| 202 | + r = _extract(tmp_path, { |
| 203 | + "models.py": "class Item: ...\n", |
| 204 | + "fallback.py": "class Item: ...\n", |
| 205 | + "service.py": ( |
| 206 | + "from typing import TYPE_CHECKING\n" # 1 |
| 207 | + "import models\n" # 2 |
| 208 | + "if TYPE_CHECKING:\n" # 3 |
| 209 | + " from models import Item\n" # 4 |
| 210 | + "else:\n" # 5 |
| 211 | + " from fallback import Item\n" # 6 |
| 212 | + "if not TYPE_CHECKING:\n" # 7 |
| 213 | + " from models import Item as Late\n" # 8 |
| 214 | + ), |
| 215 | + }) |
| 216 | + stamped = _stamped_by_line(r, "service.py") |
| 217 | + assert [line for line, flag in stamped.items() if flag] == [4] |
| 218 | + assert {1, 2, 6, 8} <= set(stamped) |
| 219 | + |
| 220 | + |
| 221 | +@pytest.mark.parametrize("service_import, expected", [ |
| 222 | + ("if TYPE_CHECKING:\n from app import AppState\n", []), |
| 223 | + ("from app import AppState\n", [["app.py", "service.py"]]), |
| 224 | +], ids=["guarded", "runtime"]) |
| 225 | +def test_python_two_file_cycle_closes_only_through_a_runtime_import(tmp_path, service_import, expected): |
| 226 | + """The shape in the issue, in a directed build.""" |
| 227 | + cycles = _cycles(tmp_path, { |
| 228 | + "app.py": "from service import Service\n\nclass AppState:\n service: Service\n", |
| 229 | + "service.py": ("from __future__ import annotations\nfrom typing import TYPE_CHECKING\n\n" |
| 230 | + + service_import |
| 231 | + + "\nclass Service:\n def run(self, state: AppState):\n return state\n"), |
| 232 | + }) |
| 233 | + assert _names(cycles) == expected |
| 234 | + |
| 235 | + |
| 236 | +@pytest.mark.parametrize("adapter_import, expected", [ |
| 237 | + ("if TYPE_CHECKING:\n from pkg.main import AppState\n", []), |
| 238 | + ("from pkg.main import AppState\n", [["adapter.py", "main.py", "service.py"]]), |
| 239 | +], ids=["guarded", "runtime"]) |
| 240 | +def test_python_three_file_ring_closes_only_through_a_runtime_import(tmp_path, adapter_import, expected): |
| 241 | + """The reporter's shape, in the default undirected build.""" |
| 242 | + cycles = _cycles(tmp_path, { |
| 243 | + "pkg/__init__.py": "", |
| 244 | + "pkg/main.py": "from pkg.service import Service\n\nclass AppState:\n service: Service\n", |
| 245 | + "pkg/service.py": "from pkg.adapter import Adapter\n\nclass Service:\n adapter: Adapter\n", |
| 246 | + "pkg/adapter.py": ("from typing import TYPE_CHECKING\n\n" + adapter_import |
| 247 | + + "\nclass Adapter:\n def bind(self, state: 'AppState'): ...\n"), |
| 248 | + }, directed=False) |
| 249 | + assert _names(cycles) == expected |
| 250 | + |
| 251 | + |
| 252 | +# A runtime import and a guarded one for the same pair: the cycle stays --------- |
| 253 | + |
| 254 | +@pytest.mark.parametrize("a_body", [ |
| 255 | + "from typing import TYPE_CHECKING\nfrom b import helper\n\nif TYPE_CHECKING:\n from b import B\n", |
| 256 | + "from typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from b import B\n\nfrom b import helper\n", |
| 257 | +], ids=["runtime-first", "guard-first"]) |
| 258 | +def test_python_runtime_and_guarded_import_of_one_module_keep_the_cycle(tmp_path, a_body): |
| 259 | + cycles = _cycles(tmp_path, { |
| 260 | + "a.py": a_body + "\ndef f(x: 'B'):\n return helper(x)\n", |
| 261 | + "b.py": "from a import f\n\nclass B: ...\n\ndef helper(x):\n return f\n", |
| 262 | + }) |
| 263 | + assert _names(cycles) == [["a.py", "b.py"]] |
| 264 | + |
| 265 | + |
| 266 | +_RING_X6 = { |
| 267 | + # a -> b is `from . import b` (resolution pass, not stamped) plus a guarded `from .b import B` |
| 268 | + "pkg/__init__.py": "", |
| 269 | + "pkg/a.py": ("from . import b\nfrom typing import TYPE_CHECKING\n\n" |
| 270 | + "if TYPE_CHECKING:\n from .b import B\n\n" |
| 271 | + "def f(x: 'B'):\n return b.helper(x)\n"), |
| 272 | + "pkg/b.py": "from pkg.c import C\n\nclass B: ...\n\ndef helper(x):\n return C\n", |
| 273 | + "pkg/c.py": "from pkg.a import f\n\nclass C:\n run = f\n", |
| 274 | +} |
| 275 | + |
| 276 | + |
| 277 | +@pytest.mark.parametrize("directed, raw", [(False, False), (True, False), (False, True)], |
| 278 | + ids=["undirected", "directed", "no-cluster-raw"]) |
| 279 | +def test_python_ring_through_a_submodule_import_and_a_guard_keeps_its_cycle(tmp_path, directed, raw): |
| 280 | + cycles = _cycles(tmp_path, _RING_X6, directed=directed, raw=raw) |
| 281 | + assert _names(cycles) == [["a.py", "b.py", "c.py"]] |
| 282 | + |
| 283 | + |
| 284 | +def test_python_guard_in_one_direction_keeps_the_runtime_import_in_the_other(tmp_path): |
| 285 | + """Undirected, a pair is one edge: a.py's guarded `import pkg.b` folds with |
| 286 | + b.py's runtime `from pkg.a import A`, which closes the ring a -> c -> b -> a.""" |
| 287 | + cycles = _cycles(tmp_path, { |
| 288 | + "pkg/__init__.py": "", |
| 289 | + "pkg/a.py": ("from typing import TYPE_CHECKING\n\nfrom pkg.c import C\n\n" |
| 290 | + "if TYPE_CHECKING:\n import pkg.b\n\nclass A:\n c: C\n"), |
| 291 | + "pkg/b.py": "from pkg.a import A\n\nclass B:\n a: A\n", |
| 292 | + "pkg/c.py": "from pkg.b import B\n\nclass C:\n b: B\n", |
| 293 | + }, directed=False) |
| 294 | + assert _names(cycles) == [["a.py", "b.py", "c.py"]] |
| 295 | + |
| 296 | + |
| 297 | +def test_a_type_import_beside_a_value_import_of_the_same_file_keeps_the_cycle(tmp_path): |
| 298 | + """The same merge hid a real cycle for TypeScript (#3123).""" |
| 299 | + cycles = _cycles(tmp_path, { |
| 300 | + "a.ts": ('import type { B } from "./b.js";\nimport { helper } from "./b.js";\n' |
| 301 | + "export const a = (x: B) => helper(x);\n"), |
| 302 | + "b.ts": ('import { a } from "./a.js";\nexport type B = number;\n' |
| 303 | + "export function helper(x: number) { return a; }\n"), |
| 304 | + }) |
| 305 | + assert _names(cycles) == [["a.ts", "b.ts"]] |
| 306 | + |
| 307 | + |
| 308 | +def test_a_runtime_import_dropped_by_the_merge_still_clears_the_marker(): |
| 309 | + """build_from_json drops a lower-confidence duplicate of an edge it already |
| 310 | + holds; the type-only marker must not outlive the runtime import it dropped.""" |
| 311 | + def edge(src, tgt, conf, line, **extra): |
| 312 | + return {"source": src, "target": tgt, "relation": "imports_from", "confidence": conf, |
| 313 | + "source_file": f"{src}.py", "source_location": f"L{line}", **extra} |
| 314 | + |
| 315 | + nodes = [{"id": n, "label": f"{n}.py", "source_file": f"{n}.py", "file_type": "code"} |
| 316 | + for n in ("a", "b")] |
| 317 | + edges = [edge("a", "b", "EXTRACTED", 1, type_only=True), |
| 318 | + edge("a", "b", "INFERRED", 2), |
| 319 | + edge("b", "a", "EXTRACTED", 1)] |
| 320 | + G = build_from_json({"nodes": nodes, "edges": edges, "hyperedges": []}, directed=True) |
| 321 | + assert _names(find_import_cycles(G)) == [["a.py", "b.py"]] |
0 commit comments