Coverage for tests / test_security_api_key_cookie_optional.py: 100%
34 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 APIKeyCookie 1adbc
3from fastapi.testclient import TestClient 1adbc
4from inline_snapshot import snapshot 1adbc
5from pydantic import BaseModel 1adbc
7app = FastAPI() 1adbc
9api_key = APIKeyCookie(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 = Depends(get_current_user)): 1adbc
25 if current_user is None: 1iejfkglh
26 return {"msg": "Create an account first"} 1ijkl
27 else:
28 return current_user 1efgh
31def test_security_api_key(): 1adbc
32 client = TestClient(app, cookies={"key": "secret"}) 1efgh
33 response = client.get("/users/me") 1efgh
34 assert response.status_code == 200, response.text 1efgh
35 assert response.json() == {"username": "secret"} 1efgh
38def test_security_api_key_no_key(): 1adbc
39 client = TestClient(app) 1ijkl
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 client = TestClient(app) 1mnop
47 response = client.get("/openapi.json") 1mnop
48 assert response.status_code == 200, response.text 1mnop
49 assert response.json() == snapshot( 1mnop
50 {
51 "openapi": "3.1.0",
52 "info": {"title": "FastAPI", "version": "0.1.0"},
53 "paths": {
54 "/users/me": {
55 "get": {
56 "responses": {
57 "200": {
58 "description": "Successful Response",
59 "content": {"application/json": {"schema": {}}},
60 }
61 },
62 "summary": "Read Current User",
63 "operationId": "read_current_user_users_me_get",
64 "security": [{"APIKeyCookie": []}],
65 }
66 }
67 },
68 "components": {
69 "securitySchemes": {
70 "APIKeyCookie": {"type": "apiKey", "name": "key", "in": "cookie"}
71 }
72 },
73 }
74 )