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