Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions lib/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -1316,6 +1316,24 @@ let
python3 ${../pkgs/deploy/test_deploy_slice2.py} ${../pkgs/deploy/deploy.py}
mkdir -p $out
'';
deploy-argv =
pkgs.runCommandLocal "check-deploy-argv"
{
nativeBuildInputs = [ pkgs.python3 ];
}
''
python3 ${../pkgs/deploy/test_argv.py} ${../pkgs/deploy/deploy.py}
mkdir -p $out
'';
deploy-argv-property =
pkgs.runCommandLocal "check-deploy-argv-property"
{
nativeBuildInputs = [ pkgs.python3 ];
}
''
python3 ${../pkgs/deploy/test_argv_property.py} ${../pkgs/deploy/deploy.py}
mkdir -p $out
'';
deploy-list-malformed = pkgs.runCommandLocal "check-deploy-list-malformed" { } ''
expect_invalid() {
registry="$1"
Expand Down
57 changes: 35 additions & 22 deletions pkgs/deploy/deploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -570,34 +570,41 @@ def describe(entry):
)


def _take_value_flag(args, flag):
while flag in args:
idx = args.index(flag)
if idx + 1 >= len(args):
return None, args, False
value = args[idx + 1]
del args[idx : idx + 2]
return value, args, True
return None, args, True


def main(argv):
args = list(argv)
registry_path = os.environ.get("DEPLOY_REGISTRY")
explicit_state = None
explicit_base = None
for flag in ("--registry", "--state-dir", "--profile-base"):
value, args, ok = _take_value_flag(args, flag)
if not ok:
# Value flags may appear before or after the subcommand, in either
# "--flag PATH" or "--flag=PATH" form, each at most once: a second
# occurrence is the typo-flag class of issue #6376, never a silent
# override of the first.
flag_values = {}
args = []
it = iter(argv)
for arg in it:
flag = next(
(
f
for f in ("--registry", "--state-dir", "--profile-base")
if arg == f or arg.startswith(f + "=")
),
None,
)
if flag is None:
args.append(arg)
continue
if flag in flag_values:
print(f"deploy: {flag} given more than once", file=sys.stderr)
return 2
value = next(it, None) if arg == flag else arg[len(flag) + 1 :]
if not value:
print(f"deploy: {flag} needs a path", file=sys.stderr)
return 2
if value is not None:
if flag == "--registry":
registry_path = value
elif flag == "--state-dir":
explicit_state = value
else:
explicit_base = value
flag_values[flag] = value
if "--registry" in flag_values:
registry_path = flag_values["--registry"]
explicit_state = flag_values.get("--state-dir")
explicit_base = flag_values.get("--profile-base")
dry_run = "--dry-run" in args
args = [a for a in args if a != "--dry-run"]
usage = (
Expand All @@ -620,6 +627,12 @@ def main(argv):
print(f"deploy: cannot load registry {registry_path}: {exc}", file=sys.stderr)
return 1
if args[0] == "list":
if len(args) > 1:
print(
f"deploy: unexpected argument {args[1]!r} after 'list'",
file=sys.stderr,
)
return 2
return cmd_list(registry)
errors = validate(registry)
if errors:
Expand Down
98 changes: 98 additions & 0 deletions pkgs/deploy/test_argv.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
#!/usr/bin/env python3
"""argv behaviour of deploy.py main() (issue #6376).

Oracle: exit codes and stderr text of main() for each documented
invocation shape. Stdlib-only, like test_dupkeys_property.py.

Usage: test_argv.py [path-to-deploy.py]
"""

import contextlib
import importlib.util
import io
import json
import os
import sys
import tempfile


def load(path):
spec = importlib.util.spec_from_file_location("deploy_under_test", path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod


def run(mod, argv, env=None):
out, err = io.StringIO(), io.StringIO()
old = os.environ.pop("DEPLOY_REGISTRY", None)
if env:
os.environ["DEPLOY_REGISTRY"] = env
try:
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = mod.main(argv)
finally:
os.environ.pop("DEPLOY_REGISTRY", None)
if old is not None:
os.environ["DEPLOY_REGISTRY"] = old
return code, out.getvalue(), err.getvalue()


def definition():
return {
"package": "/nix/store/x-pkg",
"entryPoint": "bin/x",
"args": [],
"environment": {},
"secrets": [],
"user": "svc",
"ports": [8080],
"restart": "always",
"healthCheck": None,
"targets": ["laptop"],
"class": "systemd",
}


def main(argv):
path = argv[0] if argv else os.path.join(os.path.dirname(__file__), "deploy.py")
mod = load(path)
with tempfile.TemporaryDirectory() as tmp:
regs = {}
for name in ("A", "B"):
regs[name] = os.path.join(tmp, f"reg{name}.json")
with open(regs[name], "w") as fh:
json.dump({f"svc-{name.lower()}": definition()}, fh)
a, b = regs["A"], regs["B"]

def check(label, argv, code, out_has=None, err_has=None, env=None):
got, out, err = run(mod, argv, env)
assert got == code, f"{label}: exit {got} != {code}\n{out}{err}"
if out_has:
assert out_has in out, f"{label}: stdout lacks {out_has!r}: {out}"
if err_has:
assert err_has in err, f"{label}: stderr lacks {err_has!r}: {err}"

check("plain list", ["--registry", a, "list"], 0, out_has="svc-a")
check("registry after subcommand", ["list", "--registry", a], 0, out_has="svc-a")
check("registry= form", ["--registry=" + a, "list"], 0, out_has="svc-a")
check("env fallback", ["list"], 0, out_has="svc-b", env=b)
check("flag overrides env", ["--registry", a, "list"], 0, out_has="svc-a", env=b)
# Unknown targets exit 1 on current main: slice 2 replaced the
# slice-1 "not implemented" exit 2, and test_deploy_slice2.py
# (CliTests.test_cli_unknown_target) pins exit 1.
check("unknown subcommand", ["--registry", a, "bogus"], 1, err_has="'bogus'")
check("no args", [], 2)
check("trailing junk", ["--registry", a, "list", "extra-junk"], 2, err_has="'extra-junk'")
check("typo flag", ["--registry", a, "list", "--dry-rnu"], 2, err_has="'--dry-rnu'")
check("duplicate registry", ["--registry", a, "--registry", b, "list"], 2, err_has="more than once")
check("duplicate registry reversed", ["--registry", b, "list", "--registry", a], 2, err_has="more than once")
check("duplicate mixed forms", ["--registry=" + a, "--registry", b, "list"], 2, err_has="more than once")
Comment on lines +88 to +90

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add property coverage for the rewritten argument parser

The rewritten parser has explicit invariants—each value flag occurs at most once, and valid option placement and spelling preserve the selected paths—but this suite covers only fixed examples, primarily for --registry. This violates the repository’s Testing doctrine requiring property coverage for meaningful parser invariants rather than example-only tests. Add generated cases covering all three value flags, both spellings, placement, and duplicates, with an invariant or model oracle. The existing test_dupkeys_property.py only exercises load_registry, so it does not cover argument parsing.

AGENTS.md reference: AGENTS.md:L41-L45

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6a12741: added pkgs/deploy/test_argv_property.py — generated argv cases (flag/subcommand units) covering all three value flags (--registry, --state-dir, --profile-base), both spellings (--flag PATH and --flag=PATH), random placement around the subcommand, duplicate occurrences, and missing values, checked against a sequential model of the parser contract as the oracle. Stdlib-only with a fixed seed, same conventions as test_dupkeys_property.py (which, as noted, only exercises load_registry). Wired into CI as the deploy-argv-property check in lib/default.nix. Verified locally on the laptop: property holds for the default 300 cases (seed 6376) and 1000 cases at seed 42; test_argv.py and test_dupkeys_property.py still pass.

check("registry missing path", ["list", "--registry"], 2, err_has="needs a path")
check("registry= empty", ["--registry=", "list"], 2, err_has="needs a path")
print("deploy argv checks: ok")
return 0


if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
193 changes: 193 additions & 0 deletions pkgs/deploy/test_argv_property.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
#!/usr/bin/env python3
"""Property-based coverage for the deploy argv parser (issue #6376).

Invariants (the parser contract in deploy.py main()):
- Each value flag (--registry, --state-dir, --profile-base) occurs at
most once, in "--flag PATH" or "--flag=PATH" form, before or after
the subcommand; a second occurrence is rejected, never a silent
override of the first.
- A value flag with no value (trailing "--flag", or "--flag=") is
rejected.
- A valid invocation selects exactly the registry its single
--registry names (or $DEPLOY_REGISTRY when the flag is absent);
flag placement and spelling never change the selection.

Oracle: a sequential model of the parser contract. The generator
emits argv as flag/subcommand units; the model scans the units in
order, firing the duplicate error at the second occurrence of a flag
and the missing-value error at a valueless flag, and otherwise
predicts exit 0 with the modelled registry's services listed. Any
disagreement between model and main() is a counterexample.

Stdlib-only (no hypothesis in this repo's Python tooling), like
test_dupkeys_property.py; a fixed default seed keeps CI
deterministic, and a failing case prints its seed and argv.

Usage: test_argv_property.py [path-to-deploy.py] [--seed N] [--cases N]
"""

import contextlib
import importlib.util
import io
import json
import os
import random
import sys
import tempfile

FLAGS = ("--registry", "--state-dir", "--profile-base")


def load(path):
spec = importlib.util.spec_from_file_location("deploy_under_test", path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod


def run(mod, argv, env):
out, err = io.StringIO(), io.StringIO()
old = os.environ.pop("DEPLOY_REGISTRY", None)
if env is not None:
os.environ["DEPLOY_REGISTRY"] = env
try:
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = mod.main(argv)
finally:
os.environ.pop("DEPLOY_REGISTRY", None)
if old is not None:
os.environ["DEPLOY_REGISTRY"] = old
return code, out.getvalue(), err.getvalue()


def definition():
return {
"package": "/nix/store/x-pkg",
"entryPoint": "bin/x",
"args": [],
"environment": {},
"secrets": [],
"user": "svc",
"ports": [8080],
"restart": "always",
"healthCheck": None,
"targets": ["laptop"],
"class": "systemd",
}


# A unit is ("flag", flag, spelling, value) | ("list",) | ("dry-run",).
# spelling is "space" ("--flag value") or "eq" ("--flag=value").
def render(unit):
if unit[0] == "flag":
_, flag, spelling, value = unit
return [flag, value] if spelling == "space" else [f"{flag}={value}"]
if unit[0] == "list":
return ["list"]
return ["--dry-run"]


def flag_value(rng, flag, regs):
if flag == "--registry":
return rng.choice([regs["A"], regs["B"]])
return f"/tmp/deploy-prop-{rng.randint(0, 99999)}"


def gen_valid_units(rng, regs):
flags = [f for f in FLAGS if rng.random() < 0.7]
units = [
("flag", f, rng.choice(["space", "eq"]), flag_value(rng, f, regs))
for f in flags
]
units.append(("list",))
if rng.random() < 0.3:
units.append(("dry-run",))
rng.shuffle(units)
return units


def model(units, env, regs):
"""Predict (exit_code, stderr_fragment, listed_service)."""
seen = {}
for unit in units:
if unit[0] != "flag":
continue
_, flag, _, value = unit
if flag in seen:
return 2, f"deploy: {flag} given more than once", None
seen[flag] = value
registry = seen.get("--registry", env)
if registry is None:
return 2, "no registry configured", None
return 0, None, "svc-a" if registry == regs["A"] else "svc-b"


def main(argv):
args = [a for a in argv if not a.startswith("--")]
seed, cases = 6376, 300
for i, a in enumerate(argv):
if a == "--seed":
seed = int(argv[i + 1])
if a == "--cases":
cases = int(argv[i + 1])
path = args[0] if args else os.path.join(os.path.dirname(os.path.abspath(__file__)), "deploy.py")
mod = load(path)

rng = random.Random(seed)
with tempfile.TemporaryDirectory() as tmp:
regs = {}
for name in ("A", "B"):
regs[name] = os.path.join(tmp, f"reg{name}.json")
with open(regs[name], "w") as fh:
json.dump({f"svc-{name.lower()}": definition()}, fh)

for case in range(cases):
kind = rng.choice(["valid", "valid", "duplicate", "missing"])
units = gen_valid_units(rng, regs)
env = rng.choice([regs["B"], None])
if kind == "duplicate":
present = [u[1] for u in units if u[0] == "flag"]
flag = rng.choice(present) if present else "--registry"
if flag not in present:
units.insert(0, ("flag", flag, "eq", flag_value(rng, flag, regs)))
units.insert(
rng.randint(0, len(units)),
("flag", flag, rng.choice(["space", "eq"]), flag_value(rng, flag, regs)),
)
if kind == "missing":
flag = rng.choice(FLAGS)
units = [u for u in units if not (u[0] == "flag" and u[1] == flag)]
form = rng.choice(["trailing", "eq-empty"])
if form == "trailing":
units.append(("missing-space", flag))
else:
units.insert(rng.randint(0, len(units)), ("missing-eq", flag))
tokens = []
for u in units:
if u[0] == "missing-space":
tokens.append(u[1])
elif u[0] == "missing-eq":
tokens.append(u[1] + "=")
else:
tokens.extend(render(u))
got, out, err = run(mod, tokens, env)
want = f"deploy: {flag} needs a path"
if got != 2 or want not in err:
print(f"counterexample (missing) seed={seed} case={case}: {tokens}\nexit={got} err={err!r}")
return 1
continue
tokens = [t for u in units for t in render(u)]
code, frag, svc = model(units, env, regs)
got, out, err = run(mod, tokens, env)
if got != code or (frag is not None and frag not in err) or (svc is not None and svc not in out):
print(
f"counterexample ({kind}) seed={seed} case={case}: {tokens}\n"
f"model: exit={code} frag={frag!r} svc={svc!r}\ngot: exit={got} out={out!r} err={err!r}"
)
return 1
print(f"property holds: {cases} cases (seed {seed}); duplicates and missing values rejected, valid placements/spellings preserve the modelled registry selection")
return 0


if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
Loading