Coverage for tests/test_security_oauth2_password_bearer_optional.py: 100%

28 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-12-04 08:29 +0000

1from typing import Optional 1abcdefg

2 

3from fastapi import FastAPI, Security 1abcdefg

4from fastapi.security import OAuth2PasswordBearer 1abcdefg

5from fastapi.testclient import TestClient 1abcdefg

6 

7app = FastAPI() 1abcdefg

8 

9oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token", auto_error=False) 1abcdefg

10 

11 

12@app.get("/items/") 1abcdefg

13async def read_items(token: Optional[str] = Security(oauth2_scheme)): 1abcdefg

14 if token is None: 1hijklmnopqrstuvwxyzAB

15 return {"msg": "Create an account first"} 1hiklnoqrtuwxzA

16 return {"token": token} 1jmpsvyB

17 

18 

19client = TestClient(app) 1abcdefg

20 

21 

22def test_no_token(): 1abcdefg

23 response = client.get("/items") 1iloruxA

24 assert response.status_code == 200, response.text 1iloruxA

25 assert response.json() == {"msg": "Create an account first"} 1iloruxA

26 

27 

28def test_token(): 1abcdefg

29 response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) 1jmpsvyB

30 assert response.status_code == 200, response.text 1jmpsvyB

31 assert response.json() == {"token": "testtoken"} 1jmpsvyB

32 

33 

34def test_incorrect_token(): 1abcdefg

35 response = client.get("/items", headers={"Authorization": "Notexistent testtoken"}) 1hknqtwz

36 assert response.status_code == 200, response.text 1hknqtwz

37 assert response.json() == {"msg": "Create an account first"} 1hknqtwz

38 

39 

40def test_openapi_schema(): 1abcdefg

41 response = client.get("/openapi.json") 1CDEFGHI

42 assert response.status_code == 200, response.text 1CDEFGHI

43 assert response.json() == { 1CDEFGHI

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 }