Coverage for tests/test_security_oauth2_authorization_code_bearer_description.py: 100%
26 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-05-05 00:03 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2025-05-05 00:03 +0000
1from typing import Optional 1abcdef
3from fastapi import FastAPI, Security 1abcdef
4from fastapi.security import OAuth2AuthorizationCodeBearer 1abcdef
5from fastapi.testclient import TestClient 1abcdef
7app = FastAPI() 1abcdef
9oauth2_scheme = OAuth2AuthorizationCodeBearer( 1abcdef
10 authorizationUrl="authorize",
11 tokenUrl="token",
12 description="OAuth2 Code Bearer",
13 auto_error=True,
14)
17@app.get("/items/") 1abcdef
18async def read_items(token: Optional[str] = Security(oauth2_scheme)): 1abcdef
19 return {"token": token} 1ghijkl
22client = TestClient(app) 1abcdef
25def test_no_token(): 1abcdef
26 response = client.get("/items") 1mnopqr
27 assert response.status_code == 401, response.text 1mnopqr
28 assert response.json() == {"detail": "Not authenticated"} 1mnopqr
31def test_incorrect_token(): 1abcdef
32 response = client.get("/items", headers={"Authorization": "Non-existent testtoken"}) 1stuvwx
33 assert response.status_code == 401, response.text 1stuvwx
34 assert response.json() == {"detail": "Not authenticated"} 1stuvwx
37def test_token(): 1abcdef
38 response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) 1ghijkl
39 assert response.status_code == 200, response.text 1ghijkl
40 assert response.json() == {"token": "testtoken"} 1ghijkl
43def test_openapi_schema(): 1abcdef
44 response = client.get("/openapi.json") 1yzABCD
45 assert response.status_code == 200, response.text 1yzABCD
46 assert response.json() == { 1yzABCD
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 }