import base64 import hashlib import importlib.util import json from pathlib import Path import pytest spec = importlib.util.spec_from_file_location( "stage_patch", Path(__file__).resolve().parents[1] / "scripts/stage_simulation_worker_patch.py" ) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) def fixture(tmp_path): manifest = { "source.py": hashlib.sha256(b"old").hexdigest(), "keep.py": hashlib.sha256(b"keep").hexdigest(), } encoded = json.dumps(manifest, sort_keys=True, indent=2).encode() digest = hashlib.sha256(encoded).hexdigest() releases = tmp_path / "releases" base = releases / ("ai-polygon-" + digest[:16]) base.mkdir(parents=True) (base / "source.py").write_bytes(b"old") (base / "keep.py").write_bytes(b"keep") base.with_suffix(".manifest.json").write_bytes(encoded) recipe = dict( base_release=digest[:16], base_manifest_sha256=digest, overlays={ "source.py": dict( base64=base64.b64encode(b"new").decode(), sha256=hashlib.sha256(b"new").hexdigest() ) }, ) return base, recipe def test_patch_preserves_predecessor_and_every_undeclared_file(tmp_path): base, recipe = fixture(tmp_path) result = module.stage(tmp_path, recipe) new = tmp_path / "releases" / ("ai-polygon-" + result["release"]) assert (base / "source.py").read_bytes() == b"old" assert (new / "source.py").read_bytes() == b"new" assert (new / "keep.py").read_bytes() == b"keep" assert result["changed"] == ["source.py"] and not result["activated"] with pytest.raises(ValueError, match="already exists"): module.stage(tmp_path, recipe) def test_corrupted_predecessor_refuses_before_staging(tmp_path): base, recipe = fixture(tmp_path) (base / "keep.py").write_bytes(b"corrupt") with pytest.raises(ValueError, match="Base file changed"): module.stage(tmp_path, recipe) assert len(list((tmp_path / "releases").iterdir())) == 2 @pytest.mark.parametrize("path", ["../outside", "/absolute", "C:/outside", "a\\b"]) def test_escape_rejected(tmp_path, path): with pytest.raises(ValueError): module.confined(tmp_path, path)