Coverage for tests / test_security_api_key_header_optional.py: 100%

32 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 import APIKeyHeader 1adbc

3from fastapi.testclient import TestClient 1adbc

4from inline_snapshot import snapshot 1adbc

5from pydantic import BaseModel 1adbc

6 

7app = FastAPI() 1adbc

8 

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

10 

11 

12class User(BaseModel): 1adbc

13 username: str 1abc

14 

15 

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

17 if oauth_header is None: 1iefjgkh

18 return None 1iljk

19 user = User(username=oauth_header) 1efgh

20 return user 1efgh

21 

22 

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

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

25 if current_user is None: 1iefjgkh

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

27 return current_user 1efgh

28 

29 

30client = TestClient(app) 1adbc

31 

32 

33def test_security_api_key(): 1adbc

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

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

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

37 

38 

39def test_security_api_key_no_key(): 1adbc

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

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

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

43 

44 

45def test_openapi_schema(): 1adbc

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

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

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

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 )