Coverage for tests / test_security_oauth2_authorization_code_bearer_scopes_openapi_simple.py: 100%

21 statements  

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

1# Ref: https://github.com/fastapi/fastapi/issues/14454 

2 

3from typing import Annotated 1abcd

4 

5from fastapi import Depends, FastAPI, Security 1abcd

6from fastapi.security import OAuth2AuthorizationCodeBearer 1abcd

7from fastapi.testclient import TestClient 1abcd

8from inline_snapshot import snapshot 1abcd

9 

10oauth2_scheme = OAuth2AuthorizationCodeBearer( 1abcd

11 authorizationUrl="api/oauth/authorize", 

12 tokenUrl="/api/oauth/token", 

13 scopes={"read": "Read access", "write": "Write access"}, 

14) 

15 

16 

17async def get_token(token: Annotated[str, Depends(oauth2_scheme)]) -> str: 1abcd

18 return token 1efg

19 

20 

21app = FastAPI(dependencies=[Depends(get_token)]) 1abcd

22 

23 

24@app.get("/admin", dependencies=[Security(get_token, scopes=["read", "write"])]) 1abcd

25async def read_admin(): 1abcd

26 return {"message": "Admin Access"} 1efg

27 

28 

29client = TestClient(app) 1abcd

30 

31 

32def test_read_admin(): 1abcd

33 response = client.get("/admin", headers={"Authorization": "Bearer faketoken"}) 1efg

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

35 assert response.json() == {"message": "Admin Access"} 1efg

36 

37 

38def test_openapi_schema(): 1abcd

39 response = client.get("/openapi.json") 1hij

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

41 assert response.json() == snapshot( 1hij

42 { 

43 "openapi": "3.1.0", 

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

45 "paths": { 

46 "/admin": { 

47 "get": { 

48 "summary": "Read Admin", 

49 "operationId": "read_admin_admin_get", 

50 "responses": { 

51 "200": { 

52 "description": "Successful Response", 

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

54 } 

55 }, 

56 "security": [ 

57 {"OAuth2AuthorizationCodeBearer": ["read", "write"]} 

58 ], 

59 } 

60 } 

61 }, 

62 "components": { 

63 "securitySchemes": { 

64 "OAuth2AuthorizationCodeBearer": { 

65 "type": "oauth2", 

66 "flows": { 

67 "authorizationCode": { 

68 "scopes": { 

69 "read": "Read access", 

70 "write": "Write access", 

71 }, 

72 "authorizationUrl": "api/oauth/authorize", 

73 "tokenUrl": "/api/oauth/token", 

74 } 

75 }, 

76 } 

77 } 

78 }, 

79 } 

80 )