Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apply right name to Route when created from methods #1553

Merged
merged 13 commits into from Apr 8, 2022
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):
Copy link
Sponsor Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the behavior of lambda changes now?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No:

import inspect
my_lambda = lambda: 1
assert inspect.isfunction(my_lambda) == inspect.isroutine(my_lambda)

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):
...
Kludex marked this conversation as resolved.
Show resolved Hide resolved

@classmethod
async def my_classmethod(cls, request):
...
Kludex marked this conversation as resolved.
Show resolved Hide resolved

@staticmethod
async def my_staticmethod(request):
...
Kludex marked this conversation as resolved.
Show resolved Hide resolved

def __call__(self, request):
...
Kludex marked this conversation as resolved.
Show resolved Hide resolved


@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