You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
be-optimumoh/tests/unit/test_middleware_dispatch.py

57 lines
2.2 KiB
Python

import pytest
from unittest.mock import AsyncMock, MagicMock
from fastapi import HTTPException
from src.middleware import RequestValidationMiddleware
@pytest.mark.asyncio
async def test_request_validation_middleware_query_length():
middleware = RequestValidationMiddleware(app=MagicMock())
request = MagicMock()
request.url.query = "a" * 2001
with pytest.raises(HTTPException) as excinfo:
await middleware.dispatch(request, AsyncMock())
assert excinfo.value.status_code == 414
@pytest.mark.asyncio
async def test_request_validation_middleware_too_many_params():
middleware = RequestValidationMiddleware(app=MagicMock())
request = MagicMock()
request.url.query = "a=1"
request.query_params.multi_items.return_value = [("param", "val")] * 51
with pytest.raises(HTTPException) as excinfo:
await middleware.dispatch(request, AsyncMock())
assert excinfo.value.status_code == 400
assert "Too many query parameters" in excinfo.value.detail
@pytest.mark.asyncio
async def test_request_validation_middleware_xss_detection():
middleware = RequestValidationMiddleware(app=MagicMock())
request = MagicMock()
request.url.query = "q=<script>"
request.query_params.multi_items.return_value = [("q", "<script>")]
with pytest.raises(HTTPException) as excinfo:
await middleware.dispatch(request, AsyncMock())
assert excinfo.value.status_code == 400
assert "Potential XSS payload" in excinfo.value.detail
@pytest.mark.asyncio
async def test_request_validation_middleware_pagination_logic():
middleware = RequestValidationMiddleware(app=MagicMock())
request = MagicMock()
request.url.query = "size=55"
request.query_params.multi_items.return_value = [("size", "55")]
request.headers = {}
with pytest.raises(HTTPException) as excinfo:
await middleware.dispatch(request, AsyncMock())
assert excinfo.value.status_code == 400
assert "cannot exceed 50" in excinfo.value.detail
request.query_params.multi_items.return_value = [("size", "7")]
with pytest.raises(HTTPException) as excinfo:
await middleware.dispatch(request, AsyncMock())
assert "must be a multiple of 5" in excinfo.value.detail