"""A remote server that rejects the API key stops the run with one line; an unreachable one keeps the stub.""" from __future__ import annotations import json from collections.abc import Iterator from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from threading import Thread import click import pytest from click.testing import CliRunner from unshackle.commands.dl import dl from unshackle.core import remote_service from unshackle.core.api import handlers from unshackle.core.api.errors import APIError from unshackle.core.config import config from unshackle.core.remote_protocol import APIErrorCode from unshackle.core.services import Services from unshackle.core.utilities import get_free_port KEY = "0" * 32 class Gateway(BaseHTTPRequestHandler): calls = 0 def do_GET(self) -> None: Gateway.calls += 1 body = json.dumps({"error": "unauthorized"}).encode() self.send_response(401) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, *args: object) -> None: pass @pytest.fixture def servers(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: httpd = ThreadingHTTPServer(("127.0.0.1", 0), Gateway) Thread(target=httpd.serve_forever, daemon=True).start() closed_port = get_free_port() monkeypatch.setattr( config, "remote_services", { "keyed": {"url": f"http://127.0.0.1:{httpd.server_address[1]}", "api_key": KEY}, "down": {"url": f"http://127.0.0.1:{closed_port}", "api_key": KEY}, }, ) remote_service.reset_remote_lists() Gateway.calls = 0 yield remote_service.reset_remote_lists() httpd.shutdown() httpd.server_close() def test_a_rejected_key_stops_dl_with_one_line_not_a_stub_parse_error(servers: None) -> None: result = CliRunner().invoke(dl.cli, ["--remote", "--server", "keyed", "EXAMPLE", "-ht", "1"]) assert result.exit_code != 0 assert "rejected the API key (HTTP 401)" in result.output assert "No such option" not in result.output assert KEY not in result.output def test_an_unreachable_server_keeps_the_stub_command(servers: None) -> None: cmd = Services.make_remote_command("EXAMPLE", "down") assert cmd.name == "EXAMPLE" assert cmd.help is None def test_remote_list_answers_a_rejected_key_as_auth_failed(servers: None) -> None: with pytest.raises(APIError) as e: handlers.remote_list("keyed") assert e.value.error_code == APIErrorCode.AUTH_FAILED and e.value.http_status == 424 assert "rejected the API key" in e.value.message and "\n" not in e.value.message def test_a_cached_rejection_raises_again_without_a_new_request(servers: None) -> None: raised = [] for _ in range(2): with pytest.raises(click.ClickException) as e: remote_service.remote_service_list("keyed") raised.append(e.value) calls = Gateway.calls with pytest.raises(click.ClickException) as e: remote_service.make_remote_service(None, "keyed", "EXAMPLE", "1", {}) assert Gateway.calls == calls assert raised[0] is not raised[1] assert e.value.error_code == APIErrorCode.AUTH_FAILED