]> git.ipfire.org Git - thirdparty/starlette.git/commitdiff
Apply right name to `Route` when created from methods (#1553)
authorFelix Fanghaenel <35657654+flxdot@users.noreply.github.com>
Fri, 8 Apr 2022 18:53:17 +0000 (20:53 +0200)
committerGitHub <noreply@github.com>
Fri, 8 Apr 2022 18:53:17 +0000 (20:53 +0200)
* add support to read route names from methods

* simplify implementation

* add tests for automatic route naming

* simplify tests

* Apply suggestions from code review

* Update tests/test_routing.py

* format with black

* Apply suggestions from code review

Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
starlette/routing.py
tests/test_routing.py

index 0388304c9071a856810913f651d1ecdac991c5d7..ea6ec211715a39084c893dae3ee73cf4c02e671d 100644 (file)
@@ -84,7 +84,7 @@ def websocket_session(func: typing.Callable) -> ASGIApp:
 
 
 def get_name(endpoint: typing.Callable) -> str:
-    if inspect.isfunction(endpoint) or inspect.isclass(endpoint):
+    if inspect.isroutine(endpoint) or inspect.isclass(endpoint):
         return endpoint.__name__
     return endpoint.__class__.__name__
 
index 7077c5616befbacca7139a6debeefeb4d6be611f..e8adaca48bfc0f11689237c3bd360a1ceb1f87ee 100644 (file)
@@ -1,4 +1,5 @@
 import functools
+import typing
 import uuid
 
 import pytest
@@ -710,3 +711,38 @@ def test_duplicated_param_names():
         match="Duplicated param names id, name at path /{id}/{name}/{id}/{name}",
     ):
         Route("/{id}/{name}/{id}/{name}", user)
+
+
+class Endpoint:
+    async def my_method(self, request):
+        ...  # pragma: no cover
+
+    @classmethod
+    async def my_classmethod(cls, request):
+        ...  # pragma: no cover
+
+    @staticmethod
+    async def my_staticmethod(request):
+        ...  # pragma: no cover
+
+    def __call__(self, request):
+        ...  # pragma: no cover
+
+
+@pytest.mark.parametrize(
+    "endpoint, expected_name",
+    [
+        pytest.param(func_homepage, "func_homepage", id="function"),
+        pytest.param(Endpoint().my_method, "my_method", id="method"),
+        pytest.param(Endpoint.my_classmethod, "my_classmethod", id="classmethod"),
+        pytest.param(
+            Endpoint.my_staticmethod,
+            "my_staticmethod",
+            id="staticmethod",
+        ),
+        pytest.param(Endpoint(), "Endpoint", id="object"),
+        pytest.param(lambda request: ..., "<lambda>", id="lambda"),
+    ],
+)
+def test_route_name(endpoint: typing.Callable, expected_name: str):
+    assert Route(path="/", endpoint=endpoint).name == expected_name