From 8e9342e18810e72656e75641e7365df0c406a2bf Mon Sep 17 00:00:00 2001 From: Adam Hopkins Date: Wed, 10 Aug 2022 20:36:47 +0300 Subject: [PATCH] Warn on duplicate route names (#2525) --- sanic/app.py | 12 ++++++++++++ tests/test_routes.py | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/sanic/app.py b/sanic/app.py index 59056eb2..fa0548c7 100644 --- a/sanic/app.py +++ b/sanic/app.py @@ -1521,6 +1521,18 @@ class Sanic(BaseSanic, RunnerMixin, metaclass=TouchUpMeta): self.signalize(self.config.TOUCHUP) self.finalize() + route_names = [route.name for route in self.router.routes] + duplicates = { + name for name in route_names if route_names.count(name) > 1 + } + if duplicates: + names = ", ".join(duplicates) + deprecation( + f"Duplicate route names detected: {names}. In the future, " + "Sanic will enforce uniqueness in route naming.", + 23.3, + ) + # TODO: Replace in v22.6 to check against apps in app registry if ( self.__class__._uvloop_setting is not None diff --git a/tests/test_routes.py b/tests/test_routes.py index 6fdf97d5..4ff5d9fd 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -1266,3 +1266,22 @@ async def test_added_callable_route_ctx_kwargs(app): assert request.route.ctx.foo() == "foo" assert await request.route.ctx.bar() == 99 + + +@pytest.mark.asyncio +async def test_duplicate_route_deprecation(app): + @app.route("/foo", name="duped") + async def handler_foo(request): + return text("...") + + @app.route("/bar", name="duped") + async def handler_bar(request): + return text("...") + + message = ( + r"\[DEPRECATION v23\.3\] Duplicate route names detected: " + r"test_duplicate_route_deprecation\.duped\. In the future, " + r"Sanic will enforce uniqueness in route naming\." + ) + with pytest.warns(DeprecationWarning, match=message): + await app._startup()