Coverage for tests/test_security_oauth2_password_bearer_optional.py: 100%
28 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 OAuth2PasswordBearer 1abcde
5from fastapi.testclient import TestClient 1abcde
7app = FastAPI() 1abcde
9oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token", auto_error=False) 1abcde
12@app.get("/items/") 1abcde
13async def read_items(token: Optional[str] = Security(oauth2_scheme)): 1abcde
14 if token is None: 1abcde
15 return {"msg": "Create an account first"} 1abcde
16 return {"token": token} 1abcde
19client = TestClient(app) 1abcde
22def test_no_token(): 1abcde
23 response = client.get("/items") 1abcde
24 assert response.status_code == 200, response.text 1abcde
25 assert response.json() == {"msg": "Create an account first"} 1abcde
28def test_token(): 1abcde
29 response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) 1abcde
30 assert response.status_code == 200, response.text 1abcde
31 assert response.json() == {"token": "testtoken"} 1abcde
34def test_incorrect_token(): 1abcde
35 response = client.get("/items", headers={"Authorization": "Notexistent testtoken"}) 1abcde
36 assert response.status_code == 200, response.text 1abcde
37 assert response.json() == {"msg": "Create an account first"} 1abcde
40def test_openapi_schema(): 1abcde
41 response = client.get("/openapi.json") 1abcde
42 assert response.status_code == 200, response.text 1abcde
43 assert response.json() == { 1abcde
44 "openapi": "3.1.0",
45 "info": {"title": "FastAPI", "version": "0.1.0"},
46 "paths": {
47 "/items/": {
48 "get": {
49 "responses": {
50 "200": {
51 "description": "Successful Response",
52 "content": {"application/json": {"schema": {}}},
53 }
54 },
55 "summary": "Read Items",
56 "operationId": "read_items_items__get",
57 "security": [{"OAuth2PasswordBearer": []}],
58 }
59 }
60 },
61 "components": {
62 "securitySchemes": {
63 "OAuth2PasswordBearer": {
64 "type": "oauth2",
65 "flows": {"password": {"scopes": {}, "tokenUrl": "/token"}},
66 }
67 }
68 },
69 }