"""Failures in the UI-to-API transport must remain actionable API errors.""" import unittest import httpx from site_engine.web.admin.api_client import AdminApi, ApiError class ApiClientTests(unittest.IsolatedAsyncioTestCase): async def test_invalid_error_payloads_do_not_expose_raw_response(self): for raw in ( b"sensitive upstream response", b"null", b"[]", b'{"error":{"message":"missing code"}}', ): with self.subTest(raw=raw): transport = httpx.MockTransport( lambda request, raw=raw: httpx.Response(500, content=raw) ) async with httpx.AsyncClient( transport=transport, base_url="http://internal" ) as client: with ( self.assertLogs("uvicorn.error", level="ERROR") as logs, self.assertRaises(ApiError) as captured, ): await AdminApi(client).call("POST", "/publish") self.assertEqual(captured.exception.status, 502) self.assertEqual(captured.exception.data["error"]["code"], "invalid_api_response") self.assertNotIn(raw.decode(), str(captured.exception)) self.assertNotIn("sensitive upstream response", "\n".join(logs.output)) async def test_api_transport_failure_becomes_service_unavailable(self): def unavailable(request): raise httpx.ConnectError("connection probe", request=request) async with httpx.AsyncClient( transport=httpx.MockTransport(unavailable), base_url="http://internal" ) as client: with ( self.assertLogs("uvicorn.error", level="ERROR") as logs, self.assertRaises(ApiError) as captured, ): await AdminApi(client).call("POST", "/publish") self.assertEqual(captured.exception.status, 503) self.assertEqual(captured.exception.data["error"]["code"], "api_unavailable") self.assertIn("ConnectError", "\n".join(logs.output))