"""Import-aware Python test discovery and selection.""" from __future__ import annotations import ast from pathlib import Path from typing import Dict, List, Sequence, Set from lingologos_python.ast_graph import ( discover_python_files, extract_python_graph, module_names_for_file, ) def is_test_file(rel_posix: str) -> bool: """Return True when a relative path follows Python test file naming conventions.""" name = Path(rel_posix).name return name.startswith("test_") and name.endswith(".py") or name.endswith("_test.py") def is_conftest(rel_posix: str) -> bool: """Return True when a relative path is a pytest conftest module.""" return Path(rel_posix).name == "conftest.py" def discover_test_files(workspace: Path) -> List[str]: """Return sorted POSIX relative paths of all test files in workspace.""" all_py = discover_python_files(workspace) tests_first = [p for p in all_py if is_test_file(p) and (p.startswith("tests/") or "/tests/" in p)] others = [p for p in all_py if is_test_file(p) and p not in tests_first] return tests_first + others def _naming_candidates(rel_posix: str) -> List[str]: parts = [p for p in rel_posix.replace("\\", "/").split("/") if p] if not parts: return [] stem = Path(parts[-1]).stem test_names = (f"test_{stem}.py", f"{stem}_test.py") candidates: List[str] = [] for tname in test_names: if len(parts) > 1: candidates.append("/".join([*parts[:-1], tname])) else: candidates.append(tname) candidates.append(f"tests/{tname}") candidates.append(f"tests/{stem}/{tname}") if len(parts) > 2 and parts[0] in ("src", "lib", "python"): sub_dir = "/".join(parts[1:-1]) candidates.append(f"tests/{sub_dir}/{tname}") return candidates def _imported_names_in_file(path: Path) -> Set[str]: try: source = path.read_text(encoding="utf-8", errors="replace") tree = ast.parse(source, filename=str(path)) except (OSError, SyntaxError): return set() imported: Set[str] = set() for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: imported.add(alias.name) imported.add(alias.name.split(".")[-1]) elif isinstance(node, ast.ImportFrom): if node.module: imported.add(node.module) imported.add(node.module.split(".")[-1]) for alias in node.names: if alias.name != "*": imported.add(alias.name) if node.module: imported.add(f"{node.module}.{alias.name}") return imported def select_python_tests(workspace: Path, changed_files: Sequence[str]) -> List[str]: """Select test file paths relevant to changed_files using naming and AST imports.""" root = workspace.resolve() all_tests = discover_test_files(root) if not all_tests: return [] chosen: List[str] = [] test_set = set(all_tests) # 1. Direct test file edits and naming conventions for raw in changed_files: rel = raw.replace("\\", "/") if is_conftest(rel): # A conftest carries fixtures and hooks that no import edge shows: # every test at or below its folder runs through it, so a change to # it selects that whole folder of tests rather than nothing. scope = rel[: rel.rfind("/")] if "/" in rel else "" for test_rel in all_tests: if (not scope or test_rel.startswith(scope + "/")) and test_rel not in chosen: chosen.append(test_rel) continue if rel in test_set and rel not in chosen: chosen.append(rel) continue for candidate in _naming_candidates(rel): if candidate in test_set and candidate not in chosen: chosen.append(candidate) # 2. Transitive reverse-dependency closure across discovered Python files all_py = discover_python_files(root) _, graph_edges = extract_python_graph(root, all_py) dependents_of: Dict[str, Set[str]] = {} for src, dst in graph_edges: src_file = src.split("::", 1)[0] dst_file = dst.split("::", 1)[0] if src_file != dst_file: dependents_of.setdefault(dst_file, set()).add(src_file) impacted: Set[str] = {raw.replace("\\", "/") for raw in changed_files if raw} queue: List[str] = list(impacted) while queue: current = queue.pop(0) for dep in sorted(dependents_of.get(current, ())): if dep not in impacted: impacted.add(dep) queue.append(dep) for test_rel in all_tests: if test_rel in impacted and test_rel not in chosen: chosen.append(test_rel) # 3. Fallback direct AST token scan for any remaining test files target_tokens: Dict[str, Set[str]] = {} for rel in impacted: tokens = set(module_names_for_file(rel)) stem = Path(rel).stem if stem and stem != "__init__": tokens.add(stem) target_tokens[rel] = tokens combined_tokens: Set[str] = set() for tok_set in target_tokens.values(): combined_tokens.update(tok_set) if combined_tokens: for test_rel in all_tests: if test_rel in chosen: continue test_path = root / Path(*test_rel.split("/")) imported = _imported_names_in_file(test_path) if imported & combined_tokens: chosen.append(test_rel) return chosen