test(s31): close 1 review MAJOR — guards cover the store functions and dynamic imports

This commit is contained in:
Kjell Tore Guttormsen 2026-07-25 12:56:44 +02:00
commit 5481781ca5
2 changed files with 51 additions and 0 deletions

View file

@ -273,6 +273,20 @@ def test_link_in_index_success_preserves_existing_bytes_and_order(tmp_path) -> N
assert result == original + "- [Promotert](promoted-verdict-x.md)\n"
def _dynamic_import_targets(node: ast.Call) -> list[str]:
"""Name any dynamic-import call: ``__import__(...)`` or ``<anything>.import_module(...)``.
Shared by the MAF-free guard here and the no-network guard in
``tests/test_semretrieval_loadbearing.py`` both walk imports statically, and both are blind
to a dynamic import by construction."""
func = node.func
if isinstance(func, ast.Name) and func.id == "__import__":
return ["__import__"]
if isinstance(func, ast.Attribute) and func.attr == "import_module":
return ["import_module"]
return []
@pytest.mark.parametrize("module_name", _MAF_FREE_MODULES)
def test_okf_is_maf_free(module_name: str) -> None:
"""D7 portability: each framework-neutral module IMPORTS no ``agent_framework`` / ``mcp`` (a
@ -283,10 +297,22 @@ def test_okf_is_maf_free(module_name: str) -> None:
Path(__file__).resolve().parents[1] / "src" / "portfolio_optimiser" / module_name
).read_text(encoding="utf-8")
imported: list[str] = []
dynamic: list[str] = []
for node in ast.walk(ast.parse(src)):
if isinstance(node, ast.Import):
imported += [a.name for a in node.names]
elif isinstance(node, ast.ImportFrom):
imported.append(node.module or "")
elif isinstance(node, ast.Call):
dynamic += _dynamic_import_targets(node)
forbidden = [m for m in imported if m.split(".")[0] in {"agent_framework", "mcp"}]
assert forbidden == [], f"{module_name} must not import MAF/mcp, found: {forbidden}"
# A RATCHET, green today: none of these modules imports ``importlib`` or calls ``__import__``.
# The sweep above walks only ``ast.Import``/``ast.ImportFrom``, so a single
# ``importlib.import_module("portfolio_optimiser.verdicts")`` would sail straight past it and
# pull MAF into a module this guard certifies as MAF-free. Any dynamic import is refused
# outright rather than argument-inspected: a computed target cannot be judged statically.
assert dynamic == [], (
f"{module_name} performs dynamic import(s) {dynamic} — the MAF-free guard is a STATIC "
"check and cannot see through them; use a normal import so it stays enforceable"
)