Coverage for tests/test_dependency_security_overrides.py: 100%
30 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
1from typing import List, Tuple 1abcde
3from fastapi import Depends, FastAPI, Security 1abcde
4from fastapi.security import SecurityScopes 1abcde
5from fastapi.testclient import TestClient 1abcde
7app = FastAPI() 1abcde
10def get_user(required_scopes: SecurityScopes): 1abcde
11 return "john", required_scopes.scopes 1abcde
14def get_user_override(required_scopes: SecurityScopes): 1abcde
15 return "alice", required_scopes.scopes 1abcde
18def get_data(): 1abcde
19 return [1, 2, 3] 1abcde
22def get_data_override(): 1abcde
23 return [3, 4, 5] 1abcde
26@app.get("/user") 1abcde
27def read_user( 1abcde
28 user_data: Tuple[str, List[str]] = Security(get_user, scopes=["foo", "bar"]),
29 data: List[int] = Depends(get_data),
30):
31 return {"user": user_data[0], "scopes": user_data[1], "data": data} 1abcde
34client = TestClient(app) 1abcde
37def test_normal(): 1abcde
38 response = client.get("/user") 1abcde
39 assert response.json() == { 1abcde
40 "user": "john",
41 "scopes": ["foo", "bar"],
42 "data": [1, 2, 3],
43 }
46def test_override_data(): 1abcde
47 app.dependency_overrides[get_data] = get_data_override 1abcde
48 response = client.get("/user") 1abcde
49 assert response.json() == { 1abcde
50 "user": "john",
51 "scopes": ["foo", "bar"],
52 "data": [3, 4, 5],
53 }
54 app.dependency_overrides = {} 1abcde
57def test_override_security(): 1abcde
58 app.dependency_overrides[get_user] = get_user_override 1abcde
59 response = client.get("/user") 1abcde
60 assert response.json() == { 1abcde
61 "user": "alice",
62 "scopes": ["foo", "bar"],
63 "data": [1, 2, 3],
64 }
65 app.dependency_overrides = {} 1abcde