Coverage for tests/test_security_api_key_cookie_optional.py: 100%

34 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-12-04 08:29 +0000

1from typing import Optional 1abcdefg

2 

3from fastapi import Depends, FastAPI, Security 1abcdefg

4from fastapi.security import APIKeyCookie 1abcdefg

5from fastapi.testclient import TestClient 1abcdefg

6from pydantic import BaseModel 1abcdefg

7 

8app = FastAPI() 1abcdefg

9 

10api_key = APIKeyCookie(name="key", auto_error=False) 1abcdefg

11 

12 

13class User(BaseModel): 1abcdefg

14 username: str 1abcdefg

15 

16 

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

18 if oauth_header is None: 1hoipjqkrlsmtnu

19 return None 1opqrstu

20 user = User(username=oauth_header) 1hijklmn

21 return user 1hijklmn

22 

23 

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

25def read_current_user(current_user: User = Depends(get_current_user)): 1abcdefg

26 if current_user is None: 1hoipjqkrlsmtnu

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

28 else: 

29 return current_user 1hijklmn

30 

31 

32def test_security_api_key(): 1abcdefg

33 client = TestClient(app, cookies={"key": "secret"}) 1hijklmn

34 response = client.get("/users/me") 1hijklmn

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

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

37 

38 

39def test_security_api_key_no_key(): 1abcdefg

40 client = TestClient(app) 1opqrstu

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

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

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

44 

45 

46def test_openapi_schema(): 1abcdefg

47 client = TestClient(app) 1vwxyzAB

48 response = client.get("/openapi.json") 1vwxyzAB

49 assert response.status_code == 200, response.text 1vwxyzAB

50 assert response.json() == { 1vwxyzAB

51 "openapi": "3.1.0", 

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

53 "paths": { 

54 "/users/me": { 

55 "get": { 

56 "responses": { 

57 "200": { 

58 "description": "Successful Response", 

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

60 } 

61 }, 

62 "summary": "Read Current User", 

63 "operationId": "read_current_user_users_me_get", 

64 "security": [{"APIKeyCookie": []}], 

65 } 

66 } 

67 }, 

68 "components": { 

69 "securitySchemes": { 

70 "APIKeyCookie": {"type": "apiKey", "name": "key", "in": "cookie"} 

71 } 

72 }, 

73 }