aboutsummaryrefslogtreecommitdiff
path: root/tests/views/test_dashboard.py
blob: 05730dd842fb02fa1c2e3e9de2a31c07a16f2d09 (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
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

from datetime import UTC, datetime, timedelta
from http import HTTPStatus
from uuid import UUID

import pytest
from bs4 import BeautifulSoup
from flask import Flask
from flask.testing import FlaskClient

from webmentions_ssg import db
from webmentions_ssg.models.received import ReceivedWebmention, ReceivedWebmentionStatus
from webmentions_ssg.models.scan_state import ScanState
from webmentions_ssg.models.sources import (
    SentWebmention,
    SentWebmentionStatus,
    SourceDocument,
)
from webmentions_ssg.views import dashboard

from .helpers import log_in


def received_uuid(at: datetime, sequence: int) -> UUID:
    """Construct a UUIDv7 at a controlled creation time for activity tests."""
    return UUID(
        int=(int(at.timestamp() * 1000) << 80) | (7 << 76) | (2 << 62) | sequence
    )


def test_dashboard_is_private_and_empty_by_default(
    app: Flask, client: FlaskClient
) -> None:
    response = client.get("/")
    assert response.status_code == HTTPStatus.FOUND
    assert response.headers["Location"].startswith("/login?")

    log_in(app, client)
    response = client.get("/")
    assert response.status_code == HTTPStatus.OK
    soup = BeautifulSoup(response.get_data(as_text=True), "html.parser")
    received = soup.find("section", attrs={"aria-labelledby": "received-summary"})
    outgoing = soup.find("section", attrs={"aria-labelledby": "sent-summary"})
    assert received is not None
    assert outgoing is not None
    assert "0 total" in received.get_text(" ", strip=True)
    assert "0 total" in outgoing.get_text(" ", strip=True)
    assert "No completed scan yet" in response.get_data(as_text=True)
    assert "Huey pending tasks" in response.get_data(as_text=True)
    assert 'href="/received?status=declined"' in response.get_data(as_text=True)
    assert 'href="/"' in response.get_data(as_text=True)


def test_dashboard_counts_statuses_windows_retries_and_queue(
    app: Flask, client: FlaskClient, monkeypatch: pytest.MonkeyPatch
) -> None:
    log_in(app, client)
    now = datetime.now(UTC)
    with app.app_context():
        for sequence, (status, days) in enumerate(
            (
                (ReceivedWebmentionStatus.RECEIVED, 1),
                (ReceivedWebmentionStatus.VERIFYING, 8),
                (ReceivedWebmentionStatus.VERIFIED, 31),
                (ReceivedWebmentionStatus.FAILED, 2),
                (ReceivedWebmentionStatus.SOURCE_REMOVED, 3),
            ),
            start=1,
        ):
            db.session.add(
                ReceivedWebmention(
                    uuid=received_uuid(now - timedelta(days=days), sequence),
                    source=f"https://source.example/{sequence}",
                    target="https://site.example/post",
                    status=status,
                    # Old updates must not change creation-based activity counts.
                    updated_at=now,
                )
            )
        source = SourceDocument(
            path="post/index.html",
            url="https://site.example/post",
            content_hash="0" * 32,
            revision=2,
            last_seen_at=now,
            revised_at=now,
        )
        source.sent_webmentions.extend(
            [
                SentWebmention(
                    target="https://target.example/success",
                    desired_revision=2,
                    processed_revision=2,
                    status=SentWebmentionStatus.SENT,
                    last_sent_at=now - timedelta(days=3),
                ),
                SentWebmention(
                    target="https://target.example/unsupported",
                    desired_revision=2,
                    processed_revision=2,
                    status=SentWebmentionStatus.NO_ENDPOINT,
                ),
                SentWebmention(
                    target="https://target.example/failed",
                    desired_revision=2,
                    processed_revision=2,
                    status=SentWebmentionStatus.FAILED,
                ),
                SentWebmention(
                    target="https://target.example/retry",
                    desired_revision=2,
                    status=SentWebmentionStatus.FAILED,
                    attempt_count=1,
                    next_retry_at=now + timedelta(hours=1),
                ),
                SentWebmention(
                    target="https://target.example/pending", desired_revision=2
                ),
                SentWebmention(
                    target="https://target.example/not-attempted",
                    desired_revision=2,
                    processed_revision=2,
                    linked=False,
                ),
                # A claimed in-flight send has a future deadline but no
                # recorded failure and must not count as waiting to retry.
                SentWebmention(
                    target="https://target.example/inflight",
                    desired_revision=2,
                    next_retry_at=now + timedelta(hours=1),
                ),
            ]
        )
        db.session.add(source)
        db.session.add(ScanState(id=1, last_completed_at=now))
        db.session.commit()

    monkeypatch.setattr(dashboard.huey.huey, "pending_count", lambda: 4)
    response = client.get("/")
    assert response.status_code == HTTPStatus.OK
    soup = BeautifulSoup(response.get_data(as_text=True), "html.parser")

    received = soup.find("section", attrs={"aria-labelledby": "received-summary"})
    outgoing = soup.find("section", attrs={"aria-labelledby": "sent-summary"})
    assert received is not None
    assert outgoing is not None
    received_text = received.get_text(" ", strip=True)
    outgoing_text = outgoing.get_text(" ", strip=True)
    assert "5 total" in received_text
    assert "Pending 1" in received_text
    assert "Verifying 1" in received_text
    assert "Verified 1" in received_text
    assert "Declined 2" in received_text
    assert "Failed: 1 · Source removed: 1" in received_text
    assert "7 total" in outgoing_text
    assert "Sent 1" in outgoing_text
    assert "No endpoint 1" in outgoing_text
    assert "Failed (final) 1" in outgoing_text
    assert "Not attempted 1" in outgoing_text
    assert "Pending 3" in outgoing_text
    assert "Waiting to retry: 1" in outgoing_text

    recent = soup.find("section", attrs={"aria-labelledby": "recent-activity"})
    assert recent is not None
    rows = recent.find_all("tr")
    received_cells = rows[1].find_all(["td", "th"])
    assert [cell.get_text(" ", strip=True) for cell in received_cells] == [
        "New received Webmentions",
        "3",
        "4",
    ]
    sent_cells = rows[2].find_all(["td", "th"])
    assert [cell.get_text(" ", strip=True) for cell in sent_cells] == [
        "Webmentions last sent successfully",
        "1",
        "1",
    ]
    operations = soup.find("section", attrs={"aria-labelledby": "operations"})
    assert operations is not None
    assert "Source documents 1" in operations.get_text(" ", strip=True)
    assert "Huey pending tasks 4" in operations.get_text(" ", strip=True)
    assert "Last completed source scan" in operations.get_text(" ", strip=True)
    assert operations.find("time") is not None


def test_dashboard_handles_unavailable_queue(
    app: Flask, client: FlaskClient, monkeypatch: pytest.MonkeyPatch
) -> None:
    log_in(app, client)

    def unavailable() -> int:
        raise RuntimeError("backend unavailable")

    monkeypatch.setattr(dashboard.huey.huey, "pending_count", unavailable)
    response = client.get("/")

    assert response.status_code == HTTPStatus.OK
    assert "Huey pending tasks" in response.get_data(as_text=True)
    assert "Unavailable" in response.get_data(as_text=True)