Coverage for tests/test_security_api_key_cookie.py: 100%
29 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 APIKeyCookie 1abcde
3from fastapi.testclient import TestClient 1abcde
4from pydantic import BaseModel 1abcde
6app = FastAPI() 1abcde
8api_key = APIKeyCookie(name="key") 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
25def test_security_api_key(): 1abcde
26 client = TestClient(app, cookies={"key": "secret"}) 1abcde
27 response = client.get("/users/me") 1abcde
28 assert response.status_code == 200, response.text 1abcde
29 assert response.json() == {"username": "secret"} 1abcde
32def test_security_api_key_no_key(): 1abcde
33 client = TestClient(app) 1abcde
34 response = client.get("/users/me") 1abcde
35 assert response.status_code == 403, response.text 1abcde
36 assert response.json() == {"detail": "Not authenticated"} 1abcde
39def test_openapi_schema(): 1abcde
40 client = TestClient(app) 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": [{"APIKeyCookie": []}],
58 }
59 }
60 },
61 "components": {
62 "securitySchemes": {
63 "APIKeyCookie": {"type": "apiKey", "name": "key", "in": "cookie"}
64 }
65 },
66 }