Coverage for tests / test_security_api_key_header.py: 100%

29 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") 1adbc

10 

11 

12class User(BaseModel): 1adbc

13 username: str 1abc

14 

15 

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

17 user = User(username=oauth_header) 1efgh

18 return user 1efgh

19 

20 

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

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

23 return current_user 1efgh

24 

25 

26client = TestClient(app) 1adbc

27 

28 

29def test_security_api_key(): 1adbc

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

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

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

33 

34 

35def test_security_api_key_no_key(): 1adbc

36 response = client.get("/users/me") 1ijkl

37 assert response.status_code == 401, response.text 1ijkl

38 assert response.json() == {"detail": "Not authenticated"} 1ijkl

39 assert response.headers["WWW-Authenticate"] == "APIKey" 1ijkl

40 

41 

42def test_openapi_schema(): 1adbc

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

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

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

46 { 

47 "openapi": "3.1.0", 

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

49 "paths": { 

50 "/users/me": { 

51 "get": { 

52 "responses": { 

53 "200": { 

54 "description": "Successful Response", 

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

56 } 

57 }, 

58 "summary": "Read Current User", 

59 "operationId": "read_current_user_users_me_get", 

60 "security": [{"APIKeyHeader": []}], 

61 } 

62 } 

63 }, 

64 "components": { 

65 "securitySchemes": { 

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

67 } 

68 }, 

69 } 

70 )