From a004e6abf3a6cf554de7f412289a4539075c2c11 Mon Sep 17 00:00:00 2001 From: Your Name Date: Sun, 6 Feb 2022 19:09:48 +0000 Subject: [PATCH] Forbid using a single string in tags to avoid unexpected behavior --- fastapi/routing.py | 4 ++++ tests/test_tags.py | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 tests/test_tags.py diff --git a/fastapi/routing.py b/fastapi/routing.py index 63ad72964..4b4119014 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -466,6 +466,8 @@ class APIRouter(routing.Router): "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix + if tags: + assert not isinstance(tags, str), """tags should not be a string: please use ["tag"] instead of "tag".""" self.tags: List[str] = tags or [] self.dependencies = list(dependencies or []) or [] self.deprecated = deprecated @@ -515,6 +517,7 @@ class APIRouter(routing.Router): ) current_tags = self.tags.copy() if tags: + assert not isinstance(tags, str), """tags should not be a string: please use ["tag"] instead of "tag".""" current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: @@ -668,6 +671,7 @@ class APIRouter(routing.Router): ) current_tags = [] if tags: + assert not isinstance(tags, str), """tags should not be a string: please use ["tag"] instead of "tag".""" current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) diff --git a/tests/test_tags.py b/tests/test_tags.py new file mode 100644 index 000000000..f38d84223 --- /dev/null +++ b/tests/test_tags.py @@ -0,0 +1,27 @@ +import pytest +from fastapi import APIRouter, FastAPI + + +def test_string_is_invalid_in_router_tags(): + with pytest.raises(AssertionError): + router = APIRouter(tags="test") + +def test_string_is_invalid_in_router_route_tags(): + router = APIRouter() + + with pytest.raises(AssertionError): + @router.get("", tags="test") + def test(): + ... + + +def test_string_is_invalid_in_include_router_tags(): + app = FastAPI() + router = APIRouter() + + @router.get("") + def test(): + ... + + with pytest.raises(AssertionError): + app.include_router(router, prefix="/test", tags="test") \ No newline at end of file