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
« 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
5initial_fake_database = {"rick": "Rick Sanchez"} 1abcde
7fake_database = initial_fake_database.copy() 1abcde
9initial_state = {"except": False, "finally": False} 1abcde
11state = initial_state.copy() 1abcde
13app = FastAPI() 1abcde
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
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
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
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
50client = TestClient(app) 1abcde
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
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