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
22 changes: 6 additions & 16 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ def test_missing_file(tmp_path):
config.load(tmp_path / "nope.toml")


MINIMAL = '[repo]\nname = "o/n"\n'
FORBIDDEN = ["/", "/home", "/root", "/run", "/var/run", "/run/user/1000", "/proc/1", "/dev",
"/var/run/docker.sock", "/sys/fs", "/tmp/../run"]


@pytest.mark.parametrize("text,message", [
Expand Down Expand Up @@ -102,6 +103,7 @@ def test_missing_file(tmp_path):
(MINIMAL + '[delivery.review.codex]\nallowed_efforts = "medium"\n',
"allowed_efforts must be a list"),
(MINIMAL + '[checks]\nro_paths = ["rel/path"]\n', "must be absolute"),
*((MINIMAL + table("checks", ro_paths=[path]), "must not expose") for path in FORBIDDEN),
(MINIMAL + '[checks]\nwritable = ["/run/x"]\n', "writable must not expose"),
*((MINIMAL + f'[checks]\nscratch = ["{path}"]\n', "scratch entries must be relative")
for path in ("../x", "/abs")),
Expand All @@ -127,24 +129,12 @@ def test_invalid_content(tmp_path, text, message):
assert str(info.value).startswith(str(tmp_path / "workflow.toml"))


FORBIDDEN = ["/", "/home", "/root", "/run", "/var/run", "/run/user/1000", "/proc/1", "/dev"]
FORBIDDEN += ["/var/run/docker.sock", "/sys/fs", "/tmp/../run"]


@pytest.mark.parametrize("runner", [("dispatch", "--stage"), ("python3", "tools/run_stage.py"),
("dispatch", "--opt=/operator/run.py")])
def test_runner_prefix(tmp_path, runner):
assert config.load(write(tmp_path, MINIMAL + f"[checks]\nrunner = {list(runner)!r}")).check_runner == runner


@pytest.mark.parametrize("path,allowed", [
*((path, False) for path in FORBIDDEN),
*((path, True) for path in ("/home/me/.local/bin", "/opt/tool", "/tmp/x")),
])
def test_ro_path_boundary(tmp_path, path, allowed):
cfg = write(tmp_path, f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n')
if allowed:
assert config.load(cfg).sandbox_ro == (path,)
else:
with pytest.raises(config.ConfigError, match="must not expose"):
config.load(cfg)
@pytest.mark.parametrize("path", ["/home/me/.local/bin", "/opt/tool", "/tmp/x"])
def test_ro_path_boundary(tmp_path, path):
assert config.load(write(tmp_path, MINIMAL + table("checks", ro_paths=[path]))).sandbox_ro == (path,)
34 changes: 15 additions & 19 deletions tests/test_proc.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,6 @@ def run(script, *, timeout=30, env_allowlist=("PATH",), unbuffered=False, args=(
return run


def test_run_strips_environment_to_allowlist(run_python, monkeypatch):
monkeypatch.delenv("LZ_ABSENT", raising=False)
monkeypatch.setenv("LZ_SECRET", "nope")
monkeypatch.setenv("LZ_KEEP", "yes")
done = run_python("import os; print(sorted(k for k in os.environ if k.startswith('LZ_')))",
env_allowlist=("PATH", "LZ_KEEP", "LZ_ABSENT"), extra_env={"LZ_EXTRA": "1"})
assert done.stdout.strip() == "['LZ_EXTRA', 'LZ_KEEP']"


def test_run_raises_tool_missing(tmp_path):
with pytest.raises(_proc.ToolMissing, match="definitely-not-a-tool"):
_proc.run(["definitely-not-a-tool"], cwd=tmp_path, env_allowlist=("PATH",), timeout=30)
Expand Down Expand Up @@ -122,14 +113,21 @@ def communicate(self, input=None, timeout=None):


@pytest.mark.parametrize("merge,stderr", [(True, ""), (False, "b\n")])
def test_run_captures_exit_duration_cwd_and_streams(tmp_path, run_python, merge, stderr):
def test_run_captures_streams_and_allowlisted_environment(tmp_path, run_python, monkeypatch, merge, stderr):
monkeypatch.delenv("LZ_ABSENT", raising=False)
monkeypatch.setenv("LZ_SECRET", "nope")
monkeypatch.setenv("LZ_KEEP", "yes")
done = run_python(
"import os,sys; print(os.getcwd()); print('b', file=sys.stderr); print(sys.argv[1]); sys.exit(3)",
unbuffered=True, merge_output=merge, env_allowlist=(), args=("argument with spaces",),
"import os,sys; print(os.getcwd()); print('b', file=sys.stderr); print(sys.argv[1]); "
"print(sorted(k for k in os.environ if k.startswith('LZ_'))); sys.exit(3)",
unbuffered=True, merge_output=merge, args=("argument with spaces",),
env_allowlist=("PATH", "LZ_KEEP", "LZ_ABSENT"), extra_env={"LZ_EXTRA": "1"},
)
assert (done.exit_code, done.stderr) == (3, stderr)
assert done.duration_s >= 0
assert done.stdout.splitlines() == [str(tmp_path.resolve()), *(["b"] if merge else []), "argument with spaces"]
assert done.stdout.splitlines() == [
str(tmp_path.resolve()), *(["b"] if merge else []), "argument with spaces", "['LZ_EXTRA', 'LZ_KEEP']",
]


def test_tail_keeps_last_lines():
Expand All @@ -138,7 +136,7 @@ def test_tail_keeps_last_lines():
assert _proc.tail("", 3) == ""


def test_explicit_utf8_input_under_ascii_parent_locale(tmp_path):
def test_explicit_utf8_input_under_ascii_parent_locale(run_python):
source = str(Path(_proc.__file__).resolve().parents[1])
script = r"""
import locale, sys
Expand All @@ -150,10 +148,8 @@ def test_explicit_utf8_input_under_ascii_parent_locale(tmp_path):
assert _proc.run(argv, input='\u03a9', **options).stdout.strip() == '3f'
print(_proc.run(argv, input='\u03a9\r\n\u2028\r', encoding='utf-8', **options).stdout.strip())
"""
done = _proc.run(
[sys.executable, "-c", script], cwd=tmp_path, env_allowlist=(), timeout=30,
extra_env={"PYTHONPATH": source, "LC_ALL": "C", "PYTHONUTF8": "0",
"PYTHONCOERCECLOCALE": "0"},
)
done = run_python(script, env_allowlist=(), extra_env={
"PYTHONPATH": source, "LC_ALL": "C", "PYTHONUTF8": "0", "PYTHONCOERCECLOCALE": "0",
})
assert done.exit_code == 0, done.stderr
assert done.stdout.strip() == "Ω\r\n\u2028\r".encode("utf-8").hex()
62 changes: 23 additions & 39 deletions tests/test_size_budget.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,13 @@ def test_size_budget_counts_unicode_and_propagates_read_errors(git_repo, fake_to
source.parent.mkdir(parents=True)
source.write_text("one\ntwo\n")
source.with_name("z.py").write_text("three\n")
git(git_repo, "add", ".")
base = git(git_repo, "write-tree").strip()
base = stage_tree(git_repo)
if failure == "deleted": # unstaged deletion: skipped, not an error
source.unlink()
elif failure == "show":
fake_tool("git", 'if [ "$1" = show ]; then case "$2" in */a.py) exit 1;; esac; fi\n'
f'exec {shutil.which("git")} "$@"\n')
done = subprocess.run(["bash", str(SCRIPT), base], cwd=git_repo,
env={**os.environ, "PYTHON": sys.executable},
capture_output=True, text=True, check=False)
done = run_budget(git_repo, base)
assert bool(done.returncode) is (failure == "show")
if failure != "show":
assert done.stdout.startswith("src=1 (base 3," if failure else "src=3 (base 3, delta 0,")
Expand Down Expand Up @@ -82,38 +79,29 @@ def module_path(git_repo):
_HOT_FUNCTION = _branchy("hot", 11)


@pytest.mark.parametrize("before,after,expected_rc", [
pytest.param(_SIMPLE_FUNCTION, _branchy("new_hot", 10), 1, id="new_over_cap"),
pytest.param(_HOT_FUNCTION, _HOT_FUNCTION, 0, id="existing_hold"),
pytest.param(_HOT_FUNCTION, _branchy("hot", 10), 0, id="existing_shrink"),
pytest.param(_HOT_FUNCTION, _branchy("hot", 12), 1, id="existing_grow"),
_CONTEXT_MANAGERS = "".join(f" with contextlib.suppress(ValueError):\n y = {i}\n"
for i in range(11))
_PEP758 = "import contextlib\ndef pep758(x):\n" + _CONTEXT_MANAGERS + (
" try:\n return int(x) + y\n except KeyError, TypeError:\n return 0\n"
)


@pytest.mark.parametrize("before,after,over_cap,regressions", [
pytest.param(_SIMPLE_FUNCTION, _branchy("new_hot", 10), 1, 1, id="new_over_cap"),
pytest.param(_HOT_FUNCTION, _HOT_FUNCTION, 1, 0, id="existing_hold"),
pytest.param(_HOT_FUNCTION, _branchy("hot", 10), 1, 0, id="existing_shrink"),
pytest.param(_HOT_FUNCTION, _branchy("hot", 12), 1, 1, id="existing_grow"),
pytest.param(_PEP758, _PEP758, 0, 0, id="pep758_with_blocks"),
])
def test_complexity_ratchet(git_repo, module_path, before, after, expected_rc):
def test_complexity_ratchet(git_repo, module_path, before, after, over_cap, regressions):
module_path.write_text(before)
base = stage_tree(git_repo)
if after != before:
module_path.write_text(after)
done = run_budget(git_repo, base)
assert done.returncode == expected_rc, done.stdout + done.stderr
assert ("complexity=FAIL" if expected_rc else "complexity=PASS") in done.stdout


def test_complexity_parses_pep758_and_ignores_with_blocks(git_repo, module_path):
with_blocks = "".join(f" with contextlib.suppress(ValueError):\n y = {i}\n"
for i in range(11))
module_path.write_text(
"import contextlib\n"
"def pep758(x):\n"
f"{with_blocks}"
" try:\n"
" return int(x) + y\n"
" except KeyError, TypeError:\n"
" return 0\n"
)
base = stage_tree(git_repo)
done = run_budget(git_repo, base)
assert done.returncode == 0, done.stdout + done.stderr
assert "complexity=PASS (cap 10, over_cap 0, regressions 0)" in done.stdout
assert done.returncode == int(bool(regressions)), done.stdout + done.stderr
result = "FAIL" if regressions else "PASS"
assert f"complexity={result} (cap 10, over_cap {over_cap}, regressions {regressions})" in done.stdout


def test_complexity_rejects_old_python(git_repo, module_path, tmp_path):
Expand All @@ -133,18 +121,14 @@ def test_complexity_rejects_old_python(git_repo, module_path, tmp_path):
assert "requires Python 3.14+" in done.stderr


@pytest.mark.parametrize("path,cap,grew,expected_rc", [
("core/CONTRACT.md", 1500, True, 1),
("core/CONTRACT.md", 1500, False, 0),
("docs/DELEGATION.md", 660, True, 1),
("docs/DELEGATION.md", 660, False, 0),
])
def test_markdown_doc_budgets(git_repo, path, cap, grew, expected_rc):
@pytest.mark.parametrize("path,cap", [("core/CONTRACT.md", 1500), ("docs/DELEGATION.md", 660)])
@pytest.mark.parametrize("grew", [True, False])
def test_markdown_doc_budgets(git_repo, path, cap, grew):
doc = git_repo / path
doc.parent.mkdir(parents=True)
doc.write_text("line\n" * (cap + 5))
base = stage_tree(git_repo)
if grew:
doc.write_text("line\n" * (cap + 6))
done = run_budget(git_repo, base)
assert done.returncode == expected_rc, done.stdout + done.stderr
assert done.returncode == int(grew), done.stdout + done.stderr
Loading