Coverage for tests/test_security_oauth2_password_bearer_optional_description.py: 100%

28 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +0000

1from typing import Optional 1abcde

2 

3from fastapi import FastAPI, Security 1abcde

4from fastapi.security import OAuth2PasswordBearer 1abcde

5from fastapi.testclient import TestClient 1abcde

6 

7app = FastAPI() 1abcde

8 

9oauth2_scheme = OAuth2PasswordBearer( 1abcde

10 tokenUrl="/token", 

11 description="OAuth2PasswordBearer security scheme", 

12 auto_error=False, 

13) 

14 

15 

16@app.get("/items/") 1abcde

17async def read_items(token: Optional[str] = Security(oauth2_scheme)): 1abcde

18 if token is None: 1abcde

19 return {"msg": "Create an account first"} 1abcde

20 return {"token": token} 1abcde

21 

22 

23client = TestClient(app) 1abcde

24 

25 

26def test_no_token(): 1abcde

27 response = client.get("/items") 1abcde

28 assert response.status_code == 200, response.text 1abcde

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

30 

31 

32def test_token(): 1abcde

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

34 assert response.status_code == 200, response.text 1abcde

35 assert response.json() == {"token": "testtoken"} 1abcde

36 

37 

38def test_incorrect_token(): 1abcde

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

40 assert response.status_code == 200, response.text 1abcde

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

42 

43 

44def test_openapi_schema(): 1abcde

45 response = client.get("/openapi.json") 1abcde

46 assert response.status_code == 200, response.text 1abcde

47 assert response.json() == { 1abcde

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 }