Coverage for tests/test_exception_handlers.py: 100%
37 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
1import pytest 1abcde
2from fastapi import FastAPI, HTTPException 1abcde
3from fastapi.exceptions import RequestValidationError 1abcde
4from fastapi.testclient import TestClient 1abcde
5from starlette.responses import JSONResponse 1abcde
8def http_exception_handler(request, exception): 1abcde
9 return JSONResponse({"exception": "http-exception"}) 1abcde
12def request_validation_exception_handler(request, exception): 1abcde
13 return JSONResponse({"exception": "request-validation"}) 1abcde
16def server_error_exception_handler(request, exception): 1abcde
17 return JSONResponse(status_code=500, content={"exception": "server-error"}) 1abcde
20app = FastAPI( 1abcde
21 exception_handlers={
22 HTTPException: http_exception_handler,
23 RequestValidationError: request_validation_exception_handler,
24 Exception: server_error_exception_handler,
25 }
26)
28client = TestClient(app) 1abcde
31@app.get("/http-exception") 1abcde
32def route_with_http_exception(): 1abcde
33 raise HTTPException(status_code=400) 1abcde
36@app.get("/request-validation/{param}/") 1abcde
37def route_with_request_validation_exception(param: int): 1abcde
38 pass # pragma: no cover
41@app.get("/server-error") 1abcde
42def route_with_server_error(): 1abcde
43 raise RuntimeError("Oops!") 1abcde
46def test_override_http_exception(): 1abcde
47 response = client.get("/http-exception") 1abcde
48 assert response.status_code == 200 1abcde
49 assert response.json() == {"exception": "http-exception"} 1abcde
52def test_override_request_validation_exception(): 1abcde
53 response = client.get("/request-validation/invalid") 1abcde
54 assert response.status_code == 200 1abcde
55 assert response.json() == {"exception": "request-validation"} 1abcde
58def test_override_server_error_exception_raises(): 1abcde
59 with pytest.raises(RuntimeError): 1abcde
60 client.get("/server-error") 1abcde
63def test_override_server_error_exception_response(): 1abcde
64 client = TestClient(app, raise_server_exceptions=False) 1abcde
65 response = client.get("/server-error") 1abcde
66 assert response.status_code == 500 1abcde
67 assert response.json() == {"exception": "server-error"} 1abcde