vm-tests: the typecheck fails a step that rebinds a function of its script
A VM test script and `lib/k3s.py` share one namespace, so a step that assigns `pod = ...` replaces the library's `pod()` for every later call and the test dies mid-run with `TypeError: 'dict' object is not callable`. `ty` and `ruff --select F` accept a module-level rebinding, so this cost a full VM round on #6947. `vm-test-shadow-scan.py` parses the script and fails when a name bound at module level (assignment, `for` or `with` target, `import ... as`, walrus, `except ... as`) is also a module-level `def`. It looks into `with`, `if`, `for`, `while` and `try` bodies, where `with subtest(...)` steps live, and not into function or comprehension bodies. Every `vm-test-typecheck-<name>` runs it on the script alone. `vm-test-typecheck-shadow-control` passes only when it rejects each form of rebinding and accepts the same names where they are local. The one existing case, `sources` in `k8s-services`, is renamed `cred_sources`. Closes #6951
This commit is contained in:
parent
358a13752c
commit
132d876668
4 changed files with 175 additions and 4 deletions
|
|
@ -90,7 +90,14 @@ read node config or an agent toplevel into their script, so each builds the scri
|
|||
with stand-in values (`passthru.typecheckScript`), from the same function as the real
|
||||
one.
|
||||
`vm-test-typecheck-control` passes only when the checker rejects a known type error, which shows the
|
||||
checker resolves `test_driver`. [`.forgejo/workflows/vm-nightly.yml`](../../../.forgejo/workflows/vm-nightly.yml)
|
||||
checker resolves `test_driver`.
|
||||
Each check also runs `nix/vm-test-shadow-scan.py`, which fails when a step of the script
|
||||
binds a name at module level that the script also defines as a function (`pod = ...`
|
||||
after `def pod`, for example, including inside a `with subtest(...)`). A script and
|
||||
`lib/k3s.py` share one namespace, so the assignment replaces the helper for every later
|
||||
call, and neither `ty` nor `ruff` sees it. `vm-test-typecheck-shadow-control` passes only
|
||||
when the scan rejects each way of rebinding a function and accepts the same names where
|
||||
they're local. [`.forgejo/workflows/vm-nightly.yml`](../../../.forgejo/workflows/vm-nightly.yml)
|
||||
builds them nightly at 02:30, one job per test, so the runner's one-hour job
|
||||
limit applies to each test alone and a stuck test no longer hides the others'
|
||||
results. The matrix in `vm-nightly.yml` is the list of tests;
|
||||
|
|
|
|||
83
nix/vm-test-shadow-scan.py
Normal file
83
nix/vm-test-shadow-scan.py
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
"""Fail when a VM test script rebinds a function it defines.
|
||||
|
||||
A VM test script is one module: `lib/k3s.py` and the test's own helpers are
|
||||
concatenated in front of the steps, and every `with subtest(...)` body runs in
|
||||
that module's namespace. A step that assigns `pod = ...` replaces the library's
|
||||
`pod()` for every later call, and the test dies mid-run with
|
||||
`TypeError: 'dict' object is not callable`. `ty` and `ruff --select F` don't see
|
||||
it, because a rebinding at module level is legal Python.
|
||||
|
||||
The scan names every module-level binding (assignment, `for`/`with`/`except`
|
||||
target, walrus, `import ... as`) whose name is also a module-level `def`. It
|
||||
looks into blocks that share the module's namespace (`with`, `if`, `for`,
|
||||
`while`, `try`), and not into function, class or comprehension bodies, whose
|
||||
bindings are local.
|
||||
|
||||
Usage: shadow-scan.py <script>
|
||||
"""
|
||||
|
||||
import ast
|
||||
import sys
|
||||
|
||||
# Bodies that open a namespace of their own: what is bound inside is local.
|
||||
SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)
|
||||
COMPREHENSIONS = (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)
|
||||
|
||||
|
||||
def module_level(node):
|
||||
"""Yield `node`'s descendants that run in the module's namespace.
|
||||
|
||||
A `def` or `class` is yielded itself (its name is bound here), its body is
|
||||
not entered.
|
||||
"""
|
||||
for child in ast.iter_child_nodes(node):
|
||||
yield child
|
||||
if not isinstance(child, SCOPES + COMPREHENSIONS):
|
||||
yield from module_level(child)
|
||||
|
||||
|
||||
def bindings(tree):
|
||||
"""Map each name bound at module level to the lines that bind it."""
|
||||
bound: dict[str, list[int]] = {}
|
||||
for node in module_level(tree):
|
||||
names = []
|
||||
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
|
||||
names = [node.id]
|
||||
elif isinstance(node, ast.Import | ast.ImportFrom):
|
||||
names = [(a.asname or a.name).split(".")[0] for a in node.names]
|
||||
elif isinstance(node, ast.ExceptHandler) and node.name:
|
||||
names = [node.name]
|
||||
for name in names:
|
||||
bound.setdefault(name, []).append(node.lineno)
|
||||
return bound
|
||||
|
||||
|
||||
def functions(tree):
|
||||
"""Map each module-level `def` name to its line."""
|
||||
return {
|
||||
node.name: node.lineno
|
||||
for node in module_level(tree)
|
||||
if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef)
|
||||
}
|
||||
|
||||
|
||||
def main(path: str) -> int:
|
||||
with open(path) as f:
|
||||
tree = ast.parse(f.read(), path)
|
||||
defined = functions(tree)
|
||||
failed = False
|
||||
for name, lines in sorted(bindings(tree).items()):
|
||||
if name in defined:
|
||||
for line in lines:
|
||||
print(
|
||||
f"{path}:{line}: `{name}` is bound at module level, shadowing "
|
||||
f"the function `{name}` defined at line {defined[name]}; every "
|
||||
f"later call of it fails. Rename the variable.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
failed = True
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1]))
|
||||
|
|
@ -74,9 +74,89 @@ let
|
|||
ty check testScriptWithTypes
|
||||
# driver.nix:91-99
|
||||
ruff check --select F testScriptWithTypes
|
||||
# What neither of them sees: a step that rebinds a function the script
|
||||
# defines. The script alone, so a name of the prelude or a hint isn't read
|
||||
# as the script's own.
|
||||
echo -n "$testScript" > testScriptOnly
|
||||
${shadowScan} testScriptOnly
|
||||
touch $out
|
||||
'';
|
||||
|
||||
# `vm-test-shadow-scan.py` as a command; the scan reads nothing of the machine
|
||||
# it runs on, so `-I`.
|
||||
shadowScan = "${pkgs.python3}/bin/python3 -I ${./vm-test-shadow-scan.py}";
|
||||
|
||||
# Succeeds only when the scan rejects every way a step rebinds a function of
|
||||
# its script and accepts the same names where they are local. The first
|
||||
# script is accepted whole: if it were not, the rejections below could be the
|
||||
# scan failing on anything.
|
||||
shadowControl =
|
||||
let
|
||||
script = body: pkgs.writeText "script.py" body;
|
||||
accepted = script ''
|
||||
def pod(name):
|
||||
return {"name": name}
|
||||
|
||||
def other():
|
||||
pod = 1 # local to the function
|
||||
return [pod for pod in range(3)] # a comprehension has its own scope
|
||||
|
||||
with subtest("a variable with a name of its own"):
|
||||
result = pod("a")
|
||||
'';
|
||||
rejected = {
|
||||
"a plain assignment" = ''
|
||||
def pod(name):
|
||||
return {}
|
||||
pod = pod("a")
|
||||
'';
|
||||
"an assignment inside a subtest" = ''
|
||||
def pod(name):
|
||||
return {}
|
||||
with subtest("x"):
|
||||
pod = pod("a")
|
||||
'';
|
||||
"a for target" = ''
|
||||
def pod(name):
|
||||
return {}
|
||||
for pod in range(3):
|
||||
pass
|
||||
'';
|
||||
"a with target" = ''
|
||||
def pod(name):
|
||||
return {}
|
||||
with open("x") as pod:
|
||||
pass
|
||||
'';
|
||||
"an import" = ''
|
||||
def pod(name):
|
||||
return {}
|
||||
import json as pod
|
||||
'';
|
||||
"an except target" = ''
|
||||
def pod(name):
|
||||
return {}
|
||||
try:
|
||||
pass
|
||||
except Exception as pod:
|
||||
pass
|
||||
'';
|
||||
};
|
||||
in
|
||||
pkgs.runCommand "vm-test-typecheck-shadow-control" { } ''
|
||||
${shadowScan} ${accepted}
|
||||
${lib.concatStrings (
|
||||
lib.mapAttrsToList (what: body: ''
|
||||
if ${shadowScan} ${script body} 2> scan.err; then
|
||||
echo "the scan accepted ${what}" >&2
|
||||
exit 1
|
||||
fi
|
||||
grep -q '`pod` is bound at module level' scan.err
|
||||
'') rejected
|
||||
)}
|
||||
touch $out
|
||||
'';
|
||||
|
||||
# Succeeds only when `ty` rejects an `Optional` dereference and three calls on
|
||||
# the stub machines of `hintsFor`. If `test_driver` stops resolving, every
|
||||
# name is `Unknown`, the real checks pass on anything, and this one fails.
|
||||
|
|
@ -151,4 +231,5 @@ in
|
|||
(lib.mapAttrs' (n: t: lib.nameValuePair "vm-test-typecheck-${n}" (typecheck n t)) tests)
|
||||
// {
|
||||
vm-test-typecheck-control = control;
|
||||
vm-test-typecheck-shadow-control = shadowControl;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1601,9 +1601,9 @@ pkgs.testers.runNixOSTest {
|
|||
assert env["BAO_AUTH"] == "jwt" and env["BAO_JWT_ROLE"] == CI, env
|
||||
assert "BAO_CLIENT_CERT" not in env and "BAO_CLIENT_KEY" not in env, env
|
||||
creds = next(v for v in spec["volumes"] if v["name"] == "credentials")
|
||||
sources = creds["projected"]["sources"]
|
||||
assert [src["configMap"]["name"] for src in sources] == ["hyperhive-ca-trust"], sources
|
||||
assert [(i["key"], i["path"]) for i in sources[0]["configMap"]["items"]] == [("bao-server-ca.pem", "bao-ca.pem")], sources
|
||||
cred_sources = creds["projected"]["sources"]
|
||||
assert [src["configMap"]["name"] for src in cred_sources] == ["hyperhive-ca-trust"], cred_sources
|
||||
assert [(i["key"], i["path"]) for i in cred_sources[0]["configMap"]["items"]] == [("bao-server-ca.pem", "bao-ca.pem")], cred_sources
|
||||
assert not any("secret" in v or any("secret" in src for src in v.get("projected", {}).get("sources", [])) for v in spec["volumes"]), spec["volumes"]
|
||||
assert other_secrets() == set(), other_secrets()
|
||||
# The control that the lookup finds the variable: the router's pod sets
|
||||
|
|
|
|||
Loading…
Reference in a new issue