From: Felix Fanghaenel <35657654+flxdot@users.noreply.github.com> Date: Fri, 8 Apr 2022 18:53:17 +0000 (+0200) Subject: Apply right name to `Route` when created from methods (#1553) X-Git-Tag: 0.19.1~3 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=d7cbe2a4887ad6b15fe7523ed62e28a426b7697d;p=thirdparty%2Fstarlette.git Apply right name to `Route` when created from methods (#1553) * 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 --- diff --git a/starlette/routing.py b/starlette/routing.py index 0388304c..ea6ec211 100644 --- a/starlette/routing.py +++ b/starlette/routing.py @@ -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__ diff --git a/tests/test_routing.py b/tests/test_routing.py index 7077c561..e8adaca4 100644 --- a/tests/test_routing.py +++ b/tests/test_routing.py @@ -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: ..., "", id="lambda"), + ], +) +def test_route_name(endpoint: typing.Callable, expected_name: str): + assert Route(path="/", endpoint=endpoint).name == expected_name