]> git.ipfire.org Git - thirdparty/starlette.git/commitdiff
Make UUID path parameter conversion more flexible (#2806)
authored <ed@edtheron.me>
Wed, 25 Dec 2024 08:48:06 +0000 (09:48 +0100)
committerGitHub <noreply@github.com>
Wed, 25 Dec 2024 08:48:06 +0000 (08:48 +0000)
starlette/convertors.py
tests/test_convertors.py

index 2d8ab53beb637891a435b277414947aacae433f6..84df87a586adf44bb6135d547049b9f5385f30b7 100644 (file)
@@ -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)
index ced1b86cc773e5f11f5b19a6697fea88c215c935..0fabe101b87b88a00a617c79898a19efe2bb5950 100644 (file)
@@ -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