From f267db9148e3a390a1a2e50fe71ac4675dceaea1 Mon Sep 17 00:00:00 2001 From: Dennis Fink Date: Wed, 18 Nov 2026 21:28:28 +0100 Subject: refactor(core): tighten static typing Add explicit runtime narrowing in tests and simplify Huey decorator annotations so static analysis reflects the dynamic task wrapper behavior. Clean up URL argument construction and form error updates while preserving existing application behavior. --- tests/forms/test_received.py | 2 ++ tests/forms/test_sources.py | 2 ++ tests/models/test_sources.py | 2 ++ tests/views/test_endpoint.py | 7 ++++-- tests/views/test_received.py | 39 +++++++++++++++++++++++--------- tests/views/test_sources.py | 46 ++++++++++++++++++++++++-------------- webmentions_ssg/tasks/extension.py | 12 +++++----- webmentions_ssg/views/sources.py | 22 +++++++++--------- webmentions_ssg/views/user.py | 5 ++++- 9 files changed, 90 insertions(+), 47 deletions(-) diff --git a/tests/forms/test_received.py b/tests/forms/test_received.py index 4ef9ed3..913ab6d 100644 --- a/tests/forms/test_received.py +++ b/tests/forms/test_received.py @@ -25,6 +25,8 @@ def test_received_filter_form_accepts_valid_get_params(app: Flask) -> None: assert form.validate() assert form.status.data == "declined" assert form.q.data == "example.org" + assert form.date_from.data is not None + assert form.date_to.data is not None assert form.date_from.data.isoformat() == "2026-11-08" assert form.date_to.data.isoformat() == "2026-11-14" assert "csrf_token" not in form._fields diff --git a/tests/forms/test_sources.py b/tests/forms/test_sources.py index 44b4096..082b0d3 100644 --- a/tests/forms/test_sources.py +++ b/tests/forms/test_sources.py @@ -29,6 +29,8 @@ def test_source_filter_form_accepts_get_params(app: Flask) -> None: ) assert form.validate() assert form.status.data == "retrying" + assert form.date_from.data is not None + assert form.date_to.data is not None assert form.date_from.data.isoformat() == "2026-11-08" assert form.date_to.data.isoformat() == "2026-11-14" assert (form.sort.data, form.order.data, form.per_page.data) == ( diff --git a/tests/models/test_sources.py b/tests/models/test_sources.py index 8d01d79..10af3d6 100644 --- a/tests/models/test_sources.py +++ b/tests/models/test_sources.py @@ -10,6 +10,7 @@ from typing import get_type_hints import pytest import sqlalchemy as sa from flask import Flask +from sqlalchemy.engine import CursorResult from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Mapped @@ -93,6 +94,7 @@ def test_sent_webmention_pending_sql_matches_python(app: Flask) -> None: .where(SentWebmention.awaiting_processing) .values(attempt_count=1) ) + assert isinstance(result, CursorResult) assert result.rowcount == 3 diff --git a/tests/views/test_endpoint.py b/tests/views/test_endpoint.py index cb6f426..bf99ed4 100644 --- a/tests/views/test_endpoint.py +++ b/tests/views/test_endpoint.py @@ -493,7 +493,10 @@ def test_endpoint_records_initial_and_resubmission_events( views_module: ModuleType, monkeypatch: pytest.MonkeyPatch, ) -> None: - from webmentions_ssg.models.received import ReceivedWebmentionStatusEvent + from webmentions_ssg.models.received import ( + ReceivedWebmentionStatus, + ReceivedWebmentionStatusEvent, + ) mock_endpoint_form(views_module, monkeypatch, valid=True) monkeypatch.setattr(views_module, "verify_webmention", Mock()) @@ -510,7 +513,7 @@ def test_endpoint_records_initial_and_resubmission_events( ) ).all() assert [event.action for event in events] == ["Received submission"] - mention.status = "failed" + mention.status = ReceivedWebmentionStatus.FAILED mention.failure_reason = "Previous failure" mention.updated_at = datetime.now(UTC) - timedelta(minutes=11) db.session.commit() diff --git a/tests/views/test_received.py b/tests/views/test_received.py index 1a291ae..ed31dc5 100644 --- a/tests/views/test_received.py +++ b/tests/views/test_received.py @@ -73,13 +73,17 @@ def test_received_table_hides_secondary_columns_on_mobile( assert len(headers) == len(cells) == 7 for index in (0, 3, 4, 5): # Select, target, received, updated for cell in (headers[index], cells[index]): - assert {"d-none", "d-md-table-cell"} <= set(cell.get("class", [])) + assert {"d-none", "d-md-table-cell"} <= set( + cell.get_attribute_list("class") + ) for index in (1, 2, 6): # Status, source, details stay visible - assert "d-none" not in cells[index].get("class", []) + assert "d-none" not in cells[index].get_attribute_list("class") assert cells[2].select_one(".d-md-none time") is not None - assert "text-break" in cells[2].get("class", []) + assert "text-break" in cells[2].get_attribute_list("class") for button in html.select("[data-received-bulk-action]"): - assert {"d-none", "d-md-inline-block"} <= set(button.get("class", [])) + assert {"d-none", "d-md-inline-block"} <= set( + button.get_attribute_list("class") + ) @pytest.mark.parametrize( @@ -837,7 +841,9 @@ def test_received_bulk_actions_reject_invalid_form( assert response.status_code == HTTPStatus.BAD_REQUEST form.validate_on_submit.assert_called_once_with() with app.app_context(): - assert db.session.get(ReceivedWebmention, identifier).status == "failed" + mention = db.session.get(ReceivedWebmention, identifier) + assert mention is not None + assert mention.status == "failed" @pytest.mark.parametrize( @@ -870,7 +876,9 @@ def test_received_bulk_actions_reject_invalid_filters_before_mutating( assert response.status_code == HTTPStatus.BAD_REQUEST with app.app_context(): - assert db.session.get(ReceivedWebmention, identifier).status == "failed" + mention = db.session.get(ReceivedWebmention, identifier) + assert mention is not None + assert mention.status == "failed" verify.assert_not_called() @@ -896,7 +904,9 @@ def test_received_bulk_actions_reject_empty_or_malformed_selection( assert response.status_code == HTTPStatus.BAD_REQUEST with app.app_context(): - assert db.session.get(ReceivedWebmention, identifier).status == "failed" + mention = db.session.get(ReceivedWebmention, identifier) + assert mention is not None + assert mention.status == "failed" verify.assert_not_called() @@ -929,7 +939,9 @@ def test_received_bulk_actions_reject_duplicate_oversized_or_stale_selection( assert oversized.status_code == HTTPStatus.BAD_REQUEST with app.app_context(): - assert db.session.get(ReceivedWebmention, first).status == "failed" + mention = db.session.get(ReceivedWebmention, first) + assert mention is not None + assert mention.status == "failed" assert db.session.get(ReceivedWebmention, second) is not None verify.assert_not_called() @@ -1001,7 +1013,9 @@ def test_reverify_selected_received_webmentions( assert webmention.status == "received" assert webmention.failure_reason is None assert webmention.recovery_attempts == 0 - assert db.session.get(ReceivedWebmention, unselected).status == "failed" + unselected_mention = db.session.get(ReceivedWebmention, unselected) + assert unselected_mention is not None + assert unselected_mention.status == "failed" assert verify.call_count == 2 assert {call.args[0] for call in verify.call_args_list} == {first, second} @@ -1264,12 +1278,15 @@ def test_received_detail_keeps_filters_and_returns_after_actions( "a", string=lambda value: bool(value and "Back to received" in value) ) assert back_link is not None - assert parse_qs(urlsplit(back_link["href"]).query) == { + back_href = back_link["href"] + assert isinstance(back_href, str) + assert parse_qs(urlsplit(back_href).query) == { key: [value] for key, value in query.items() } - action = soup.find(attrs={"data-title": "Reverify webmention?"}) + action = soup.select_one('button[data-title="Reverify webmention?"]') assert action is not None action_url = action["data-action"] + assert isinstance(action_url, str) assert parse_qs(urlsplit(action_url).query) == { **{key: [value] for key, value in query.items()}, "return_to": ["detail"], diff --git a/tests/views/test_sources.py b/tests/views/test_sources.py index c851833..a41c18c 100644 --- a/tests/views/test_sources.py +++ b/tests/views/test_sources.py @@ -12,7 +12,7 @@ from unittest.mock import Mock from urllib.parse import parse_qs, urlsplit import pytest -from bs4 import BeautifulSoup +from bs4 import BeautifulSoup, Tag from flask import Flask from flask.testing import FlaskClient @@ -33,6 +33,13 @@ from .helpers import ( ) +def _href(tag: Tag) -> str: + """Return an HTML link target, checking BeautifulSoup's attribute type.""" + href = tag.get("href") + assert isinstance(href, str) + return unescape(href) + + @pytest.fixture def sources_module(app: Flask) -> ModuleType: _ = app @@ -81,10 +88,12 @@ def test_sent_sources_table_hides_secondary_columns_on_mobile( assert len(headers) == len(cells) == 7 for index in (2, 4, 5, 6): # URL, revision, created, last seen for cell in (headers[index], cells[index]): - assert {"d-none", "d-md-table-cell"} <= set(cell.get("class", [])) + assert {"d-none", "d-md-table-cell"} <= set( + cell.get_attribute_list("class") + ) for index in (0, 1, 3): # Path, count, status stay visible - assert "d-none" not in cells[index].get("class", []) - assert "text-break" in cells[1].get("class", []) + assert "d-none" not in cells[index].get_attribute_list("class") + assert "text-break" in cells[1].get_attribute_list("class") def test_sent_source_lists_webmentions(app: Flask, client: FlaskClient) -> None: @@ -128,9 +137,11 @@ def test_sent_webmentions_table_keeps_status_and_actions_on_mobile( assert len(headers) == len(cells) == 7 for index in (2, 3, 4, 5): # Active, revisions, delivery, activity for cell in (headers[index], cells[index]): - assert {"d-none", "d-md-table-cell"} <= set(cell.get("class", [])) + assert {"d-none", "d-md-table-cell"} <= set( + cell.get_attribute_list("class") + ) for index in (0, 1, 6): # Target, status, resend action stay visible - assert "d-none" not in cells[index].get("class", []) + assert "d-none" not in cells[index].get_attribute_list("class") assert cells[6].select_one("button[data-action]") is not None @@ -380,9 +391,11 @@ def test_sources_filter_by_delivery_state_without_duplicate_rows( response = client.get("/sources", query_string={"status": status}) assert response.status_code == HTTPStatus.OK soup = BeautifulSoup(response.get_data(as_text=True), "html.parser") - paths = [ - row.select_one("td a").get_text(strip=True) for row in soup.select("tbody tr") - ] + paths = [] + for row in soup.select("tbody tr"): + link = row.select_one("td a") + assert link is not None + paths.append(link.get_text(strip=True)) assert set(paths) == {f"blog/{name}/index.html" for name in expected} assert len(paths) == len(expected) assert ( @@ -458,9 +471,9 @@ def test_sources_sort_links_preserve_filters( soup = BeautifulSoup(html, "html.parser") assert soup.select_one('th[aria-sort="ascending"]') is not None links = [ - parse_qs(urlsplit(unescape(a["href"])).query) + parse_qs(urlsplit(_href(a)).query) for a in soup.select("th a[href]") - if urlsplit(unescape(a["href"])).path == "/sources" + if urlsplit(_href(a)).path == "/sources" ] assert len(links) == 7 for link in links: @@ -495,10 +508,9 @@ def test_sources_sort_orders_by_count_and_path(app: Flask, client: FlaskClient) response = client.get("/sources", query_string={"sort": sort, "order": order}) assert response.status_code == HTTPStatus.OK soup = BeautifulSoup(response.get_data(as_text=True), "html.parser") - assert ( - soup.select_one("tbody tr td a").get_text(strip=True) - == f"blog/{expected_first}/index.html" - ) + link = soup.select_one("tbody tr td a") + assert link is not None + assert link.get_text(strip=True) == f"blog/{expected_first}/index.html" def test_sources_filter_pagination_and_navigation_preserve_parameters( @@ -520,7 +532,7 @@ def test_sources_filter_pagination_and_navigation_preserve_parameters( assert "28 sources" in html soup = BeautifulSoup(html, "html.parser") assert len(soup.select("tbody tr")) == 10 - urls = [unescape(a["href"]) for a in soup.select("a[href]")] + urls = [_href(a) for a in soup.select("a[href]")] assert any( urlsplit(url).path == "/sources" and parse_qs(urlsplit(url).query) @@ -541,7 +553,7 @@ def test_sources_filter_pagination_and_navigation_preserve_parameters( 'a[href*="/sources?"]' ) assert back is not None - assert parse_qs(urlsplit(unescape(back["href"])).query) == { + assert parse_qs(urlsplit(_href(back)).query) == { **{k: [v] for k, v in filters.items()}, "page": ["2"], } diff --git a/webmentions_ssg/tasks/extension.py b/webmentions_ssg/tasks/extension.py index a878e16..0ba87d8 100644 --- a/webmentions_ssg/tasks/extension.py +++ b/webmentions_ssg/tasks/extension.py @@ -185,9 +185,9 @@ class FlaskHuey: handle.bind() return handle - def task[**P, R]( + def task( self, *task_args: Any, **task_kwargs: Any - ) -> Callable[[Callable[P, R]], _DeferredTask]: + ) -> Callable[[Callable[..., Any]], _DeferredTask]: """Declare a task even before :meth:`init_app` has run. :param task_args: Positional arguments for the Huey task decorator. @@ -195,14 +195,14 @@ class FlaskHuey: :returns: Decorator that registers and returns a lazily bound task. """ - def decorator(func: Callable[P, R]) -> _DeferredTask: + def decorator(func: Callable[..., Any]) -> _DeferredTask: return self._register_task(func, task_args, task_kwargs, periodic=False) return decorator - def periodic_task[**P, R]( + def periodic_task( self, *task_args: Any, **task_kwargs: Any - ) -> Callable[[Callable[P, R]], _DeferredTask]: + ) -> Callable[[Callable[..., Any]], _DeferredTask]: """Declare a periodic task against the current or next backend. :param task_args: Positional arguments for the Huey periodic-task decorator. @@ -210,7 +210,7 @@ class FlaskHuey: :returns: Decorator that registers and returns a lazily bound periodic task. """ - def decorator(func: Callable[P, R]) -> _DeferredTask: + def decorator(func: Callable[..., Any]) -> _DeferredTask: return self._register_task(func, task_args, task_kwargs, periodic=True) return decorator diff --git a/webmentions_ssg/views/sources.py b/webmentions_ssg/views/sources.py index 1c9cc58..84b98fb 100644 --- a/webmentions_ssg/views/sources.py +++ b/webmentions_ssg/views/sources.py @@ -183,11 +183,10 @@ def rescan_sources() -> ResponseReturnValue: manual_scan_sources() flash("Source rescan queued.", "success") - query_args: dict[str, str | int] = dict(filters) page = request.args.get("page", 1, type=int) - if page > 1: - query_args["page"] = page - return redirect(url_for("webmentions.source_list", **query_args)) + return redirect( + url_for("webmentions.source_list", page=page if page > 1 else None, **filters) + ) @webmentions_bp.route("/sources/") @@ -256,11 +255,14 @@ def resend_webmention( flash(f"Webmention {webmention.uuid} queued for resend.", "success") - detail_args: dict[str, str | int] = dict(filters) - for name in ("page", "source_page"): - page = request.args.get(name, 1, type=int) - if page > 1: - detail_args[name] = page + page = request.args.get("page", 1, type=int) + source_page = request.args.get("source_page", 1, type=int) return redirect( - url_for("webmentions.source_detail", source_uuid=source_uuid, **detail_args) + url_for( + "webmentions.source_detail", + source_uuid=source_uuid, + page=page if page > 1 else None, + source_page=source_page if source_page > 1 else None, + **filters, + ) ) diff --git a/webmentions_ssg/views/user.py b/webmentions_ssg/views/user.py index 4675ade..ec253c4 100644 --- a/webmentions_ssg/views/user.py +++ b/webmentions_ssg/views/user.py @@ -25,7 +25,10 @@ def user_page() -> ResponseReturnValue: if form.validate_on_submit(): user = cast(User, current_user._get_current_object()) if not user.check_password(form.current_password.data or ""): - form.current_password.errors.append("Current password is incorrect.") + form.current_password.errors = [ + *form.current_password.errors, + "Current password is incorrect.", + ] else: user.password = form.new_password.data or "" db.session.commit() -- cgit v1.3.1