Coverage for tests / test_security_api_key_query_optional.py: 100%
32 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-04-06 01:24 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-04-06 01:24 +0000
1from fastapi import Depends, FastAPI, Security 1adbc
2from fastapi.security import APIKeyQuery 1adbc
3from fastapi.testclient import TestClient 1adbc
4from inline_snapshot import snapshot 1adbc
5from pydantic import BaseModel 1adbc
7app = FastAPI() 1adbc
9api_key = APIKeyQuery(name="key", auto_error=False) 1adbc
12class User(BaseModel): 1adbc
13 username: str 1abc
16def get_current_user(oauth_header: str | None = Security(api_key)): 1adbc
17 if oauth_header is None: 1iejfkglh
18 return None 1ijkl
19 user = User(username=oauth_header) 1efgh
20 return user 1efgh
23@app.get("/users/me") 1adbc
24def read_current_user(current_user: User | None = Depends(get_current_user)): 1adbc
25 if current_user is None: 1iejfkglh
26 return {"msg": "Create an account first"} 1ijkl
27 return current_user 1efgh
30client = TestClient(app) 1adbc
33def test_security_api_key(): 1adbc
34 response = client.get("/users/me?key=secret") 1efgh
35 assert response.status_code == 200, response.text 1efgh
36 assert response.json() == {"username": "secret"} 1efgh
39def test_security_api_key_no_key(): 1adbc
40 response = client.get("/users/me") 1ijkl
41 assert response.status_code == 200, response.text 1ijkl
42 assert response.json() == {"msg": "Create an account first"} 1ijkl
45def test_openapi_schema(): 1adbc
46 response = client.get("/openapi.json") 1mnop
47 assert response.status_code == 200, response.text 1mnop
48 assert response.json() == snapshot( 1mnop
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 )