Coverage for tests/test_dependency_normal_exceptions.py: 100%

48 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-01-13 13:38 +0000

1import pytest 1abcde

2from fastapi import Body, Depends, FastAPI, HTTPException 1abcde

3from fastapi.testclient import TestClient 1abcde

4 

5initial_fake_database = {"rick": "Rick Sanchez"} 1abcde

6 

7fake_database = initial_fake_database.copy() 1abcde

8 

9initial_state = {"except": False, "finally": False} 1abcde

10 

11state = initial_state.copy() 1abcde

12 

13app = FastAPI() 1abcde

14 

15 

16async def get_database(): 1abcde

17 temp_database = fake_database.copy() 1fkjlgmhnio

18 try: 1fkjlgmhnio

19 yield temp_database 1fkjlgmhnio

20 fake_database.update(temp_database) 1klmno

21 except HTTPException: 1fjghi

22 state["except"] = True 1fjghi

23 raise 1fjghi

24 finally: 

25 state["finally"] = True 1fklgmhnio

26 

27 

28@app.put("/invalid-user/{user_id}") 1abcde

29def put_invalid_user( 1abcde

30 user_id: str, name: str = Body(), db: dict = Depends(get_database) 

31): 

32 db[user_id] = name 1fjghi

33 raise HTTPException(status_code=400, detail="Invalid user") 1fjghi

34 

35 

36@app.put("/user/{user_id}") 1abcde

37def put_user(user_id: str, name: str = Body(), db: dict = Depends(get_database)): 1abcde

38 db[user_id] = name 1klmno

39 return {"message": "OK"} 1klmno

40 

41 

42@pytest.fixture(autouse=True) 1abcde

43def reset_state_and_db(): 1abcde

44 global fake_database 

45 global state 

46 fake_database = initial_fake_database.copy() 1abcde

47 state = initial_state.copy() 1abcde

48 

49 

50client = TestClient(app) 1abcde

51 

52 

53def test_dependency_gets_exception(): 1abcde

54 assert state["except"] is False 1fjghi

55 assert state["finally"] is False 1fjghi

56 response = client.put("/invalid-user/rick", json="Morty") 1fjghi

57 assert response.status_code == 400, response.text 1fjghi

58 assert response.json() == {"detail": "Invalid user"} 1fjghi

59 assert state["except"] is True 1fjghi

60 assert state["finally"] is True 1fjghi

61 assert fake_database["rick"] == "Rick Sanchez" 1fjghi

62 

63 

64def test_dependency_no_exception(): 1abcde

65 assert state["except"] is False 1klmno

66 assert state["finally"] is False 1klmno

67 response = client.put("/user/rick", json="Morty") 1klmno

68 assert response.status_code == 200, response.text 1klmno

69 assert response.json() == {"message": "OK"} 1klmno

70 assert state["except"] is False 1klmno

71 assert state["finally"] is True 1klmno

72 assert fake_database["rick"] == "Morty" 1klmno