Allow empty routed path (issue #414) (#415)

This commit is contained in:
Vitaliy Kucheryaviy 2019-08-25 03:39:48 +03:00 committed by Sebastián Ramírez
parent 033bc2a6c9
commit f7f17fcfd6
2 changed files with 39 additions and 1 deletions

View File

@ -201,7 +201,6 @@ class APIRoute(routing.Route):
response_class: Type[Response] = JSONResponse,
dependency_overrides_provider: Any = None,
) -> None:
assert path.startswith("/"), "Routed paths must always start with '/'"
self.path = path
self.endpoint = endpoint
self.name = get_name(endpoint) if name is None else name
@ -448,6 +447,12 @@ class APIRouter(routing.Router):
assert not prefix.endswith(
"/"
), "A path prefix must not end with '/', as the routes will start with '/'"
else:
for r in router.routes:
if not r.path:
raise Exception(
f"Prefix and path cannot be both empty (operation: {r.name})"
)
if responses is None:
responses = {}
for route in router.routes:

View File

@ -0,0 +1,33 @@
import pytest
from fastapi import APIRouter, FastAPI
from starlette.testclient import TestClient
app = FastAPI()
router = APIRouter()
@router.get("")
def get_empty():
return ["OK"]
app.include_router(router, prefix="/prefix")
client = TestClient(app)
def test_use_empty():
with client:
response = client.get("/prefix")
assert response.json() == ["OK"]
response = client.get("/prefix/")
assert response.status_code == 404
def test_include_empty():
# if both include and router.path are empty - it should raise exception
with pytest.raises(Exception):
app.include_router(router)