Coverage for tests / test_security_openid_connect_optional.py: 100%

37 statements  

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

1from typing import Optional 1abcd

2 

3from fastapi import Depends, FastAPI, Security 1abcd

4from fastapi.security.open_id_connect_url import OpenIdConnect 1abcd

5from fastapi.testclient import TestClient 1abcd

6from inline_snapshot import snapshot 1abcd

7from pydantic import BaseModel 1abcd

8 

9app = FastAPI() 1abcd

10 

11oid = OpenIdConnect(openIdConnectUrl="/openid", auto_error=False) 1abcd

12 

13 

14class User(BaseModel): 1abcd

15 username: str 1abcd

16 

17 

18def get_current_user(oauth_header: Optional[str] = Security(oid)): 1abcd

19 if oauth_header is None: 1ekfglhimj

20 return None 1klm

21 user = User(username=oauth_header) 1efghij

22 return user 1efghij

23 

24 

25@app.get("/users/me") 1abcd

26def read_current_user(current_user: Optional[User] = Depends(get_current_user)): 1abcd

27 if current_user is None: 1ekfglhimj

28 return {"msg": "Create an account first"} 1klm

29 return current_user 1efghij

30 

31 

32client = TestClient(app) 1abcd

33 

34 

35def test_security_oauth2(): 1abcd

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

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

38 assert response.json() == {"username": "Bearer footokenbar"} 1egi

39 

40 

41def test_security_oauth2_password_other_header(): 1abcd

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

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

44 assert response.json() == {"username": "Other footokenbar"} 1fhj

45 

46 

47def test_security_oauth2_password_bearer_no_header(): 1abcd

48 response = client.get("/users/me") 1klm

49 assert response.status_code == 200, response.text 1klm

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

51 

52 

53def test_openapi_schema(): 1abcd

54 response = client.get("/openapi.json") 1nop

55 assert response.status_code == 200, response.text 1nop

56 assert response.json() == snapshot( 1nop

57 { 

58 "openapi": "3.1.0", 

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

60 "paths": { 

61 "/users/me": { 

62 "get": { 

63 "responses": { 

64 "200": { 

65 "description": "Successful Response", 

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

67 } 

68 }, 

69 "summary": "Read Current User", 

70 "operationId": "read_current_user_users_me_get", 

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

72 } 

73 } 

74 }, 

75 "components": { 

76 "securitySchemes": { 

77 "OpenIdConnect": { 

78 "type": "openIdConnect", 

79 "openIdConnectUrl": "/openid", 

80 } 

81 } 

82 }, 

83 } 

84 )