Coverage for tests/test_dependency_yield_except_httpexception.py: 100%

48 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-12-04 08:29 +0000

1import pytest 1abcdefg

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

3from fastapi.testclient import TestClient 1abcdefg

4 

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

6 

7fake_database = initial_fake_database.copy() 1abcdefg

8 

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

10 

11state = initial_state.copy() 1abcdefg

12 

13app = FastAPI() 1abcdefg

14 

15 

16async def get_database(): 1abcdefg

17 temp_database = fake_database.copy() 1honpiqjrksltmu

18 try: 1honpiqjrksltmu

19 yield temp_database 1honpiqjrksltmu

20 fake_database.update(temp_database) 1opqrstu

21 except HTTPException: 1hnijklm

22 state["except"] = True 1hnijklm

23 raise 1hnijklm

24 finally: 

25 state["finally"] = True 1hopiqjrksltmu

26 

27 

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

29def put_invalid_user( 1abcdefg

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

31): 

32 db[user_id] = name 1hnijklm

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

34 

35 

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

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

38 db[user_id] = name 1opqrstu

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

40 

41 

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

43def reset_state_and_db(): 1abcdefg

44 global fake_database 

45 global state 

46 fake_database = initial_fake_database.copy() 1abcdefg

47 state = initial_state.copy() 1abcdefg

48 

49 

50client = TestClient(app) 1abcdefg

51 

52 

53def test_dependency_gets_exception(): 1abcdefg

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

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

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

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

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

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

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

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

62 

63 

64def test_dependency_no_exception(): 1abcdefg

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

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

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

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

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

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

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

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