Coverage for tests / test_dependency_paramless.py: 100%

34 statements  

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

1from typing import Annotated, Union 1abcd

2 

3from fastapi import FastAPI, HTTPException, Security 1abcd

4from fastapi.security import ( 1abcd

5 OAuth2PasswordBearer, 

6 SecurityScopes, 

7) 

8from fastapi.testclient import TestClient 1abcd

9 

10app = FastAPI() 1abcd

11 

12oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") 1abcd

13 

14 

15def process_auth( 1abcd

16 credentials: Annotated[Union[str, None], Security(oauth2_scheme)], 

17 security_scopes: SecurityScopes, 

18): 

19 # This is an incorrect way of using it, this is not checking if the scopes are 

20 # provided by the token, only if the endpoint is requesting them, but the test 

21 # here is just to check if FastAPI is indeed registering and passing the scopes 

22 # correctly when using Security with parameterless dependencies. 

23 if "a" not in security_scopes.scopes or "b" not in security_scopes.scopes: 1efkghlijm

24 raise HTTPException(detail="a or b not in scopes", status_code=401) 1klm

25 return {"token": credentials, "scopes": security_scopes.scopes} 1efghij

26 

27 

28@app.get("/get-credentials") 1abcd

29def get_credentials( 1abcd

30 credentials: Annotated[dict, Security(process_auth, scopes=["a", "b"])], 

31): 

32 return credentials 1egi

33 

34 

35@app.get( 1abcd

36 "/parameterless-with-scopes", 

37 dependencies=[Security(process_auth, scopes=["a", "b"])], 

38) 

39def get_parameterless_with_scopes(): 1abcd

40 return {"status": "ok"} 1fhj

41 

42 

43@app.get( 1abcd

44 "/parameterless-without-scopes", 

45 dependencies=[Security(process_auth)], 

46) 

47def get_parameterless_without_scopes(): 1abcd

48 return {"status": "ok"} 1nop

49 

50 

51client = TestClient(app) 1abcd

52 

53 

54def test_get_credentials(): 1abcd

55 response = client.get("/get-credentials", headers={"authorization": "Bearer token"}) 1egi

56 assert response.status_code == 200, response.text 1egi

57 assert response.json() == {"token": "token", "scopes": ["a", "b"]} 1egi

58 

59 

60def test_parameterless_with_scopes(): 1abcd

61 response = client.get( 1fhj

62 "/parameterless-with-scopes", headers={"authorization": "Bearer token"} 

63 ) 

64 assert response.status_code == 200, response.text 1fhj

65 assert response.json() == {"status": "ok"} 1fhj

66 

67 

68def test_parameterless_without_scopes(): 1abcd

69 response = client.get( 1klm

70 "/parameterless-without-scopes", headers={"authorization": "Bearer token"} 

71 ) 

72 assert response.status_code == 401, response.text 1klm

73 assert response.json() == {"detail": "a or b not in scopes"} 1klm

74 

75 

76def test_call_get_parameterless_without_scopes_for_coverage(): 1abcd

77 assert get_parameterless_without_scopes() == {"status": "ok"} 1nop