Coverage for tests / test_security_api_key_header_optional.py: 100%

32 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-21 17:29 +0000

1from fastapi import Depends, FastAPI, Security 1abcd

2from fastapi.security import APIKeyHeader 1abcd

3from fastapi.testclient import TestClient 1abcd

4from inline_snapshot import snapshot 1abcd

5from pydantic import BaseModel 1abcd

6 

7app = FastAPI() 1abcd

8 

9api_key = APIKeyHeader(name="key", auto_error=False) 1abcd

10 

11 

12class User(BaseModel): 1abcd

13 username: str 1abcd

14 

15 

16def get_current_user(oauth_header: str | None = Security(api_key)): 1abcd

17 if oauth_header is None: 1ehfigj

18 return None 1hij

19 user = User(username=oauth_header) 1efg

20 return user 1efg

21 

22 

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

24def read_current_user(current_user: User | None = Depends(get_current_user)): 1abcd

25 if current_user is None: 1ehfigj

26 return {"msg": "Create an account first"} 1hij

27 return current_user 1efg

28 

29 

30client = TestClient(app) 1abcd

31 

32 

33def test_security_api_key(): 1abcd

34 response = client.get("/users/me", headers={"key": "secret"}) 1efg

35 assert response.status_code == 200, response.text 1efg

36 assert response.json() == {"username": "secret"} 1efg

37 

38 

39def test_security_api_key_no_key(): 1abcd

40 response = client.get("/users/me") 1hij

41 assert response.status_code == 200, response.text 1hij

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

43 

44 

45def test_openapi_schema(): 1abcd

46 response = client.get("/openapi.json") 1klm

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

48 assert response.json() == snapshot( 1klm

49 { 

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": [{"APIKeyHeader": []}], 

64 } 

65 } 

66 }, 

67 "components": { 

68 "securitySchemes": { 

69 "APIKeyHeader": {"type": "apiKey", "name": "key", "in": "header"} 

70 } 

71 }, 

72 } 

73 )