"""HTTP client: retries, error surfaces and non-replayable POSTs.""" from __future__ import annotations import unittest from proxdomain.errors import ApiError from proxdomain.http import JsonClient from tests.support import FakeTransport def client(transport: FakeTransport, **kwargs) -> JsonClient: return JsonClient( "https://api.example.com", transport=transport, retries=kwargs.pop("retries", 2), sleep=lambda _seconds: None, **kwargs, ) class RetryTests(unittest.TestCase): def test_get_is_retried_on_502(self) -> None: transport = FakeTransport() transport.add("GET", "/x", {"errors": [{"message": "bad gateway"}]}, status=502) with self.assertRaises(ApiError) as ctx: client(transport).get("/x") self.assertEqual(transport.count("GET", "/x"), 3) self.assertEqual(ctx.exception.status, 502) self.assertIn("bad gateway", str(ctx.exception)) def test_post_is_not_replayed_on_502(self) -> None: transport = FakeTransport() transport.add("POST", "/y", {"errors": [{"message": "bad gateway"}]}, status=502) with self.assertRaises(ApiError): client(transport).post("/y", {"name": "web01"}) self.assertEqual(transport.count("POST", "/y"), 1) def test_post_is_retried_on_429(self) -> None: transport = FakeTransport() transport.add("POST", "/y", {"errors": [{"message": "rate limited"}]}, status=429) with self.assertRaises(ApiError): client(transport).post("/y", {"name": "web01"}) self.assertEqual(transport.count("POST", "/y"), 3) def test_success_returns_parsed_json(self) -> None: transport = FakeTransport() transport.add("GET", "/z", {"ok": True}) self.assertEqual(client(transport).get("/z"), {"ok": True}) def test_delete_missing_is_returned_as_error(self) -> None: transport = FakeTransport() transport.add("DELETE", "/z/1", {"success": False}, status=404) with self.assertRaises(ApiError) as ctx: client(transport).delete("/z/1") self.assertEqual(ctx.exception.status, 404) def test_retries_can_be_disabled(self) -> None: transport = FakeTransport() transport.add("GET", "/x", {"errors": []}, status=503) with self.assertRaises(ApiError): client(transport, retries=0).get("/x") self.assertEqual(transport.count("GET", "/x"), 1) if __name__ == "__main__": unittest.main()