"""Tests for HTTP client retry logic.""" import httpx import pytest import respx from finn_eiendom.http import HTTPClient @pytest.mark.asyncio async def test_get_retries_on_500(): """Test that HTTPClient retries on 500 errors and succeeds on second attempt.""" client = HTTPClient(request_delay_seconds=0.0, retries=2) with respx.mock: route = respx.get("https://example.com/api") route.side_effect = [ httpx.Response(500, text="Server Error"), httpx.Response(200, text="Success"), ] response = await client.get("https://example.com/api") assert response.status_code == 200 @pytest.mark.asyncio async def test_get_raises_on_404(): """Test that HTTPClient raises on 4xx errors immediately.""" client = HTTPClient(request_delay_seconds=0.0, retries=2) with respx.mock: respx.get("https://example.com/api").mock(return_value=httpx.Response(404)) with pytest.raises(httpx.HTTPStatusError) as exc_info: await client.get("https://example.com/api") assert exc_info.value.response.status_code == 404 @pytest.mark.asyncio async def test_get_retries_on_502_bad_gateway(): """Test that HTTPClient retries on 502 Bad Gateway.""" client = HTTPClient(request_delay_seconds=0.0, retries=2) with respx.mock: route = respx.get("https://example.com/api") route.side_effect = [ httpx.Response(502, text="Bad Gateway"), httpx.Response(200, text="Success"), ] response = await client.get("https://example.com/api") assert response.status_code == 200 @pytest.mark.asyncio async def test_post_retries_on_503(): """Test that HTTPClient retries POST on 503 Service Unavailable.""" client = HTTPClient(request_delay_seconds=0.0, retries=2) with respx.mock: route = respx.post("https://example.com/api") route.side_effect = [ httpx.Response(503, text="Service Unavailable"), httpx.Response(201, json={"success": True}), ] response = await client.post("https://example.com/api", json={"test": "data"}) assert response.status_code == 201 @pytest.mark.asyncio async def test_get_eventually_fails_on_persistent_500(): """Test that HTTPClient gives up after max retries.""" client = HTTPClient(request_delay_seconds=0.0, retries=1) with respx.mock: respx.get("https://example.com/api").mock(return_value=httpx.Response(500)) with pytest.raises(httpx.HTTPStatusError) as exc_info: await client.get("https://example.com/api") assert exc_info.value.response.status_code == 500