| 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 |
raise |
| 24 |
finally: |
| 25 |
state["finally"] = True |
| 26 |
|
| 27 |
|
| 28 |
@app.put("/invalid-user/{user_id}") |
| 29 |
def put_invalid_user( |
| 30 |
user_id: str, name: str = Body(), db: dict = Depends(get_database) |
| 31 |
): |
| 32 |
db[user_id] = name |
| 33 |
raise HTTPException(status_code=400, detail="Invalid user") |
| 34 |
|
| 35 |
|
| 36 |
@app.put("/user/{user_id}") |
| 37 |
def put_user(user_id: str, name: str = Body(), db: dict = Depends(get_database)): |
| 38 |
db[user_id] = name |
| 39 |
return {"message": "OK"} |
| 40 |
|
| 41 |
|
| 42 |
@pytest.fixture(autouse=True) |
| 43 |
def reset_state_and_db(): |
| 44 |
global fake_database |
| 45 |
global state |
| 46 |
fake_database = initial_fake_database.copy() |
| 47 |
state = initial_state.copy() |
| 48 |
|
| 49 |
|
| 50 |
client = TestClient(app) |
| 51 |
|
| 52 |
|
| 53 |
def test_dependency_gets_exception(): |
| 54 |
assert state["except"] is False |
| 55 |
assert state["finally"] is False |
| 56 |
response = client.put("/invalid-user/rick", json="Morty") |
| 57 |
assert response.status_code == 400, response.text |
| 58 |
assert response.json() == {"detail": "Invalid user"} |
| 59 |
assert state["except"] is True |
| 60 |
assert state["finally"] is True |
| 61 |
assert fake_database["rick"] == "Rick Sanchez" |
| 62 |
|
| 63 |
|
| 64 |
def test_dependency_no_exception(): |
| 65 |
assert state["except"] is False |
| 66 |
assert state["finally"] is False |
| 67 |
response = client.put("/user/rick", json="Morty") |
| 68 |
assert response.status_code == 200, response.text |
| 69 |
assert response.json() == {"message": "OK"} |
| 70 |
assert state["except"] is False |
| 71 |
assert state["finally"] is True |
| 72 |
assert fake_database["rick"] == "Morty" |