Coverage for src/governed_harness/friction/affected.py: 91%

61 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-12 16:06 +0000

1"""The Python tests a ChangeSet affects (#58, item 5), found from the paths and the imports. 

2 

3A test file is affected when the ChangeSet changes it, when its name names a changed module 

4(``test_pricing.py`` for ``pricing.py``) or when it imports a changed module (``import pricing``, 

5``from sample.pricing import ...``, ``from sample import pricing``). Nothing is executed; the 

6selection only orders the work: the affected tests run first so a failing attempt stops early, 

7and the full suite still runs before the gate. Other technologies have no selection (their 

8full suite runs as before).""" 

9 

10from __future__ import annotations 

11 

12import re 

13from collections.abc import Iterable 

14from pathlib import Path, PurePosixPath 

15 

16from governed_harness.checks.model import is_test_path 

17from governed_harness.validators.traceability import discover_test_files 

18 

19MAX_TEST_FILE_BYTES = 1_000_000 

20MAX_AFFECTED_TESTS = 200 

21_SOURCE_ROOTS = ("src/", "lib/") 

22 

23 

24def _module_names(path: str) -> set[str]: 

25 """Dotted names a changed Python file can be imported as (with and without the source 

26 root), and its last component.""" 

27 pure = PurePosixPath(path) 

28 parts = list(pure.with_suffix("").parts) 

29 if parts and parts[-1] == "__init__": 29 ↛ 30line 29 didn't jump to line 30 because the condition on line 29 was never true

30 parts = parts[:-1] 

31 if not parts: 31 ↛ 32line 31 didn't jump to line 32 because the condition on line 31 was never true

32 return set() 

33 names = {".".join(parts), parts[-1]} 

34 for root in _SOURCE_ROOTS: 

35 prefix = PurePosixPath(root).parts 

36 if tuple(parts[: len(prefix)]) == prefix and len(parts) > len(prefix): 

37 names.add(".".join(parts[len(prefix) :])) 

38 return {name for name in names if name} 

39 

40 

41def _imports(text: str, names: set[str]) -> bool: 

42 for name in names: 

43 dotted = re.escape(name) 

44 head, _, last = name.rpartition(".") 

45 patterns = [ 

46 rf"^\s*import\s+{dotted}\b", 

47 rf"^\s*from\s+{dotted}(\.\w+)*\s+import\b", 

48 ] 

49 if head: 

50 patterns.append(rf"^\s*from\s+{re.escape(head)}\s+import\s+[^#\n]*\b{last}\b") 

51 if any(re.search(pattern, text, re.MULTILINE) for pattern in patterns): 

52 return True 

53 return False 

54 

55 

56def affected_python_tests(workspace: Path, changed: Iterable[str]) -> list[str]: 

57 """Workspace-relative test files affected by the ``changed`` paths, sorted (at most 

58 ``MAX_AFFECTED_TESTS``). Empty when no Python file changed.""" 

59 changed_paths = [item.replace("\\", "/") for item in changed] 

60 python = [item for item in changed_paths if item.endswith(".py")] 

61 if not python: 

62 return [] 

63 selected: set[str] = { 

64 item 

65 for item in python 

66 if is_test_path(item) 

67 and PurePosixPath(item).name.startswith("test") 

68 and (workspace / item).is_file() 

69 } 

70 sources = [item for item in python if not is_test_path(item)] 

71 names: set[str] = set() 

72 stems: set[str] = set() 

73 for item in sources: 

74 names |= _module_names(item) 

75 stems.add(PurePosixPath(item).stem) 

76 if names: 

77 selected.update( 

78 relative 

79 for relative in discover_test_files(workspace, ("python",)) 

80 if relative not in selected 

81 and relative.endswith(".py") 

82 and _reaches(workspace, relative, names, stems) 

83 ) 

84 return sorted(selected)[:MAX_AFFECTED_TESTS] 

85 

86 

87def _reaches(workspace: Path, relative: str, names: set[str], stems: set[str]) -> bool: 

88 """A test file is affected when it is named after a changed module (``test_x.py``, 

89 ``x_test.py``) or imports one.""" 

90 stem = PurePosixPath(relative).stem 

91 if stem.removeprefix("test_") in stems or stem.removesuffix("_test") in stems: 

92 return True 

93 text = _test_text(workspace / relative) 

94 return text is not None and _imports(text, names) 

95 

96 

97def _test_text(path: Path) -> str | None: 

98 """The text of a test file, ``None`` when it is too large or cannot be read.""" 

99 try: 

100 if path.stat().st_size > MAX_TEST_FILE_BYTES: 100 ↛ 101line 100 didn't jump to line 101 because the condition on line 100 was never true

101 return None 

102 return path.read_text(encoding="utf-8", errors="replace") 

103 except OSError: 

104 return None 

105 

106 

107__all__ = ["affected_python_tests"]