Coverage for tests / test_security_api_key_query_description.py: 100%

29 statements  

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

1from fastapi import Depends, FastAPI, Security 1abcd

2from fastapi.security import APIKeyQuery 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 = APIKeyQuery(name="key", description="API Key Query") 1abcd

10 

11 

12class User(BaseModel): 1abcd

13 username: str 1abcd

14 

15 

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

17 user = User(username=oauth_header) 1efg

18 return user 1efg

19 

20 

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

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

23 return current_user 1efg

24 

25 

26client = TestClient(app) 1abcd

27 

28 

29def test_security_api_key(): 1abcd

30 response = client.get("/users/me?key=secret") 1efg

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

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

33 

34 

35def test_security_api_key_no_key(): 1abcd

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

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

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

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

40 

41 

42def test_openapi_schema(): 1abcd

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

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

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

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

61 } 

62 } 

63 }, 

64 "components": { 

65 "securitySchemes": { 

66 "APIKeyQuery": { 

67 "type": "apiKey", 

68 "name": "key", 

69 "in": "query", 

70 "description": "API Key Query", 

71 } 

72 } 

73 }, 

74 } 

75 )