From 36d945b0262756d45d9d721c30f9dff329480135 Mon Sep 17 00:00:00 2001 From: Joe Knapper Date: Mon, 23 Nov 2026 17:01:24 +0000 Subject: [PATCH 1/5] Pin swagger to pre-virtualization removal --- src/labthings_fastapi/server/__init__.py | 41 ++++++++++++++++++++++-- tests/test_server.py | 16 +++++++++ 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/src/labthings_fastapi/server/__init__.py b/src/labthings_fastapi/server/__init__.py index 208a4765..fa283c10 100644 --- a/src/labthings_fastapi/server/__init__.py +++ b/src/labthings_fastapi/server/__init__.py @@ -18,7 +18,11 @@ from anyio.from_thread import BlockingPortal from fastapi import APIRouter, FastAPI, Request from fastapi.middleware.cors import CORSMiddleware -from fastapi.responses import JSONResponse +from fastapi.openapi.docs import ( + get_swagger_ui_html, + get_swagger_ui_oauth2_redirect_html, +) +from fastapi.responses import HTMLResponse, JSONResponse from fastapi.testclient import TestClient from pydantic import ValidationError from pydantic_core import PydanticSerializationError @@ -145,7 +149,12 @@ def __init__( self._config = ThingServerConfig(**kwargs) if self._config.settings_folder is None: self._config.settings_folder = "./settings" - self.app = FastAPI(lifespan=self.lifespan, separate_input_output_schemas=False) + # docs_url=None prevents the default docs page so labthings-fastapi + # can customise its own + self.app = FastAPI( + lifespan=self.lifespan, separate_input_output_schemas=False, docs_url=None + ) + self._add_swagger_ui() self._set_cors_middleware() self._set_url_for_middleware() self._add_exception_handlers() @@ -163,6 +172,34 @@ def __init__( self._connect_things() self._attach_things_to_server() + def _add_swagger_ui(self) -> None: + """Replace FastAPI's default Swagger UI with a pinned version.""" + # Swagger UI 5.33 introduced virtualization, so Ctrl+F misses endpoints + # that haven't been rendered. Pin 5.32.15 to keep browser Find working. + assets = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.32.15" + openapi_url = self.app.openapi_url + oauth2_redirect_url = self.app.swagger_ui_oauth2_redirect_url + assert openapi_url is not None and oauth2_redirect_url is not None # noqa: S101 + + async def swagger_ui_html(request: Request) -> HTMLResponse: + root_path = request.scope.get("root_path", "").rstrip("/") + # Recreate the docs page with the pinned JavaScript and CSS assets. + return get_swagger_ui_html( + openapi_url=root_path + openapi_url, + title=f"{self.app.title} - Swagger UI", + oauth2_redirect_url=root_path + oauth2_redirect_url, + swagger_js_url=f"{assets}/swagger-ui-bundle.js", + swagger_css_url=f"{assets}/swagger-ui.css", + ) + + async def swagger_ui_redirect(_request: Request) -> HTMLResponse: + return get_swagger_ui_oauth2_redirect_html() + + self.app.add_route("/docs", swagger_ui_html, include_in_schema=False) + self.app.add_route( + oauth2_redirect_url, swagger_ui_redirect, include_in_schema=False + ) + @classmethod def from_things( cls, diff --git a/tests/test_server.py b/tests/test_server.py index dc23ce39..a728d17c 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -5,6 +5,7 @@ """ import pytest +from fastapi.testclient import TestClient from starlette.routing import Route import labthings_fastapi as lt @@ -12,6 +13,21 @@ from labthings_fastapi.server.config_model import ThingServerConfig +def test_swagger_ui_assets(): + """Check that the docs use the pinned assets and respect the root path.""" + server = lt.ThingServer.from_things({}) + client = TestClient(server.app, root_path="/lab") + response = client.get("/docs") + response.raise_for_status() + + assets = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.32.15" + assert f'{assets}/swagger-ui-bundle.js"' in response.text + assert f'{assets}/swagger-ui.css"' in response.text + assert "url: '/lab/openapi.json'" in response.text + assert "'/lab/docs/oauth2-redirect'" in response.text + client.get("/docs/oauth2-redirect").raise_for_status() + + def test_server_from_config_non_thing_error(): """Test a typeerror is raised if something that's not a Thing is added.""" with pytest.raises(TypeError, match="not a Thing"): From 223e8802abb20e3bc1d33a0d6c977d500b18fc6e Mon Sep 17 00:00:00 2001 From: Joe Knapper Date: Mon, 23 Nov 2026 17:01:24 +0000 Subject: [PATCH 2/5] Pin swagger to pre-virtualization removal --- src/labthings_fastapi/server/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/labthings_fastapi/server/__init__.py b/src/labthings_fastapi/server/__init__.py index fa283c10..3f30089d 100644 --- a/src/labthings_fastapi/server/__init__.py +++ b/src/labthings_fastapi/server/__init__.py @@ -179,7 +179,8 @@ def _add_swagger_ui(self) -> None: assets = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.32.15" openapi_url = self.app.openapi_url oauth2_redirect_url = self.app.swagger_ui_oauth2_redirect_url - assert openapi_url is not None and oauth2_redirect_url is not None # noqa: S101 + if openapi_url is None or oauth2_redirect_url is None: + raise ValueError("Swagger UI requires OpenAPI and OAuth2 redirect URLs.") async def swagger_ui_html(request: Request) -> HTMLResponse: root_path = request.scope.get("root_path", "").rstrip("/") From 544f3362394cc47802bfd7c7bca937b02aa35dee Mon Sep 17 00:00:00 2001 From: Joe Knapper Date: Mon, 23 Nov 2026 17:19:41 +0000 Subject: [PATCH 3/5] Update docstring with ValueError --- src/labthings_fastapi/server/__init__.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/labthings_fastapi/server/__init__.py b/src/labthings_fastapi/server/__init__.py index 3f30089d..03c57c5b 100644 --- a/src/labthings_fastapi/server/__init__.py +++ b/src/labthings_fastapi/server/__init__.py @@ -173,7 +173,10 @@ def __init__( self._attach_things_to_server() def _add_swagger_ui(self) -> None: - """Replace FastAPI's default Swagger UI with a pinned version.""" + """Replace FastAPI's default Swagger UI with a pinned version. + + :raises ValueError: If the OpenAPI or OAuth2 redirect URL is missing. + """ # Swagger UI 5.33 introduced virtualization, so Ctrl+F misses endpoints # that haven't been rendered. Pin 5.32.15 to keep browser Find working. assets = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.32.15" From 5fed0cb45bb08510975de0d469db0c90f51a36f5 Mon Sep 17 00:00:00 2001 From: Joe Knapper Date: Mon, 23 Nov 2026 17:30:49 +0000 Subject: [PATCH 4/5] Add unit test for missing URL --- tests/test_server.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/test_server.py b/tests/test_server.py index a728d17c..612258a8 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -28,6 +28,20 @@ def test_swagger_ui_assets(): client.get("/docs/oauth2-redirect").raise_for_status() +@pytest.mark.parametrize( + "url_attribute", ["openapi_url", "swagger_ui_oauth2_redirect_url"] +) +def test_swagger_ui_requires_urls(url_attribute): + """Raise ValueError if either URL required by Swagger UI is missing.""" + server = lt.ThingServer.from_things({}) + setattr(server.app, url_attribute, None) + + with pytest.raises( + ValueError, match="Swagger UI requires OpenAPI and OAuth2 redirect URLs" + ): + server._add_swagger_ui() + + def test_server_from_config_non_thing_error(): """Test a typeerror is raised if something that's not a Thing is added.""" with pytest.raises(TypeError, match="not a Thing"): From 6a122ec7da856203a9749331cdef6e71f90cf2f8 Mon Sep 17 00:00:00 2001 From: JohemianKnapsody <43779362+JohemianKnapsody@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:19:32 +0000 Subject: [PATCH 5/5] Update tests/test_server.py Co-authored-by: Richard Bowman --- tests/test_server.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/test_server.py b/tests/test_server.py index 612258a8..1131e542 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -16,16 +16,16 @@ def test_swagger_ui_assets(): """Check that the docs use the pinned assets and respect the root path.""" server = lt.ThingServer.from_things({}) - client = TestClient(server.app, root_path="/lab") + with server.test_client() as client: response = client.get("/docs") - response.raise_for_status() + response.raise_for_status() - assets = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.32.15" - assert f'{assets}/swagger-ui-bundle.js"' in response.text - assert f'{assets}/swagger-ui.css"' in response.text - assert "url: '/lab/openapi.json'" in response.text - assert "'/lab/docs/oauth2-redirect'" in response.text - client.get("/docs/oauth2-redirect").raise_for_status() + assets = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.32.15" + assert f'{assets}/swagger-ui-bundle.js"' in response.text + assert f'{assets}/swagger-ui.css"' in response.text + assert "url: '/lab/openapi.json'" in response.text + assert "'/docs/oauth2-redirect'" in response.text + client.get("/docs/oauth2-redirect").raise_for_status() @pytest.mark.parametrize(