desloppify icon indicating copy to clipboard operation
desloppify copied to clipboard

Python external-test mapping loses service import roots and Windows graph path matches

Open CyberDay1 opened this issue 1 month ago • 1 comments

Desloppify 1.0, Windows, scanning a Python service subdirectory with tests outside it. A synthetic fixture reproduces two coverage-mapping discrepancies without any project-specific code or state changes.

Layout:

repo/
  service/main.py                 # from routes.math_ops import add
  service/routes/__init__.py
  service/routes/math_ops.py      # def add(a, b): return a + b
  tests/test_route_behavior.py    # from routes.math_ops import add; assert add(1, 2) == 3

The service runs with service/ on sys.path (e.g. starting from that directory), and the test setup supplies that same import root. Scan target is service/ from the repository root. External tests are discovered, but their imports do not map to the scanned source.

Read-only detector reproduction, with DESLOPPIFY_ROOT pointing at the fixture root:

graph = build_dep_graph(root / 'service')
production = {'service/routes/math_ops.py'}
tests = {str(root / 'tests/test_route_behavior.py')}
print(import_based_mapping(graph, tests, production, 'python'))
normalized = _normalize_graph_paths(graph)
print(sorted(normalized))
print(normalized.get('service/routes/math_ops.py'))
print(normalized.get(os.path.join('service', 'routes', 'math_ops.py'), {}).get('importer_count'))

Imports are from languages.python.detectors.deps, engine.detectors.coverage.mapping, and engine.detectors.test_coverage.discovery, respectively.

Observed:

set()
['service\\main.py', 'service\\routes\\__init__.py', 'service\\routes\\math_ops.py']
None
1

Expected: the directly imported module is mapped as tested; coverage lookup sees the existing importer rather than reporting zero.

Source evidence:

  • coverage/mapping_analysis.py:_build_prod_by_module builds service.routes.math_ops and math_ops aliases, but not routes.math_ops relative to the scan/import root.
  • python/test_coverage.py:resolve_import_spec considers repository-relative, src/-prefixed, and test-sibling paths, but not the service scan root. The fallback removes trailing spec components rather than the source-root prefix, so it cannot repair this case.
  • test_coverage/discovery.py:_normalize_graph_paths strips the absolute root but retains Windows backslashes; production zone keys use forward slashes. Graph lookups then miss valid nodes and edges.

Please retain source-root context in external-test import mapping, with explicit handling of ambiguous same-named modules in multi-service repositories, and normalize graph keys/edges consistently with zone paths. Regression fixtures should include external tests, a service import root distinct from repository root, ambiguous parallel services, and Windows-native graph paths.

The scan's coverage summary also labels its weighted potential as a count of production files, although discovery.py computes it as a sum of capped sqrt(LOC) weights. That label makes diagnosing the mismatch harder.

Installed tool code and stored scores/findings were not modified for this diagnosis.

CyberDay1 avatar Oct 29 '26 01:10 CyberDay1

Independent confirmation of the third point (_normalize_graph_paths keeps Windows backslashes), on a plain src layout with tests at the repository root, so it is not specific to service subdirectories.

Desloppify installed with uv tool, Python 3.13, Windows 11, scan run from the repository root with desloppify --lang python scan --path ..

repo/
  pyproject.toml
  src/pkg/__init__.py      # from .core import add
  src/pkg/core.py          # from .util import helper; add() and sub()
  src/pkg/util.py          # helper(), 18 LOC (above _MIN_LOC)
  tests/test_ops.py        # from pkg.core import add, sub; asserts both

desloppify show test_coverage:

src/pkg/util.py  (1 issues)
  ○ T3 [high] Untested module (18 LOC, 0 importers)

core.py is mapped as tested through resolve_import_spec (which handles src/), but util.py is only reachable through the graph, and every graph lookup misses because the normalized keys are src\pkg\util.py while the zone keys are src/pkg/util.py. The orphaned detector does not flag util.py, so the graph itself has the edge; only the test-coverage normalization loses it. On a real project this marked every module reached only transitively as untested.

Suggested patch for that part only (not the service import-root mapping). I could not run the test suite in my environment, so it is untested beyond reading:

diff --git a/desloppify/engine/detectors/test_coverage/discovery.py b/desloppify/engine/detectors/test_coverage/discovery.py
index 32a65bc..99c16bf 100644
--- a/desloppify/engine/detectors/test_coverage/discovery.py
+++ b/desloppify/engine/detectors/test_coverage/discovery.py
@@ -5,6 +5,7 @@ from __future__ import annotations
 import math
 import os
 
+from desloppify.base.discovery.file_paths import normalize_path_separators
 from desloppify.base.discovery.paths import get_project_root
 from desloppify.engine.policy.zones import FileZoneMap, Zone
 
@@ -16,15 +17,19 @@ _MAX_NO_TESTS_ENTRIES = 50
 
 
 def _normalize_graph_paths(graph: dict) -> dict:
-    """Normalize graph paths to relative paths."""
-    root_prefix = str(get_project_root()) + os.sep
+    """Normalize graph paths to project-relative paths with forward slashes.
 
-    def _to_rel(path: str) -> str:
-        return path[len(root_prefix) :] if path.startswith(root_prefix) else path
+    Production and test file sets use forward slashes on every platform, so a
+    Windows graph key such as ``C:\\proj\\src\\mod.py`` must become
+    ``src/mod.py`` or no lookup into the graph ever matches.
+    """
+    root = str(get_project_root())
+    root_prefixes = (root + "/", root + "\\")
 
-    needs_norm = any(k.startswith(root_prefix) for k in graph)
-    if not needs_norm:
-        return graph
+    def _to_rel(path: str) -> str:
+        if path.startswith(root_prefixes):
+            path = path[len(root) + 1 :]
+        return normalize_path_separators(path)
 
     norm_graph: dict = {}
     for key, value in graph.items():
diff --git a/desloppify/tests/detectors/coverage/test_coverage_internals.py b/desloppify/tests/detectors/coverage/test_coverage_internals.py
index 2e83e26..acd28d4 100644
--- a/desloppify/tests/detectors/coverage/test_coverage_internals.py
+++ b/desloppify/tests/detectors/coverage/test_coverage_internals.py
@@ -109,10 +109,23 @@ def test_normalize_graph_paths_converts_absolute_to_relative():
 
     result = discovery_mod._normalize_graph_paths(graph)
 
-    expected_key = "src" + sep + "module.py"
-    expected_import = "src" + sep + "other.py"
-    assert expected_key in result
-    assert expected_import in result[expected_key]["imports"]
+    assert "src/module.py" in result
+    assert "src/other.py" in result["src/module.py"]["imports"]
+
+
+def test_normalize_graph_paths_uses_forward_slashes_for_backslash_paths(monkeypatch):
+    monkeypatch.setattr(discovery_mod, "get_project_root", lambda: "C:\\proj")
+    graph = {
+        "C:\\proj\\src\\pkg\\core.py": {
+            "imports": {"C:\\proj\\src\\pkg\\util.py", "src\\pkg\\other.py"},
+            "importer_count": 0,
+        }
+    }
+
+    result = discovery_mod._normalize_graph_paths(graph)
+
+    assert set(result) == {"src/pkg/core.py"}
+    assert result["src/pkg/core.py"]["imports"] == {"src/pkg/util.py", "src/pkg/other.py"}
 
 
 def test_normalize_graph_paths_skips_already_relative():

The existing test_normalize_graph_paths_converts_absolute_to_relative expected os.sep in the output, which encodes the bug on Windows; the patch changes it to forward slashes and adds a test with backslash paths that runs on any platform. The needs_norm early return is dropped so that relative keys with backslashes are normalized too.

R3yD4rK avatar Nov 02 '26 19:11 R3yD4rK