Coverage for tests/test_security_openid_connect_description.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( 1abcde

9 openIdConnectUrl="/openid", description="OpenIdConnect security scheme" 

10) 

11 

12 

13class User(BaseModel): 1abcde

14 username: str 1abcde

15 

16 

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

18 user = User(username=oauth_header) 1abcde

19 return user 1abcde

20 

21 

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

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

24 return current_user 1abcde

25 

26 

27client = TestClient(app) 1abcde

28 

29 

30def test_security_oauth2(): 1abcde

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

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

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

34 

35 

36def test_security_oauth2_password_other_header(): 1abcde

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

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

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

40 

41 

42def test_security_oauth2_password_bearer_no_header(): 1abcde

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

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

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

46 

47 

48def test_openapi_schema(): 1abcde

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

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

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

52 "openapi": "3.1.0", 

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

54 "paths": { 

55 "/users/me": { 

56 "get": { 

57 "responses": { 

58 "200": { 

59 "description": "Successful Response", 

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

61 } 

62 }, 

63 "summary": "Read Current User", 

64 "operationId": "read_current_user_users_me_get", 

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

66 } 

67 } 

68 }, 

69 "components": { 

70 "securitySchemes": { 

71 "OpenIdConnect": { 

72 "type": "openIdConnect", 

73 "openIdConnectUrl": "/openid", 

74 "description": "OpenIdConnect security scheme", 

75 } 

76 } 

77 }, 

78 }