Coverage for tests/test_security_openid_connect_optional.py: 100%

36 statements  

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

1from typing import Optional 1abcde

2 

3from fastapi import Depends, FastAPI, Security 1abcde

4from fastapi.security.open_id_connect_url import OpenIdConnect 1abcde

5from fastapi.testclient import TestClient 1abcde

6from pydantic import BaseModel 1abcde

7 

8app = FastAPI() 1abcde

9 

10oid = OpenIdConnect(openIdConnectUrl="/openid", auto_error=False) 1abcde

11 

12 

13class User(BaseModel): 1abcde

14 username: str 1abcde

15 

16 

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

18 if oauth_header is None: 1abcde

19 return None 1abcde

20 user = User(username=oauth_header) 1abcde

21 return user 1abcde

22 

23 

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

25def read_current_user(current_user: Optional[User] = Depends(get_current_user)): 1abcde

26 if current_user is None: 1abcde

27 return {"msg": "Create an account first"} 1abcde

28 return current_user 1abcde

29 

30 

31client = TestClient(app) 1abcde

32 

33 

34def test_security_oauth2(): 1abcde

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

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

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

38 

39 

40def test_security_oauth2_password_other_header(): 1abcde

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

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

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

44 

45 

46def test_security_oauth2_password_bearer_no_header(): 1abcde

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

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

49 assert response.json() == {"msg": "Create an account first"} 1abcde

50 

51 

52def test_openapi_schema(): 1abcde

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

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

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

56 "openapi": "3.1.0", 

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

58 "paths": { 

59 "/users/me": { 

60 "get": { 

61 "responses": { 

62 "200": { 

63 "description": "Successful Response", 

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

65 } 

66 }, 

67 "summary": "Read Current User", 

68 "operationId": "read_current_user_users_me_get", 

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

70 } 

71 } 

72 }, 

73 "components": { 

74 "securitySchemes": { 

75 "OpenIdConnect": { 

76 "type": "openIdConnect", 

77 "openIdConnectUrl": "/openid", 

78 } 

79 } 

80 }, 

81 }