Coverage for tests / test_security_api_key_query_optional.py: 100%
32 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-21 17:29 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-21 17:29 +0000
1from fastapi import Depends, FastAPI, Security 1abcd
2from fastapi.security import APIKeyQuery 1abcd
3from fastapi.testclient import TestClient 1abcd
4from inline_snapshot import snapshot 1abcd
5from pydantic import BaseModel 1abcd
7app = FastAPI() 1abcd
9api_key = APIKeyQuery(name="key", auto_error=False) 1abcd
12class User(BaseModel): 1abcd
13 username: str 1abcd
16def get_current_user(oauth_header: str | None = Security(api_key)): 1abcd
17 if oauth_header is None: 1ehfigj
18 return None 1hij
19 user = User(username=oauth_header) 1efg
20 return user 1efg
23@app.get("/users/me") 1abcd
24def read_current_user(current_user: User | None = Depends(get_current_user)): 1abcd
25 if current_user is None: 1ehfigj
26 return {"msg": "Create an account first"} 1hij
27 return current_user 1efg
30client = TestClient(app) 1abcd
33def test_security_api_key(): 1abcd
34 response = client.get("/users/me?key=secret") 1efg
35 assert response.status_code == 200, response.text 1efg
36 assert response.json() == {"username": "secret"} 1efg
39def test_security_api_key_no_key(): 1abcd
40 response = client.get("/users/me") 1hij
41 assert response.status_code == 200, response.text 1hij
42 assert response.json() == {"msg": "Create an account first"} 1hij
45def test_openapi_schema(): 1abcd
46 response = client.get("/openapi.json") 1klm
47 assert response.status_code == 200, response.text 1klm
48 assert response.json() == snapshot( 1klm
49 {
50 "openapi": "3.1.0",
51 "info": {"title": "FastAPI", "version": "0.1.0"},
52 "paths": {
53 "/users/me": {
54 "get": {
55 "responses": {
56 "200": {
57 "description": "Successful Response",
58 "content": {"application/json": {"schema": {}}},
59 }
60 },
61 "summary": "Read Current User",
62 "operationId": "read_current_user_users_me_get",
63 "security": [{"APIKeyQuery": []}],
64 }
65 }
66 },
67 "components": {
68 "securitySchemes": {
69 "APIKeyQuery": {"type": "apiKey", "name": "key", "in": "query"}
70 }
71 },
72 }
73 )