Coverage for tests / test_security_api_key_cookie_optional.py: 100%

35 statements  

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

1from typing import Optional 1abcd

2 

3from fastapi import Depends, FastAPI, Security 1abcd

4from fastapi.security import APIKeyCookie 1abcd

5from fastapi.testclient import TestClient 1abcd

6from inline_snapshot import snapshot 1abcd

7from pydantic import BaseModel 1abcd

8 

9app = FastAPI() 1abcd

10 

11api_key = APIKeyCookie(name="key", auto_error=False) 1abcd

12 

13 

14class User(BaseModel): 1abcd

15 username: str 1abcd

16 

17 

18def get_current_user(oauth_header: Optional[str] = Security(api_key)): 1abcd

19 if oauth_header is None: 1ehfigj

20 return None 1hij

21 user = User(username=oauth_header) 1efg

22 return user 1efg

23 

24 

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

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

27 if current_user is None: 1ehfigj

28 return {"msg": "Create an account first"} 1hij

29 else: 

30 return current_user 1efg

31 

32 

33def test_security_api_key(): 1abcd

34 client = TestClient(app, cookies={"key": "secret"}) 1efg

35 response = client.get("/users/me") 1efg

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

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

38 

39 

40def test_security_api_key_no_key(): 1abcd

41 client = TestClient(app) 1hij

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

43 assert response.status_code == 200, response.text 1hij

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

45 

46 

47def test_openapi_schema(): 1abcd

48 client = TestClient(app) 1klm

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

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

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

52 { 

53 "openapi": "3.1.0", 

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

55 "paths": { 

56 "/users/me": { 

57 "get": { 

58 "responses": { 

59 "200": { 

60 "description": "Successful Response", 

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

62 } 

63 }, 

64 "summary": "Read Current User", 

65 "operationId": "read_current_user_users_me_get", 

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

67 } 

68 } 

69 }, 

70 "components": { 

71 "securitySchemes": { 

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

73 } 

74 }, 

75 } 

76 )