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


import uuid
from types import ModuleType
from unittest.mock import patch

import pytest
from flask import Flask
from huey.exceptions import TaskLockedException

from webmentions_ssg import db
from webmentions_ssg.extensions import huey
from webmentions_ssg.models.received import ReceivedWebmention


@pytest.fixture
def notifications(app: Flask) -> ModuleType:
    # Digest URLs are generated without a request context. Keep the public
    # hostname local to these tests instead of changing all Flask test clients.
    app.config.update(SERVER_NAME="mentions.example.com", PREFERRED_URL_SCHEME="https")

    from webmentions_ssg.tasks import notifications

    return notifications


def create_mention(app: Flask, status: str = "verified") -> uuid.UUID:
    identifier = uuid.uuid7()
    with app.app_context():
        db.session.add(
            ReceivedWebmention(
                uuid=identifier,
                source=f"https://source.example/{identifier}",
                target="https://dennisfink.me/post",
                status=status,
            )
        )
        db.session.commit()
    return identifier


def test_digest_sends_one_email_for_multiple_verified_mentions(
    notifications: ModuleType, app: Flask
) -> None:
    app.config["DIGEST_EMAIL"] = "owner@example.com"

    first = create_mention(app)
    second = create_mention(app)
    unverified = create_mention(app, "failed")

    with app.app_context():
        with patch("webmentions_ssg.tasks.notifications.mail.send") as send:
            notifications.email_verified_digest()
            notifications.email_verified_digest()

        send.assert_called_once()
        message = send.call_args.args[0]

        assert message.recipients == ["owner@example.com"]
        assert message.subject == "2 new verified webmentions on your site"
        assert "2 new verified webmentions" in message.body
        assert message.html is None
        assert message.body.count("Mentioned by:") == 2
        for identifier in (first, second):
            source_url = f"https://source.example/{identifier}"
            assert source_url in message.body
            detail_url = f"https://mentions.example.com/received/{identifier}"
            assert f"View details: {detail_url}" in message.body
        assert message.body.count("https://dennisfink.me/post") == 2
        assert str(unverified) not in message.body
        dashboard_url = "https://mentions.example.com/received?status=verified"
        assert dashboard_url in message.body

        first_mention = db.session.get(ReceivedWebmention, first)
        second_mention = db.session.get(ReceivedWebmention, second)
        unverified_mention = db.session.get(ReceivedWebmention, unverified)

        assert first_mention is not None
        assert second_mention is not None
        assert unverified_mention is not None

        assert first_mention.notification_sent_at is not None
        assert second_mention.notification_sent_at is not None
        assert unverified_mention.notification_sent_at is None


def test_digest_uses_singular_wording_for_one_verified_mention(
    notifications: ModuleType, app: Flask
) -> None:
    app.config["DIGEST_EMAIL"] = "owner@example.com"
    identifier = create_mention(app)

    with app.app_context():
        with patch("webmentions_ssg.tasks.notifications.mail.send") as send:
            notifications.email_verified_digest()

        message = send.call_args.args[0]
        assert message.subject == "1 new verified webmention on your site"
        assert "1 new verified webmention!" in message.body
        assert message.html is None
        assert f"https://source.example/{identifier}" in message.body
        assert f"https://mentions.example.com/received/{identifier}" in message.body


def test_digest_links_handle_admin_url_path_prefix(
    notifications: ModuleType, app: Flask
) -> None:
    app.config["DIGEST_EMAIL"] = "owner@example.com"
    app.config.update(APPLICATION_ROOT="/manage")
    identifier = create_mention(app)

    with app.app_context():
        with patch("webmentions_ssg.tasks.notifications.mail.send") as send:
            notifications.email_verified_digest()

        message = send.call_args.args[0]
        detail_url = f"https://mentions.example.com/manage/received/{identifier}"
        dashboard_url = "https://mentions.example.com/manage/received?status=verified"
        assert detail_url in message.body
        assert message.html is None
        assert dashboard_url in message.body


def test_digest_uses_server_name_with_port(
    notifications: ModuleType, app: Flask
) -> None:
    app.config.update(
        DIGEST_EMAIL="owner@example.com",
        SERVER_NAME="mentions.example.com:8443",
        PREFERRED_URL_SCHEME="https",
    )
    identifier = create_mention(app)

    with app.app_context():
        with patch("webmentions_ssg.tasks.notifications.mail.send") as send:
            notifications.email_verified_digest()

        message = send.call_args.args[0]
        detail_url = f"https://mentions.example.com:8443/received/{identifier}"
        dashboard_url = "https://mentions.example.com:8443/received?status=verified"
        assert f"View details: {detail_url}" in message.body
        assert message.html is None
        assert dashboard_url in message.body


def test_digest_server_name_respects_application_root(
    notifications: ModuleType, app: Flask
) -> None:
    app.config.update(
        DIGEST_EMAIL="owner@example.com",
        SERVER_NAME="mentions.example.com",
        PREFERRED_URL_SCHEME="https",
        APPLICATION_ROOT="/manage",
    )
    identifier = create_mention(app)

    with app.app_context():
        with patch("webmentions_ssg.tasks.notifications.mail.send") as send:
            notifications.email_verified_digest()

        message = send.call_args.args[0]
        detail_url = f"https://mentions.example.com/manage/received/{identifier}"
        dashboard_url = "https://mentions.example.com/manage/received?status=verified"
        assert detail_url in message.body
        assert message.html is None
        assert dashboard_url in message.body


def test_digest_without_server_name_does_not_send_or_mark_mentions(
    notifications: ModuleType, app: Flask
) -> None:
    app.config.update(DIGEST_EMAIL="owner@example.com", SERVER_NAME=None)
    identifier = create_mention(app)

    with app.app_context():
        with (
            patch("webmentions_ssg.tasks.notifications.mail.send") as send,
            pytest.raises(RuntimeError, match="SERVER_NAME"),
        ):
            notifications.email_verified_digest()

        send.assert_not_called()
        mention = db.session.get(ReceivedWebmention, identifier)
        assert mention is not None and mention.notification_sent_at is None


def test_digest_preserves_urls_in_plain_text_without_html(
    notifications: ModuleType, app: Flask
) -> None:
    app.config["DIGEST_EMAIL"] = "owner@example.com"
    identifier = create_mention(app)
    source = 'https://source.example/post?tag="onmouseover="alert(1)&x=<script>'
    target = 'https://dennisfink.me/post?tag=<strong>&other="test"'

    with app.app_context():
        mention = db.session.get(ReceivedWebmention, identifier)
        assert mention is not None
        mention.source = source
        mention.target = target
        db.session.commit()

        with patch("webmentions_ssg.tasks.notifications.mail.send") as send:
            notifications.email_verified_digest()

        message = send.call_args.args[0]
        assert source in message.body
        assert target in message.body
        assert message.html is None


def test_digest_only_marks_mentions_in_the_sent_message(
    notifications: ModuleType, app: Flask
) -> None:
    app.config["DIGEST_EMAIL"] = "owner@example.com"
    first = create_mention(app)
    new_arrival: list[uuid.UUID] = []

    def receive_during_send(message) -> None:
        assert str(first) in message.body
        new_arrival.append(create_mention(app))

    with app.app_context():
        with patch(
            "webmentions_ssg.tasks.notifications.mail.send",
            side_effect=receive_during_send,
        ):
            notifications.email_verified_digest()

        first_mention = db.session.get(ReceivedWebmention, first)
        later_mention = db.session.get(ReceivedWebmention, new_arrival[0])
        assert first_mention is not None
        assert later_mention is not None
        assert first_mention.notification_sent_at is not None
        assert later_mention.notification_sent_at is None


def test_digest_skips_when_notifications_disabled(
    notifications: ModuleType, app: Flask
) -> None:
    app.config["DIGEST_EMAIL"] = None
    identifier = create_mention(app)

    with app.app_context():
        with patch("webmentions_ssg.tasks.notifications.mail.send") as send:
            notifications.email_verified_digest()

        send.assert_not_called()
        mention = db.session.get(ReceivedWebmention, identifier)

        assert mention is not None
        assert mention.notification_sent_at is None


def test_digest_does_not_mark_mentions_when_email_fails(
    notifications: ModuleType, app: Flask
) -> None:
    app.config["DIGEST_EMAIL"] = "owner@example.com"
    identifier = create_mention(app)

    with app.app_context():
        with (
            patch(
                "webmentions_ssg.tasks.notifications.mail.send",
                side_effect=RuntimeError("SMTP unavailable"),
            ),
            pytest.raises(RuntimeError, match="SMTP unavailable"),
        ):
            notifications.email_verified_digest()

        mention = db.session.get(ReceivedWebmention, identifier)

        assert mention is not None
        assert mention.notification_sent_at is None

        with patch("webmentions_ssg.tasks.notifications.mail.send") as send:
            notifications.email_verified_digest()

        send.assert_called_once()
        mention = db.session.get(ReceivedWebmention, identifier)

        assert mention is not None
        assert mention.notification_sent_at is not None


def test_digest_skips_when_no_new_mentions(
    notifications: ModuleType, app: Flask
) -> None:
    app.config["DIGEST_EMAIL"] = "owner@example.com"

    with app.app_context():
        with patch("webmentions_ssg.tasks.notifications.mail.send") as send:
            notifications.email_verified_digest()

        send.assert_not_called()


def test_digest_lock_uses_current_backend(
    notifications: ModuleType, app: Flask
) -> None:
    """Verify that a previously imported digest uses the new backend lock.

    :param notifications: Digest notification module under test.
    :param app: Configured Flask application fixture.
    """
    with app.app_context():
        previous_backend = huey.huey
        huey.init_app(app)
        assert huey.huey is not previous_backend

        with (
            huey.lock_task("send-webmention-digest"),
            pytest.raises(TaskLockedException),
        ):
            notifications.email_verified_digest()