[Python] Trying to write a unit test to test a fastapi app with a middleware that changes the...

Discussão em 'Python' iniciado por Stack, Agosto 13, 2025.

  1. Stack

    Stack Membro Participativo

    This is the code below. I want to test a request coming in that has part of its path prefixed by external means. This middleware removes it before servicing the request.

    app = FastAPI(
    title="title",
    description="description",
    version="1.0.0",
    contact={"name": "Me"},
    )

    # Middleware to remove ingress_path from incoming requests which is required for various environments
    # where an additional path is added to the URL before the actual path.
    # This middleware is only applied if the environment variable INGRESS_PATH_TO_REMOVE_FROM_INCOMING_REQUESTS is set.
    # Further down in the code, the remove_path is used to construct the URL for the Swagger UI.
    ingress_path = os.getenv(
    "INGRESS_PATH_TO_REMOVE_FROM_INCOMING_REQUESTS",
    "",
    )

    if ingress_path != "":

    @app.middleware("http")
    async def modify_request_response_middleware(request: Request, call_next):
    # Intercept and modify the incoming request
    if ingress_path in request.url.path:
    logging.debug(
    f"Removing ingress path '{ingress_path}' from the Request URL: '{request.url.path}'"
    )
    new_path = str(request.url.path).replace(ingress_path, "")
    logging.debug(f"Modified URL: '{new_path}'")
    request.scope["path"] = new_path
    # Process the modified request
    response = await call_next(request)

    return response


    Test: (mock_dependencies just mocks out some unneeded stuff for the purposes of this test)

    import os
    import pytest
    from unittest.mock import patch, AsyncMock, MagicMock
    from fastapi import FastAPI
    from fastapi.testclient import TestClient
    from api import app

    @pytest.fixture
    def app_with_ingress_path(mock_dependencies):
    """Create FastAPI app with ingress path middleware"""
    os.environ['INGRESS_PATH_TO_REMOVE_FROM_INCOMING_REQUESTS'] = '/api/v1'
    return app


    def test_middleware_removes_ingress_path_from_url(app_with_ingress_path):
    """Test that middleware removes ingress path from request URL"""
    # Use the app_with_ingress_path fixture directly

    # Mock a simple endpoint for testing
    @app_with_ingress_path.get("/test")
    async def test_endpoint(): # noqa: F811
    return {"message": "test"}

    client = TestClient(app_with_ingress_path)
    # Request should be processed after middleware removes /api/v1 prefix
    response = client.get("/api/v1/test")
    assert response.status_code == 200


    The assert fails:

    > assert response.status_code == 200
    E assert 404 == 200
    E + where 404 = <Response [404 Not Found]>.status_code


    I don't know how to get this to work.

    Continue reading...

Compartilhe esta Página