Skip to content

Commit

Permalink
Apply right name to Route when created from methods (#1553)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
flxdot and Kludex committed Apr 8, 2022
1 parent 487f05d commit d7cbe2a
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
2 changes: 1 addition & 1 deletion starlette/routing.py
Expand Up @@ -84,7 +84,7 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:


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__

Expand Down
36 changes: 36 additions & 0 deletions tests/test_routing.py
@@ -1,4 +1,5 @@
import functools
import typing
import uuid

import pytest
Expand Down Expand Up @@ -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

0 comments on commit d7cbe2a

Please sign in to comment.