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
feat(core): demote PHP production classes named Test.php outside testsuites (#3234) (#3399)
Rishabh Mishra388ed6479990
diff --git a/packages/core/src/repowise/core/analysis/test_selection.py b/packages/core/src/repowise/core/analysis/test_selection.pyindex 54fe71811..4d57c291c 100644--- a/packages/core/src/repowise/core/analysis/test_selection.py+++ b/packages/core/src/repowise/core/analysis/test_selection.py@@ -68,6 +68,7 @@ from typing import TYPE_CHECKING, Anyimport pathspec+from ..phpunit_roots import PhpunitRootsfrom ..pytest_roots import PYTEST_CONFIG_NAMES, PytestRootsfrom ..support_paths import DOC_EXTENSIONSfrom ..test_paths import is_test_path, is_test_related_path, is_test_support_path@@ -463,13 +464,22 @@ def is_test_helper(path: str) -> bool:)-def is_runnable_test(path: str, roots: PytestRoots | None = None) -> bool:+def is_runnable_test(+ path: str,+ roots: PytestRoots | None = None,+ phpunit_roots: PhpunitRoots | None = None,+) -> bool:"""A test-shaped file name with an extension a runner collects tests from.With *roots*, a Python file pytest's config leaves out of collection(``core/test_paths.py``) is not one: the same rule that stamps ``is_test``.+ With *phpunit_roots*, a PHP file PHPUnit leaves out of collection is not runnable."""- return _runnable_name(path) and (roots is None or is_test_path(path, roots=roots))+ return (+ _runnable_name(path)+ and (roots is None or is_test_path(path, roots=roots))+ and (phpunit_roots is None or is_test_path(path, phpunit_roots=phpunit_roots))+ )@functools.lru_cache(maxsize=_PATH_MEMO)diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.pyindex 0b931d9e9..b4456469f 100644--- a/packages/core/src/repowise/core/ingestion/traverser.py+++ b/packages/core/src/repowise/core/ingestion/traverser.py@@ -26,7 +26,7 @@ from collections.abc import Callable, Iterable, Iterator, Sequencefrom dataclasses import dataclass, fieldfrom datetime import datetimefrom pathlib import Path-from typing import NamedTuple+from typing import Any, NamedTupleimport pathspecimport structlog@@ -36,6 +36,13 @@ from ..code_origin import is_generated_headerfrom ..dotnet_test_projects import DotnetTestProjects, read_dotnet_test_projectsfrom ..entry_candidacy import conventional_entry_stems, not_an_execution_startfrom ..owned_paths import MANAGED_FILES, OWNED_PATTERNS, only_repowise_differs+from ..phpunit_roots import (+ PHPUNIT_CONFIG_NAMES,+ PhpunitConfigUnreadableError,+ PhpunitRoots,+ parse_phpunit_options,+ phpunit_roots,+)from ..pytest_roots import (PYTEST_CONFIG_NAMES,PytestRoots,@@ -495,6 +502,11 @@ class FileTraverser:"""Where pytest collects, from the configs the console-script pass read."""return self._console_script_tables().pytest_roots+ @property+ def phpunit_roots(self) -> PhpunitRoots:+ """Where PHPUnit collects, from the configs the console-script pass read."""+ return self._console_script_tables().phpunit_roots+@propertydef dotnet_test_projects(self) -> DotnetTestProjects:"""The .NET test projects, from the .csproj files the config pass read."""@@ -874,12 +886,13 @@ class FileTraverser:_is_console_script_target(rel_str, self._console_script_modules)or rel_str in self._distribution_inits)- scripts = self._console_script_tables()+ tables = self._console_script_tables()is_test = is_test_related_path(rel_str,language,- roots=scripts.pytest_roots,- dotnet_projects=scripts.dotnet_test_projects,+ roots=tables.pytest_roots,+ dotnet_projects=tables.dotnet_test_projects,+ phpunit_roots=tables.phpunit_roots,)entry = _is_entry_point(rel_str, abs_path, language) or manifest_entryreturn FileInfo(@@ -1227,6 +1240,8 @@ class ConsoleScriptTables(NamedTuple):"""Repo-relative ``__init__.py`` of each distribution's own import package."""pytest_roots: PytestRoots = PytestRoots()"""Where a bare pytest run collects tests, which decides a test-named module."""+ phpunit_roots: PhpunitRoots = PhpunitRoots()+ """Where PHPUnit collects tests, which decides a test-named PHP class."""dotnet_test_projects: DotnetTestProjects = DotnetTestProjects()""".NET test projects, which govern .cs files beneath them."""@@ -1242,7 +1257,8 @@ def _collect_console_scripts(before the colon is the module it imports; ``[project].name`` is thedistribution. Best-effort: unparsable files are skipped. The pytestconfigs (``pytest.ini``, ``tox.ini``, ``setup.cfg`` and the same- ``pyproject.toml``) come off this one walk and one read each.+ ``pyproject.toml``) and PHPUnit configs (``phpunit.xml``,+ ``phpunit.dist.xml``, ``phpunit.xml.dist``) come off this one walk."""from repowise.core.fs_walk import iter_glob@@ -1252,8 +1268,10 @@ def _collect_console_scripts(inits: set[str] = set()pytest_configs: list[tuple[str, dict]] = []unreadable: list[str] = []+ phpunit_configs: list[tuple[str, Any]] = []+ phpunit_unreadable: list[str] = []csproj_files: list[tuple[str, str]] = []- manifest_patterns = (*PYTEST_CONFIG_NAMES, "*.csproj")+ manifest_patterns = (*PYTEST_CONFIG_NAMES, *PHPUNIT_CONFIG_NAMES, "*.csproj")try:config_files = list(iter_glob(repo_root, manifest_patterns, prune_nested_git=prune_nested_git)@@ -1261,7 +1279,8 @@ def _collect_console_scripts(except OSError:return ConsoleScriptTables(frozenset(), frozenset(), frozenset(), frozenset())for config_file in config_files:- if config_file.name.endswith(".csproj"):+ name = config_file.name+ if name.endswith(".csproj"):rel = config_file.relative_to(repo_root).as_posix()try:text = config_file.read_text(encoding="utf-8", errors="replace")@@ -1269,26 +1288,38 @@ def _collect_console_scripts(except Exception:csproj_files.append((rel, ""))continue- project, options, parsed = _read_python_config(config_file)rel = config_file.relative_to(repo_root).as_posix()- if options is not None:- pytest_configs.append((rel, options))- if not parsed:- unreadable.append(rel)- if project is None:- continue- dist = project.get("name")- if isinstance(dist, str) and dist.strip():- distributions.add(dist.strip())- if (init := _distribution_init(repo_root, config_file.parent, dist)) is not None:- inits.add(init)- _add_script_targets(project, names, modules)+ if name in PHPUNIT_CONFIG_NAMES:+ try:+ text = config_file.read_text(encoding="utf-8")+ options = parse_phpunit_options(text)+ if options is not None:+ phpunit_configs.append((rel, options))+ else:+ phpunit_unreadable.append(rel)+ except (OSError, UnicodeDecodeError, PhpunitConfigUnreadableError):+ phpunit_unreadable.append(rel)+ if name in PYTEST_CONFIG_NAMES:+ project, options, parsed = _read_python_config(config_file)+ if options is not None:+ pytest_configs.append((rel, options))+ if not parsed:+ unreadable.append(rel)+ if project is None:+ continue+ dist = project.get("name")+ if isinstance(dist, str) and dist.strip():+ distributions.add(dist.strip())+ if (init := _distribution_init(repo_root, config_file.parent, dist)) is not None:+ inits.add(init)+ _add_script_targets(project, names, modules)return ConsoleScriptTables(frozenset(names),frozenset(modules),frozenset(distributions),frozenset(inits),pytest_roots(pytest_configs, unreadable),+ phpunit_roots(phpunit_configs, phpunit_unreadable),read_dotnet_test_projects(csproj_files),)diff --git a/packages/core/src/repowise/core/phpunit_roots.py b/packages/core/src/repowise/core/phpunit_roots.pynew file mode 100644index 000000000..c1395276c--- /dev/null+++ b/packages/core/src/repowise/core/phpunit_roots.py@@ -0,0 +1,286 @@+"""Where PHPUnit collects tests from, read from its config files.++A PHP file whose class name ends in ``Test`` (``src/Testing/Attributes/UnitTest.php``)+is production code when PHPUnit's own configuration keeps it out of collection:+``<testsuites>`` defines the suites, directories, files and exclusions that a+PHPUnit test run executes. :mod:`.test_paths` asks :meth:`PhpunitRoots.collects`+before trusting a test-shaped PHP name outside any test directory.++Pure: callers hand in config text, so ingestion reads each config once in the+walk it already makes and a server can call this with data it holds.++Each config governs its own directory, nearest first. Precedence within a+directory: ``phpunit.xml``, ``phpunit.dist.xml``, ``phpunit.xml.dist``.+A nested config's suites are resolved against its own directory and against the+repository root, and a file any config above it collects counts as collected.++Fail-closed: only a definite ``False`` demotes. No config, an unreadable config,+or a config with no ``<testsuites>`` keeps today's answer, and any config that+collects the file keeps it a test.+"""++from __future__ import annotations++import xml.etree.ElementTree as ET+from collections.abc import Iterable, Mapping+from dataclasses import dataclass, field+from fnmatch import fnmatchcase+from pathlib import PurePosixPath++PHPUNIT_CONFIG_FILES: tuple[str, ...] = (+ "phpunit.xml",+ "phpunit.dist.xml",+ "phpunit.xml.dist",+)+PHPUNIT_CONFIG_NAMES: frozenset[str] = frozenset(PHPUNIT_CONFIG_FILES)+_PRECEDENCE = {name: rank for rank, name in enumerate(PHPUNIT_CONFIG_FILES)}+++class PhpunitConfigUnreadableError(ValueError):+ """A PHPUnit config file that does not parse."""+++@dataclass(frozen=True, slots=True)+class _SuiteDirectory:+ path: str+ suffix: str = "Test.php"+ prefix: str = ""+ excludes: tuple[str, ...] = ()+++@dataclass(frozen=True, slots=True)+class _TestSuite:+ name: str+ directories: tuple[_SuiteDirectory, ...] = ()+ files: tuple[str, ...] = ()+ excludes: tuple[str, ...] = ()+++@dataclass(frozen=True, slots=True)+class _PhpunitCollection:+ suites: tuple[_TestSuite, ...]+++@dataclass(frozen=True, slots=True)+class PhpunitRoots:+ """Test suite collections for each directory holding a PHPUnit config."""++ by_dir: Mapping[str, _PhpunitCollection] = field(default_factory=dict)+ unreadable: frozenset[str] = frozenset()++ def collects(self, path: str) -> bool | None:+ """Whether PHPUnit collects *path*; ``None`` when no config governs it.++ Collected when any governing config at or above it collects it;+ only a unanimous "no" demotes a test. If an ancestor directory has an+ unreadable config, returns ``None`` (fail-closed).+ """+ p = PurePosixPath(path)+ dirs = ["" if str(parent) == "." else str(parent) for parent in p.parents]+ if any(d in self.unreadable for d in dirs):+ return None+ verdicts = [+ _collected(p, p.relative_to(parent), collection)+ for parent in p.parents+ if (collection := self.by_dir.get("" if str(parent) == "." else str(parent))) is not None+ ]+ return any(verdicts) if verdicts else None+++def _matches_pattern_or_parent(+ candidate: PurePosixPath, pattern_str: str, parents: tuple[PurePosixPath, ...]+) -> bool:+ if pattern_str in (".", ""):+ return True+ pat_path = PurePosixPath(pattern_str)+ if candidate == pat_path or pat_path in parents:+ return True+ all_str_candidates = (str(candidate), *(str(c) for c in parents if str(c) != "."))+ return any(fnmatchcase(c, pattern_str) for c in all_str_candidates)+++def _suite_collects(path: PurePosixPath, rel: PurePosixPath, suite: _TestSuite) -> bool:+ path_parents = tuple(path.parents)+ rel_parents = tuple(rel.parents)++ # Suite-level exclusions+ for ex in suite.excludes:+ if _matches_pattern_or_parent(rel, ex, rel_parents) or _matches_pattern_or_parent(+ path, ex, path_parents+ ):+ return False++ # Explicit files+ for f in suite.files:+ f_path = PurePosixPath(f)+ if rel == f_path or path == f_path or fnmatchcase(str(rel), f) or fnmatchcase(str(path), f):+ return True++ # Directories+ filename = path.name+ for d in suite.directories:+ # Check directory-level exclusions+ if any(+ _matches_pattern_or_parent(rel, ex, rel_parents)+ or _matches_pattern_or_parent(path, ex, path_parents)+ for ex in d.excludes+ ):+ continue++ # Check if the path falls within the directory+ if not (+ _matches_pattern_or_parent(rel, d.path, rel_parents)+ or _matches_pattern_or_parent(path, d.path, path_parents)+ ):+ continue++ # Check filename suffix and prefix+ if d.prefix and not filename.startswith(d.prefix):+ continue++ if d.suffix:+ if d.suffix.startswith("*"):+ if not fnmatchcase(filename, d.suffix):+ continue+ elif not filename.endswith(d.suffix):+ continue++ return True++ return False+++def _collected(path: PurePosixPath, rel: PurePosixPath, collection: _PhpunitCollection) -> bool:+ return any(_suite_collects(path, rel, suite) for suite in collection.suites)+++def phpunit_options(text: str) -> _PhpunitCollection | None:+ """The PHPUnit suite collection of one config, or ``None`` if absent or unreadable."""+ try:+ return parse_phpunit_options(text)+ except PhpunitConfigUnreadableError:+ return None+++def parse_phpunit_options(text: str) -> _PhpunitCollection | None:+ """:func:`phpunit_options`, raising :class:`PhpunitConfigUnreadableError` on malformed XML."""+ if not text.strip():+ return None+ try:+ root = ET.fromstring(text)+ except ET.ParseError as exc:+ raise PhpunitConfigUnreadableError(f"Malformed XML: {exc}") from exc++ # A PHPUnit configuration root tag is <phpunit>+ if root.tag.lower() != "phpunit":+ return None++ suite_elements = list(root.iter("testsuite"))+ if not suite_elements:+ return None++ suites: list[_TestSuite] = []+ for suite_elem in suite_elements:+ name = suite_elem.get("name", "")+ suite_excludes = tuple(+ _clean_path(ex.text) for ex in suite_elem.findall("exclude") if _clean_path(ex.text)+ )+ suite_files = tuple(+ _clean_path(f.text) for f in suite_elem.findall("file") if _clean_path(f.text)+ )++ directories: list[_SuiteDirectory] = []+ for dir_elem in suite_elem.findall("directory"):+ dir_path = _clean_path(dir_elem.text)+ if not dir_path:+ continue+ suffix = dir_elem.attrib.get("suffix", "Test.php")+ prefix = dir_elem.attrib.get("prefix", "")+ dir_excludes = tuple(+ _clean_path(ex.text) for ex in dir_elem.findall("exclude") if _clean_path(ex.text)+ )+ directories.append(+ _SuiteDirectory(+ path=dir_path,+ suffix=suffix,+ prefix=prefix,+ excludes=dir_excludes,+ )+ )++ suites.append(+ _TestSuite(+ name=name,+ directories=tuple(directories),+ files=suite_files,+ excludes=suite_excludes,+ )+ )++ return _PhpunitCollection(suites=tuple(suites))+++def _clean_path(val: str | None) -> str:+ if not val:+ return ""+ cleaned = val.strip().replace("\\", "/").strip("/")+ if cleaned.startswith("./"):+ cleaned = cleaned[2:].strip("/")+ return cleaned+++def _dir_key(path: PurePosixPath) -> str:+ return "" if str(path.parent) == "." else str(path.parent)+++def phpunit_roots(+ configs: Iterable[tuple[str, _PhpunitCollection]], unreadable: Iterable[str] = ()+) -> PhpunitRoots:+ """Build from ``(config path, collection)`` pairs.++ The highest-precedence config in each directory wins. If an unreadable or+ unknown config has higher or equal precedence than any parsed config in the+ same directory, that directory fails closed (marked unreadable).+ """+ chosen: dict[str, tuple[int, _PhpunitCollection]] = {}+ for path, collection in configs:+ p = PurePosixPath(path)+ key = _dir_key(p)+ rank = _PRECEDENCE.get(p.name, len(_PRECEDENCE))+ if key not in chosen or rank < chosen[key][0]:+ chosen[key] = (rank, collection)++ unreadable_ranks: dict[str, int] = {}+ for path in unreadable:+ p = PurePosixPath(path)+ key = _dir_key(p)+ rank = _PRECEDENCE.get(p.name, len(_PRECEDENCE))+ if key not in unreadable_ranks or rank < unreadable_ranks[key]:+ unreadable_ranks[key] = rank++ unreadable_dirs: set[str] = set()+ for key, unreadable_rank in unreadable_ranks.items():+ if key not in chosen or unreadable_rank <= chosen[key][0]:+ unreadable_dirs.add(key)+ chosen.pop(key, None)++ return PhpunitRoots(+ by_dir={key: col for key, (_, col) in chosen.items()},+ unreadable=frozenset(unreadable_dirs),+ )+++def read_phpunit_roots(texts: Iterable[tuple[str, str]]) -> PhpunitRoots:+ """:func:`phpunit_roots` from ``(config path, text)`` pairs."""+ configs: list[tuple[str, _PhpunitCollection]] = []+ unreadable: list[str] = []+ for path, text in texts:+ try:+ options = parse_phpunit_options(text)+ if options is not None:+ configs.append((path, options))+ else:+ unreadable.append(path)+ except PhpunitConfigUnreadableError:+ unreadable.append(path)+ return phpunit_roots(configs, unreadable)diff --git a/packages/core/src/repowise/core/test_paths.py b/packages/core/src/repowise/core/test_paths.pyindex 783e9a6f3..a86e063ca 100644--- a/packages/core/src/repowise/core/test_paths.py+++ b/packages/core/src/repowise/core/test_paths.py@@ -66,6 +66,7 @@ if TYPE_CHECKING:from collections.abc import Collectionfrom .dotnet_test_projects import DotnetTestProjects+ from .phpunit_roots import PhpunitRootsfrom .pytest_roots import PytestRoots# Directory segments that mark every file beneath them as test material,@@ -423,6 +424,7 @@ def _classify(language: str | None,roots: PytestRoots | None = None,dotnet_projects: DotnetTestProjects | None = None,+ phpunit_roots: PhpunitRoots | None = None,) -> str:"""``"test"``, ``"support"``, or ``""`` for production code.@@ -455,8 +457,13 @@ def _classify(if _REPO_METADATA_DIR in segments:return "test" if named_test else ""- # A test name outside a test directory still needs pytest to collect it.- needs_test_dir = not named_test or _pytest_skips(path, filename, roots)+ # A test name outside a test directory still needs pytest to collect it,+ # or PHPUnit config not to keep it out of collection.+ needs_test_dir = (+ not named_test+ or _pytest_skips(path, filename, roots)+ or _phpunit_skips(path, filename, phpunit_roots)+ )if (needs_test_dirand not _is_test_dir(segments, original_segments, filename, language)@@ -471,6 +478,15 @@ def _classify(return "test"+def _phpunit_skips(path: str, filename: str, roots: PhpunitRoots | None) -> bool:+ """Whether PHPUnit's config keeps a test-named PHP file out of collection."""+ return (+ roots is not None+ and PurePosixPath(filename).suffix.lower() == ".php"+ and roots.collects(path.replace("\\", "/")) is False+ )++def _dotnet_project_collects(path: str, filename: str, dotnet_projects: DotnetTestProjects | None) -> bool:@@ -496,6 +512,7 @@ def is_test_path(language: str | None = None,roots: PytestRoots | None = None,dotnet_projects: DotnetTestProjects | None = None,+ phpunit_roots: PhpunitRoots | None = None,) -> bool:"""Whether *path* is a test.@@ -504,10 +521,11 @@ def is_test_path(*language* when it is known: it decides the ambiguous ``spec/``/``t/``cases, which are RSpec for Ruby and a Perl-style test tree for Python,and specification or miscellaneous folders for everything else. Pass- *roots* to let pytest's config overrule a test-shaped Python name. Pass- *dotnet_projects* to recognize C# files governed by a test project.+ *roots* to let pytest's config overrule a test-shaped Python name, pass+ *dotnet_projects* to recognize C# files governed by a test project, and+ pass *phpunit_roots* to let PHPUnit's config overrule a test-shaped PHP name."""- return _classify(path, language, roots, dotnet_projects) == "test"+ return _classify(path, language, roots, dotnet_projects, phpunit_roots) == "test"def is_test_support_path(@@ -515,6 +533,7 @@ def is_test_support_path(language: str | None = None,roots: PytestRoots | None = None,dotnet_projects: DotnetTestProjects | None = None,+ phpunit_roots: PhpunitRoots | None = None,) -> bool:"""Whether *path* is test infrastructure rather than a test.@@ -522,7 +541,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) == "support"+ return _classify(path, language, roots, dotnet_projects, phpunit_roots) == "support"def is_test_related_path(@@ -530,6 +549,7 @@ def is_test_related_path(language: str | None = None,roots: PytestRoots | None = None,dotnet_projects: DotnetTestProjects | None = None,+ phpunit_roots: PhpunitRoots | None = None,) -> bool:"""Whether *path* is a test **or** test support.@@ -538,8 +558,7 @@ def is_test_related_path(skipping files, a health biomarker exempting them. Callers that rank orsearch should prefer :func:`is_test_path`, so fixtures stay findable."""- return _classify(path, language, roots, dotnet_projects) != ""-+ return _classify(path, language, roots, dotnet_projects, phpunit_roots) != ""def in_test_tree(path: str, language: str | None = None) -> bool:diff --git a/tests/unit/analysis/test_test_selection.py b/tests/unit/analysis/test_test_selection.pyindex 87c5f98e7..e3736ee1a 100644--- a/tests/unit/analysis/test_test_selection.py+++ b/tests/unit/analysis/test_test_selection.py@@ -26,6 +26,7 @@ from repowise.core.analysis.test_selection import (select_tests,with_rewired,)+from repowise.core.phpunit_roots import read_phpunit_rootsfrom repowise.core.pytest_roots import read_pytest_roots_NONE = TestSelectionConfig()@@ -932,6 +933,21 @@ def test_a_test_named_module_pytest_does_not_collect_is_not_runnable() -> None:assert is_runnable_test("src/pkg/test_paths.py")+def test_a_test_named_php_class_phpunit_does_not_collect_is_not_runnable() -> None:+ """``src/Testing/Attributes/UnitTest.php`` is test-shaped, but PHPUnit never collects it."""+ config = (+ '<phpunit><testsuites><testsuite name="Suite">'+ '<directory suffix="Test.php">./tests</directory>'+ '</testsuite></testsuites></phpunit>'+ )+ roots = read_phpunit_roots([("phpunit.xml.dist", config)])+ assert not is_runnable_test("src/Testing/Attributes/UnitTest.php", phpunit_roots=roots)+ assert is_runnable_test("tests/RouterTest.php", phpunit_roots=roots)+ assert is_runnable_test("tests/sub/DeepTest.php", phpunit_roots=roots)+ # With no config the name decides.+ assert is_runnable_test("src/Testing/Attributes/UnitTest.php")++def test_a_runner_gets_only_its_own_always_run_tests_and_hears_of_the_rest() -> None:config = TestSelectionConfig(always_run=("tests/test_smoke.py", "apps/android/FooTest.kt", "e2e/")diff --git a/tests/unit/ingestion/test_traverser.py b/tests/unit/ingestion/test_traverser.pyindex 64ea6f467..a3f7dd909 100644--- a/tests/unit/ingestion/test_traverser.py+++ b/tests/unit/ingestion/test_traverser.py@@ -568,6 +568,53 @@ class TestFileTraverser:assert files["tests/test_demo.py"] is Trueassert files["tools/test_cli.py"] is True+ def test_a_test_named_php_class_outside_phpunit_testsuites_is_production(+ self, tmp_path: Path+ ) -> None:+ (tmp_path / "phpunit.xml.dist").write_text(+ '<phpunit><testsuites><testsuite name="Suite">'+ '<directory suffix="Test.php">./tests</directory>'+ '</testsuite></testsuites></phpunit>'+ )+ for rel in (+ "src/Testing/Attributes/UnitTest.php",+ "tests/RouterTest.php",+ "tools/HelperTest.php",+ ):+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)+ (tmp_path / rel).write_text("<?php\n")+ # A nested config governs its own directory.+ (tmp_path / "tools" / "phpunit.xml").write_text(+ '<phpunit><testsuites><testsuite name="Tools">'+ '<directory>tests</directory>'+ '</testsuite></testsuites></phpunit>'+ )+ files = {f.path: f.is_test for f in FileTraverser(tmp_path).traverse()}+ assert files["src/Testing/Attributes/UnitTest.php"] is False+ assert files["tests/RouterTest.php"] is True+ assert files["tools/HelperTest.php"] is False++ def test_malformed_primary_phpunit_config_does_not_fall_back_to_dist(+ self, tmp_path: Path+ ) -> None:+ (tmp_path / "phpunit.xml").write_text("not valid xml <")+ (tmp_path / "phpunit.xml.dist").write_text(+ '<phpunit><testsuites><testsuite name="Suite">'+ '<directory suffix="Test.php">./tests</directory>'+ '</testsuite></testsuites></phpunit>'+ )+ for rel in (+ "src/Testing/Attributes/UnitTest.php",+ "tests/RouterTest.php",+ ):+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)+ (tmp_path / rel).write_text("<?php\n")++ files = {f.path: f.is_test for f in FileTraverser(tmp_path).traverse()}+ # Fails closed: unreadable primary does not fall back, so test-named class stays True+ assert files["src/Testing/Attributes/UnitTest.php"] is True+ assert files["tests/RouterTest.php"] is True+def test_csharp_test_project_classifies_files_as_tests(self, tmp_path: Path) -> None:(tmp_path / "acceptance" / "Acme.Acceptance.csproj").parent.mkdir(parents=True, exist_ok=True)(tmp_path / "acceptance" / "Acme.Acceptance.csproj").write_text(diff --git a/tests/unit/test_phpunit_roots.py b/tests/unit/test_phpunit_roots.pynew file mode 100644index 000000000..7a41dc7f2--- /dev/null+++ b/tests/unit/test_phpunit_roots.py@@ -0,0 +1,282 @@+"""Where PHPUnit collects tests from, read from its XML config files."""++from __future__ import annotations++import pytest++from repowise.core.phpunit_roots import (+ PhpunitConfigUnreadableError,+ parse_phpunit_options,+ phpunit_options,+ read_phpunit_roots,+)++_LARAVEL_CONFIG = """+<phpunit>+ <testsuites>+ <testsuite name="Suite">+ <directory suffix="Test.php">./tests</directory>+ </testsuite>+ </testsuites>+</phpunit>+"""++_MULTI_SUITE_CONFIG = """+<phpunit>+ <testsuites>+ <testsuite name="Unit">+ <directory>tests/Unit</directory>+ </testsuite>+ <testsuite name="Feature">+ <directory>tests/Feature</directory>+ </testsuite>+ </testsuites>+</phpunit>+"""++_EXCLUDE_AND_FILE_CONFIG = """+<phpunit>+ <testsuites>+ <testsuite name="Suite">+ <directory suffix="Test.php">tests</directory>+ <file>custom/SpecialCase.php</file>+ <exclude>tests/Fixtures</exclude>+ </testsuite>+ </testsuites>+</phpunit>+"""+++ ("files", "path", "expected"),+ [+ ({"phpunit.xml.dist": _LARAVEL_CONFIG}, "tests/RouterTest.php", True),+ ({"phpunit.xml.dist": _LARAVEL_CONFIG}, "tests/Sub/DeepTest.php", True),+ ({"phpunit.xml.dist": _LARAVEL_CONFIG}, "src/Testing/Attributes/UnitTest.php", False),+ ({"phpunit.xml.dist": _LARAVEL_CONFIG}, "src/Console/Concerns/CreatesMatchingTest.php", False),+ # Default suffix is Test.php when omitted+ ({"phpunit.xml": _MULTI_SUITE_CONFIG}, "tests/Unit/UserTest.php", True),+ ({"phpunit.xml": _MULTI_SUITE_CONFIG}, "tests/Feature/LoginTest.php", True),+ ({"phpunit.xml": _MULTI_SUITE_CONFIG}, "src/Support/SomeTest.php", False),+ # Explicit file and exclude+ ({"phpunit.xml": _EXCLUDE_AND_FILE_CONFIG}, "custom/SpecialCase.php", True),+ ({"phpunit.xml": _EXCLUDE_AND_FILE_CONFIG}, "tests/RouterTest.php", True),+ ({"phpunit.xml": _EXCLUDE_AND_FILE_CONFIG}, "tests/Fixtures/MockTest.php", False),+ # No testsuites or malformed XML yields None (fail-closed)+ ({"phpunit.xml": "<phpunit></phpunit>"}, "src/UnitTest.php", None),+ ({"phpunit.xml": "<phpunit><testsuites></testsuites></phpunit>"}, "src/UnitTest.php", None),+ ({"phpunit.xml": "not valid xml <"}, "src/UnitTest.php", None),+ ({}, "src/UnitTest.php", None),+ ],+)+def test_collects_follows_the_root_config(files, path, expected) -> None:+ assert read_phpunit_roots(files.items()).collects(path) is expected+++def test_directory_with_custom_suffix_and_prefix() -> None:+ config = """+ <phpunit>+ <testsuites>+ <testsuite name="Custom">+ <directory suffix="Spec.php" prefix="test_">specs</directory>+ </testsuite>+ </testsuites>+ </phpunit>+ """+ roots = read_phpunit_roots([("phpunit.xml", config)])+ assert roots.collects("specs/test_authSpec.php") is True+ assert roots.collects("specs/authSpec.php") is False+ assert roots.collects("specs/test_authTest.php") is False+++def test_directory_level_exclude_child_tag() -> None:+ config = """+ <phpunit>+ <testsuites>+ <testsuite name="Suite">+ <directory suffix="Test.php">+ tests+ <exclude>tests/Helpers</exclude>+ </directory>+ </testsuite>+ </testsuites>+ </phpunit>+ """+ roots = read_phpunit_roots([("phpunit.xml", config)])+ assert roots.collects("tests/RouterTest.php") is True+ assert roots.collects("tests/Helpers/MockTest.php") is False+++def test_the_nearest_config_governs_its_own_directory() -> None:+ roots = read_phpunit_roots(+ [+ ("phpunit.xml.dist", _LARAVEL_CONFIG),+ (+ "packages/api/phpunit.xml",+ """+ <phpunit>+ <testsuites>+ <testsuite name="Api">+ <directory>tests</directory>+ </testsuite>+ </testsuites>+ </phpunit>+ """,+ ),+ ]+ )+ assert roots.collects("packages/api/tests/ApiTest.php") is True+ assert roots.collects("packages/api/src/ApiHelperTest.php") is False+ assert roots.collects("tests/RouterTest.php") is True+ assert roots.collects("src/Testing/Attributes/UnitTest.php") is False+++def test_a_file_an_ancestor_config_collects_stays_collected() -> None:+ """If an ancestor config collects a path, it stays collected."""+ roots = read_phpunit_roots(+ [+ ("phpunit.xml", _LARAVEL_CONFIG),+ (+ "tests/sub/phpunit.xml",+ """+ <phpunit>+ <testsuites>+ <testsuite name="Sub">+ <directory>other</directory>+ </testsuite>+ </testsuites>+ </phpunit>+ """,+ ),+ ]+ )+ # The root config collects tests/sub/RouterTest.php, so it remains collected+ assert roots.collects("tests/sub/RouterTest.php") is True+++def test_precedence_in_same_directory() -> None:+ """phpunit.xml takes precedence over phpunit.xml.dist."""+ roots = read_phpunit_roots(+ [+ ("phpunit.xml.dist", _LARAVEL_CONFIG),+ (+ "phpunit.xml",+ """+ <phpunit>+ <testsuites>+ <testsuite name="Overridden">+ <directory>custom_tests</directory>+ </testsuite>+ </testsuites>+ </phpunit>+ """,+ ),+ ]+ )+ assert roots.collects("custom_tests/CustomTest.php") is True+ assert roots.collects("tests/RouterTest.php") is False+++def test_a_config_that_does_not_parse_is_recorded_as_unknown() -> None:+ with pytest.raises(PhpunitConfigUnreadableError):+ parse_phpunit_options("<phpunit><testsuites>")+ assert phpunit_options("<phpunit><testsuites>") is None+ roots = read_phpunit_roots([("phpunit.xml", "<phpunit><testsuites>")])+ assert roots.collects("src/UnitTest.php") is None+++def test_malformed_primary_config_does_not_fall_back_to_dist() -> None:+ """A broken phpunit.xml does not fall back to phpunit.xml.dist (fail-closed)."""+ roots = read_phpunit_roots(+ [+ ("phpunit.xml", "malformed <xml"),+ ("phpunit.xml.dist", _LARAVEL_CONFIG),+ ]+ )+ assert roots.collects("src/UnitTest.php") is None+ assert roots.collects("tests/RouterTest.php") is None+++def test_no_testsuites_primary_config_does_not_fall_back_to_dist() -> None:+ """A phpunit.xml without testsuites does not fall back to phpunit.xml.dist."""+ roots = read_phpunit_roots(+ [+ ("phpunit.xml", "<phpunit></phpunit>"),+ ("phpunit.xml.dist", _LARAVEL_CONFIG),+ ]+ )+ assert roots.collects("src/UnitTest.php") is None+ assert roots.collects("tests/RouterTest.php") is None+++def test_valid_primary_config_ignores_malformed_dist() -> None:+ """A valid phpunit.xml wins precedence over a malformed phpunit.xml.dist."""+ roots = read_phpunit_roots(+ [+ ("phpunit.xml", _LARAVEL_CONFIG),+ ("phpunit.xml.dist", "malformed <xml"),+ ]+ )+ assert roots.collects("tests/RouterTest.php") is True+ assert roots.collects("src/UnitTest.php") is False+++def test_unreadable_primary_config_in_subdirectory_does_not_fall_back() -> None:+ roots = read_phpunit_roots(+ [+ ("phpunit.xml", _LARAVEL_CONFIG),+ ("packages/api/phpunit.xml", "malformed <xml"),+ ("packages/api/phpunit.xml.dist", _LARAVEL_CONFIG),+ ]+ )+ assert roots.collects("packages/api/src/ApiTest.php") is None+ assert roots.collects("tests/RouterTest.php") is True+++def test_precedence_dist_files_order() -> None:+ """phpunit.dist.xml takes precedence over phpunit.xml.dist when both are present."""+ roots = read_phpunit_roots(+ [+ ("phpunit.xml.dist", _LARAVEL_CONFIG),+ (+ "phpunit.dist.xml",+ """+ <phpunit>+ <testsuites>+ <testsuite name="DistXml">+ <directory>dist_tests</directory>+ </testsuite>+ </testsuites>+ </phpunit>+ """,+ ),+ ]+ )+ assert roots.collects("dist_tests/SomeTest.php") is True+ assert roots.collects("tests/RouterTest.php") is False+++def test_valid_dist_xml_ignores_malformed_xml_dist() -> None:+ """A valid phpunit.dist.xml wins precedence over a malformed phpunit.xml.dist."""+ roots = read_phpunit_roots(+ [+ ("phpunit.dist.xml", _LARAVEL_CONFIG),+ ("phpunit.xml.dist", "malformed <xml"),+ ]+ )+ assert roots.collects("tests/RouterTest.php") is True+ assert roots.collects("src/UnitTest.php") is False+++def test_malformed_dist_xml_does_not_fall_back_to_xml_dist() -> None:+ """A broken phpunit.dist.xml does not fall back to phpunit.xml.dist (fail-closed)."""+ roots = read_phpunit_roots(+ [+ ("phpunit.dist.xml", "malformed <xml"),+ ("phpunit.xml.dist", _LARAVEL_CONFIG),+ ]+ )+ assert roots.collects("tests/RouterTest.php") is None+ assert roots.collects("src/UnitTest.php") is None++diff --git a/tests/unit/test_test_paths.py b/tests/unit/test_test_paths.pyindex c0685d25a..c768fbcee 100644--- a/tests/unit/test_test_paths.py+++ b/tests/unit/test_test_paths.py@@ -11,6 +11,7 @@ from __future__ import annotationsimport pytestfrom repowise.core.dotnet_test_projects import read_dotnet_test_projects+from repowise.core.phpunit_roots import read_phpunit_rootsfrom repowise.core.pytest_roots import read_pytest_rootsfrom repowise.core.test_paths import (is_skippable_test_path,@@ -439,6 +440,49 @@ def test_pytest_config_overrules_a_test_shaped_python_name(path: str, expected:assert is_test_related_path(path)+_PHPUNIT_ROOTS = read_phpunit_roots(+ [+ (+ "phpunit.xml.dist",+ """+ <phpunit>+ <testsuites>+ <testsuite name="Suite">+ <directory suffix="Test.php">./tests</directory>+ </testsuite>+ </testsuites>+ </phpunit>+ """,+ )+ ]+)+++ ("path", "expected"),+ [+ # Suite tests keep their test classification+ ("tests/RouterTest.php", "test"),+ # Laravel framework production classes named like tests are demoted+ ("src/Testing/Attributes/UnitTest.php", ""),+ ("src/Illuminate/Console/Concerns/CreatesMatchingTest.php", ""),+ ("src/Illuminate/Support/Testing/Fakes/ChainedBatchTruthTest.php", ""),+ # Non-PHP files are untouched by PHPUnit config+ ("src/app/format.test.ts", "test"),+ ("pkg/server/handler_test.go", "test"),+ ],+)+def test_phpunit_config_overrules_a_test_shaped_php_name(path: str, expected: str) -> None:+ got = "test" if is_test_path(path, phpunit_roots=_PHPUNIT_ROOTS) else ""+ got = "support" if is_test_support_path(path, phpunit_roots=_PHPUNIT_ROOTS) else got+ assert got == expected+ # Without the config, test-shaped PHP filenames decide+ if path.endswith(".php"):+ assert is_test_related_path(path)++++@pytest.mark.parametrize(("test_path", "source", "siblings", "named"),[