Files
goodwe-addon/.gitea/ci/affected_tests.py
T
glenn schrooyenandClaude Opus 5.5 22ef89bf10
checks / unit (pull_request) Successful in 20m22s
infra-pin / fresh (pull_request) Successful in 1s
CI-18 review: --head needs B checked out; guard the CI image against CI_ONLY
The selector reads the graph, and run-affected.sh runs the tests, from the
working tree, so a --base/--head range is only right with the head checked
out. The CI image is built from the merged tree, so an ENV CI_ONLY in its
Dockerfile would make the gate partial; test_affected_tests.py now fails on it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 23:29:34 +01:00

404 lines
16 KiB
Python

#!/usr/bin/env python3
"""CI-18: which test_*.py files does a diff affect? For DEV and REVIEW rounds only.
python3 .gitea/ci/affected_tests.py # merge-base(origin/release/1.0) .. working tree
python3 .gitea/ci/affected_tests.py --base A --head B # a committed range (the graph is read from the working tree: check out B)
python3 .gitea/ci/affected_tests.py --files f1 f2 # explicit changed paths (no git)
... --names # only the file names, one per line
It prints what it chose and why, then the verdict line `SELECT n of N` or
`SELECT ALL`. It never replaces the merge gate: the required context
`checks / unit (pull_request)` runs every test_*.py (checks.yml, run-tests.sh).
WHAT IS SELECTED (the union of):
1. every test file that reaches a changed file through the static graph of
the tree: imports (absolute, relative, `from pkg import mod`), plus any
STRING in the source that names a file (`"predeploy_check.py"`,
`"tools/x.py"`, a dotted `app.mqtt` as in `-m` or import_module). Tests
launch tools by path and read sources as text, so imports alone miss them.
Transitive: a module that imports a changed module carries its tests.
2. every changed test file;
3. the ALWAYS-RUN SAFETY SET below.
A test that walks a directory (`HERE / "app"`, `glob("test_*.py")`) names
that directory or a pattern in a string, so it depends on every file there.
FAILS OPEN. Anything it cannot map selects ALL: a changed file that is not
.py (config.yaml, translations, static, Dockerfile, run-tests.sh, docs, ...),
a deleted or renamed file, a .py nothing references, a file that does not
parse, a base ref that does not exist, a diff it cannot read. Doubt is never "skip". (An EMPTY diff selects the
safety set only: nothing changed.)
OVER-APPROXIMATION IS THE DESIGN. A false edge runs one more file; a missing
edge would skip one. The scan favours false edges (strings, not comments;
suffix matching of module names; any directory name a test spells out).
"""
import argparse
import ast
import fnmatch
import os
import re
import subprocess
import sys
# --- the always-run safety set -------------------------------------------------
# Name and reason, one each. They run on every selection, whatever changed.
# Add a file only with a reason and say it here.
SAFETY_SET = {
"test_bytecode.py": "grades the mutation harness itself; a stale-bytecode "
"survivor makes every other 'it went red' claim void",
"test_ci_gate.py": "grades the gate's checkout/guard shell; cheap, and it "
"is the file that says what a green means",
"test_split_patches.py": "tripwire that tests patch a Controller global "
"where it is read; spans app/main.py and ctl_*.py",
"test_defaults_pin.py": "pins every schema default against config.yaml "
"and scans all modules for literal fallbacks",
"test_docs.py": "operator docs must say what the code does (validator, "
"entity ids)",
}
SKIP_DIRS = {".git", "__pycache__", "node_modules"}
class Fail(Exception):
"""The selector cannot answer; the caller selects ALL."""
def repo_root(start):
p = subprocess.run(["git", "-C", start, "rev-parse", "--show-toplevel"],
capture_output=True, text=True)
if p.returncode != 0:
raise Fail("not inside a git work tree")
return p.stdout.strip()
def all_py(root):
out = []
for d, dirs, files in os.walk(root):
dirs[:] = [x for x in dirs if x not in SKIP_DIRS]
for f in files:
if f.endswith(".py"):
out.append(os.path.relpath(os.path.join(d, f), root))
return sorted(out)
def module_names(rel):
"""Every dotted suffix a file can be imported as: a/b/c.py -> c, b.c, a.b.c."""
parts = rel[:-3].split(os.sep)
if parts[-1] == "__init__":
parts = parts[:-1]
return {".".join(parts[i:]) for i in range(len(parts))} if parts else set()
class Index:
def __init__(self, files):
self.files = files
self.by_mod = {}
self.by_base = {}
self.dirs = {}
# directories that hold test files (the project root): naming one is
# naming the whole tree, which says nothing about a dependency
self.test_dirs = {os.path.basename(os.path.dirname(f))
for f in files
if os.path.basename(f).startswith("test_")}
for f in files:
for m in module_names(f):
self.by_mod.setdefault(m, set()).add(f)
self.by_base.setdefault(os.path.basename(f), set()).add(f)
for comp in os.path.dirname(f).split(os.sep):
if comp:
self.dirs.setdefault(comp, set()).add(f)
def parents(self, rel):
"""Package __init__ files an import of `rel` also runs."""
out = set()
parts = rel.split(os.sep)[:-1]
while parts:
init = os.sep.join(parts + ["__init__.py"])
if init in self.files:
out.add(init)
parts.pop()
return out
def docstring_nodes(tree):
ids = set()
for n in ast.walk(tree):
if isinstance(n, (ast.Module, ast.ClassDef, ast.FunctionDef,
ast.AsyncFunctionDef)) and n.body:
b = n.body[0]
if isinstance(b, ast.Expr) and isinstance(b.value, ast.Constant) \
and isinstance(b.value.value, str):
ids.add(id(b.value))
return ids
# Calls that list a directory: a file making one depends on what the
# directories it names contain (`ast.walk` is not one, and is excluded).
ENUM_CALLS = {"glob", "iglob", "rglob", "listdir", "scandir", "iterdir",
"walk", "copytree"}
# Edge reasons that mean "executes the other file" (they propagate through a
# test file); every other reason means "reads it as data or text".
IMPORT_KINDS = ("import ", "from ", "package of", "dynamic import")
DOTTED = re.compile(r"[A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)+")
IDENT = re.compile(r"^[A-Za-z_]\w*$")
def edges_of(rel, root, idx):
"""{file `rel` depends on: first reason}."""
path = os.path.join(root, rel)
try:
with open(path, encoding="utf-8") as fh:
src = fh.read()
tree = ast.parse(src, filename=rel)
except (OSError, SyntaxError, UnicodeDecodeError, ValueError) as e:
raise Fail("cannot parse %s: %s" % (rel, e))
deps = {}
def add(target, why):
if target != rel:
deps.setdefault(target, why)
def add_mod(name, why):
hit = idx.by_mod.get(name)
if hit:
for t in hit:
add(t, why)
for p in idx.parents(t):
add(p, "package of " + t)
here = os.path.dirname(rel).split(os.sep) if os.path.dirname(rel) else []
dynamic = False
enumerates = False
consts = []
skip = docstring_nodes(tree)
for n in ast.walk(tree):
if isinstance(n, ast.Import):
for a in n.names:
add_mod(a.name, "import " + a.name)
elif isinstance(n, ast.ImportFrom):
base = n.module or ""
if n.level:
up = here[:len(here) - (n.level - 1)] if n.level > 1 else here
base = ".".join(up + ([base] if base else []))
if base:
add_mod(base, "from %s import" % base)
for a in n.names:
if a.name != "*":
add_mod((base + "." if base else "") + a.name,
"from %s import %s" % (base, a.name))
elif isinstance(n, ast.Call):
fn = n.func
name = fn.attr if isinstance(fn, ast.Attribute) else \
fn.id if isinstance(fn, ast.Name) else ""
obj = fn.value.id if isinstance(fn, ast.Attribute) and \
isinstance(fn.value, ast.Name) else ""
if name in ("import_module", "__import__", "run_module",
"spec_from_file_location", "run_path"):
dynamic = True
if name in ENUM_CALLS and obj != "ast":
enumerates = True
elif isinstance(n, ast.Constant) and isinstance(n.value, str) \
and id(n) not in skip and len(n.value) <= 4000:
consts.append(n.value)
named_dirs = set()
for s in consts:
for m in re.finditer(r"[\w./-]*\.py\b", s):
base = os.path.basename(m.group(0))
for t in idx.by_base.get(base, ()):
add(t, "names file %r" % base)
for tok in DOTTED.findall(s):
add_mod(tok, "names module %r" % tok)
# `app.mqtt.Thing` or `tools.x.main`: shorten from the right
parts = tok.split(".")
for i in range(len(parts) - 1, 0, -1):
add_mod(".".join(parts[:i]), "names module %r" % tok)
if dynamic and IDENT.match(s):
add_mod(s, "dynamic import of %r" % s)
for piece in set(re.split(r"[/\\]", s)) if ("/" in s or "\\" in s) \
else {s}:
if piece in idx.dirs and piece not in idx.test_dirs:
named_dirs.add(piece)
# A file that enumerates directories depends on everything in the ones it
# names, and on what a glob pattern it spells matches in its own directory.
if enumerates:
for d in named_dirs:
for t in idx.dirs[d]:
add(t, "enumerates directory %r" % d)
for s in consts:
if "*" in s and s.endswith(".py"):
pat = os.path.basename(s)
# `test_*.py` globs the tests next to this file; any other
# pattern globs the directories this file names, and only when
# it names none, its own directory.
own = pat.startswith("test_") or not named_dirs
for t in idx.files:
inside = (own and os.path.dirname(t)
== os.path.dirname(rel)) or \
any(c in named_dirs for c in os.path.dirname(t)
.split(os.sep))
if inside and fnmatch.fnmatch(os.path.basename(t), pat):
add(t, "pattern %r" % s)
return deps
def build(root, files):
idx = Index(set(files))
return {f: edges_of(f, root, idx) for f in files}
def is_test(rel):
b = os.path.basename(rel)
return os.path.dirname(rel) == "goodwe_controller" and \
b.startswith("test_") and b.endswith(".py")
def git_changes(root, base, head):
"""[(status, path)] for base..head, or merge-base..working tree."""
def run(*a):
p = subprocess.run(["git", "-C", root] + list(a),
capture_output=True, text=True)
if p.returncode != 0:
raise Fail("git %s failed: %s" % (" ".join(a), p.stderr.strip()))
return p.stdout
if head:
mb = run("merge-base", base, head).strip()
out = run("diff", "--name-status", "--no-renames", "-z", mb, head)
else:
mb = run("merge-base", base, "HEAD").strip()
out = run("diff", "--name-status", "--no-renames", "-z", mb)
toks = out.split("\0")
ch = []
i = 0
while i + 1 < len(toks):
ch.append((toks[i][:1], toks[i + 1]))
i += 2
if not head:
for u in run("ls-files", "-o", "--exclude-standard", "-z").split("\0"):
if u:
ch.append(("A", u))
return ch
def select(root, changes):
"""-> (names, reasons, all_reason). all_reason is not None when ALL."""
files = all_py(root)
tests = sorted(f for f in files if is_test(f))
if not tests:
return None, None, "no test_*.py found under the tree"
reasons = {}
def why(t, r):
reasons.setdefault(t, []).append(r)
if not changes:
for t in SAFETY_SET:
if "goodwe_controller/" + t in tests:
why("goodwe_controller/" + t, "always-run safety set (empty "
"diff): " + SAFETY_SET[t])
return sorted(reasons), reasons, None
changed_py = []
for st, p in changes:
if st not in ("M", "A"):
return None, None, "%s %s (deleted/renamed/type change: the old " \
"importers are not in this tree)" % (st, p)
if not p.endswith(".py"):
return None, None, "changed file %s is not Python (nothing here " \
"can say which tests read it)" % p
if not os.path.exists(os.path.join(root, p)):
return None, None, "changed file %s is not in the work tree" % p
changed_py.append(p)
try:
graph = build(root, files)
except Fail as e:
return None, None, str(e)
rev = {}
for f, deps in graph.items():
for d, r in deps.items():
rev.setdefault(d, {})[f] = r
for p in changed_py:
if is_test(p):
why(p, "changed test file")
continue
# reverse BFS from each changed file
for p in changed_py:
seen = {p: None}
expanded = {p}
queue = [p]
while queue:
cur = queue.pop(0)
for f, r in rev.get(cur, {}).items():
if f not in seen:
seen[f] = (cur, r)
# A test that merely READS another file (names it, globs it)
# is affected by it, but is not a dependency of a third test:
# test_inverter reading every test_*.py as text must not make
# everything that imports a module "affected by test_inverter".
# Only an import carries the change on through a test file.
if f not in expanded and (not is_test(f)
or r.startswith(IMPORT_KINDS)):
expanded.add(f)
queue.append(f)
hit = [f for f in seen if is_test(f) and f != p]
if not hit and not is_test(p):
return None, None, "changed %s is referenced by no test, " \
"directly or through another file" % p
for t in hit:
chain, cur = [], t
while seen[cur]:
nxt, r = seen[cur]
chain.append("%s (%s)" % (os.path.basename(nxt), r))
cur = nxt
why(t, "reaches changed %s via %s" % (p, " <- ".join(
reversed(chain)) if len(chain) > 1 else chain[0]))
for t, r in SAFETY_SET.items():
if "goodwe_controller/" + t in tests:
why("goodwe_controller/" + t, "always-run safety set: " + r)
names = sorted(reasons)
return names, reasons, None
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--base", default="origin/release/1.0")
ap.add_argument("--head", default=None,
help="a ref; default: the working tree")
ap.add_argument("--files", nargs="*", help="changed paths, repo-relative")
ap.add_argument("--root", default=None)
ap.add_argument("--names", action="store_true",
help="print only the chosen file names (one per line), "
"or every test name on SELECT ALL")
a = ap.parse_args(argv)
try:
root = a.root or repo_root(os.getcwd())
changes = [("M", f) for f in a.files] if a.files is not None \
else git_changes(root, a.base, a.head)
names, reasons, all_reason = select(root, changes)
except Fail as e:
names, reasons, all_reason = None, None, str(e)
root = a.root or os.getcwd()
tests = sorted(f for f in all_py(root) if is_test(f)) \
if os.path.isdir(root) else []
if all_reason is not None:
if a.names:
print("\n".join(os.path.basename(t) for t in tests))
else:
print("SELECT ALL - %s" % all_reason)
print("SELECT ALL (%d of %d)" % (len(tests), len(tests)))
return 0
if a.names:
print("\n".join(os.path.basename(t) for t in names))
return 0
print("changed: %s" % (", ".join(p for _, p in changes) or "(nothing)"))
for t in names:
for r in reasons[t][:3]:
print(" %-34s %s" % (os.path.basename(t), r))
print("SELECT %d of %d" % (len(names), len(tests)))
return 0
if __name__ == "__main__":
sys.exit(main())