Coverage for tests/test_security_api_key_query_optional.py: 100%

32 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-05-05 00:03 +0000

1from typing import Optional 1abcdef

2 

3from fastapi import Depends, FastAPI, Security 1abcdef

4from fastapi.security import APIKeyQuery 1abcdef

5from fastapi.testclient import TestClient 1abcdef

6from pydantic import BaseModel 1abcdef

7 

8app = FastAPI() 1abcdef

9 

10api_key = APIKeyQuery(name="key", auto_error=False) 1abcdef

11 

12 

13class User(BaseModel): 1abcdef

14 username: str 1abcdef

15 

16 

17def get_current_user(oauth_header: Optional[str] = Security(api_key)): 1abcdef

18 if oauth_header is None: 1gmhniojpkqlr

19 return None 1mnopqr

20 user = User(username=oauth_header) 1ghijkl

21 return user 1ghijkl

22 

23 

24@app.get("/users/me") 1abcdef

25def read_current_user(current_user: Optional[User] = Depends(get_current_user)): 1abcdef

26 if current_user is None: 1gmhniojpkqlr

27 return {"msg": "Create an account first"} 1mnopqr

28 return current_user 1ghijkl

29 

30 

31client = TestClient(app) 1abcdef

32 

33 

34def test_security_api_key(): 1abcdef

35 response = client.get("/users/me?key=secret") 1ghijkl

36 assert response.status_code == 200, response.text 1ghijkl

37 assert response.json() == {"username": "secret"} 1ghijkl

38 

39 

40def test_security_api_key_no_key(): 1abcdef

41 response = client.get("/users/me") 1mnopqr

42 assert response.status_code == 200, response.text 1mnopqr

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

44 

45 

46def test_openapi_schema(): 1abcdef

47 response = client.get("/openapi.json") 1stuvwx

48 assert response.status_code == 200, response.text 1stuvwx

49 assert response.json() == { 1stuvwx

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

64 } 

65 } 

66 }, 

67 "components": { 

68 "securitySchemes": { 

69 "APIKeyQuery": {"type": "apiKey", "name": "key", "in": "query"} 

70 } 

71 }, 

72 }