| 1 |
from typing import Annotated |
| 2 |
|
| 3 |
import pytest |
| 4 |
from fastapi import Depends, FastAPI, Security |
| 5 |
from fastapi.testclient import TestClient |
| 6 |
|
| 7 |
|
| 8 |
@pytest.fixture(name="call_counter") |
| 9 |
def call_counter_fixture(): |
| 10 |
return {"count": 0} |
| 11 |
|
| 12 |
|
| 13 |
@pytest.fixture(name="app") |
| 14 |
def app_fixture(call_counter: dict[str, int]): |
| 15 |
def get_db(): |
| 16 |
call_counter["count"] += 1 |
| 17 |
return f"db_{call_counter['count']}" |
| 18 |
|
| 19 |
def get_user(db: Annotated[str, Depends(get_db)]): |
| 20 |
return "user" |
| 21 |
|
| 22 |
app = FastAPI() |
| 23 |
|
| 24 |
@app.get("/") |
| 25 |
def endpoint( |
| 26 |
db: Annotated[str, Depends(get_db)], |
| 27 |
user: Annotated[str, Security(get_user, scopes=["read"])], |
| 28 |
): |
| 29 |
return {"db": db} |
| 30 |
|
| 31 |
return app |
| 32 |
|
| 33 |
|
| 34 |
@pytest.fixture(name="client") |
| 35 |
def client_fixture(app: FastAPI): |
| 36 |
return TestClient(app) |
| 37 |
|
| 38 |
|
| 39 |
def test_security_scopes_dependency_called_once( |
| 40 |
client: TestClient, call_counter: dict[str, int] |
| 41 |
): |
| 42 |
response = client.get("/") |
| 43 |
|
| 44 |
assert response.status_code == 200 |
| 45 |
assert call_counter["count"] == 1 |