wireframe 0.4.0-alpha1

Simplify building servers and clients for custom binary protocols.
Documentation
"""Specify the workspace release commands against a scripted registry."""

import hashlib
import itertools
import json
import typing as typ
import urllib.error

import pytest
from crates_io_transport_http import DOWNLOAD_ATTEMPTS
from crates_io_transport_support import FakeOpener, FakeResponse, missing_response
from release_reconcile_crates import RegistryState
from release_workspace_cli import EXIT_OK, EXIT_REFUSED, main
from release_workspace_policy import (
    SurveyError,
    plan_publication,
    plan_rehearsal,
    verify_published,
)
from release_workspace_registry import Registry, observe_state
from verify_crates_io_bytes import (
    ArchiveAbsentError,
    DownloadAvailability,
    DownloadObservation,
)
from workspace_candidate import CrateArchive, read_candidate
from workspace_candidate_support import COMMIT, CRATES, VERSION, write_release

if typ.TYPE_CHECKING:
    import pathlib

TAG = f"v{VERSION}"
REFUSED_STATES = (
    RegistryState.CONFLICT,
    RegistryState.YANKED,
    RegistryState.INDETERMINATE,
)


class Release(typ.NamedTuple):
    """Carry the paths one recorded candidate occupies."""

    root: pathlib.Path
    packages: pathlib.Path
    candidate: pathlib.Path

    def record(self, tag: str) -> int:
        """Record the packaged archives, returning the exit code."""
        return main([
            "record",
            *("--candidate", str(self.candidate), "--commit", COMMIT, "--tag", tag),
            *("--package-directory", str(self.packages)),
            *("--workspace-root", str(self.root)),
        ])

    def digests(self) -> list[str]:
        """Return the recorded digests, in publish order."""
        return [crate.sha256 for crate in read_candidate(self.candidate).crates]

    def survey(self, *outcomes: FakeResponse | BaseException) -> tuple[int, str]:
        """Survey a scripted registry, returning the exit code and outputs."""
        output = self.root / "github-output"
        registry = Registry(FakeOpener(*outcomes), lambda _delay: None)
        arguments = ["survey", "--candidate", str(self.candidate)]
        arguments += ["--github-output", str(output)]
        result = main(arguments, registry=registry)
        return result, output.read_text() if output.exists() else ""

    def verify(self, *outcomes: FakeResponse | BaseException) -> int:
        """Verify against a scripted registry, returning the exit code."""
        registry = Registry(FakeOpener(*outcomes), lambda _delay: None)
        return main(["verify", "--candidate", str(self.candidate)], registry=registry)


@pytest.fixture
def release(tmp_path: pathlib.Path) -> Release:
    """Return a packaged workspace whose candidate is not yet recorded."""
    return Release(tmp_path, write_release(tmp_path), tmp_path / "retained" / "candidate.json")


def published(digest: str, *, version: str = VERSION) -> FakeResponse:
    """Return crates.io's answer for one published version."""
    record = {"num": version, "checksum": digest, "yanked": False}
    return FakeResponse(200, json.dumps({"version": record}).encode())


def absent() -> urllib.error.HTTPError:
    """Return crates.io's answer for a version that does not exist."""
    return missing_response("https://crates.io/api/v1/crates/wireframe/1", b"{}")


def test_only_the_recorded_archives_are_retained(release: Release) -> None:
    """An archive left over from another version is not part of the candidate."""
    (release.packages / "wireframe-0.0.1.crate").write_bytes(b"stale")
    release.record(TAG)
    retained = {path.name for path in release.candidate.parent.iterdir()}
    assert retained == {
        "candidate.json",
        *(f"{name}-{VERSION}.crate" for name in CRATES),
    }


def test_an_unpublished_release_is_published(release: Release) -> None:
    """Every crate is absent, so the run publishes the recorded version."""
    assert release.record(TAG) == EXIT_OK
    before = set(release.root.rglob("*"))

    result, outputs = release.survey(absent(), absent())

    assert (result, outputs) == (EXIT_OK, f"action=publish\nversion={VERSION}\n")
    assert set(release.root.rglob("*")) - before == {release.root / "github-output"}


def test_an_interrupted_release_resumes(release: Release) -> None:
    """A published first crate does not stop the second from being published."""
    release.record(TAG)
    result, outputs = release.survey(published(release.digests()[0]), absent())
    assert result == EXIT_OK
    assert "action=publish\n" in outputs


def test_a_completed_release_is_skipped(release: Release) -> None:
    """Re-running a finished release asks for no credential."""
    release.record(TAG)
    result, outputs = release.survey(*map(published, release.digests()))
    assert result == EXIT_OK
    assert "action=skip\n" in outputs


@pytest.mark.parametrize(
    "outcome",
    [
        pytest.param(published("ab" * 32), id="different-bytes"),
        pytest.param(FakeResponse(503, b"{}"), id="server-error"),
        pytest.param(FakeResponse(200, b"\xff"), id="undecodable"),
        pytest.param(FakeResponse(200, b"[]"), id="unexpected-shape"),
        pytest.param(urllib.error.URLError("offline"), id="offline"),
    ],
)
def test_a_release_refuses_anything_but_absence_or_identity(
    release: Release,
    outcome: FakeResponse | BaseException,
    capsys: pytest.CaptureFixture[str],
) -> None:
    """No uncertain or conflicting answer reaches the publishing step."""
    release.record(TAG)
    result, outputs = release.survey(absent(), outcome)
    assert result == EXIT_REFUSED
    assert "action" not in outputs
    assert CRATES[1] in capsys.readouterr().err


def test_a_rehearsal_of_a_published_version_is_skipped(release: Release) -> None:
    """A pull request before the version bump has nothing to rehearse."""
    release.record("")
    result, outputs = release.survey(published("ab" * 32), published("cd" * 32))
    assert result == EXIT_OK
    assert "action=skip\n" in outputs


@pytest.mark.parametrize(
    "states", list(itertools.product(RegistryState, repeat=2))
)
def test_the_plans_agree_except_on_known_version_conflicts(
    states: tuple[RegistryState, RegistryState],
) -> None:
    """Only an observed conflict or yank may skip a rehearsal."""
    named = dict(zip(CRATES, states, strict=True))
    if any(state in REFUSED_STATES for state in states):
        with pytest.raises(SurveyError):
            plan_publication(named)
        if RegistryState.INDETERMINATE in states:
            with pytest.raises(SurveyError):
                plan_rehearsal(named)
        else:
            assert plan_rehearsal(named) == "skip"
    else:
        assert plan_rehearsal(named) == plan_publication(named)


def test_published_bytes_that_match_are_verified(release: Release) -> None:
    """Each archive is downloaded and compared with its recorded digest."""
    release.record(TAG)
    archives = [
        FakeResponse(200, (release.packages / crate.filename).read_bytes())
        for crate in read_candidate(release.candidate).crates
    ]
    assert release.verify(*archives) == EXIT_OK


def test_verification_yields_each_archive_without_reporting_success(
    release: Release, capsys: pytest.CaptureFixture[str]
) -> None:
    """Verification consumes typed observations and leaves output to its caller."""
    release.record(TAG)
    candidate = read_candidate(release.candidate)

    def matched(crate: CrateArchive) -> DownloadObservation:
        """Return the matching observation for the requested crate."""
        return DownloadObservation(DownloadAvailability.PRESENT, crate.sha256)

    assert tuple(verify_published(candidate, matched)) == candidate.crates
    assert capsys.readouterr().out == "", "the verifier must leave reporting to the caller"


def test_verification_stops_when_an_archive_is_absent(release: Release) -> None:
    """An absent archive must never be yielded as verified."""
    release.record(TAG)
    candidate = read_candidate(release.candidate)

    def absent_observation(_crate: CrateArchive) -> DownloadObservation:
        """Report that the requested archive does not exist."""
        return DownloadObservation(DownloadAvailability.ABSENT)

    with pytest.raises(ArchiveAbsentError, match=candidate.crates[0].name):
        next(verify_published(candidate, absent_observation))


@pytest.mark.parametrize(
    "outcome",
    [
        pytest.param(FakeResponse(200, b"different"), id="different-bytes"),
        pytest.param(FakeResponse(422, b""), id="unusable-status"),
        pytest.param(FakeResponse(200, b"<?xml absent"), id="absent-key"),
    ],
)
def test_published_bytes_that_differ_fail_verification(
    release: Release, outcome: FakeResponse
) -> None:
    """A release is not complete until the registry serves the candidate."""
    release.record(TAG)
    first = read_candidate(release.candidate).crates[0]
    archive = FakeResponse(200, (release.packages / first.filename).read_bytes())
    assert release.verify(archive, outcome) == EXIT_REFUSED


def test_the_check_command_refuses_a_rebuilt_archive(release: Release) -> None:
    """The publishing job repeats the check before it asks for a credential."""
    release.record(TAG)
    arguments = ["check", "--candidate", str(release.candidate), "--tag", TAG]
    arguments += ["--commit", COMMIT, "--package-directory", str(release.packages)]
    assert main(arguments) == EXIT_OK
    (release.packages / f"{CRATES[0]}-{VERSION}.crate").write_bytes(b"rebuilt")
    assert main(arguments) == EXIT_REFUSED


def test_a_tag_for_another_version_records_nothing(release: Release) -> None:
    """A mistyped tag stops before any candidate exists."""
    assert release.record("v9.9.9") == EXIT_REFUSED
    assert not release.candidate.exists()


def test_verification_refuses_a_download_without_an_http_response(
    release: Release, capsys: pytest.CaptureFixture[str]
) -> None:
    """Exhausting the download budget reports the transport failure."""
    release.record(TAG)
    offline = [urllib.error.URLError("offline") for _ in range(DOWNLOAD_ATTEMPTS)]

    assert release.verify(*offline) == EXIT_REFUSED
    captured = capsys.readouterr()
    assert "download returned no HTTP response" in captured.err
    assert "offline" in captured.err
    assert captured.out == ""


@pytest.mark.parametrize(
    ("outcome", "reason"),
    [
        pytest.param(FakeResponse(200, b"[]"), "unreadable registry answer", id="shape"),
        pytest.param(urllib.error.URLError("offline"), "offline", id="offline"),
    ],
)
def test_observation_returns_its_reason_instead_of_printing_it(
    release: Release,
    outcome: FakeResponse | BaseException,
    reason: str,
    capsys: pytest.CaptureFixture[str],
) -> None:
    """Only the command boundary writes to standard error."""
    release.record(TAG)
    crate = read_candidate(release.candidate).crates[0]
    _ = capsys.readouterr()
    registry = Registry(FakeOpener(outcome), lambda _delay: None)

    observed = observe_state(crate, registry)

    assert observed.state is RegistryState.INDETERMINATE, "fail closed"
    assert capsys.readouterr().err == "", "observation must not print diagnostics"
    assert reason in observed.reason, "return why the state is unknown"


@pytest.mark.parametrize("tag", [TAG, ""], ids=["release", "rehearsal"])
def test_the_survey_command_reports_an_unreadable_crate(
    release: Release, capsys: pytest.CaptureFixture[str], tag: str
) -> None:
    """The survey reports observation failures and refuses either mode."""
    release.record(tag)

    result, outputs = release.survey(absent(), FakeResponse(200, b"[]"))

    assert result == EXIT_REFUSED, "an unreadable crate must fail the survey"
    assert not outputs, "a failed survey must publish no action"
    assert f"{CRATES[1]}: unreadable registry answer" in capsys.readouterr().err, (
        "the command boundary must report the observation's reason"
    )


def test_the_digests_command_lists_the_recorded_archives(release: Release) -> None:
    """lading receives each retained archive's real digest, in publish order."""
    release.record(TAG)
    output = release.root / "expected-digests"
    arguments = ["digests", "--candidate", str(release.candidate)]
    assert main([*arguments, "--output", str(output)]) == EXIT_OK
    expected = [
        f"{hashlib.sha256((release.packages / name).read_bytes()).hexdigest()}  {name}"
        for name in (f"{crate}-{VERSION}.crate" for crate in CRATES)
    ]
    assert output.read_text(encoding="utf-8").splitlines() == expected


def test_the_digests_command_refuses_a_malformed_record(release: Release) -> None:
    """Nothing is written when the record cannot be read."""
    release.candidate.parent.mkdir(parents=True)
    release.candidate.write_text("{}", encoding="utf-8")
    output = release.root / "expected-digests"
    arguments = ["digests", "--candidate", str(release.candidate)]
    assert main([*arguments, "--output", str(output)]) == EXIT_REFUSED
    assert not output.exists()