From 13f7b68e990cb1eb2f55e108421ac8a233e5beb5 Mon Sep 17 00:00:00 2001 From: Ahmar Ali Date: Mon, 23 Nov 2026 06:52:22 +0500 Subject: [PATCH 1/5] Make scripts/check.py run on Windows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On Windows the gate could not start: scripts/_uv.py pinned uv only for the macOS and Linux tarballs, so it exited with "Install uv 0.13.7 to run the gate on this bootstrap platform." With uv installed by hand, generate.py --check still failed ("The generated Python API differs"). The generator read openapi.public.json with read_text() and no encoding, so on Windows Python used the legacy code page (cp1252) and the UTF-8 "§" became "§" in a docstring. Its text writes also used Windows line endings (CRLF), which ruff format keeps. The committed files only matched because Git for Windows checks them out as CRLF too. Now: - _uv.py pins the official x86_64 and aarch64 Windows zips of uv 0.13.7 and reads uv.exe from them, with the same checksum and version checks. release_target() and unpack() hold the platform mapping and archive reading; the tarball path is unchanged. - generate.py and contracts.py read and write text as UTF-8, and the generator's ruff format pass uses LF line endings. - .gitattributes (* text=auto eol=lf) makes Windows clones check out LF files, like CI. Tests: tests/test_generate.py runs generate.py --check under a non-UTF-8 default encoding (ASCII on Linux, cp1252 on Windows), and tests/test_uv.py covers the platform mapping and both archive types. Both fail on main and pass now. On Windows, a fresh clone with core.autocrlf=true now passes the whole gate. --- .gitattributes | 3 +++ scripts/_uv.py | 51 ++++++++++++++++++++++++++++-------------- scripts/contracts.py | 4 ++-- scripts/generate.py | 33 +++++++++++++++++++-------- tests/test_generate.py | 25 +++++++++++++++++++++ tests/test_uv.py | 46 +++++++++++++++++++++++++++++++++++++ 6 files changed, 134 insertions(+), 28 deletions(-) create mode 100644 .gitattributes create mode 100644 tests/test_generate.py create mode 100644 tests/test_uv.py diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..76c17dcc --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# Check out text files with LF on every OS, so the gate's byte comparisons +# and formatters see the same files as CI. +* text=auto eol=lf diff --git a/scripts/_uv.py b/scripts/_uv.py index 1eb82687..37e954f3 100644 --- a/scripts/_uv.py +++ b/scripts/_uv.py @@ -8,6 +8,7 @@ import shutil import subprocess import tarfile +import zipfile from pathlib import Path from urllib.request import urlopen @@ -18,6 +19,8 @@ "x86_64-apple-darwin": "20c47e4c1f630b8abaff8c291fa9b9aa300fef92c4fbff95adf198b55287cda7", "aarch64-unknown-linux-gnu": "71279f8d3c67241e807b9d8db872d1bf541579fb9f08b7d1eb1682196d1e57dc", "x86_64-unknown-linux-gnu": "c5221ff41b7892bfc223543883600125f6a47fe845093e0f5bdff4f359196d83", + "aarch64-pc-windows-msvc": "505d9e65e7692bac3ddf98c66754aa26c5050c409c184af30a881a0a72cc85e3", + "x86_64-pc-windows-msvc": "0cdc5b38fe5a8168ed6a25814f5ba43c21d313dd3187314fccb37b7cec46e021", } @@ -31,21 +34,43 @@ def matching(executable: Path) -> bool: return False +def release_target(system: str, machine: str) -> str: + # Windows reports AMD64 or ARM64; macOS reports arm64. + architecture = {"arm64": "aarch64", "aarch64": "aarch64", "x86_64": "x86_64", "amd64": "x86_64"} + systems = {"Darwin": "apple-darwin", "Linux": "unknown-linux-gnu", "Windows": "pc-windows-msvc"} + return f"{architecture.get(machine.lower())}-{systems.get(system)}" + + +def unpack(content: bytes, target: str) -> bytes: + """Return the uv executable from a verified release archive.""" + if target.endswith("-windows-msvc"): + # The Windows release is a zip with uv.exe at its root. + with zipfile.ZipFile(io.BytesIO(content)) as package: + return package.read("uv.exe") + with tarfile.open(fileobj=io.BytesIO(content), mode="r:gz") as package: + member = package.getmember(f"uv-{target}/uv") + if not member.isfile(): + raise SystemExit("The verified uv archive has no regular uv executable.") + source = package.extractfile(member) + if source is None: + raise SystemExit("The verified uv archive has no uv executable.") + with source: + return source.read() + + def executable(tools: Path) -> Path: installed = shutil.which("uv") if installed is not None and matching(Path(installed)): return Path(installed) - architecture = {"arm64": "aarch64", "aarch64": "aarch64", "x86_64": "x86_64"}.get( - platform.machine() - ) - system = {"Darwin": "apple-darwin", "Linux": "unknown-linux-gnu"}.get(platform.system()) - target = f"{architecture}-{system}" + target = release_target(platform.system(), platform.machine()) if target not in CHECKSUMS: raise SystemExit("Install uv 0.13.7 to run the gate on this bootstrap platform.") + windows = target.endswith("-windows-msvc") tools.mkdir(parents=True, exist_ok=True) - archive = tools / f"uv-{VERSION}-{target}.tar.gz" + suffix = ".zip" if windows else ".tar.gz" + archive = tools / f"uv-{VERSION}-{target}{suffix}" if not archive.exists(): - url = f"https://github.com/astral-sh/uv/releases/download/{VERSION}/uv-{target}.tar.gz" + url = f"https://github.com/astral-sh/uv/releases/download/{VERSION}/uv-{target}{suffix}" with urlopen(url, timeout=30) as response: content = response.read(64 * 1024 * 1024) if hashlib.sha256(content).hexdigest() != CHECKSUMS[target]: @@ -54,16 +79,8 @@ def executable(tools: Path) -> Path: content = archive.read_bytes() if hashlib.sha256(content).hexdigest() != CHECKSUMS[target]: raise SystemExit("The cached uv archive does not match the pinned official checksum.") - binary = tools / f"uv-{VERSION}-{target}" - with tarfile.open(fileobj=io.BytesIO(content), mode="r:gz") as package: - member = package.getmember(f"uv-{target}/uv") - if not member.isfile(): - raise SystemExit("The verified uv archive has no regular uv executable.") - source = package.extractfile(member) - if source is None: - raise SystemExit("The verified uv archive has no uv executable.") - with source: - binary.write_bytes(source.read()) + binary = tools / f"uv-{VERSION}-{target}{'.exe' if windows else ''}" + binary.write_bytes(unpack(content, target)) binary.chmod(0o755) if not matching(binary): raise SystemExit("The verified uv executable has an unexpected version.") diff --git a/scripts/contracts.py b/scripts/contracts.py index 6e6255a2..e7bd5925 100644 --- a/scripts/contracts.py +++ b/scripts/contracts.py @@ -13,7 +13,7 @@ def main() -> None: - document = json.loads((ROOT / "openapi.public.json").read_text()) + document = json.loads((ROOT / "openapi.public.json").read_text(encoding="utf-8")) declared = { operation["operationId"] for item in json_operations(document)["paths"].values() @@ -52,7 +52,7 @@ def main() -> None: raise SystemExit(f"{client.__name__} operations differ from the public contract.") prohibited = {"safe", "passed", "clean"} for path in (ROOT / "proofline").rglob("*.py"): - for node in ast.walk(ast.parse(path.read_text())): + for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): identifier = None if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): identifier = node.name diff --git a/scripts/generate.py b/scripts/generate.py index a35a26b6..5a0e9e15 100644 --- a/scripts/generate.py +++ b/scripts/generate.py @@ -85,7 +85,7 @@ def generate(destination: Path) -> None: raise SystemExit(f"Generation requires openapi-python-client=={VERSION}.") if importlib.metadata.version("ruff") != RUFF_VERSION: raise SystemExit(f"Generation requires ruff=={RUFF_VERSION}.") - document = json.loads(DOCUMENT.read_text()) + document = json.loads(DOCUMENT.read_text(encoding="utf-8")) # The 7.2 SDK accepts (checkpoint, due_at, result) positionally. The # generator emits optional constructor arguments in schema property order. checkpoint = document["components"]["schemas"]["DeployCoverageCheckpoint"] @@ -107,13 +107,14 @@ def generate(destination: Path) -> None: } with tempfile.TemporaryDirectory(prefix="proofline-json-contract-") as temporary: json_document = Path(temporary) / "openapi.json" - json_document.write_text(json.dumps(json_operations(document))) + json_document.write_text(json.dumps(json_operations(document)), encoding="utf-8") generate_json(destination, json_document) def check_version() -> None: - document = json.loads(DOCUMENT.read_text()) - version = tomllib.loads((ROOT / "pyproject.toml").read_text())["project"]["version"] + document = json.loads(DOCUMENT.read_text(encoding="utf-8")) + pyproject = (ROOT / "pyproject.toml").read_text(encoding="utf-8") + version = tomllib.loads(pyproject)["project"]["version"] package_version = tuple(map(int, version.split("."))) api_version = tuple(map(int, document["info"]["version"].split("."))) if package_version[:2] != api_version[:2] or package_version[2] < api_version[2]: @@ -162,8 +163,8 @@ def generate_json(destination: Path, document: Path) -> None: sync=custom["ProoflineClient"], asynchronous=custom["AsyncProoflineClient"], ) - (destination / "api/operations.py").write_text(facade) - body = json.loads(document.read_text())["paths"][ + (destination / "api/operations.py").write_text(facade, encoding="utf-8") + body = json.loads(document.read_text(encoding="utf-8"))["paths"][ "/api/v1/organizations/{org_id}/repositories/{repo_id}/pull-requests/{number}/review" ]["post"].get("requestBody") if body is not None: @@ -175,7 +176,7 @@ def generate_json(destination: Path, document: Path) -> None: ): raise SystemExit("request_review requires its optional named RunNowRequest JSON body.") endpoint = destination / "api" / "default" / "request_review.py" - source = endpoint.read_text() + source = endpoint.read_text(encoding="utf-8") header = ' headers["Content-Type"] = "application/json"\n' json_body = ( ' if not isinstance(body, Unset):\n _kwargs["json"] = body.to_dict()\n' @@ -188,7 +189,8 @@ def generate_json(destination: Path, document: Path) -> None: raise SystemExit("The pinned optional request_review body template has changed.") # The pinned generator sets this header even when its optional body is UNSET. endpoint.write_text( - source.replace(header, " if not isinstance(body, Unset):\n " + header) + source.replace(header, " if not isinstance(body, Unset):\n " + header), + encoding="utf-8", ) shutil.copyfile(ROOT / "templates" / "LICENSE.openapi-python-client", destination / "LICENSE") subprocess.run( @@ -207,7 +209,20 @@ def generate_json(destination: Path, document: Path) -> None: check=True, cwd=ROOT, ) - subprocess.run([sys.executable, "-m", "ruff", "format", str(destination)], check=True, cwd=ROOT) + # The generator writes CRLF on Windows; the committed files are LF on every OS. + subprocess.run( + [ + sys.executable, + "-m", + "ruff", + "format", + "--config", + "format.line-ending = 'lf'", + str(destination), + ], + check=True, + cwd=ROOT, + ) def files(directory: Path) -> dict[Path, bytes]: diff --git a/tests/test_generate.py b/tests/test_generate.py new file mode 100644 index 00000000..26ed06bb --- /dev/null +++ b/tests/test_generate.py @@ -0,0 +1,25 @@ +"""The committed generated API is reproducible whatever the machine's text encoding.""" + +import os +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def test_generation_does_not_depend_on_the_locale_encoding() -> None: + # Windows defaults to a legacy code page such as cp1252, and a C locale to ASCII. + # -X utf8=0 keeps Python from switching to UTF-8 on its own. + env = {name: value for name, value in os.environ.items() if name != "PYTHONUTF8"} + env.update({"LC_ALL": "C", "LANG": "C", "PYTHONCOERCECLOCALE": "0"}) + result = subprocess.run( + [sys.executable, "-X", "utf8=0", "scripts/generate.py", "--check"], + cwd=ROOT, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + ) + assert result.returncode == 0, result.stderr diff --git a/tests/test_uv.py b/tests/test_uv.py new file mode 100644 index 00000000..aa488eef --- /dev/null +++ b/tests/test_uv.py @@ -0,0 +1,46 @@ +"""The gate can bootstrap its pinned uv on Windows as well as macOS and Linux.""" + +import importlib.util +import io +import tarfile +import zipfile +from pathlib import Path + +import pytest + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts/_uv.py" +spec = importlib.util.spec_from_file_location("_uv", SCRIPT) +assert spec is not None and spec.loader is not None +uv = importlib.util.module_from_spec(spec) +spec.loader.exec_module(uv) + + +@pytest.mark.parametrize( + ("system", "machine", "target"), + [ + ("Windows", "AMD64", "x86_64-pc-windows-msvc"), + ("Windows", "ARM64", "aarch64-pc-windows-msvc"), + ("Linux", "x86_64", "x86_64-unknown-linux-gnu"), + ("Darwin", "arm64", "aarch64-apple-darwin"), + ], +) +def test_supported_platforms_have_a_pinned_archive(system: str, machine: str, target: str) -> None: + assert uv.release_target(system, machine) == target + assert target in uv.CHECKSUMS + + +def test_windows_archive_yields_its_uv_executable() -> None: + archive = io.BytesIO() + with zipfile.ZipFile(archive, "w") as package: + package.writestr("uv.exe", b"uv") + package.writestr("uvx.exe", b"uvx") + assert uv.unpack(archive.getvalue(), "x86_64-pc-windows-msvc") == b"uv" + + +def test_unix_archive_still_yields_its_uv_executable() -> None: + archive = io.BytesIO() + with tarfile.open(fileobj=archive, mode="w:gz") as package: + member = tarfile.TarInfo("uv-x86_64-unknown-linux-gnu/uv") + member.size = 2 + package.addfile(member, io.BytesIO(b"uv")) + assert uv.unpack(archive.getvalue(), "x86_64-unknown-linux-gnu") == b"uv" From 19d891f52f7c60b5960f996a2f4a2c09acc67445 Mon Sep 17 00:00:00 2001 From: Ahmar Ali Date: Mon, 23 Nov 2026 07:17:57 +0500 Subject: [PATCH 2/5] Accept CRLF working copies in generate.py --check and test the Windows bootstrap Proofline review, round 1: - .gitattributes only changes how files are checked out from now on. A Windows clone made before it keeps CRLF files, so --check still said "differs" there, although Git stores the same LF content. files() now compares text with CRLF turned into LF (files containing a NUL byte, i.e. binary files, stay byte-exact). Line-ending drift can't be committed anyway: .gitattributes makes Git store LF. - Because the check now ignores line endings, a new test checks the generator's own output for CRLF, so the LF option stays covered. - test_uv.py only tested the helpers, so executable() could have asked for a .tar.gz or saved a file without .exe on Windows and still passed. A new test runs executable() for both Windows targets with a fake download and checks the .zip URL, the .exe path and the bytes. Each of the four guarded lines was mutated and made its test fail. --- scripts/generate.py | 7 ++++++- tests/test_generate.py | 27 +++++++++++++++++++++++++++ tests/test_uv.py | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 1 deletion(-) diff --git a/scripts/generate.py b/scripts/generate.py index 5a0e9e15..7f2f3c72 100644 --- a/scripts/generate.py +++ b/scripts/generate.py @@ -225,9 +225,14 @@ def generate_json(destination: Path, document: Path) -> None: ) +def text(content: bytes) -> bytes: + # .gitattributes stores text with LF, so a CRLF working copy is the same file. + return content if b"\0" in content else content.replace(b"\r\n", b"\n") + + def files(directory: Path) -> dict[Path, bytes]: return { - path.relative_to(directory): path.read_bytes() + path.relative_to(directory): text(path.read_bytes()) for path in directory.rglob("*") if path.is_file() and "__pycache__" not in path.parts } diff --git a/tests/test_generate.py b/tests/test_generate.py index 26ed06bb..8b72f738 100644 --- a/tests/test_generate.py +++ b/tests/test_generate.py @@ -1,9 +1,11 @@ """The committed generated API is reproducible whatever the machine's text encoding.""" +import importlib.util import os import subprocess import sys from pathlib import Path +from types import ModuleType ROOT = Path(__file__).resolve().parents[1] @@ -23,3 +25,28 @@ def test_generation_does_not_depend_on_the_locale_encoding() -> None: errors="replace", ) assert result.returncode == 0, result.stderr + + +def load_generate() -> ModuleType: + spec = importlib.util.spec_from_file_location("generate", ROOT / "scripts/generate.py") + assert spec is not None and spec.loader is not None + generate = importlib.util.module_from_spec(spec) + spec.loader.exec_module(generate) + return generate + + +def test_check_treats_a_crlf_working_copy_as_unchanged() -> None: + generate = load_generate() + assert generate.text(b"a = 1\r\nb = 2\r\n") == b"a = 1\nb = 2\n" + assert generate.text(b"\0binary\r\n") == b"\0binary\r\n" + + +def test_generated_files_use_lf_line_endings(tmp_path: Path) -> None: + # Windows text writes produce CRLF; the check compares with line endings + # normalized, so assert the generator's own output directly. + generate = load_generate() + destination = tmp_path / "generated" + generate.generate(destination) + files = [path for path in destination.rglob("*") if path.is_file()] + assert files + assert [path for path in files if b"\r\n" in path.read_bytes()] == [] diff --git a/tests/test_uv.py b/tests/test_uv.py index aa488eef..95e093c7 100644 --- a/tests/test_uv.py +++ b/tests/test_uv.py @@ -1,5 +1,6 @@ """The gate can bootstrap its pinned uv on Windows as well as macOS and Linux.""" +import hashlib import importlib.util import io import tarfile @@ -37,6 +38,37 @@ def test_windows_archive_yields_its_uv_executable() -> None: assert uv.unpack(archive.getvalue(), "x86_64-pc-windows-msvc") == b"uv" +@pytest.mark.parametrize( + ("machine", "target"), + [("AMD64", "x86_64-pc-windows-msvc"), ("ARM64", "aarch64-pc-windows-msvc")], +) +def test_windows_bootstrap_downloads_the_zip_and_saves_an_exe( + machine: str, target: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + archive = io.BytesIO() + with zipfile.ZipFile(archive, "w") as package: + package.writestr("uv.exe", b"uv") + content = archive.getvalue() + requested = [] + + def download(url: str, timeout: int) -> io.BytesIO: + requested.append(url) + return io.BytesIO(content) + + monkeypatch.setattr(uv.shutil, "which", lambda name: None) + monkeypatch.setattr(uv.platform, "system", lambda: "Windows") + monkeypatch.setattr(uv.platform, "machine", lambda: machine) + monkeypatch.setattr(uv, "urlopen", download) + monkeypatch.setitem(uv.CHECKSUMS, target, hashlib.sha256(content).hexdigest()) + monkeypatch.setattr(uv, "matching", lambda executable: True) + binary = uv.executable(tmp_path) + assert requested == [ + f"https://github.com/astral-sh/uv/releases/download/{uv.VERSION}/uv-{target}.zip" + ] + assert binary == tmp_path / f"uv-{uv.VERSION}-{target}.exe" + assert binary.read_bytes() == b"uv" + + def test_unix_archive_still_yields_its_uv_executable() -> None: archive = io.BytesIO() with tarfile.open(fileobj=archive, mode="w:gz") as package: From c7c8fe278eac334a491a87c32595714519537d51 Mon Sep 17 00:00:00 2001 From: Ahmar Ali Date: Mon, 23 Nov 2026 07:22:02 +0500 Subject: [PATCH 3/5] Test the CRLF comparison, LF formatting and checksum refusal on every OS Proofline review, round 2: - The CRLF test called text() directly, so files() could stop using it and the test would still pass. It now compares files() on an LF folder and a CRLF folder, and checks that a file with a NUL byte is still compared byte for byte. - The LF test ran the whole generator, but on Linux the generator already writes LF, so CI could not notice if the LF option were removed. The ruff format step is now format_python(), and the test feeds it a CRLF file, so it fails on any OS without the option. - Nothing checked that a Windows zip with a wrong checksum is refused. A new test covers a fresh download (refused and never saved) and a cached archive (refused and never extracted). Each guarded line was mutated and made its test fail. --- scripts/generate.py | 4 ++++ tests/test_generate.py | 30 +++++++++++++------------ tests/test_uv.py | 51 +++++++++++++++++++++++++++++++++--------- 3 files changed, 61 insertions(+), 24 deletions(-) diff --git a/scripts/generate.py b/scripts/generate.py index 7f2f3c72..ac0ac605 100644 --- a/scripts/generate.py +++ b/scripts/generate.py @@ -209,6 +209,10 @@ def generate_json(destination: Path, document: Path) -> None: check=True, cwd=ROOT, ) + format_python(destination) + + +def format_python(destination: Path) -> None: # The generator writes CRLF on Windows; the committed files are LF on every OS. subprocess.run( [ diff --git a/tests/test_generate.py b/tests/test_generate.py index 8b72f738..801c4bfd 100644 --- a/tests/test_generate.py +++ b/tests/test_generate.py @@ -35,18 +35,20 @@ def load_generate() -> ModuleType: return generate -def test_check_treats_a_crlf_working_copy_as_unchanged() -> None: +def test_check_treats_a_crlf_working_copy_as_unchanged(tmp_path: Path) -> None: generate = load_generate() - assert generate.text(b"a = 1\r\nb = 2\r\n") == b"a = 1\nb = 2\n" - assert generate.text(b"\0binary\r\n") == b"\0binary\r\n" - - -def test_generated_files_use_lf_line_endings(tmp_path: Path) -> None: - # Windows text writes produce CRLF; the check compares with line endings - # normalized, so assert the generator's own output directly. - generate = load_generate() - destination = tmp_path / "generated" - generate.generate(destination) - files = [path for path in destination.rglob("*") if path.is_file()] - assert files - assert [path for path in files if b"\r\n" in path.read_bytes()] == [] + for name, newline in (("lf", b"\n"), ("crlf", b"\r\n")): + (tmp_path / name / "models").mkdir(parents=True) + (tmp_path / name / "models" / "a.py").write_bytes(b"a = 1" + newline + b"b = 2" + newline) + assert generate.files(tmp_path / "lf") == generate.files(tmp_path / "crlf") + # A file with a NUL byte is binary and still compared byte for byte. + (tmp_path / "lf" / "data.bin").write_bytes(b"\0\n") + (tmp_path / "crlf" / "data.bin").write_bytes(b"\0\r\n") + assert generate.files(tmp_path / "lf") != generate.files(tmp_path / "crlf") + + +def test_generated_python_is_formatted_with_lf_line_endings(tmp_path: Path) -> None: + # Windows text writes produce CRLF; the formatting step must turn them into LF. + (tmp_path / "model.py").write_bytes(b"a = 1\r\nb = 2\r\n") + load_generate().format_python(tmp_path) + assert (tmp_path / "model.py").read_bytes() == b"a = 1\nb = 2\n" diff --git a/tests/test_uv.py b/tests/test_uv.py index 95e093c7..b4964e68 100644 --- a/tests/test_uv.py +++ b/tests/test_uv.py @@ -38,18 +38,16 @@ def test_windows_archive_yields_its_uv_executable() -> None: assert uv.unpack(archive.getvalue(), "x86_64-pc-windows-msvc") == b"uv" -@pytest.mark.parametrize( - ("machine", "target"), - [("AMD64", "x86_64-pc-windows-msvc"), ("ARM64", "aarch64-pc-windows-msvc")], -) -def test_windows_bootstrap_downloads_the_zip_and_saves_an_exe( - machine: str, target: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: +def windows_zip() -> bytes: archive = io.BytesIO() with zipfile.ZipFile(archive, "w") as package: package.writestr("uv.exe", b"uv") - content = archive.getvalue() - requested = [] + return archive.getvalue() + + +def fake_windows(monkeypatch: pytest.MonkeyPatch, machine: str, content: bytes) -> list[str]: + """Pretend to be Windows with no matching uv installed; serve `content` as the release.""" + requested: list[str] = [] def download(url: str, timeout: int) -> io.BytesIO: requested.append(url) @@ -59,8 +57,20 @@ def download(url: str, timeout: int) -> io.BytesIO: monkeypatch.setattr(uv.platform, "system", lambda: "Windows") monkeypatch.setattr(uv.platform, "machine", lambda: machine) monkeypatch.setattr(uv, "urlopen", download) - monkeypatch.setitem(uv.CHECKSUMS, target, hashlib.sha256(content).hexdigest()) monkeypatch.setattr(uv, "matching", lambda executable: True) + return requested + + +@pytest.mark.parametrize( + ("machine", "target"), + [("AMD64", "x86_64-pc-windows-msvc"), ("ARM64", "aarch64-pc-windows-msvc")], +) +def test_windows_bootstrap_downloads_the_zip_and_saves_an_exe( + machine: str, target: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + content = windows_zip() + requested = fake_windows(monkeypatch, machine, content) + monkeypatch.setitem(uv.CHECKSUMS, target, hashlib.sha256(content).hexdigest()) binary = uv.executable(tmp_path) assert requested == [ f"https://github.com/astral-sh/uv/releases/download/{uv.VERSION}/uv-{target}.zip" @@ -69,6 +79,27 @@ def download(url: str, timeout: int) -> io.BytesIO: assert binary.read_bytes() == b"uv" +@pytest.mark.parametrize( + ("cached", "message"), + [(False, "release archive does not match"), (True, "cached uv archive does not match")], +) +def test_windows_zip_with_a_wrong_checksum_is_refused( + cached: bool, message: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + content = windows_zip() + fake_windows(monkeypatch, "AMD64", content) + target = "x86_64-pc-windows-msvc" + monkeypatch.setitem(uv.CHECKSUMS, target, "0" * 64) + archive = tmp_path / f"uv-{uv.VERSION}-{target}.zip" + if cached: + archive.write_bytes(content) + with pytest.raises(SystemExit, match=message): + uv.executable(tmp_path) + # A rejected download is never saved, and a rejected archive is never extracted. + assert archive.exists() == cached + assert not (tmp_path / f"uv-{uv.VERSION}-{target}.exe").exists() + + def test_unix_archive_still_yields_its_uv_executable() -> None: archive = io.BytesIO() with tarfile.open(fileobj=archive, mode="w:gz") as package: From 3ededd960b2787c29204e2c354d44d14ca2413fc Mon Sep 17 00:00:00 2001 From: Ahmar Ali Date: Mon, 23 Nov 2026 07:25:10 +0500 Subject: [PATCH 4/5] Check the version test and verify-before-unpack in the Windows bootstrap tests Proofline review, round 3: - The Windows bootstrap test accepted any version check. It now records which executable matching() was asked about and expects exactly the returned uv.exe. - The wrong-checksum test now fails if unpack() runs, so an archive can't be unpacked before its checksum is checked. Both were mutation-checked: skipping the version check, or unpacking a cached archive before verifying it, now fails a test. --- tests/test_uv.py | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/tests/test_uv.py b/tests/test_uv.py index b4964e68..1396fed4 100644 --- a/tests/test_uv.py +++ b/tests/test_uv.py @@ -45,9 +45,15 @@ def windows_zip() -> bytes: return archive.getvalue() -def fake_windows(monkeypatch: pytest.MonkeyPatch, machine: str, content: bytes) -> list[str]: - """Pretend to be Windows with no matching uv installed; serve `content` as the release.""" +def fake_windows( + monkeypatch: pytest.MonkeyPatch, machine: str, content: bytes +) -> tuple[list[str], list[Path]]: + """Pretend to be Windows with no matching uv installed; serve `content` as the release. + + Returns the requested URLs and the executables whose version was checked. + """ requested: list[str] = [] + checked: list[Path] = [] def download(url: str, timeout: int) -> io.BytesIO: requested.append(url) @@ -57,8 +63,13 @@ def download(url: str, timeout: int) -> io.BytesIO: monkeypatch.setattr(uv.platform, "system", lambda: "Windows") monkeypatch.setattr(uv.platform, "machine", lambda: machine) monkeypatch.setattr(uv, "urlopen", download) - monkeypatch.setattr(uv, "matching", lambda executable: True) - return requested + + def matching(executable: Path) -> bool: + checked.append(executable) + return True + + monkeypatch.setattr(uv, "matching", matching) + return requested, checked @pytest.mark.parametrize( @@ -69,7 +80,7 @@ def test_windows_bootstrap_downloads_the_zip_and_saves_an_exe( machine: str, target: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: content = windows_zip() - requested = fake_windows(monkeypatch, machine, content) + requested, checked = fake_windows(monkeypatch, machine, content) monkeypatch.setitem(uv.CHECKSUMS, target, hashlib.sha256(content).hexdigest()) binary = uv.executable(tmp_path) assert requested == [ @@ -77,6 +88,7 @@ def test_windows_bootstrap_downloads_the_zip_and_saves_an_exe( ] assert binary == tmp_path / f"uv-{uv.VERSION}-{target}.exe" assert binary.read_bytes() == b"uv" + assert checked == [binary] @pytest.mark.parametrize( @@ -90,6 +102,11 @@ def test_windows_zip_with_a_wrong_checksum_is_refused( fake_windows(monkeypatch, "AMD64", content) target = "x86_64-pc-windows-msvc" monkeypatch.setitem(uv.CHECKSUMS, target, "0" * 64) + + def unpack(content: bytes, target: str) -> bytes: + raise AssertionError("an unverified archive was unpacked") + + monkeypatch.setattr(uv, "unpack", unpack) archive = tmp_path / f"uv-{uv.VERSION}-{target}.zip" if cached: archive.write_bytes(content) From 4913069db996dff9bbcfcbf30f2772a91abb61ef Mon Sep 17 00:00:00 2001 From: Ahmar Ali Date: Mon, 23 Nov 2026 07:28:03 +0500 Subject: [PATCH 5/5] Test that the Windows bootstrap refuses an unexpected uv version Proofline review, round 4: the Windows tests always made the version check succeed, so executable() could ignore its result and still pass. A new test serves a zip with a valid checksum, makes the version check fail, and expects "The verified uv executable has an unexpected version." Ignoring the result (mutation) now fails the test. --- tests/test_uv.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/tests/test_uv.py b/tests/test_uv.py index 1396fed4..2588b456 100644 --- a/tests/test_uv.py +++ b/tests/test_uv.py @@ -91,6 +91,17 @@ def test_windows_bootstrap_downloads_the_zip_and_saves_an_exe( assert checked == [binary] +def test_windows_bootstrap_refuses_an_unexpected_uv_version( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + content = windows_zip() + fake_windows(monkeypatch, "AMD64", content) + monkeypatch.setitem(uv.CHECKSUMS, "x86_64-pc-windows-msvc", hashlib.sha256(content).hexdigest()) + monkeypatch.setattr(uv, "matching", lambda executable: False) + with pytest.raises(SystemExit, match="unexpected version"): + uv.executable(tmp_path) + + @pytest.mark.parametrize( ("cached", "message"), [(False, "release archive does not match"), (True, "cached uv archive does not match")],