Coverage for tests / test_dependency_yield_except_httpexception.py: 100%
48 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-04-06 01:24 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-04-06 01:24 +0000
1import pytest 1abcd
2from fastapi import Body, Depends, FastAPI, HTTPException 1abcd
3from fastapi.testclient import TestClient 1abcd
5initial_fake_database = {"rick": "Rick Sanchez"} 1abcd
7fake_database = initial_fake_database.copy() 1abcd
9initial_state = {"except": False, "finally": False} 1abcd
11state = initial_state.copy() 1abcd
13app = FastAPI() 1abcd
16async def get_database(): 1abcd
17 temp_database = fake_database.copy() 1eifjgkhl
18 try: 1eifjgkhl
19 yield temp_database 1eifjgkhl
20 fake_database.update(temp_database) 1ijkl
21 except HTTPException: 1efgh
22 state["except"] = True 1efgh
23 raise 1efgh
24 finally:
25 state["finally"] = True 1eifjgkhl
28@app.put("/invalid-user/{user_id}") 1abcd
29def put_invalid_user( 1abcd
30 user_id: str, name: str = Body(), db: dict = Depends(get_database)
31):
32 db[user_id] = name 1efgh
33 raise HTTPException(status_code=400, detail="Invalid user") 1efgh
36@app.put("/user/{user_id}") 1abcd
37def put_user(user_id: str, name: str = Body(), db: dict = Depends(get_database)): 1abcd
38 db[user_id] = name 1ijkl
39 return {"message": "OK"} 1ijkl
42@pytest.fixture(autouse=True) 1abcd
43def reset_state_and_db(): 1abcd
44 global fake_database
45 global state
46 fake_database = initial_fake_database.copy() 1mnopqrst
47 state = initial_state.copy() 1mnopqrst
50client = TestClient(app) 1abcd
53def test_dependency_gets_exception(): 1abcd
54 assert state["except"] is False 1efgh
55 assert state["finally"] is False 1efgh
56 response = client.put("/invalid-user/rick", json="Morty") 1efgh
57 assert response.status_code == 400, response.text 1efgh
58 assert response.json() == {"detail": "Invalid user"} 1efgh
59 assert state["except"] is True 1efgh
60 assert state["finally"] is True 1efgh
61 assert fake_database["rick"] == "Rick Sanchez" 1efgh
64def test_dependency_no_exception(): 1abcd
65 assert state["except"] is False 1ijkl
66 assert state["finally"] is False 1ijkl
67 response = client.put("/user/rick", json="Morty") 1ijkl
68 assert response.status_code == 200, response.text 1ijkl
69 assert response.json() == {"message": "OK"} 1ijkl
70 assert state["except"] is False 1ijkl
71 assert state["finally"] is True 1ijkl
72 assert fake_database["rick"] == "Morty" 1ijkl