Files
romm/backend/utils/test_router.py
Michael Manganiello 8abbae4c02 misc: Make backend handle URLs with trailing slash
According to multiple FastAPI discussions [1], FastAPI only includes a
built-in mechanism to redirect requests including a trailing slash, to
its variation without slash, using a `307` status code.

This can be an issue when certain clients do not send the same headers
on the redirected request.

This change adds a custom FastAPI `APIRouter`, that registers both route
path variations (with and without trailing slash), while only marking
the path without slash for being included in the OpenAPI schema.

[1] https://github.com/fastapi/fastapi/discussions/7298
2024-08-07 00:22:21 -03:00

32 lines
800 B
Python

import itertools
import pytest
from fastapi import Request
from utils.router import APIRouter
@pytest.mark.parametrize(
"method, route_path",
itertools.product(
("get", "post", "put", "delete", "patch"),
("/test", "/test/"),
),
)
def test_route_path_with_trailing_slash(method, route_path):
router = APIRouter()
@router.get(route_path)
@router.post(route_path)
@router.put(route_path)
@router.delete(route_path)
@router.patch(route_path)
def test_route(request: Request):
return {"test": "test"}
assert test_route(Request({"type": "http", "method": method, "url": "/test"})) == {
"test": "test"
}
assert test_route(Request({"type": "http", "method": method, "url": "/test/"})) == {
"test": "test"
}