# SPDX-FileCopyrightText: 2026 Dennis Fink # # SPDX-License-Identifier: BSD-3-Clause import uuid from datetime import UTC, datetime from http import HTTPStatus 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 from webmentions_ssg import db from webmentions_ssg.models.received import ReceivedWebmention from webmentions_ssg.models.sources import ( SentWebmention, SentWebmentionStatus, SourceDocument, ) from webmentions_ssg.models.utils import target_digest def test_uuid_annotations_and_relationships_resolve() -> None: """Verify that UUID columns and forward relationships map correctly.""" for model in (ReceivedWebmention, SourceDocument, SentWebmention): assert get_type_hints(model)["uuid"] == Mapped[uuid.UUID] assert sa.inspect(model).columns["uuid"].primary_key assert ( sa.inspect(SourceDocument).relationships["sent_webmentions"].mapper.class_ is SentWebmention ) assert ( sa.inspect(SentWebmention).relationships["source"].mapper.class_ is SourceDocument ) @pytest.mark.parametrize( ("desired_revision", "processed_revision", "expected"), [(1, None, True), (1, 0, True), (2, 1, True), (1, 1, False), (1, 2, False)], ) def test_sent_webmention_pending( desired_revision: int, processed_revision: int | None, expected: bool ) -> None: webmention = SentWebmention( target="https://example.com/post", desired_revision=desired_revision, processed_revision=processed_revision, ) assert webmention.awaiting_processing is expected def test_sent_webmention_pending_sql_matches_python(app: Flask) -> None: cases = [(1, None, True), (1, 0, True), (2, 1, True), (1, 1, False), (1, 2, False)] with app.app_context(): now = datetime.now(UTC) source = SourceDocument( path="pending/index.html", url="https://site.example/pending/", content_hash="0" * 32, last_seen_at=now, revised_at=now, ) for i, (desired, processed, _) in enumerate(cases): source.sent_webmentions.append( SentWebmention( target=f"https://example.com/post/{i}", desired_revision=desired, processed_revision=processed, ) ) db.session.add(source) db.session.commit() pending_ids = set( db.session.scalars( sa.select(SentWebmention.uuid).where(SentWebmention.awaiting_processing) ) ) for webmention, (_, _, expected) in zip( source.sent_webmentions, cases, strict=True ): assert webmention.awaiting_processing is expected assert (webmention.uuid in pending_ids) is expected result = db.session.execute( sa.update(SentWebmention) .where(SentWebmention.awaiting_processing) .values(attempt_count=1) ) assert isinstance(result, CursorResult) assert result.rowcount == 3 def test_source_repr() -> None: source = SourceDocument( path="example/index.html", url="https://dennisfink.me/blog/example/", content_hash="0" * 32, revision=1, last_seen_at=datetime.now(UTC), revised_at=datetime.now(UTC), ) assert repr(source) == "" def test_sent_webmention_repr() -> None: webmention = SentWebmention(target="https://example.com/post", desired_revision=1) assert repr(webmention) == "" def test_reopen_preserves_delivery_history() -> None: sent_at = datetime.now(UTC) mention = SentWebmention( target="https://example.com/post", linked=True, desired_revision=2, processed_revision=2, sent_revision=2, status=SentWebmentionStatus.SENT, attempt_count=3, next_retry_at=sent_at, last_sent_at=sent_at, ) assert mention.reset_for_revision(3, False) is None assert mention.desired_revision == 3 assert mention.linked is False assert mention.attempt_count == 0 assert mention.next_retry_at is None assert mention.status == SentWebmentionStatus.SENT assert mention.sent_revision == 2 def test_resend_requeues_current_revision_without_losing_send_history() -> None: sent_at = datetime.now(UTC) mention = SentWebmention( target="https://example.com/post", linked=True, desired_revision=3, processed_revision=3, sent_revision=2, status=SentWebmentionStatus.FAILED, failure_reason="Previous failure", webmention_endpoint="https://example.com/webmention", endpoint_response_status=HTTPStatus.SERVICE_UNAVAILABLE, status_url="https://example.com/status", attempt_count=3, next_retry_at=sent_at, last_attempted_at=sent_at, last_sent_at=sent_at, ) assert not mention.awaiting_processing assert mention.clear_result_for_resend() is None assert mention.desired_revision == 3 assert mention.linked is True assert mention.awaiting_processing assert mention.processed_revision is None assert mention.status is None assert mention.failure_reason is None assert mention.webmention_endpoint is None assert mention.endpoint_response_status is None assert mention.status_url is None assert mention.attempt_count == 0 assert mention.next_retry_at is None assert mention.sent_revision == 2 assert mention.last_attempted_at == sent_at assert mention.last_sent_at == sent_at def test_long_sent_targets_enforce_uniqueness_without_indexing_url_text( app: Flask, ) -> None: now = datetime.now(UTC) long_target = "https://destination.example/" + "a" * 4000 with app.app_context(): source = SourceDocument( path="long/index.html", url="https://example.com/long", content_hash="0" * 32, revision=1, last_seen_at=now, revised_at=now, ) source.sent_webmentions.append( SentWebmention(target=long_target, desired_revision=1) ) db.session.add(source) db.session.commit() assert source.sent_webmentions[0].target_digest == target_digest(long_target) source.sent_webmentions.append( SentWebmention(target=long_target, desired_revision=1) ) with pytest.raises(IntegrityError): db.session.commit() db.session.rollback()