Coverage for tests / test_security_oauth2_password_bearer_optional.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(tokenUrl="/token", auto_error=False) 1abcd

11 

12 

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

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

15 if token is None: 1efghijklm

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

17 return {"token": token} 1gjm

18 

19 

20client = TestClient(app) 1abcd

21 

22 

23def test_no_token(): 1abcd

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

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

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

27 

28 

29def test_token(): 1abcd

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

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

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

33 

34 

35def test_incorrect_token(): 1abcd

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

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

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

39 

40 

41def test_openapi_schema(): 1abcd

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

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

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

45 { 

46 "openapi": "3.1.0", 

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

48 "paths": { 

49 "/items/": { 

50 "get": { 

51 "responses": { 

52 "200": { 

53 "description": "Successful Response", 

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

55 } 

56 }, 

57 "summary": "Read Items", 

58 "operationId": "read_items_items__get", 

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

60 } 

61 } 

62 }, 

63 "components": { 

64 "securitySchemes": { 

65 "OAuth2PasswordBearer": { 

66 "type": "oauth2", 

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

68 } 

69 } 

70 }, 

71 } 

72 )