# SPDX-FileCopyrightText: 2026 Dennis Fink # # SPDX-License-Identifier: BSD-3-Clause import uuid from collections.abc import Callable from datetime import UTC, datetime from typing import get_type_hints import pytest import sqlalchemy as sa from flask import Flask from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Mapped from webmentions_ssg import db from webmentions_ssg.models import ( ReceivedStatus, ReceivedWebmention, SentWebmention, Source, User, received_url_digest, sent_target_digest, uuid7_to_datetime, ) def test_uuid_annotations_and_relationships_resolve() -> None: """Keep UUID columns and forward relationships mapped without future annotations.""" for model in (ReceivedWebmention, Source, SentWebmention): assert get_type_hints(model)["uuid"] == Mapped[uuid.UUID] assert sa.inspect(model).columns["uuid"].primary_key assert ( sa.inspect(Source).relationships["sent_webmentions"].mapper.class_ is SentWebmention ) assert sa.inspect(SentWebmention).relationships["source"].mapper.class_ is Source def test_user_repr() -> None: user = User(username="admin", password="secret") assert repr(user) == "" def test_user_password_is_write_only() -> None: user = User(username="admin", password="secret") with pytest.raises(AttributeError, match="Password is write-only"): _ = user.password def test_user_password_is_hashed_and_can_be_checked() -> None: user = User(username="admin", password="secret") assert user.password_hash != "secret" assert user.check_password("secret") assert not user.check_password("wrong") @pytest.mark.parametrize( ("status", "expected"), [ (ReceivedStatus.RECEIVED, False), (ReceivedStatus.VERIFYING, False), (ReceivedStatus.VERIFIED, True), (ReceivedStatus.FAILED, False), (ReceivedStatus.DELETED, False), ], ) def test_received_webmention_verified(status: ReceivedStatus, expected: bool) -> None: webmention = ReceivedWebmention( uuid=uuid.uuid7(), source="https://source.example/post", target="https://dennisfink.me/blog/example/", status=status, ) assert webmention.verified is expected @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.pending 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 = Source( 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.pending) ) ) for webmention, (_, _, expected) in zip( source.sent_webmentions, cases, strict=True ): assert webmention.pending is expected assert (webmention.uuid in pending_ids) is expected result = db.session.execute( sa.update(SentWebmention) .where(SentWebmention.pending) .values(attempt_count=1) ) assert result.rowcount == 3 def test_uuid7_to_datetime() -> None: identifier = uuid.uuid7() timestamp = uuid7_to_datetime(identifier) assert timestamp.tzinfo is UTC assert timestamp.timestamp() == pytest.approx(identifier.time / 1000) @pytest.mark.parametrize( "factory", [ pytest.param( lambda identifier: ReceivedWebmention( uuid=identifier, source="https://source.example/post", target="https://dennisfink.me/blog/example/", ), id="received-webmention", ), pytest.param( lambda identifier: Source( uuid=identifier, 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), ), id="source", ), pytest.param( lambda identifier: SentWebmention( uuid=identifier, target="https://example.com/post", desired_revision=1 ), id="sent-webmention", ), ], ) def test_created_at_comes_from_uuid7_timestamp( factory: Callable[[uuid.UUID], ReceivedWebmention | Source | SentWebmention], ) -> None: identifier = uuid.uuid7() model = factory(identifier) assert model.created_at == uuid7_to_datetime(identifier) def test_received_webmention_repr() -> None: webmention = ReceivedWebmention( uuid=uuid.uuid7(), source="https://source.example/post", target="https://dennisfink.me/blog/example/", ) assert repr(webmention) == ( " " "'https://dennisfink.me/blog/example/'>" ) def test_source_repr() -> None: source = Source( 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_user_session_id_changes_when_password_hash_changes() -> None: user = User(username="admin", password="a strong passphrase", id=42) original_hash = user.password_hash original_id = user.get_id() assert original_id.startswith("42:") assert original_hash not in original_id assert len(original_id.split(":", 1)[1]) == 64 # Even a reset to the same password rehashes with a new salt, revoking # any old session token. user.password = "a strong passphrase" assert user.password_hash != original_hash assert user.get_id() != original_id def test_received_status_uses_non_native_enum() -> None: status_type = ReceivedWebmention.__table__.c.status.type assert isinstance(status_type, sa.Enum) assert status_type.enum_class is ReceivedStatus assert status_type.native_enum is False assert status_type.enums == [status.value for status in ReceivedStatus] def test_received_status_round_trips_as_enum(app: Flask) -> None: with app.app_context(): identifier = uuid.uuid7() mention = ReceivedWebmention( uuid=identifier, source="https://source.example/post", target="https://dennisfink.me/blog/example/", status=ReceivedStatus.VERIFIED, ) db.session.add(mention) db.session.commit() assert ( db.session.scalar( sa.text("SELECT status FROM received_webmentions WHERE uuid = :uuid"), {"uuid": identifier.hex}, ) == "verified" ) db.session.expunge_all() loaded = db.session.get(ReceivedWebmention, identifier) assert loaded is not None assert loaded.status is ReceivedStatus.VERIFIED def test_received_verification_reset_is_reusable_for_atomic_updates() -> None: from webmentions_ssg.models import ReceivedStatus mention = ReceivedWebmention( uuid=uuid.uuid7(), source="https://source.example/post", target="https://dennisfink.me/post", status=ReceivedStatus.FAILED, failure_reason="Old error", recovery_attempts=3, ) assert mention.reset_for_verification() is None assert mention.status == ReceivedStatus.RECEIVED assert mention.failure_reason is None assert mention.recovery_attempts == 0 assert mention.updated_at is not None def test_reopen_preserves_delivery_history() -> None: from webmentions_ssg.models import SentWebmentionStatus sent_at = datetime.now(UTC) mention = SentWebmention( target="https://example.com/post", active=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.reopen(3, False) is None assert mention.desired_revision == 3 assert mention.active 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: from webmentions_ssg.models import SentWebmentionStatus sent_at = datetime.now(UTC) mention = SentWebmention( target="https://example.com/post", active=True, desired_revision=3, processed_revision=3, sent_revision=2, status=SentWebmentionStatus.FAILED, failure_reason="Previous failure", endpoint="https://example.com/webmention", response_status=503, 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.pending assert mention.resend() is None assert mention.desired_revision == 3 assert mention.active is True assert mention.pending assert mention.processed_revision is None assert mention.status is None assert mention.failure_reason is None assert mention.endpoint is None assert mention.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_received_pair_fingerprint_is_unambiguous() -> None: assert received_url_digest("a", "bc") != received_url_digest("ab", "c") assert received_url_digest("a", "b") != received_url_digest("b", "a") def test_models_hash_url_fields_when_created_or_changed() -> None: received = ReceivedWebmention( uuid=uuid.uuid7(), source="https://source.example/a", target="https://site.example/b", ) assert received.url_digest == received_url_digest(received.source, received.target) received.source = "https://source.example/c" assert received.url_digest == received_url_digest(received.source, received.target) received.target = "https://site.example/d" assert received.url_digest == received_url_digest(received.source, received.target) sent = SentWebmention(target="https://site.example/a", desired_revision=1) assert sent.target_digest == sent_target_digest(sent.target) sent.target = "https://site.example/b" assert sent.target_digest == sent_target_digest(sent.target) def test_long_received_pair_can_be_stored_with_unique_digest(app: Flask) -> None: long_source = "https://source.example/" + "a" * 4000 long_target = "https://dennisfink.me/" + "b" * 4000 with app.app_context(): db.session.add( ReceivedWebmention( uuid=uuid.uuid7(), source=long_source, target=long_target ) ) db.session.commit() match = db.session.scalar( sa.select(ReceivedWebmention).where( ReceivedWebmention.url_digest == received_url_digest(long_source, long_target) ) ) assert match is not None assert match.source == long_source assert match.target == long_target db.session.add( ReceivedWebmention( uuid=uuid.uuid7(), source=long_source, target=long_target ) ) with pytest.raises(IntegrityError): db.session.commit() db.session.rollback() 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 = Source( 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 == sent_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()