Coverage for tests/test_security_oauth2_authorization_code_bearer_description.py: 100%

26 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-12-04 08:29 +0000

1from typing import Optional 1abcdefg

2 

3from fastapi import FastAPI, Security 1abcdefg

4from fastapi.security import OAuth2AuthorizationCodeBearer 1abcdefg

5from fastapi.testclient import TestClient 1abcdefg

6 

7app = FastAPI() 1abcdefg

8 

9oauth2_scheme = OAuth2AuthorizationCodeBearer( 1abcdefg

10 authorizationUrl="authorize", 

11 tokenUrl="token", 

12 description="OAuth2 Code Bearer", 

13 auto_error=True, 

14) 

15 

16 

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

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

19 return {"token": token} 1hijklmn

20 

21 

22client = TestClient(app) 1abcdefg

23 

24 

25def test_no_token(): 1abcdefg

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

27 assert response.status_code == 401, response.text 1opqrstu

28 assert response.json() == {"detail": "Not authenticated"} 1opqrstu

29 

30 

31def test_incorrect_token(): 1abcdefg

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

33 assert response.status_code == 401, response.text 1vwxyzAB

34 assert response.json() == {"detail": "Not authenticated"} 1vwxyzAB

35 

36 

37def test_token(): 1abcdefg

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

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

40 assert response.json() == {"token": "testtoken"} 1hijklmn

41 

42 

43def test_openapi_schema(): 1abcdefg

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

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

46 assert response.json() == { 1CDEFGHI

47 "openapi": "3.1.0", 

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

49 "paths": { 

50 "/items/": { 

51 "get": { 

52 "responses": { 

53 "200": { 

54 "description": "Successful Response", 

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

56 } 

57 }, 

58 "summary": "Read Items", 

59 "operationId": "read_items_items__get", 

60 "security": [{"OAuth2AuthorizationCodeBearer": []}], 

61 } 

62 } 

63 }, 

64 "components": { 

65 "securitySchemes": { 

66 "OAuth2AuthorizationCodeBearer": { 

67 "type": "oauth2", 

68 "flows": { 

69 "authorizationCode": { 

70 "authorizationUrl": "authorize", 

71 "tokenUrl": "token", 

72 "scopes": {}, 

73 } 

74 }, 

75 "description": "OAuth2 Code Bearer", 

76 } 

77 } 

78 }, 

79 }