Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(core): classify test-helpers and test-utils directories as test support (#3257)
Bharat Kaurav97a71537786b
diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.pyindex b4456469f..1990d19d9 100644--- a/packages/core/src/repowise/core/ingestion/traverser.py+++ b/packages/core/src/repowise/core/ingestion/traverser.py@@ -462,6 +462,9 @@ class FileTraverser:self._count_lock = threading.Lock()self._console_scripts_lock = threading.Lock()self._dir_ignore_lock = threading.Lock()+ # Repo-relative dir -> whether it holds a package manifest; asked only+ # about test-helper-named dirs (see :meth:`_is_package_root_dir`).+ self._package_root_cache: dict[str, bool] = {}log.info("FileTraverser initialised",repo_root=str(self.repo_root),@@ -893,6 +896,7 @@ class FileTraverser:roots=tables.pytest_roots,dotnet_projects=tables.dotnet_test_projects,phpunit_roots=tables.phpunit_roots,+ package_root=self._is_package_root_dir,)entry = _is_entry_point(rel_str, abs_path, language) or manifest_entryreturn FileInfo(@@ -911,6 +915,21 @@ class FileTraverser:is_reachability_root=entry,)+ def _is_package_root_dir(self, rel_dir: str) -> bool:+ """Whether *rel_dir* holds a package manifest, so it ships as a package.++ :mod:`..test_paths` asks this only about a ``test-utils/``-style+ directory, so it is a few stats per such directory rather than the full+ :meth:`package_manifests` scan. Racing workers compute the same answer,+ so the cache needs no lock.+ """+ cached = self._package_root_cache.get(rel_dir)+ if cached is None:+ base = self.repo_root / rel_dir+ cached = any((base / name).is_file() for name in _MANIFEST_FILES)+ self._package_root_cache[rel_dir] = cached+ return cached+# ------------------------------------------------------------------# Internal: monorepo detection# ------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/test_paths.py b/packages/core/src/repowise/core/test_paths.pyindex a86e063ca..f67f84b0f 100644--- a/packages/core/src/repowise/core/test_paths.py+++ b/packages/core/src/repowise/core/test_paths.py@@ -63,12 +63,15 @@ from pathlib import PurePath, PurePosixPathfrom typing import TYPE_CHECKINGif TYPE_CHECKING:- from collections.abc import Collection+ from collections.abc import Callable, Collectionfrom .dotnet_test_projects import DotnetTestProjectsfrom .phpunit_roots import PhpunitRootsfrom .pytest_roots import PytestRoots+ # Whether a repo-relative directory holds a package manifest.+ PackageRootProbe = Callable[[str], bool]+# Directory segments that mark every file beneath them as test material,# whatever the filename. ``__test__`` is the Jest variant of ``__tests__``;# ``integration_test`` is the directory Flutter's integration tests must live in;@@ -176,6 +179,25 @@ _SUPPORT_DIR_TOKENS_ANYWHERE: frozenset[str] = frozenset({"__fixtures__", "__mocks__", "__snapshots__", "testdata"})+# Helper directories named for tests, matched on the segment's words run+# together like ``testdata`` above: ``test-helpers/``, ``test_utils/``,+# ``testutil/`` (Go), ``test-support/``. They hold the mocks, render rigs and+# fixtures only tests import, so they count wherever they sit, where the bare+# ``helpers``/``support`` words above need a test tree around them.+#+# Unlike golden data, a helper directory can ship: preact's ``test-utils/`` is a+# package of its own published as ``preact/test-utils``. So one that is a+# package root (holds a registry package manifest) stays production. Path-only+# callers can see that only when the manifest is the path itself+# (``test-utils/package.json``); ingestion passes ``package_root`` so every file+# beneath one reads as production too. Known miss: react-dom's+# ``src/test-utils/`` is re-exported as the public ``react-dom/test-utils`` from+# a manifest one level up, and reads as support. ``testing`` stays out: it names+# shipped packages (Laravel's ``Illuminate/Testing``, Go helper libraries).+_SUPPORT_DIR_WORDS_UNLESS_PACKAGE: frozenset[str] = frozenset(+ {"testhelpers", "testhelper", "testutils", "testutil", "testsupport"}+)+# A source file whose name ends in "test" and a scaffolding word is the support# for some module's tests: ``bot.test-harness.ts``, ``card-test-helpers.ts``,@@ -205,6 +227,7 @@ class _Conventions:dir_suffixes: tuple[str, ...]unambiguous_dir_suffixes: tuple[str, ...]lang_dir_tokens: dict[str, frozenset[str]]+ manifest_names: frozenset[str]@cache@@ -247,6 +270,7 @@ def _conventions() -> _Conventions:if s.lstrip(".").lower() not in _AMBIGUOUS_TEST_DIR_TOKENS),lang_dir_tokens=REGISTRY.test_dir_tokens_by_language(),+ manifest_names=REGISTRY.package_manifest_filenames(),)@@ -273,6 +297,33 @@ def _is_support_anywhere_dir(segment: str) -> bool:)+def _in_support_anywhere_dir(+ segments: list[str], original: list[str], filename: str, package_root: PackageRootProbe | None+) -> bool:+ """Whether a directory that needs no test tree around it holds this file."""+ for i, seg in enumerate(segments):+ if _is_support_anywhere_dir(seg):+ return True+ if "".join(_words(seg)) in _SUPPORT_DIR_WORDS_UNLESS_PACKAGE and not _is_package_root(+ original[: i + 1], filename if i == len(segments) - 1 else "", package_root+ ):+ return True+ return False+++def _is_package_root(+ dir_parts: list[str], filename: str, package_root: PackageRootProbe | None+) -> bool:+ """Whether the directory *dir_parts* names is a package (see above).++ *filename* is the file being classified when it sits directly in that+ directory: a manifest there proves it without asking anyone.+ """+ if filename in _conventions().manifest_names:+ return True+ return package_root is not None and package_root("/".join(dir_parts))++def _is_test_name(filename: str) -> bool:"""Whether the filename alone marks a test (test_x.py, x_test.go, x.spec.ts)."""if not filename:@@ -425,6 +476,7 @@ def _classify(roots: PytestRoots | None = None,dotnet_projects: DotnetTestProjects | None = None,phpunit_roots: PhpunitRoots | None = None,+ package_root: PackageRootProbe | None = None,) -> str:"""``"test"``, ``"support"``, or ``""`` for production code.@@ -447,7 +499,9 @@ def _classify(# A scaffolding directory that needs no test tree around it settles the# question before the tree rules run, ``.github/`` included. A test-shaped# filename still wins, so ``testdata/build_test.go`` stays a test.- if not named_test and any(_is_support_anywhere_dir(seg) for seg in segments):+ if not named_test and _in_support_anywhere_dir(+ segments, original_segments, filename, package_root+ ):return "support"# ``.github/`` holds CI workflows, actions, issue templates and agent@@ -513,6 +567,7 @@ def is_test_path(roots: PytestRoots | None = None,dotnet_projects: DotnetTestProjects | None = None,phpunit_roots: PhpunitRoots | None = None,+ package_root: PackageRootProbe | None = None,) -> bool:"""Whether *path* is a test.@@ -525,7 +580,7 @@ def is_test_path(*dotnet_projects* to recognize C# files governed by a test project, andpass *phpunit_roots* to let PHPUnit's config overrule a test-shaped PHP name."""- return _classify(path, language, roots, dotnet_projects, phpunit_roots) == "test"+ return _classify(path, language, roots, dotnet_projects, phpunit_roots, package_root) == "test"def is_test_support_path(@@ -534,6 +589,7 @@ def is_test_support_path(roots: PytestRoots | None = None,dotnet_projects: DotnetTestProjects | None = None,phpunit_roots: PhpunitRoots | None = None,+ package_root: PackageRootProbe | None = None,) -> bool:"""Whether *path* is test infrastructure rather than a test.@@ -541,7 +597,7 @@ def is_test_support_path(scaffolding directories inside a test tree (``tests/factories/user.py``).Never true at the same time as :func:`is_test_path`."""- return _classify(path, language, roots, dotnet_projects, phpunit_roots) == "support"+ return _classify(path, language, roots, dotnet_projects, phpunit_roots, package_root) == "support"def is_test_related_path(@@ -550,6 +606,7 @@ def is_test_related_path(roots: PytestRoots | None = None,dotnet_projects: DotnetTestProjects | None = None,phpunit_roots: PhpunitRoots | None = None,+ package_root: PackageRootProbe | None = None,) -> bool:"""Whether *path* is a test **or** test support.@@ -557,8 +614,10 @@ def is_test_related_path(should use when they mean "not production code" - a refactoring detectorskipping files, a health biomarker exempting them. Callers that rank orsearch should prefer :func:`is_test_path`, so fixtures stay findable.+ *package_root*, which answers whether a repo-relative directory holds a+ package manifest, keeps a shipped ``test-utils/`` package production."""- return _classify(path, language, roots, dotnet_projects, phpunit_roots) != ""+ return _classify(path, language, roots, dotnet_projects, phpunit_roots, package_root) != ""def in_test_tree(path: str, language: str | None = None) -> bool:diff --git a/tests/unit/ingestion/test_traverser.py b/tests/unit/ingestion/test_traverser.pyindex a3f7dd909..b178f9ab0 100644--- a/tests/unit/ingestion/test_traverser.py+++ b/tests/unit/ingestion/test_traverser.py@@ -568,6 +568,27 @@ class TestFileTraverser:assert files["tests/test_demo.py"] is Trueassert files["tools/test_cli.py"] is True+ def test_test_helper_directories_are_test_material(self, tmp_path: Path) -> None:+ """#3244: helper dirs only tests import are not production code, unless+ the directory is a package root of its own (preact's ``test-utils/``)."""+ files_on_disk = {+ "ui/src/test-helpers/load-styles.ts": "export function loadStyles(): void {}\n",+ "ui/src/ui/app.test.ts": (+ 'import { loadStyles } from "../test-helpers/load-styles";\nloadStyles();\n'+ ),+ "src/test-utils/async.ts": "export const tick = () => Promise.resolve();\n",+ "test-utils/package.json": '{"name": "test-utils"}\n',+ "test-utils/src/index.js": "export function act() {}\n",+ }+ for rel, text in files_on_disk.items():+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)+ (tmp_path / rel).write_text(text)+ files = {f.path: f.is_test for f in FileTraverser(tmp_path).traverse()}+ assert files["ui/src/test-helpers/load-styles.ts"] is True+ assert files["src/test-utils/async.ts"] is True+ assert files["ui/src/ui/app.test.ts"] is True+ assert files["test-utils/src/index.js"] is False+def test_a_test_named_php_class_outside_phpunit_testsuites_is_production(self, tmp_path: Path) -> None:diff --git a/tests/unit/test_test_paths.py b/tests/unit/test_test_paths.pyindex c768fbcee..a98f608c3 100644--- a/tests/unit/test_test_paths.py+++ b/tests/unit/test_test_paths.py@@ -191,7 +191,32 @@ _CORPUS: tuple[tuple[str, str | None, str], ...] = (# a library for writing tests is that library's production code("packages/testing-library/src/index.ts", None, ""),("src/testing_library/render.py", None, ""),- ("src/test-utils/render.ts", None, ""),+ # #3244: but a helper directory named for tests holds what only tests+ # import, wherever it sits, read on its words run together like `testdata`+ ("ui/src/test-helpers/load-styles.ts", None, "support"),+ ("src/test_helpers/x.py", None, "support"),+ ("src/testhelpers/x.ts", None, "support"),+ ("src/test-utils/render.ts", None, "support"),+ ("src/test_utils/x.py", None, "support"),+ ("internal/testutils/x.go", None, "support"),+ ("pkg/testutil/x.go", None, "support"),+ ("src/test-support/x.ts", None, "support"),+ ("src/test_support/x.rb", None, "support"),+ ("tests/test-utils/x.ts", None, "support"),+ # a test-shaped filename inside one is still a test+ ("ui/src/test-helpers/foo.test.ts", None, "test"),+ ("pkg/testutil/x_test.go", None, "test"),+ # the bare words still need a test tree, and `testing` names shipped packages+ ("src/helpers/x.ts", None, ""),+ ("src/support/x.ts", None, ""),+ ("src/utils/x.ts", None, ""),+ ("tests/helpers/x.ts", None, "support"),+ ("src/testing/x.py", None, ""),+ ("src/latest-utils/x.py", None, ""),+ # a helper directory that is a package root ships (preact's `test-utils/`);+ # path-only, its own manifest is the evidence+ ("test-utils/package.json", None, ""),+ ("pkg/testutil/go.mod", None, ""),# `test-data` / `test_data` are golden data, the same as Go's `testdata`("test-data/users.json", None, "support"),("pkg/test_data/input.csv", None, "support"),@@ -308,6 +333,21 @@ def test_related_is_the_union(path: str, language: str | None, expected: str) ->assert is_test_related_path(path, language) is (expected != "")+def test_a_test_helper_directory_that_is_a_package_root_stays_production() -> None:+ """#3244: preact's ``test-utils/`` is a package published as+ ``preact/test-utils``. Only the caller knows the directory holds a manifest,+ so it says so through *package_root*; path-only callers read it as support."""+ roots = {"test-utils"}.__contains__+ assert not is_test_related_path("test-utils/src/index.js", package_root=roots)+ assert is_test_support_path("test-utils/src/index.js")+ # Only the helper directory is asked about, so a package root elsewhere on+ # the path does not rescue it, and a test file in a shipped package is a test.+ assert is_test_support_path("src/test-utils/x.ts", package_root={"src"}.__contains__)+ assert is_test_path("test-utils/test/index.test.js", package_root=roots)+ # Golden data is not a package even beside a manifest (Go fixture modules).+ assert is_test_support_path("testdata/mod/x.go", package_root=lambda _d: True)++@pytest.mark.parametrize("path", ["", ".", "/"])def test_degenerate_paths_are_not_tests(path: str) -> None:assert not is_test_related_path(path)