|
| 1 | +import pytest |
| 2 | +from fastapi import Body, Depends, FastAPI, HTTPException |
| 3 | +from fastapi.testclient import TestClient |
| 4 | + |
| 5 | +initial_fake_database = {"rick": "Rick Sanchez"} |
| 6 | + |
| 7 | +fake_database = initial_fake_database.copy() |
| 8 | + |
| 9 | +initial_state = {"except": False, "finally": False} |
| 10 | + |
| 11 | +state = initial_state.copy() |
| 12 | + |
| 13 | +app = FastAPI() |
| 14 | + |
| 15 | + |
| 16 | +async def get_database(): |
| 17 | + temp_database = fake_database.copy() |
| 18 | + try: |
| 19 | + yield temp_database |
| 20 | + fake_database.update(temp_database) |
| 21 | + except HTTPException: |
| 22 | + state["except"] = True |
| 23 | + finally: |
| 24 | + state["finally"] = True |
| 25 | + |
| 26 | + |
| 27 | +@app.put("/invalid-user/{user_id}") |
| 28 | +def put_invalid_user( |
| 29 | + user_id: str, name: str = Body(...), db: dict = Depends(get_database) |
| 30 | +): |
| 31 | + db[user_id] = name |
| 32 | + raise HTTPException(status_code=400, detail="Invalid user") |
| 33 | + |
| 34 | + |
| 35 | +@app.put("/user/{user_id}") |
| 36 | +def put_user(user_id: str, name: str = Body(...), db: dict = Depends(get_database)): |
| 37 | + db[user_id] = name |
| 38 | + return {"message": "OK"} |
| 39 | + |
| 40 | + |
| 41 | +@pytest.fixture(autouse=True) |
| 42 | +def reset_state_and_db(): |
| 43 | + global fake_database |
| 44 | + global state |
| 45 | + fake_database = initial_fake_database.copy() |
| 46 | + state = initial_state.copy() |
| 47 | + |
| 48 | + |
| 49 | +client = TestClient(app) |
| 50 | + |
| 51 | + |
| 52 | +def test_dependency_gets_exception(): |
| 53 | + assert state["except"] is False |
| 54 | + assert state["finally"] is False |
| 55 | + response = client.put("/invalid-user/rick", json="Morty") |
| 56 | + assert response.status_code == 400, response.text |
| 57 | + assert response.json() == {"detail": "Invalid user"} |
| 58 | + assert state["except"] is True |
| 59 | + assert state["finally"] is True |
| 60 | + assert fake_database["rick"] == "Rick Sanchez" |
| 61 | + |
| 62 | + |
| 63 | +def test_dependency_no_exception(): |
| 64 | + assert state["except"] is False |
| 65 | + assert state["finally"] is False |
| 66 | + response = client.put("/user/rick", json="Morty") |
| 67 | + assert response.status_code == 200, response.text |
| 68 | + assert response.json() == {"message": "OK"} |
| 69 | + assert state["except"] is False |
| 70 | + assert state["finally"] is True |
| 71 | + assert fake_database["rick"] == "Morty" |
0 commit comments