aboutsummaryrefslogtreecommitdiff
path: root/tests/models/test_sources.py
blob: 10af3d6e2f886d2eeb6886b849c37c509ff5adbf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# 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) == "<SourceDocument 'https://dennisfink.me/blog/example/'>"


def test_sent_webmention_repr() -> None:
    webmention = SentWebmention(target="https://example.com/post", desired_revision=1)
    assert repr(webmention) == "<SentWebmention 'https://example.com/post'>"


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()