Coverage for tests / test_security_openid_connect_description.py: 100%
33 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.open_id_connect_url import OpenIdConnect 1adbc
3from fastapi.testclient import TestClient 1adbc
4from inline_snapshot import snapshot 1adbc
5from pydantic import BaseModel 1adbc
7app = FastAPI() 1adbc
9oid = OpenIdConnect( 1adbc
10 openIdConnectUrl="/openid", description="OpenIdConnect security scheme"
11)
14class User(BaseModel): 1adbc
15 username: str 1abc
18def get_current_user(oauth_header: str = Security(oid)): 1adbc
19 user = User(username=oauth_header) 1efghijkl
20 return user 1efghijkl
23@app.get("/users/me") 1adbc
24def read_current_user(current_user: User = Depends(get_current_user)): 1adbc
25 return current_user 1efghijkl
28client = TestClient(app) 1adbc
31def test_security_oauth2(): 1adbc
32 response = client.get("/users/me", headers={"Authorization": "Bearer footokenbar"}) 1fhjl
33 assert response.status_code == 200, response.text 1fhjl
34 assert response.json() == {"username": "Bearer footokenbar"} 1fhjl
37def test_security_oauth2_password_other_header(): 1adbc
38 response = client.get("/users/me", headers={"Authorization": "Other footokenbar"}) 1egik
39 assert response.status_code == 200, response.text 1egik
40 assert response.json() == {"username": "Other footokenbar"} 1egik
43def test_security_oauth2_password_bearer_no_header(): 1adbc
44 response = client.get("/users/me") 1mnop
45 assert response.status_code == 401, response.text 1mnop
46 assert response.json() == {"detail": "Not authenticated"} 1mnop
47 assert response.headers["WWW-Authenticate"] == "Bearer" 1mnop
50def test_openapi_schema(): 1adbc
51 response = client.get("/openapi.json") 1qrst
52 assert response.status_code == 200, response.text 1qrst
53 assert response.json() == snapshot( 1qrst
54 {
55 "openapi": "3.1.0",
56 "info": {"title": "FastAPI", "version": "0.1.0"},
57 "paths": {
58 "/users/me": {
59 "get": {
60 "responses": {
61 "200": {
62 "description": "Successful Response",
63 "content": {"application/json": {"schema": {}}},
64 }
65 },
66 "summary": "Read Current User",
67 "operationId": "read_current_user_users_me_get",
68 "security": [{"OpenIdConnect": []}],
69 }
70 }
71 },
72 "components": {
73 "securitySchemes": {
74 "OpenIdConnect": {
75 "type": "openIdConnect",
76 "openIdConnectUrl": "/openid",
77 "description": "OpenIdConnect security scheme",
78 }
79 }
80 },
81 }
82 )