Coverage for tests / test_security_oauth2_password_bearer_optional_description.py: 100%

29 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-12 18:15 +0000

1from typing import Optional 1abcd

2 

3from fastapi import FastAPI, Security 1abcd

4from fastapi.security import OAuth2PasswordBearer 1abcd

5from fastapi.testclient import TestClient 1abcd

6from inline_snapshot import snapshot 1abcd

7 

8app = FastAPI() 1abcd

9 

10oauth2_scheme = OAuth2PasswordBearer( 1abcd

11 tokenUrl="/token", 

12 description="OAuth2PasswordBearer security scheme", 

13 auto_error=False, 

14) 

15 

16 

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

18async def read_items(token: Optional[str] = Security(oauth2_scheme)): 1abcd

19 if token is None: 1efghijklm

20 return {"msg": "Create an account first"} 1efhikl

21 return {"token": token} 1gjm

22 

23 

24client = TestClient(app) 1abcd

25 

26 

27def test_no_token(): 1abcd

28 response = client.get("/items") 1fil

29 assert response.status_code == 200, response.text 1fil

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

31 

32 

33def test_token(): 1abcd

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

35 assert response.status_code == 200, response.text 1gjm

36 assert response.json() == {"token": "testtoken"} 1gjm

37 

38 

39def test_incorrect_token(): 1abcd

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

41 assert response.status_code == 200, response.text 1ehk

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

43 

44 

45def test_openapi_schema(): 1abcd

46 response = client.get("/openapi.json") 1nop

47 assert response.status_code == 200, response.text 1nop

48 assert response.json() == snapshot( 1nop

49 { 

50 "openapi": "3.1.0", 

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

52 "paths": { 

53 "/items/": { 

54 "get": { 

55 "responses": { 

56 "200": { 

57 "description": "Successful Response", 

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

59 } 

60 }, 

61 "summary": "Read Items", 

62 "operationId": "read_items_items__get", 

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

64 } 

65 } 

66 }, 

67 "components": { 

68 "securitySchemes": { 

69 "OAuth2PasswordBearer": { 

70 "type": "oauth2", 

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

72 "description": "OAuth2PasswordBearer security scheme", 

73 } 

74 } 

75 }, 

76 } 

77 )