from __future__ import annotations

import urllib.error

import pytest

from bootstrap.payload import BootstrapAlreadyClaimed, fetch_bootstrap_payload


def test_fetch_bootstrap_payload_raises_claimed_on_409(monkeypatch) -> None:
    def _raise_409(*_args, **_kwargs):
        raise urllib.error.HTTPError(
            url="http://server/runs/run-1/bootstrap",
            code=409,
            msg="Conflict",
            hdrs=None,
            fp=None,
        )

    monkeypatch.setattr("bootstrap.payload._urlopen_json_with_retries", _raise_409)

    with pytest.raises(BootstrapAlreadyClaimed):
        fetch_bootstrap_payload("http://server", "run-1", "token")


def test_fetch_bootstrap_payload_reraises_other_http_errors(monkeypatch) -> None:
    def _raise_500(*_args, **_kwargs):
        raise urllib.error.HTTPError(
            url="http://server/runs/run-1/bootstrap",
            code=500,
            msg="Server error",
            hdrs=None,
            fp=None,
        )

    monkeypatch.setattr("bootstrap.payload._urlopen_json_with_retries", _raise_500)

    with pytest.raises(urllib.error.HTTPError) as exc_info:
        fetch_bootstrap_payload("http://server", "run-1", "token")

    assert exc_info.value.code == 500
