Coverage for tests / test_security_api_key_query_description.py: 100%
29 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", description="API Key Query") 1adbc
12class User(BaseModel): 1adbc
13 username: str 1abc
16def get_current_user(oauth_header: str = Security(api_key)): 1adbc
17 user = User(username=oauth_header) 1efgh
18 return user 1efgh
21@app.get("/users/me") 1adbc
22def read_current_user(current_user: User = Depends(get_current_user)): 1adbc
23 return current_user 1efgh
26client = TestClient(app) 1adbc
29def test_security_api_key(): 1adbc
30 response = client.get("/users/me?key=secret") 1efgh
31 assert response.status_code == 200, response.text 1efgh
32 assert response.json() == {"username": "secret"} 1efgh
35def test_security_api_key_no_key(): 1adbc
36 response = client.get("/users/me") 1ijkl
37 assert response.status_code == 401, response.text 1ijkl
38 assert response.json() == {"detail": "Not authenticated"} 1ijkl
39 assert response.headers["WWW-Authenticate"] == "APIKey" 1ijkl
42def test_openapi_schema(): 1adbc
43 response = client.get("/openapi.json") 1mnop
44 assert response.status_code == 200, response.text 1mnop
45 assert response.json() == snapshot( 1mnop
46 {
47 "openapi": "3.1.0",
48 "info": {"title": "FastAPI", "version": "0.1.0"},
49 "paths": {
50 "/users/me": {
51 "get": {
52 "responses": {
53 "200": {
54 "description": "Successful Response",
55 "content": {"application/json": {"schema": {}}},
56 }
57 },
58 "summary": "Read Current User",
59 "operationId": "read_current_user_users_me_get",
60 "security": [{"APIKeyQuery": []}],
61 }
62 }
63 },
64 "components": {
65 "securitySchemes": {
66 "APIKeyQuery": {
67 "type": "apiKey",
68 "name": "key",
69 "in": "query",
70 "description": "API Key Query",
71 }
72 }
73 },
74 }
75 )