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