diff --git a/desdeo/api/routers/generic.py b/desdeo/api/routers/generic.py index b7a5d01da..22467ea9f 100644 --- a/desdeo/api/routers/generic.py +++ b/desdeo/api/routers/generic.py @@ -194,3 +194,35 @@ def calculate_score_bands_from_objective_data( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Error calculating SCORE bands parameters: {e!r}", ) from e + + +@router.get("/debug/{httpcode}", tags=["debug"]) +async def trigger_error(httpcode: int): + """Debug endpoint to simulate HTTP errors. + + This endpoint takes a 3-digit HTTP status code as a path parameter + and raises the corresponding HTTPException. + + Example usage: + /method/generic/debug/404 + /method/generic/debug/500 + + Args: + httpcode (int): A valid HTTP status code (100-599) + + Raises: + HTTPException: Returns the HTTP error corresponding to `httpcode`. + + Reference: + https://fastapi.tiangolo.com/tutorial/handling-errors/ + """ + if httpcode < 100 or httpcode > 599: # noqa: PLR2004 + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Invalid HTTP code. Must be between 100 and 599.", + ) + + raise HTTPException( + status_code=httpcode, + detail=f"Debug triggered HTTP {httpcode} error", + ) diff --git a/desdeo/api/tests/test_routes.py b/desdeo/api/tests/test_routes.py index 8c8095227..a0ba1e1c6 100644 --- a/desdeo/api/tests/test_routes.py +++ b/desdeo/api/tests/test_routes.py @@ -113,6 +113,25 @@ def test_refresh(client: TestClient): assert response_good.json()["access_token"] != response_refresh.json()["access_token"] +def test_debug_endpoint_valid_codes(client): + """Test that debug endpoint returns the requested HTTP error codes.""" + # Test 404 + response = client.get("/method/generic/debug/404") + assert response.status_code == status.HTTP_404_NOT_FOUND + assert response.json()["detail"] == "Debug triggered HTTP 404 error" + + # Test 500 + response = client.get("/method/generic/debug/500") + assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR + assert response.json()["detail"] == "Debug triggered HTTP 500 error" + + +def test_debug_endpoint_invalid_code(client): + """Test that invalid HTTP codes return 400.""" + response = client.get("/method/generic/debug/999") + assert response.status_code == status.HTTP_400_BAD_REQUEST + assert "Invalid HTTP code" in response.json()["detail"] + def test_get_problem(client: TestClient): """Test fetching specific problems based on their id."""