Testing middleware and async function

August 17, 2022

import pytest
from fastapi import Request
from fastapi.responses import JSONResponse
 
from app.middleware import exception_middleware
 
 
@pytest.fixture
def fixt_request() -> Request:
    scope = {"type": "http", "method": "get"}
    r = Request(scope=scope)
    return r
 
 
class TestMiddleware:
    @pytest.mark.asyncio
    async def test_exception_middleware(self, fixt_request: Request):
        async def call_next_func(r: Request):
            raise ValueError("This is a simulated error")
 
        resp = await exception_middleware(request=fixt_request, call_next=call_next_func)
 
        assert isinstance(resp, JSONResponse)
        assert resp.status_code == 500