Home / File/ test_custom_middleware_exception.py — fastapi Source File

test_custom_middleware_exception.py — fastapi Source File

Architecture documentation for test_custom_middleware_exception.py, a python file in the fastapi codebase. 6 imports, 0 dependents.

File python FastAPI Applications 6 imports 3 functions 1 classes

Entity Profile

Dependency Diagram

graph LR
  701a2e1b_486c_9b9e_27dc_b223ac1a3925["test_custom_middleware_exception.py"]
  b3e303a2_3f2d_638d_930c_3a5dcc2f5a42["pathlib"]
  701a2e1b_486c_9b9e_27dc_b223ac1a3925 --> b3e303a2_3f2d_638d_930c_3a5dcc2f5a42
  0dda2280_3359_8460_301c_e98c77e78185["typing"]
  701a2e1b_486c_9b9e_27dc_b223ac1a3925 --> 0dda2280_3359_8460_301c_e98c77e78185
  534f6e44_61b8_3c38_8b89_6934a6df9802["__init__.py"]
  701a2e1b_486c_9b9e_27dc_b223ac1a3925 --> 534f6e44_61b8_3c38_8b89_6934a6df9802
  01c652c5_d85c_f45e_848e_412c94ea4172["exceptions.py"]
  701a2e1b_486c_9b9e_27dc_b223ac1a3925 --> 01c652c5_d85c_f45e_848e_412c94ea4172
  53e07af2_3e5c_ea1f_ee6c_abc9792bf48b["HTTPException"]
  701a2e1b_486c_9b9e_27dc_b223ac1a3925 --> 53e07af2_3e5c_ea1f_ee6c_abc9792bf48b
  a7c04dee_ee23_5891_b185_47ff6bed036d["testclient.py"]
  701a2e1b_486c_9b9e_27dc_b223ac1a3925 --> a7c04dee_ee23_5891_b185_47ff6bed036d
  style 701a2e1b_486c_9b9e_27dc_b223ac1a3925 fill:#6366f1,stroke:#818cf8,color:#fff

Relationship Graph

Source Code

from pathlib import Path
from typing import Optional

from fastapi import APIRouter, FastAPI, File, UploadFile
from fastapi.exceptions import HTTPException
from fastapi.testclient import TestClient

app = FastAPI()

router = APIRouter()


class ContentSizeLimitMiddleware:
    """Content size limiting middleware for ASGI applications
    Args:
      app (ASGI application): ASGI application
      max_content_size (optional): the maximum content size allowed in bytes, None for no limit
    """

    def __init__(self, app: APIRouter, max_content_size: Optional[int] = None):
        self.app = app
        self.max_content_size = max_content_size

    def receive_wrapper(self, receive):
        received = 0

        async def inner():
            nonlocal received
            message = await receive()
            if message["type"] != "http.request":
                return message  # pragma: no cover

            body_len = len(message.get("body", b""))
            received += body_len
            if received > self.max_content_size:
                raise HTTPException(
                    422,
                    detail={
                        "name": "ContentSizeLimitExceeded",
                        "code": 999,
                        "message": "File limit exceeded",
                    },
                )
            return message

        return inner

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http" or self.max_content_size is None:
            await self.app(scope, receive, send)
            return

        wrapper = self.receive_wrapper(receive)
        await self.app(scope, wrapper, send)


@router.post("/middleware")
def run_middleware(file: UploadFile = File(..., description="Big File")):
    return {"message": "OK"}


app.include_router(router)
app.add_middleware(ContentSizeLimitMiddleware, max_content_size=2**8)


client = TestClient(app)


def test_custom_middleware_exception(tmp_path: Path):
    default_pydantic_max_size = 2**16
    path = tmp_path / "test.txt"
    path.write_bytes(b"x" * (default_pydantic_max_size + 1))

    with client:
        with open(path, "rb") as file:
            response = client.post("/middleware", files={"file": file})
        assert response.status_code == 422, response.text
        assert response.json() == {
            "detail": {
                "name": "ContentSizeLimitExceeded",
                "code": 999,
                "message": "File limit exceeded",
            }
        }


def test_custom_middleware_exception_not_raised(tmp_path: Path):
    path = tmp_path / "test.txt"
    path.write_bytes(b"<file content>")

    with client:
        with open(path, "rb") as file:
            response = client.post("/middleware", files={"file": file})
        assert response.status_code == 200, response.text
        assert response.json() == {"message": "OK"}

Domain

Subdomains

Frequently Asked Questions

What does test_custom_middleware_exception.py do?
test_custom_middleware_exception.py is a source file in the fastapi codebase, written in python. It belongs to the FastAPI domain, Applications subdomain.
What functions are defined in test_custom_middleware_exception.py?
test_custom_middleware_exception.py defines 3 function(s): run_middleware, test_custom_middleware_exception, test_custom_middleware_exception_not_raised.
What does test_custom_middleware_exception.py depend on?
test_custom_middleware_exception.py imports 6 module(s): HTTPException, __init__.py, exceptions.py, pathlib, testclient.py, typing.
Where is test_custom_middleware_exception.py in the architecture?
test_custom_middleware_exception.py is located at tests/test_custom_middleware_exception.py (domain: FastAPI, subdomain: Applications, directory: tests).

Analyze Your Own Codebase

Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.

Try Supermodel Free