aboutsummaryrefslogtreecommitdiff
path: root/tests/test_models.py
blob: bb95be2c25f645d9228020eda4a2c82f8c813a64 (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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

import uuid
from collections.abc import Callable
from datetime import UTC, datetime

import pytest
import sqlalchemy as sa
from flask import Flask
from sqlalchemy.exc import IntegrityError

from webmentions_ssg import db
from webmentions_ssg.models import (
    ReceivedWebmention,
    SentWebmention,
    Source,
    User,
    received_url_digest,
    sent_target_digest,
    uuid7_to_datetime,
)


def test_user_repr() -> None:
    user = User(username="admin", password="secret")
    assert repr(user) == "<User admin>"


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"),
    [
        ("received", False),
        ("verifying", False),
        ("verified", True),
        ("failed", False),
        ("deleted", False),
    ],
)
def test_received_webmention_verified(status: str, 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) == (
        "<ReceivedWebmention 'https://source.example/post' -> "
        "'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) == "<Source '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_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_remains_text_with_enum_constants() -> None:
    from sqlalchemy import Text

    from webmentions_ssg.models import ReceivedStatus

    assert isinstance(ReceivedWebmention.__table__.c.status.type, Text)
    assert ReceivedStatus.VERIFIED == "verified"
    assert ReceivedStatus.DELETED == "deleted"


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