mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-27 20:29:04 +01:00
Gate test reqs on the pytest import closure
Python tests CI was red: requirements-test.txt lacked hypothesis (phone_lease tests) and jeepney (game_rec, loaded by linux_configuration/tests). requirements-test-sync skipped tests/ and never looked at linux_configuration. Its new --testpaths mode walks the import closure of pyproject's testpaths, tests included, and skips TYPE_CHECKING imports. Pin both packages. Bug-class-check: pre-commit hook requirements-test-sync (check_requirements_sync.py --testpaths) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5e0d8727d6
commit
6cc5cb75c7
@ -334,15 +334,17 @@ repos:
|
||||
pass_filenames: false
|
||||
files: ^(python_pkg/.*\.py|requirements\.txt)$
|
||||
- id: requirements-test-sync
|
||||
name: requirements-test.txt covers all python_pkg imports
|
||||
name: requirements-test.txt covers every import the CI pytest run makes
|
||||
# python-tests.yml installs this SUBSET rather than the full list, so
|
||||
# it needs the same completeness guarantee. Without this hook a new
|
||||
# third-party import would pass locally and fail in CI with a bare
|
||||
# ModuleNotFoundError.
|
||||
entry: python3 meta/scripts/check_requirements_sync.py --package python_pkg --requirements meta/requirements-test.txt
|
||||
# it needs the same completeness guarantee. --testpaths walks the
|
||||
# import closure of pyproject's testpaths, tests included: a test-only
|
||||
# import (hypothesis) or a dependency of a linux_configuration script
|
||||
# the tests load (jeepney) otherwise passed here and failed CI with a
|
||||
# bare ModuleNotFoundError.
|
||||
entry: python3 meta/scripts/check_requirements_sync.py --testpaths python_pkg linux_configuration/tests --requirements meta/requirements-test.txt
|
||||
language: system
|
||||
pass_filenames: false
|
||||
files: ^(python_pkg/.*\.py|meta/requirements-test\.txt)$
|
||||
files: ^(python_pkg/.*|linux_configuration/.*|meta/scripts/.*)\.py$|^meta/requirements-test\.txt$
|
||||
- id: session-autopsy-hook-mutations
|
||||
name: session_autopsy hook tests are non-vacuous (mutation)
|
||||
entry: python3 meta/scripts/mutate_session_autopsy_hooks.py
|
||||
|
||||
@ -0,0 +1,36 @@
|
||||
{
|
||||
"intent": "Fix the red Python tests CI job (ModuleNotFoundError: hypothesis, jeepney) and block the bug class: requirements-test.txt missing an import the CI pytest run makes.",
|
||||
"scope": [
|
||||
"meta/requirements-test.txt and meta/requirements.txt: pin hypothesis==6.170.17 and jeepney==0.9.0 (newest stable)",
|
||||
"meta/scripts/check_requirements_sync.py: new --testpaths mode; meta/scripts/_requirements_closure.py walks the import closure",
|
||||
".pre-commit-config.yaml: requirements-test-sync hook uses --testpaths and triggers on linux_configuration and meta/scripts .py files",
|
||||
"Non-goal: the --package mode used by requirements-sync is unchanged"
|
||||
],
|
||||
"changes": [
|
||||
"The old check skipped tests/ directories and never looked at linux_configuration, so a test-only import (hypothesis in phone_lease tests) and a dependency of a script that linux_configuration/tests loads (jeepney via game_rec_dbus) passed locally and failed CI",
|
||||
"--testpaths starts from every .py under the pytest testpaths, follows bare first-party imports into python_pkg, linux_configuration and meta/scripts, skips if TYPE_CHECKING blocks, and reports non-stdlib names missing from the requirements file"
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "python3 meta/scripts/check_requirements_sync.py --testpaths python_pkg linux_configuration/tests --requirements meta/requirements-test.txt",
|
||||
"result": "pass",
|
||||
"evidence": "before the pins: exit 1 listing exactly hypothesis and jeepney (the two CI ImportErrors); after: exit 0"
|
||||
},
|
||||
{
|
||||
"command": "check_requirements_sync.py --root ~/data/claude-scratch/reqsync --testpaths pkg lc/tests --requirements req.txt",
|
||||
"result": "pass",
|
||||
"evidence": "scratch tree: flags test-only import hyp and lazydep imported by a sibling helper; skips a TYPE_CHECKING import"
|
||||
},
|
||||
{
|
||||
"command": "check_requirements_sync.py --package python_pkg (with and without --requirements meta/requirements-test.txt)",
|
||||
"result": "pass",
|
||||
"evidence": "exit 0 both, old mode unchanged"
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"A lazy import inside a function of a linux_configuration script counts as required even if no test reaches that function; the fix is to pin it, which costs CI install time only"
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; the hook returns to the --package python_pkg mode"
|
||||
]
|
||||
}
|
||||
@ -27,6 +27,8 @@ coverage==7.17.5
|
||||
defusedxml==0.7.1
|
||||
fastmcp==4.2.6
|
||||
genanki==0.13.1
|
||||
hypothesis==6.170.17
|
||||
jeepney==0.9.0
|
||||
kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
|
||||
markdownify==1.2.4
|
||||
numpy==2.5.5
|
||||
|
||||
@ -43,6 +43,7 @@ howlongtobeatpy==1.0.24
|
||||
hypothesis==6.170.17
|
||||
importlib-metadata==10.2.0
|
||||
interrogate==1.7.0
|
||||
jeepney==0.9.0
|
||||
kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
|
||||
# isort is deliberately not pinned: nothing here imports it (ruff's isort
|
||||
# rules replaced it) and pylint constrains it (`isort!=5.13,<10,>=5` as of
|
||||
|
||||
106
meta/scripts/_requirements_closure.py
Executable file
106
meta/scripts/_requirements_closure.py
Executable file
@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Find every module the CI pytest run imports, for check_requirements_sync.
|
||||
|
||||
python-tests.yml installs only ``meta/requirements-test.txt`` and runs pytest
|
||||
over the ``testpaths`` in ``meta/pyproject.toml``. The package-wide check
|
||||
skips ``tests/`` directories and never looks at ``linux_configuration``, so a
|
||||
test-only import (``hypothesis``) or a dependency of a script that
|
||||
``linux_configuration/tests`` loads (``jeepney`` via ``game_rec_dbus``) passed
|
||||
locally and failed CI with ``ModuleNotFoundError``.
|
||||
|
||||
This module walks the import closure instead: it starts from every ``.py``
|
||||
file under the test paths (tests included) and follows bare first-party
|
||||
imports into the repo's own modules, so only code the suite can actually
|
||||
import is held to the test requirements.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
from collections import deque
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
# Directories whose modules the suite can import by bare name: the testpaths'
|
||||
# top-level trees plus meta/scripts (conftest puts it on sys.path).
|
||||
_EXTRA_SEARCH_DIRS = ("meta/scripts",)
|
||||
|
||||
|
||||
def _is_type_checking(node: ast.AST) -> bool:
|
||||
"""Tell whether ``node`` is an ``if TYPE_CHECKING:`` block (never run)."""
|
||||
if not isinstance(node, ast.If):
|
||||
return False
|
||||
test = node.test
|
||||
name = test.attr if isinstance(test, ast.Attribute) else getattr(test, "id", "")
|
||||
return name == "TYPE_CHECKING"
|
||||
|
||||
|
||||
def _imports(module: Path) -> set[str]:
|
||||
"""Return the top-level names one file imports at runtime.
|
||||
|
||||
Absolute imports only; imports under ``if TYPE_CHECKING:`` are skipped,
|
||||
because pytest never executes them.
|
||||
"""
|
||||
tree = ast.parse(module.read_text(encoding="utf-8"), filename=str(module))
|
||||
names: set[str] = set()
|
||||
stack: list[ast.AST] = [tree]
|
||||
while stack:
|
||||
node = stack.pop()
|
||||
if isinstance(node, ast.Import):
|
||||
names.update(alias.name.split(".", 1)[0] for alias in node.names)
|
||||
elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
|
||||
names.add(node.module.split(".", 1)[0])
|
||||
stack.extend(
|
||||
child
|
||||
for child in ast.iter_child_nodes(node)
|
||||
if not _is_type_checking(child)
|
||||
)
|
||||
return names
|
||||
|
||||
|
||||
def _local_index(search_dirs: list[Path]) -> dict[str, list[Path]]:
|
||||
"""Map each importable first-party name to the files that define it.
|
||||
|
||||
A ``name.py`` file defines ``name``; a directory with ``__init__.py``
|
||||
defines its own name with every file below it. A name defined twice maps
|
||||
to both, because which one wins depends on sys.path order.
|
||||
"""
|
||||
index: dict[str, list[Path]] = {}
|
||||
for base in search_dirs:
|
||||
for path in sorted(base.rglob("*.py")):
|
||||
index.setdefault(path.stem, []).append(path)
|
||||
if path.name == "__init__.py":
|
||||
index.setdefault(path.parent.name, []).extend(
|
||||
sorted(path.parent.rglob("*.py")),
|
||||
)
|
||||
index.pop("__init__", None)
|
||||
return index
|
||||
|
||||
|
||||
def import_closure(root: Path, testpaths: list[str]) -> set[str]:
|
||||
"""Return the non-stdlib, non-local names the test paths can import.
|
||||
|
||||
Every file under each test path is a start point. A bare import that
|
||||
names a first-party module pulls that module's files into the walk;
|
||||
anything else outside the standard library is external.
|
||||
"""
|
||||
starts = [root / path for path in testpaths]
|
||||
tops = {root / Path(path).parts[0] for path in testpaths}
|
||||
search = sorted(tops | {root / extra for extra in _EXTRA_SEARCH_DIRS})
|
||||
index = _local_index([path for path in search if path.is_dir()])
|
||||
queue = deque(path for start in starts for path in sorted(start.rglob("*.py")))
|
||||
seen: set[Path] = set()
|
||||
local = {top.name for top in tops}
|
||||
external: set[str] = set()
|
||||
while queue:
|
||||
module = queue.popleft()
|
||||
if module in seen:
|
||||
continue
|
||||
seen.add(module)
|
||||
for name in _imports(module):
|
||||
if name in index:
|
||||
local.add(name)
|
||||
queue.extend(index[name])
|
||||
elif name not in local and name not in sys.stdlib_module_names:
|
||||
external.add(name)
|
||||
return external
|
||||
@ -30,6 +30,8 @@ from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
|
||||
from _requirements_closure import import_closure
|
||||
|
||||
# Import-name -> distribution-name overrides for the rare cases where PEP 503
|
||||
# normalisation (lowercase, runs of -/_/. collapsed to '-') is not enough.
|
||||
# Most packages import under their normalised dist name (crdt_sync ->
|
||||
@ -185,6 +187,11 @@ def _parse_args(argv: list[str] | None) -> argparse.Namespace:
|
||||
default="requirements.txt",
|
||||
help="Path to requirements.txt (default: %(default)s).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--testpaths",
|
||||
nargs="+",
|
||||
help="Check the import closure of these pytest paths, tests included.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--root",
|
||||
default=".",
|
||||
@ -208,20 +215,28 @@ def main(argv: list[str] | None = None) -> int:
|
||||
"""Entry point: exit non-zero (with a report) when deps are missing."""
|
||||
args = _parse_args(argv)
|
||||
root = Path(args.root).resolve()
|
||||
package = args.package or _detect_package(root)
|
||||
package_dir = root / package
|
||||
requirements = root / args.requirements
|
||||
|
||||
if not package_dir.is_dir():
|
||||
sys.exit(f"Package directory not found: {package_dir}")
|
||||
if not requirements.is_file():
|
||||
sys.exit(f"Requirements file not found: {requirements}")
|
||||
if args.testpaths:
|
||||
external = import_closure(root, args.testpaths) - _FOREIGN_RUNTIME_IMPORTS
|
||||
declared = _requirement_names(requirements)
|
||||
missing = sorted(n for n in external if _distribution_for(n) not in declared)
|
||||
return _report(" ".join(args.testpaths), requirements, missing)
|
||||
package = args.package or _detect_package(root)
|
||||
package_dir = root / package
|
||||
if not package_dir.is_dir():
|
||||
sys.exit(f"Package directory not found: {package_dir}")
|
||||
|
||||
missing = check(package, package_dir, requirements)
|
||||
return _report(package, requirements, check(package, package_dir, requirements))
|
||||
|
||||
|
||||
def _report(scope: str, requirements: Path, missing: list[str]) -> int:
|
||||
"""Print the missing imports for ``scope``; return the exit code."""
|
||||
if missing:
|
||||
joined = "\n - ".join(missing)
|
||||
sys.stderr.write(
|
||||
f"{package}: these third-party imports are not declared in "
|
||||
f"{scope}: these third-party imports are not declared in "
|
||||
f"{requirements.name} (CI installs only that file, so they will "
|
||||
f"fail with ModuleNotFoundError):\n - {joined}\n",
|
||||
)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user