From a0a6cd39402b268cc2f075de0bc6efd0c43bb53e Mon Sep 17 00:00:00 2001 From: rzeta-10 Date: Mon, 23 Mar 2026 14:48:35 +0530 Subject: [PATCH] add tests for handling HTTP errors in AktoGuardrail --- .../guardrails_tests/test_akto_guardrails.py | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/tests/guardrails_tests/test_akto_guardrails.py b/tests/guardrails_tests/test_akto_guardrails.py index b5ae729f80f..3860e8bec7e 100644 --- a/tests/guardrails_tests/test_akto_guardrails.py +++ b/tests/guardrails_tests/test_akto_guardrails.py @@ -364,6 +364,54 @@ async def test_fail_closed_on_unreachable(): assert "localhost" not in exc_info.value.detail +@pytest.mark.asyncio +async def test_fail_open_on_http_error(): + """Non-200 from Akto (e.g. 401, 429) is caught via raise_for_status() and handled as fail_open.""" + g = AktoGuardrail( + akto_base_url="http://localhost:9090", + akto_api_key="test-token", + unreachable_fallback="fail_open", + guardrail_name="http-error-test", + event_hook="pre_call", + ) + mock_response = MagicMock(spec=httpx.Response) + mock_response.status_code = 429 + mock_request = MagicMock() + g.async_handler.post = AsyncMock( + side_effect=httpx.HTTPStatusError( + "Too Many Requests", request=mock_request, response=mock_response + ) + ) + + inputs = GenericGuardrailAPIInputs(texts=["test"], model="gpt-4") + result = await g.apply_guardrail(inputs=inputs, request_data={}, input_type="request") + assert result.get("texts") == ["test"] + + +@pytest.mark.asyncio +async def test_fail_closed_on_http_error(): + """Non-200 from Akto (e.g. 401, 429) is caught via raise_for_status() and handled as fail_closed.""" + g = AktoGuardrail( + akto_base_url="http://localhost:9090", + akto_api_key="test-token", + unreachable_fallback="fail_closed", + guardrail_name="http-error-test", + event_hook="pre_call", + ) + mock_response = MagicMock(spec=httpx.Response) + mock_response.status_code = 401 + mock_request = MagicMock() + g.async_handler.post = AsyncMock( + side_effect=httpx.HTTPStatusError( + "Unauthorized", request=mock_request, response=mock_response + ) + ) + + inputs = GenericGuardrailAPIInputs(texts=["test"], model="gpt-4") + with pytest.raises(HTTPException) as exc_info: + await g.apply_guardrail(inputs=inputs, request_data={}, input_type="request") + assert exc_info.value.status_code == 503 + # --------------------------------------------------------------------------- # Helper method tests