Coverage for tests / test_security_oauth2_password_bearer_optional_description.py: 100%

28 statements  

« 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 OAuth2PasswordBearer 1abcd

3from fastapi.testclient import TestClient 1abcd

4from inline_snapshot import snapshot 1abcd

5 

6app = FastAPI() 1abcd

7 

8oauth2_scheme = OAuth2PasswordBearer( 1abcd

9 tokenUrl="/token", 

10 description="OAuth2PasswordBearer security scheme", 

11 auto_error=False, 

12) 

13 

14 

15@app.get("/items/") 1abcd

16async def read_items(token: str | None = Security(oauth2_scheme)): 1abcd

17 if token is None: 1efghijklmno

18 return {"msg": "Create an account first"} 1efhjkmn

19 return {"token": token} 1gilo

20 

21 

22client = TestClient(app) 1abcd

23 

24 

25def test_no_token(): 1abcd

26 response = client.get("/items") 1fhkn

27 assert response.status_code == 200, response.text 1fhkn

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

29 

30 

31def test_token(): 1abcd

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

33 assert response.status_code == 200, response.text 1gilo

34 assert response.json() == {"token": "testtoken"} 1gilo

35 

36 

37def test_incorrect_token(): 1abcd

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

39 assert response.status_code == 200, response.text 1epjm

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

41 

42 

43def test_openapi_schema(): 1abcd

44 response = client.get("/openapi.json") 1qrst

45 assert response.status_code == 200, response.text 1qrst

46 assert response.json() == snapshot( 1qrst

47 { 

48 "openapi": "3.1.0", 

49 "info": {"title": "FastAPI", "version": "0.1.0"}, 

50 "paths": { 

51 "/items/": { 

52 "get": { 

53 "responses": { 

54 "200": { 

55 "description": "Successful Response", 

56 "content": {"application/json": {"schema": {}}}, 

57 } 

58 }, 

59 "summary": "Read Items", 

60 "operationId": "read_items_items__get", 

61 "security": [{"OAuth2PasswordBearer": []}], 

62 } 

63 } 

64 }, 

65 "components": { 

66 "securitySchemes": { 

67 "OAuth2PasswordBearer": { 

68 "type": "oauth2", 

69 "flows": {"password": {"scopes": {}, "tokenUrl": "/token"}}, 

70 "description": "OAuth2PasswordBearer security scheme", 

71 } 

72 } 

73 }, 

74 } 

75 )