Forbid using a single string in tags to avoid unexpected behavior

This commit is contained in:
Your Name 2022-02-06 19:09:48 +00:00
parent 672c55ac62
commit a004e6abf3
2 changed files with 31 additions and 0 deletions

View File

@ -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)

27
tests/test_tags.py Normal file
View File

@ -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")