Coverage for tests/test_dependency_normal_exceptions.py: 100%

48 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +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() 1abcde

18 try: 1abcde

19 yield temp_database 1abcde

20 fake_database.update(temp_database) 1abcde

21 except HTTPException: 1abcde

22 state["except"] = True 1abcde

23 raise 1abcde

24 finally: 

25 state["finally"] = True 1abcde

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 1abcde

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

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 1abcde

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

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 1abcde

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

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

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

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

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

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

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

62 

63 

64def test_dependency_no_exception(): 1abcde

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

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

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

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

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

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

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

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