Coverage for tests / test_security_oauth2_authorization_code_bearer_description.py: 100%
26 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 FastAPI, Security 1abcd
2from fastapi.security import OAuth2AuthorizationCodeBearer 1abcd
3from fastapi.testclient import TestClient 1abcd
4from inline_snapshot import snapshot 1abcd
6app = FastAPI() 1abcd
8oauth2_scheme = OAuth2AuthorizationCodeBearer( 1abcd
9 authorizationUrl="authorize",
10 tokenUrl="token",
11 description="OAuth2 Code Bearer",
12 auto_error=True,
13)
16@app.get("/items/") 1abcd
17async def read_items(token: str | None = Security(oauth2_scheme)): 1abcd
18 return {"token": token} 1efgh
21client = TestClient(app) 1abcd
24def test_no_token(): 1abcd
25 response = client.get("/items") 1ijkl
26 assert response.status_code == 401, response.text 1ijkl
27 assert response.json() == {"detail": "Not authenticated"} 1ijkl
30def test_incorrect_token(): 1abcd
31 response = client.get("/items", headers={"Authorization": "Non-existent testtoken"}) 1mnop
32 assert response.status_code == 401, response.text 1mnop
33 assert response.json() == {"detail": "Not authenticated"} 1mnop
36def test_token(): 1abcd
37 response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) 1efgh
38 assert response.status_code == 200, response.text 1efgh
39 assert response.json() == {"token": "testtoken"} 1efgh
42def test_openapi_schema(): 1abcd
43 response = client.get("/openapi.json") 1qrst
44 assert response.status_code == 200, response.text 1qrst
45 assert response.json() == snapshot( 1qrst
46 {
47 "openapi": "3.1.0",
48 "info": {"title": "FastAPI", "version": "0.1.0"},
49 "paths": {
50 "/items/": {
51 "get": {
52 "responses": {
53 "200": {
54 "description": "Successful Response",
55 "content": {"application/json": {"schema": {}}},
56 }
57 },
58 "summary": "Read Items",
59 "operationId": "read_items_items__get",
60 "security": [{"OAuth2AuthorizationCodeBearer": []}],
61 }
62 }
63 },
64 "components": {
65 "securitySchemes": {
66 "OAuth2AuthorizationCodeBearer": {
67 "type": "oauth2",
68 "flows": {
69 "authorizationCode": {
70 "authorizationUrl": "authorize",
71 "tokenUrl": "token",
72 "scopes": {},
73 }
74 },
75 "description": "OAuth2 Code Bearer",
76 }
77 }
78 },
79 }
80 )