Debian Codegraph @

tests/test_security_http_base_optional.py

raw
1 from fastapi import FastAPI, Security
2 from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBase
3 from fastapi.testclient import TestClient
4 from inline_snapshot import snapshot
5
6 app = FastAPI()
7
8 security = HTTPBase(scheme="Other", auto_error=False)
9
10
11 @app.get("/users/me")
12 def read_current_user(
13 credentials: HTTPAuthorizationCredentials | None = Security(security),
14 ):
15 if credentials is None:
16 return {"msg": "Create an account first"}
17 return {"scheme": credentials.scheme, "credentials": credentials.credentials}
18
19
20 client = TestClient(app)
21
22
23 def test_security_http_base():
24 response = client.get("/users/me", headers={"Authorization": "Other foobar"})
25 assert response.status_code == 200, response.text
26 assert response.json() == {"scheme": "Other", "credentials": "foobar"}
27
28
29 def test_security_http_base_no_credentials():
30 response = client.get("/users/me")
31 assert response.status_code == 200, response.text
32 assert response.json() == {"msg": "Create an account first"}
33
34
35 def test_openapi_schema():
36 response = client.get("/openapi.json")
37 assert response.status_code == 200, response.text
38 assert response.json() == snapshot(
39 {
40 "openapi": "3.1.0",
41 "info": {"title": "FastAPI", "version": "0.1.0"},
42 "paths": {
43 "/users/me": {
44 "get": {
45 "responses": {
46 "200": {
47 "description": "Successful Response",
48 "content": {"application/json": {"schema": {}}},
49 }
50 },
51 "summary": "Read Current User",
52 "operationId": "read_current_user_users_me_get",
53 "security": [{"HTTPBase": []}],
54 }
55 }
56 },
57 "components": {
58 "securitySchemes": {"HTTPBase": {"type": "http", "scheme": "Other"}}
59 },
60 }
61 )