From 111de8995783ca3a8b8bbdbabae6d15bb2009ffa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20S=C3=A1nchez?= Date: Thu, 30 Oct 2025 10:50:23 +0100 Subject: [PATCH] Add check for ciruclar imports + test --- fastapi/routing.py | 1 + tests/test_router_circular_import.py | 11 +++++++++++ 2 files changed, 12 insertions(+) create mode 100644 tests/test_router_circular_import.py diff --git a/fastapi/routing.py b/fastapi/routing.py index 0b59d250a..eb3d2c620 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -1333,6 +1333,7 @@ class APIRouter(routing.Router): app.include_router(internal_router) ``` """ + assert self is not router, "Cannot include router into itself" if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith("/"), ( diff --git a/tests/test_router_circular_import.py b/tests/test_router_circular_import.py new file mode 100644 index 000000000..dfec8d24c --- /dev/null +++ b/tests/test_router_circular_import.py @@ -0,0 +1,11 @@ +import pytest +from fastapi import APIRouter, FastAPI + + +def test_router_circular_import(): + app = FastAPI() + router = APIRouter() + + app.include_router(router) + with pytest.raises(AssertionError, match="Router cannot be the same as parent"): + router.include_router(router) \ No newline at end of file