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

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

6 

7 

8def http_exception_handler(request, exception): 1abcde

9 return JSONResponse({"exception": "http-exception"}) 1abcde

10 

11 

12def request_validation_exception_handler(request, exception): 1abcde

13 return JSONResponse({"exception": "request-validation"}) 1abcde

14 

15 

16def server_error_exception_handler(request, exception): 1abcde

17 return JSONResponse(status_code=500, content={"exception": "server-error"}) 1abcde

18 

19 

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) 

27 

28client = TestClient(app) 1abcde

29 

30 

31@app.get("/http-exception") 1abcde

32def route_with_http_exception(): 1abcde

33 raise HTTPException(status_code=400) 1abcde

34 

35 

36@app.get("/request-validation/{param}/") 1abcde

37def route_with_request_validation_exception(param: int): 1abcde

38 pass # pragma: no cover 

39 

40 

41@app.get("/server-error") 1abcde

42def route_with_server_error(): 1abcde

43 raise RuntimeError("Oops!") 1abcde

44 

45 

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

50 

51 

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

56 

57 

58def test_override_server_error_exception_raises(): 1abcde

59 with pytest.raises(RuntimeError): 1abcde

60 client.get("/server-error") 1abcde

61 

62 

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