From cba90a77fe1b5929ae99616af597665120704b7e Mon Sep 17 00:00:00 2001 From: ed Date: Wed, 25 Dec 2024 09:48:06 +0100 Subject: [PATCH] Make UUID path parameter conversion more flexible (#2806) --- starlette/convertors.py | 2 +- tests/test_convertors.py | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/starlette/convertors.py b/starlette/convertors.py index 2d8ab53b..84df87a5 100644 --- a/starlette/convertors.py +++ b/starlette/convertors.py @@ -67,7 +67,7 @@ class FloatConvertor(Convertor[float]): class UUIDConvertor(Convertor[uuid.UUID]): - regex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" + regex = "[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}" def convert(self, value: str) -> uuid.UUID: return uuid.UUID(value) diff --git a/tests/test_convertors.py b/tests/test_convertors.py index ced1b86c..0fabe101 100644 --- a/tests/test_convertors.py +++ b/tests/test_convertors.py @@ -1,5 +1,6 @@ from datetime import datetime from typing import Iterator +from uuid import UUID import pytest @@ -70,3 +71,26 @@ def test_default_float_convertor(test_client_factory: TestClientFactory, param: client = test_client_factory(app) response = client.get(f"/{param}") assert response.status_code == status_code + + +@pytest.mark.parametrize( + "param, status_code", + [ + ("00000000-aaaa-ffff-9999-000000000000", 200), + ("00000000aaaaffff9999000000000000", 200), + ("00000000-AAAA-FFFF-9999-000000000000", 200), + ("00000000AAAAFFFF9999000000000000", 200), + ("not-a-uuid", 404), + ], +) +def test_default_uuid_convertor(test_client_factory: TestClientFactory, param: str, status_code: int) -> None: + def uuid_convertor(request: Request) -> JSONResponse: + param = request.path_params["param"] + assert isinstance(param, UUID) + return JSONResponse("ok") + + app = Router(routes=[Route("/{param:uuid}", endpoint=uuid_convertor)]) + + client = test_client_factory(app) + response = client.get(f"/{param}") + assert response.status_code == status_code -- 2.47.3