Coverage for tests/test_custom_middleware_exception.py: 100%
51 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-01-13 13:38 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2025-01-13 13:38 +0000
1from pathlib import Path 1klmno
2from typing import Optional 1klmno
4from fastapi import APIRouter, FastAPI, File, UploadFile 1klmno
5from fastapi.exceptions import HTTPException 1klmno
6from fastapi.testclient import TestClient 1klmno
8app = FastAPI() 1klmno
10router = APIRouter() 1klmno
13class ContentSizeLimitMiddleware: 1klmno
14 """Content size limiting middleware for ASGI applications
15 Args:
16 app (ASGI application): ASGI application
17 max_content_size (optional): the maximum content size allowed in bytes, None for no limit
18 """
20 def __init__(self, app: APIRouter, max_content_size: Optional[int] = None): 1klmno
21 self.app = app 1abcde
22 self.max_content_size = max_content_size 1abcde
24 def receive_wrapper(self, receive): 1klmno
25 received = 0 1afbgchdiej
27 async def inner(): 1afbgchdiej
28 nonlocal received
29 message = await receive() 1afbgchdiej
30 if message["type"] != "http.request": 1afbgchdiej
31 return message # pragma: no cover
33 body_len = len(message.get("body", b"")) 1afbgchdiej
34 received += body_len 1afbgchdiej
35 if received > self.max_content_size: 1afbgchdiej
36 raise HTTPException( 1abcde
37 422,
38 detail={
39 "name": "ContentSizeLimitExceeded",
40 "code": 999,
41 "message": "File limit exceeded",
42 },
43 )
44 return message 1fghij
46 return inner 1afbgchdiej
48 async def __call__(self, scope, receive, send): 1klmno
49 if scope["type"] != "http" or self.max_content_size is None: 1afbgchdiej
50 await self.app(scope, receive, send) 1afbgchdiej
51 return 1afbgchdiej
53 wrapper = self.receive_wrapper(receive) 1afbgchdiej
54 await self.app(scope, wrapper, send) 1afbgchdiej
57@router.post("/middleware") 1klmno
58def run_middleware(file: UploadFile = File(..., description="Big File")): 1klmno
59 return {"message": "OK"} 1fghij
62app.include_router(router) 1klmno
63app.add_middleware(ContentSizeLimitMiddleware, max_content_size=2**8) 1klmno
66client = TestClient(app) 1klmno
69def test_custom_middleware_exception(tmp_path: Path): 1klmno
70 default_pydantic_max_size = 2**16 1abcde
71 path = tmp_path / "test.txt" 1abcde
72 path.write_bytes(b"x" * (default_pydantic_max_size + 1)) 1abcde
74 with client: 1abcde
75 with open(path, "rb") as file: 1abcde
76 response = client.post("/middleware", files={"file": file}) 1abcde
77 assert response.status_code == 422, response.text 1abcde
78 assert response.json() == { 1abcde
79 "detail": {
80 "name": "ContentSizeLimitExceeded",
81 "code": 999,
82 "message": "File limit exceeded",
83 }
84 }
87def test_custom_middleware_exception_not_raised(tmp_path: Path): 1klmno
88 path = tmp_path / "test.txt" 1fghij
89 path.write_bytes(b"<file content>") 1fghij
91 with client: 1fghij
92 with open(path, "rb") as file: 1fghij
93 response = client.post("/middleware", files={"file": file}) 1fghij
94 assert response.status_code == 200, response.text 1fghij
95 assert response.json() == {"message": "OK"} 1fghij