Coverage for tests / test_security_openid_connect.py: 100%

33 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-04-06 01:24 +0000

1from fastapi import Depends, FastAPI, Security 1adbc

2from fastapi.security.open_id_connect_url import OpenIdConnect 1adbc

3from fastapi.testclient import TestClient 1adbc

4from inline_snapshot import snapshot 1adbc

5from pydantic import BaseModel 1adbc

6 

7app = FastAPI() 1adbc

8 

9oid = OpenIdConnect(openIdConnectUrl="/openid") 1adbc

10 

11 

12class User(BaseModel): 1adbc

13 username: str 1abc

14 

15 

16def get_current_user(oauth_header: str = Security(oid)): 1adbc

17 user = User(username=oauth_header) 1efghijkl

18 return user 1efghijkl

19 

20 

21@app.get("/users/me") 1adbc

22def read_current_user(current_user: User = Depends(get_current_user)): 1adbc

23 return current_user 1efghijkl

24 

25 

26client = TestClient(app) 1adbc

27 

28 

29def test_security_oauth2(): 1adbc

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

31 assert response.status_code == 200, response.text 1fhjl

32 assert response.json() == {"username": "Bearer footokenbar"} 1fhjl

33 

34 

35def test_security_oauth2_password_other_header(): 1adbc

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

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

38 assert response.json() == {"username": "Other footokenbar"} 1egik

39 

40 

41def test_security_oauth2_password_bearer_no_header(): 1adbc

42 response = client.get("/users/me") 1mnop

43 assert response.status_code == 401, response.text 1mnop

44 assert response.json() == {"detail": "Not authenticated"} 1mnop

45 assert response.headers["WWW-Authenticate"] == "Bearer" 1mnop

46 

47 

48def test_openapi_schema(): 1adbc

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

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

51 assert response.json() == snapshot( 1qrst

52 { 

53 "openapi": "3.1.0", 

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

55 "paths": { 

56 "/users/me": { 

57 "get": { 

58 "responses": { 

59 "200": { 

60 "description": "Successful Response", 

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

62 } 

63 }, 

64 "summary": "Read Current User", 

65 "operationId": "read_current_user_users_me_get", 

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

67 } 

68 } 

69 }, 

70 "components": { 

71 "securitySchemes": { 

72 "OpenIdConnect": { 

73 "type": "openIdConnect", 

74 "openIdConnectUrl": "/openid", 

75 } 

76 } 

77 }, 

78 } 

79 )