Skip to content

Commit 71cd7fc

Browse files
committed
test: add unit test for handling invalid JSON from upstream server
This test verifies that the middleware correctly returns a 502 error when invalid JSON is received from an upstream server, ensuring robust error handling in the application.
1 parent f4cb492 commit 71cd7fc

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

tests/test_middleware.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,3 +101,21 @@ async def test_endpoint():
101101
assert response.status_code == 200
102102
assert "text/plain" in response.headers["content-type"]
103103
assert response.text == "invalid json"
104+
105+
106+
def test_json_response_middleware_invalid_json_upstream():
107+
"""Test that invalid JSON from upstream server returns 502 error."""
108+
app = FastAPI()
109+
app.add_middleware(ExampleJsonResponseMiddleware)
110+
111+
@app.get("/test")
112+
async def test_endpoint():
113+
# Return invalid JSON with JSON content type to trigger the error handling
114+
return Response(content="invalid json content", media_type="application/json")
115+
116+
client = TestClient(app)
117+
response = client.get("/test")
118+
assert response.status_code == 502
119+
assert response.headers["content-type"] == "application/json"
120+
data = response.json()
121+
assert data == {"error": "Received invalid JSON from upstream server"}

0 commit comments

Comments
 (0)