diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 874b79fa..99692359 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -496,13 +496,6 @@ def _paged(endpoint: str, key: str = "check_runs") -> list: return list(_iter_paged(endpoint, key)) -def _with_file(content: str) -> Path: - fd, name = tempfile.mkstemp(suffix=".loopzero", text=True) - with open(fd, "w", encoding="utf-8") as handle: - handle.write(content) - return Path(name) - - def api_get(endpoint: str) -> object: """`gh api ` parsed as JSON (None on an empty body).""" return _gh_json("api", endpoint) @@ -530,11 +523,12 @@ def _not_found(number: int, exc: Exception) -> GhError: def _api(endpoint: str, payload: dict, method: str = "POST", token: str | None = None) -> object: - path = _with_file(json.dumps(payload)) - try: - return _gh_json("api", endpoint, "--method", method, "--input", str(path), token=token) - finally: - path.unlink(missing_ok=True) + with tempfile.NamedTemporaryFile( + mode="w", suffix=".loopzero", encoding="utf-8", delete_on_close=False + ) as handle: + handle.write(json.dumps(payload)) + handle.close() + return _gh_json("api", endpoint, "--method", method, "--input", handle.name, token=token) def merge_hold(number: int, labels: tuple[str, ...]) -> str | None: diff --git a/tests/test_gh_contract.py b/tests/test_gh_contract.py index 9f31898a..2869e0df 100644 --- a/tests/test_gh_contract.py +++ b/tests/test_gh_contract.py @@ -2,11 +2,15 @@ from __future__ import annotations +import errno import json import os import re +import resource import shutil +import signal import subprocess +import tempfile from pathlib import Path import pytest @@ -27,6 +31,22 @@ REAL_GH = shutil.which("gh") +def test_api_removes_payload_when_staging_fails(tmp_path, monkeypatch): + monkeypatch.setattr(tempfile, "tempdir", str(tmp_path)) + monkeypatch.setattr(github, "_gh_json", lambda *args, **kwargs: pytest.fail("unexpected dispatch")) + original_limit = resource.getrlimit(resource.RLIMIT_FSIZE) + handler = signal.signal(signal.SIGXFSZ, signal.SIG_IGN) + try: + resource.setrlimit(resource.RLIMIT_FSIZE, (0, original_limit[1])) + with pytest.raises(OSError) as failure: + github._api("repos/example/project/issues", {"body": "synthetic"}) + finally: + resource.setrlimit(resource.RLIMIT_FSIZE, original_limit) + signal.signal(signal.SIGXFSZ, handler) + assert failure.value.errno == errno.EFBIG + assert not list(tmp_path.glob("*.loopzero")) + + @pytest.fixture(scope="module") def captured_argv(tmp_path_factory: pytest.TempPathFactory) -> list[dict]: """Drive every public operation through production code and retain its exact argv."""