Coverage for tests/test_security_api_key_header_description.py: 100%
27 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 fastapi import Depends, FastAPI, Security 1abcde
2from fastapi.security import APIKeyHeader 1abcde
3from fastapi.testclient import TestClient 1abcde
4from pydantic import BaseModel 1abcde
6app = FastAPI() 1abcde
8api_key = APIKeyHeader(name="key", description="An API Key Header") 1abcde
11class User(BaseModel): 1abcde
12 username: str 1abcde
15def get_current_user(oauth_header: str = Security(api_key)): 1abcde
16 user = User(username=oauth_header) 1abcde
17 return user 1abcde
20@app.get("/users/me") 1abcde
21def read_current_user(current_user: User = Depends(get_current_user)): 1abcde
22 return current_user 1abcde
25client = TestClient(app) 1abcde
28def test_security_api_key(): 1abcde
29 response = client.get("/users/me", headers={"key": "secret"}) 1abcde
30 assert response.status_code == 200, response.text 1abcde
31 assert response.json() == {"username": "secret"} 1abcde
34def test_security_api_key_no_key(): 1abcde
35 response = client.get("/users/me") 1abcde
36 assert response.status_code == 403, response.text 1abcde
37 assert response.json() == {"detail": "Not authenticated"} 1abcde
40def test_openapi_schema(): 1abcde
41 response = client.get("/openapi.json") 1abcde
42 assert response.status_code == 200, response.text 1abcde
43 assert response.json() == { 1abcde
44 "openapi": "3.1.0",
45 "info": {"title": "FastAPI", "version": "0.1.0"},
46 "paths": {
47 "/users/me": {
48 "get": {
49 "responses": {
50 "200": {
51 "description": "Successful Response",
52 "content": {"application/json": {"schema": {}}},
53 }
54 },
55 "summary": "Read Current User",
56 "operationId": "read_current_user_users_me_get",
57 "security": [{"APIKeyHeader": []}],
58 }
59 }
60 },
61 "components": {
62 "securitySchemes": {
63 "APIKeyHeader": {
64 "type": "apiKey",
65 "name": "key",
66 "in": "header",
67 "description": "An API Key Header",
68 }
69 }
70 },
71 }