Debian Codegraph @

tests/test_dependency_paramless.py

raw
1 from typing import Annotated
2
3 from fastapi import FastAPI, HTTPException, Security
4 from fastapi.security import (
5 OAuth2PasswordBearer,
6 SecurityScopes,
7 )
8 from fastapi.testclient import TestClient
9
10 app = FastAPI()
11
12 oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
13
14
15 def process_auth(
16 credentials: Annotated[str | None, Security(oauth2_scheme)],
17 security_scopes: SecurityScopes,
18 ):
19 # This is an incorrect way of using it, this is not checking if the scopes are
20 # provided by the token, only if the endpoint is requesting them, but the test
21 # here is just to check if FastAPI is indeed registering and passing the scopes
22 # correctly when using Security with parameterless dependencies.
23 if "a" not in security_scopes.scopes or "b" not in security_scopes.scopes:
24 raise HTTPException(detail="a or b not in scopes", status_code=401)
25 return {"token": credentials, "scopes": security_scopes.scopes}
26
27
28 @app.get("/get-credentials")
29 def get_credentials(
30 credentials: Annotated[dict, Security(process_auth, scopes=["a", "b"])],
31 ):
32 return credentials
33
34
35 @app.get(
36 "/parameterless-with-scopes",
37 dependencies=[Security(process_auth, scopes=["a", "b"])],
38 )
39 def get_parameterless_with_scopes():
40 return {"status": "ok"}
41
42
43 @app.get(
44 "/parameterless-without-scopes",
45 dependencies=[Security(process_auth)],
46 )
47 def get_parameterless_without_scopes():
48 return {"status": "ok"}
49
50
51 client = TestClient(app)
52
53
54 def test_get_credentials():
55 response = client.get("/get-credentials", headers={"authorization": "Bearer token"})
56 assert response.status_code == 200, response.text
57 assert response.json() == {"token": "token", "scopes": ["a", "b"]}
58
59
60 def test_parameterless_with_scopes():
61 response = client.get(
62 "/parameterless-with-scopes", headers={"authorization": "Bearer token"}
63 )
64 assert response.status_code == 200, response.text
65 assert response.json() == {"status": "ok"}
66
67
68 def test_parameterless_without_scopes():
69 response = client.get(
70 "/parameterless-without-scopes", headers={"authorization": "Bearer token"}
71 )
72 assert response.status_code == 401, response.text
73 assert response.json() == {"detail": "a or b not in scopes"}
74
75
76 def test_call_get_parameterless_without_scopes_for_coverage():
77 assert get_parameterless_without_scopes() == {"status": "ok"}