Coverage for tests/test_security_openid_connect.py: 100%

31 statements  

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

1from fastapi import Depends, FastAPI, Security 1abcde

2from fastapi.security.open_id_connect_url import OpenIdConnect 1abcde

3from fastapi.testclient import TestClient 1abcde

4from pydantic import BaseModel 1abcde

5 

6app = FastAPI() 1abcde

7 

8oid = OpenIdConnect(openIdConnectUrl="/openid") 1abcde

9 

10 

11class User(BaseModel): 1abcde

12 username: str 1abcde

13 

14 

15def get_current_user(oauth_header: str = Security(oid)): 1abcde

16 user = User(username=oauth_header) 1abcde

17 return user 1abcde

18 

19 

20@app.get("/users/me") 1abcde

21def read_current_user(current_user: User = Depends(get_current_user)): 1abcde

22 return current_user 1abcde

23 

24 

25client = TestClient(app) 1abcde

26 

27 

28def test_security_oauth2(): 1abcde

29 response = client.get("/users/me", headers={"Authorization": "Bearer footokenbar"}) 1abcde

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

31 assert response.json() == {"username": "Bearer footokenbar"} 1abcde

32 

33 

34def test_security_oauth2_password_other_header(): 1abcde

35 response = client.get("/users/me", headers={"Authorization": "Other footokenbar"}) 1abcde

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

37 assert response.json() == {"username": "Other footokenbar"} 1abcde

38 

39 

40def test_security_oauth2_password_bearer_no_header(): 1abcde

41 response = client.get("/users/me") 1abcde

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

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

44 

45 

46def test_openapi_schema(): 1abcde

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

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

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

50 "openapi": "3.1.0", 

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

52 "paths": { 

53 "/users/me": { 

54 "get": { 

55 "responses": { 

56 "200": { 

57 "description": "Successful Response", 

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

59 } 

60 }, 

61 "summary": "Read Current User", 

62 "operationId": "read_current_user_users_me_get", 

63 "security": [{"OpenIdConnect": []}], 

64 } 

65 } 

66 }, 

67 "components": { 

68 "securitySchemes": { 

69 "OpenIdConnect": { 

70 "type": "openIdConnect", 

71 "openIdConnectUrl": "/openid", 

72 } 

73 } 

74 }, 

75 }