Coverage for tests/test_security_oauth2_authorization_code_bearer.py: 100%

26 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 OAuth2AuthorizationCodeBearer 1abcde

5from fastapi.testclient import TestClient 1abcde

6 

7app = FastAPI() 1abcde

8 

9oauth2_scheme = OAuth2AuthorizationCodeBearer( 1abcde

10 authorizationUrl="authorize", tokenUrl="token", auto_error=True 

11) 

12 

13 

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

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

16 return {"token": token} 1abcde

17 

18 

19client = TestClient(app) 1abcde

20 

21 

22def test_no_token(): 1abcde

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

24 assert response.status_code == 401, response.text 1abcde

25 assert response.json() == {"detail": "Not authenticated"} 1abcde

26 

27 

28def test_incorrect_token(): 1abcde

29 response = client.get("/items", headers={"Authorization": "Non-existent testtoken"}) 1abcde

30 assert response.status_code == 401, response.text 1abcde

31 assert response.json() == {"detail": "Not authenticated"} 1abcde

32 

33 

34def test_token(): 1abcde

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

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

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

38 

39 

40def test_openapi_schema(): 1abcde

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

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

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

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": [{"OAuth2AuthorizationCodeBearer": []}], 

58 } 

59 } 

60 }, 

61 "components": { 

62 "securitySchemes": { 

63 "OAuth2AuthorizationCodeBearer": { 

64 "type": "oauth2", 

65 "flows": { 

66 "authorizationCode": { 

67 "authorizationUrl": "authorize", 

68 "tokenUrl": "token", 

69 "scopes": {}, 

70 } 

71 }, 

72 } 

73 } 

74 }, 

75 }