Debian Codegraph @

tests/test_delivery_tracking_paths.py

raw
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28 """Cover delivery-skip paths that depend on an earlier step.
29
30 Each case lets the outer workflow run, then reports that only the inner
31 message, upload, batch, or lookup was already completed.
32 """
33
34 # Disable logging for a cleaner testing output
35 import contextlib
36 import logging
37 import os
38 import socket
39 from unittest import mock
40
41 from helpers import ATTACHMENT, delivery_marks, ok_response
42 import pytest
43
44 from apprise import Apprise, AppriseAttachment, NotifyType
45 from apprise.plugins.base import NotifyBase, _delivery_tracker
46
47 logging.disable(logging.CRITICAL)
48
49
50 def kind(prefix):
51 """Answer "already delivered" only for keys of this kind."""
52
53 def answer(key, per_message=False):
54 return isinstance(key, tuple) and bool(key) and key[0] == prefix
55
56 return answer
57
58
59 def _nothing(key, per_message=False):
60 """Answer "not delivered yet" for everything."""
61 return False
62
63
64 def _everything(key, per_message=False):
65 """Answer "already delivered" for everything."""
66 return True
67
68
69 def _send(obj):
70 """Deliver a plain message."""
71 obj.send(body="test", title="test")
72
73
74 def _send_attached(obj):
75 """Deliver a message that carries a file."""
76 obj.send(body="test", title="test", attach=AppriseAttachment(ATTACHMENT))
77
78
79 @contextlib.contextmanager
80 def _offline(answer, clients=(), methods=(), obj=None):
81 """Replace every outbound path and count what the service uses."""
82
83 direct = []
84 stubs = []
85 sent = mock.MagicMock()
86 with (
87 mock.patch("requests.post", side_effect=ok_response) as post,
88 mock.patch("requests.get", side_effect=ok_response) as get,
89 mock.patch("requests.put", side_effect=ok_response) as put,
90 mock.patch("requests.patch", side_effect=ok_response) as patch,
91 mock.patch("apprise.plugins.base.time.sleep"),
92 mock.patch.object(socket.socket, "connect"),
93 mock.patch.object(socket.socket, "sendall", sent),
94 mock.patch.object(socket.socket, "send", sent),
95 mock.patch.object(socket.socket, "recv", return_value=b""),
96 mock.patch.object(NotifyBase, "is_delivered", side_effect=answer),
97 delivery_marks() as recorded,
98 contextlib.ExitStack() as extra,
99 ):
100 direct.extend((post, get, put, patch, sent))
101
102 for dotted in clients:
103 # A service with its own client speaks through the stub
104 # rather than through requests, so it is counted too.
105 stubs.append(extra.enter_context(mock.patch(dotted)))
106
107 for attr, value in methods:
108 # A step answered for us is still work the service asked
109 # for, so it is counted like any other outbound call.
110 direct.append(
111 extra.enter_context(
112 mock.patch.object(type(obj), attr, return_value=value)
113 )
114 )
115
116 def work():
117 """Return how far the service has reached out so far."""
118 return sum(call.call_count for call in direct) + sum(
119 len(stub.mock_calls) for stub in stubs
120 )
121
122 yield work, recorded
123
124
125 def _skips(url, answer, send=None, clients=(), methods=(), setup=None):
126 """Deliver twice and prove the pre-decided answer saved work.
127
128 The first run has nothing delivered yet, so it does the whole job.
129 The second is told part of it already arrived, and has to leave
130 exactly that part alone:
131
132 - it reaches out less often than the first run, so the skipped work
133 really was skipped
134 - it records nothing it was already told about, so nothing went out
135 a second time under a different name
136 """
137
138 if send is None:
139 send = _send
140
141 done = []
142 for pre_decided in (_nothing, answer):
143 obj = _build(url)
144 if setup is not None:
145 setup(obj)
146
147 with _offline(
148 pre_decided, clients=clients, methods=methods, obj=obj
149 ) as (work, recorded):
150 send(obj)
151
152 done.append((work(), list(recorded)))
153
154 (busy, _marked), (quiet, marked) = done
155
156 repeated = [key for key in marked if answer(key)]
157 assert not repeated, (
158 f"{repeated[0]!r} was sent again even though the service had"
159 " already been told it arrived"
160 )
161
162 assert quiet < busy, (
163 f"the service reached out {quiet} times either way; nothing was"
164 " skipped even though it was told the work had already arrived"
165 )
166
167
168 @pytest.fixture()
169 def tracker():
170 """Provide an empty tracker for the duration of one test."""
171 token = _delivery_tracker.set(set())
172 try:
173 yield
174
175 finally:
176 _delivery_tracker.reset(token)
177
178
179 def _build(url):
180 """Load a service and make sure the URL is still good."""
181 obj = Apprise.instantiate(url, suppress_exceptions=True)
182 assert obj is not None, f"{url} no longer loads"
183 return obj
184
185
186 def test_telegram_skips_sent_piece(tracker):
187 """Telegram leaves a piece of a split message alone once it lands."""
188
189 _skips(
190 "tgram://123456789:ABCdefGHIjklMNOpqrSTUvwxYZ1234567890/111/",
191 kind("body"),
192 )
193
194
195 def test_humhub_skips_sent_attachment(tracker):
196 """HumHub leaves an upload alone once it is on the post."""
197
198 _skips(
199 "humhubs://mytoken@hostname/1",
200 kind("attachment"),
201 send=_send_attached,
202 )
203
204
205 def test_pushbullet_skips_sent_attachment(tracker):
206 """PushBullet leaves an upload alone once it has gone out."""
207
208 _skips(
209 "pbul://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/#chan1",
210 kind("attachment"),
211 send=_send_attached,
212 )
213
214
215 def test_pushover_clears_title_after_skip(tracker):
216 """Pushover drops the title once the first upload has gone out."""
217
218 _skips(
219 "pover://uuuuuuuuuuuuuuuuuuuuuuuuuuuuuu@"
220 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DEVICE1/",
221 kind("attachment"),
222 send=_send_attached,
223 )
224
225
226 def test_pushsafer_clears_message_after_skip(tracker):
227 """PushSafer stops repeating the text once a batch has gone out."""
228
229 _skips(
230 "psafer://eeeeeeeeeeeeeeeeeeee/12",
231 kind("attachment"),
232 send=_send_attached,
233 )
234
235
236 def test_home_assistant_skips_sent_batch(tracker):
237 """Home Assistant leaves a finished batch of devices alone."""
238
239 # The ":" form gives one service several devices, and those are what
240 # get split into batches.
241 url = "hassio://localhost/long.lived.token/notify.mobile:dev1,dev2"
242 assert _build(url).targets[0][2] == ["dev1", "dev2"]
243
244 _skips(url, kind("batch"))
245
246
247 def test_smpp_skips_sent_segment(tracker):
248 """SMPP leaves a message part alone once it has gone out."""
249
250 pytest.importorskip("smpplib")
251 _skips(
252 "smpp://user:pass@localhost:2775/12125550000/12125550001",
253 kind("part"),
254 clients=["smpplib.client.Client"],
255 )
256
257
258 def test_twitter_skips_sent_recipient(tracker):
259 """Twitter leaves a direct message alone once it has arrived."""
260
261 def answer(key, per_message=False):
262 # Twitter pairs the message number with the recipient
263 return (
264 isinstance(key, tuple)
265 and len(key) == 2
266 and isinstance(key[0], int)
267 )
268
269 _skips(
270 "twitter://ck/cs/at/as/user1",
271 answer,
272 methods=[("_user_lookup", {"user1": 1})],
273 )
274
275
276 def test_irc_skips_sent_targets(tracker):
277 """IRC leaves a channel or a user alone once the message lands."""
278
279 url = "ircs://nick@localhost/%23chan1/@bob"
280 client = ["apprise.plugins.irc.base.IRCClient"]
281
282 _skips(url, kind("channel"), clients=client)
283 _skips(url, kind("user"), clients=client)
284
285
286 def test_emby_skips_sent_session(tracker):
287 """Emby leaves a session alone once it has the message."""
288
289 _skips(
290 "emby://user:pass@localhost",
291 _everything,
292 methods=[("login", True), ("sessions", {"abc": {}})],
293 )
294
295
296 def test_twist_skips_sent_channel(tracker):
297 """Twist leaves a channel alone once it has the message."""
298
299 def learned(obj):
300 # Twist normally learns its channels from the server
301 obj.channel_ids = {"1:2"}
302
303 _skips(
304 "twist://password:[email protected]",
305 _everything,
306 methods=[("login", True), ("get_channels", {"general": 1})],
307 setup=learned,
308 )
309
310
311 def test_rocketchat_skips_sent_room(tracker):
312 """Rocket.Chat leaves a room alone once it has the message."""
313
314 url = "rocket://user:pass@localhost/room1"
315 assert _build(url).rooms == ["room1"]
316
317 _skips(
318 url,
319 _everything,
320 methods=[("login", True), ("logout", True)],
321 )
322
323
324 def test_matrix_skips_sent_user(tracker):
325 """Matrix leaves a direct message alone once it has arrived."""
326
327 url = "matrix://user:pass@localhost/@bob"
328 assert _build(url).users
329
330 _skips(url, kind("user"))
331
332
333 def test_matrix_skips_sent_attachment(tracker):
334 """Matrix leaves an upload alone once it is in the room."""
335
336 prepared = [{"body": "x", "msgtype": "m.image", "url": "mxc://x/1"}]
337
338 _skips(
339 "matrix://user:pass@localhost/#room1",
340 kind("attachment"),
341 send=_send_attached,
342 methods=[("_send_attachments", prepared)],
343 )
344
345
346 def test_telegram_skips_sent_attachment(tracker):
347 """Telegram leaves an upload alone once it has gone out."""
348
349 def send(obj):
350 assert (
351 obj._send_attachments(
352 obj.targets[0],
353 notify_type=NotifyType.INFO,
354 attach=AppriseAttachment(ATTACHMENT),
355 )
356 is True
357 )
358
359 _skips(
360 "tgram://123456789:ABCdefGHIjklMNOpqrSTUvwxYZ1234567890/111/",
361 kind("attachment"),
362 send=send,
363 )
364
365
366 def test_slack_skips_shared_upload(tracker):
367 """Slack moves on when no channel still needs the upload."""
368
369 # Slack answers each call with the channel it posted to
370 answer = {
371 "ok": True,
372 "channel": "C1",
373 "file_id": "F1",
374 "upload_url": "https://localhost/u",
375 "files": [{"id": "F1"}],
376 }
377
378 _skips(
379 "slack://xoxb-1234-1234-abc123/#chan1",
380 kind("attachment"),
381 send=_send_attached,
382 methods=[("_send", answer)],
383 )
384
385
386 def test_slack_stops_after_upload_failure(tracker):
387 """Slack gives up on the attachment once an upload is refused."""
388
389 obj = _build("slack://xoxb-1234-1234-abc123/#chan1")
390
391 posted = {
392 "ok": True,
393 "channel": "C1",
394 "file_id": "F1",
395 "upload_url": "https://localhost/u",
396 "files": [{"id": "F1"}],
397 }
398
399 def answer(url, *args, **kwargs):
400 # The upload itself is refused; everything else is accepted
401 return None if str(url).endswith("/u") else posted
402
403 with (
404 mock.patch("requests.post", side_effect=ok_response),
405 mock.patch("requests.get", side_effect=ok_response),
406 mock.patch("apprise.plugins.base.time.sleep"),
407 mock.patch.object(NotifyBase, "is_delivered", return_value=False),
408 mock.patch.object(type(obj), "_send", side_effect=answer),
409 ):
410 assert (
411 obj.send(
412 body="test",
413 title="test",
414 attach=AppriseAttachment(ATTACHMENT),
415 )
416 is False
417 )
418
419
420 def test_slack_skips_sent_channel(tracker):
421 """Slack leaves a channel alone once its message has arrived."""
422
423 obj = _build("slack://xoxb-1234-1234-abc123/#chan1")
424
425 with _offline(_everything) as (work, _recorded):
426 _send_attached(obj)
427
428 # The message and its upload both arrived on an earlier attempt
429 assert work() == 0
430
431
432 def test_aprs_skips_sent_callsign(tracker):
433 """APRS leaves a callsign alone once the message has gone out."""
434
435 obj = _build("aprs://DF1ABC:12345@DF1DEF/DF1GHI")
436
437 # APRS talks over a socket rather than HTTP, so stand one in. The
438 # login exchange is answered for us; it is not what is under test.
439 stand_in = mock.MagicMock()
440
441 with (
442 mock.patch("socket.create_connection", return_value=stand_in),
443 mock.patch.object(type(obj), "aprsis_login", return_value=True),
444 mock.patch.object(type(obj), "socket_reset"),
445 mock.patch("apprise.plugins.base.time.sleep"),
446 mock.patch.object(NotifyBase, "is_delivered", return_value=True),
447 ):
448 obj.send(body="test", title="test")
449
450 # Every callsign was skipped, so nothing was written to the socket
451 assert stand_in.sendall.call_count == 0
452
453
454 def test_vapid_skips_sent_endpoint(tracker, tmpdir):
455 """Vapid counts a skipped endpoint so a retry still reports success."""
456
457 pytest.importorskip("cryptography")
458
459 from apprise import asset
460 from apprise.common import PersistentStoreMode
461 from apprise.plugins.vapid import NotifyVapid
462 from apprise.plugins.vapid.subscription import (
463 WebPushSubscriptionManager,
464 )
465
466 # The key pair a browser hands over when it subscribes
467 p256dh = (
468 "BI2RNIK2PkeCVoEfgVQNjievBi4gWvZxMiuCpOx6K6qCO"
469 "5caru5QCPuc-nEaLplbbFkHxTrR9YzE8ZkTjie5Fq0"
470 )
471
472 work = str(tmpdir.mkdir("vapid-skip"))
473 subfile = os.path.join(work, "subscriptions.json")
474
475 manager = WebPushSubscriptionManager()
476 assert manager.add(
477 {
478 "endpoint": "https://web.push.apple.com/ABC",
479 "keys": {"p256dh": p256dh, "auth": "k9Xzm43nBGo="},
480 },
481 name="abc123",
482 )
483 assert manager.write(subfile)
484
485 obj = NotifyVapid(
486 "[email protected]",
487 targets=["abc123"],
488 subfile=subfile,
489 asset=asset.AppriseAsset(
490 storage_mode=PersistentStoreMode.FLUSH,
491 storage_path=work,
492 pem_autogen=True,
493 ),
494 )
495
496 with (
497 mock.patch("requests.post", side_effect=ok_response) as posted,
498 mock.patch("apprise.plugins.base.time.sleep"),
499 mock.patch.object(NotifyBase, "is_delivered", return_value=True),
500 ):
501 # The endpoint was reached on an earlier attempt. It still
502 # counts, so this reports success instead of "nothing was sent".
503 assert obj.send(body="test", title="test") is True
504
505 # ...and nothing was pushed a second time
506 assert posted.call_count == 0
507
508
509 def test_matrix_skips_sent_encrypted_attachment(tracker):
510 """Matrix leaves an encrypted upload alone once it is in the room."""
511
512 pytest.importorskip("cryptography")
513
514 url = "matrixs://user:pass@localhost/#room1?e2ee=yes"
515 obj = _build(url)
516 if not (obj.e2ee and obj.secure):
517 pytest.skip("this build has no end-to-end encryption support")
518
519 prepared = [{"body": "x", "msgtype": "m.image", "url": "mxc://x/1"}]
520
521 _skips(
522 url,
523 kind("attachment"),
524 send=_send_attached,
525 methods=[
526 ("_send_attachments", prepared),
527 ("_room_join", "!room1:localhost"),
528 ("_e2ee_send_to_room", True),
529 ("_e2ee_get_megolm", object()),
530 ("_e2ee_room_encrypted", True),
531 ("_e2ee_setup", True),
532 # Signing in is not what is under test here
533 ("_login", True),
534 ("_whoami", {}),
535 ],
536 )
537
538
539 def test_matrix_skips_sent_message(tracker):
540 """Matrix leaves a room's message alone once it has arrived."""
541
542 _skips(
543 "matrix://user:pass@localhost/#room1",
544 kind("message"),
545 methods=[
546 ("_room_join", "!room1:localhost"),
547 ("_login", True),
548 ("_whoami", {}),
549 ],
550 )
551
552
553 def test_matrix_skips_sent_encrypted_message(tracker):
554 """Matrix leaves an encrypted message alone once it has arrived."""
555
556 pytest.importorskip("cryptography")
557
558 url = "matrixs://user:pass@localhost/#room1?e2ee=yes"
559 obj = _build(url)
560 if not (obj.e2ee and obj.secure):
561 pytest.skip("this build has no end-to-end encryption support")
562
563 _skips(
564 url,
565 kind("message"),
566 methods=[
567 ("_room_join", "!room1:localhost"),
568 ("_e2ee_setup", True),
569 ("_e2ee_room_encrypted", True),
570 ("_e2ee_send_to_room", True),
571 ("_e2ee_get_megolm", object()),
572 ("_login", True),
573 ("_whoami", {}),
574 ],
575 )
576
577
578 def test_matrix_skips_sent_image(tracker):
579 """Matrix leaves the notification image alone once it is posted."""
580
581 # The inline image is only posted by the v2 API
582 _skips(
583 "matrix://user:pass@localhost/#room1?image=yes&version=2",
584 kind("image"),
585 methods=[
586 ("_room_join", "!room1:localhost"),
587 ("_login", True),
588 ("_whoami", {}),
589 ],
590 )
591
592
593 def test_xmpp_skips_sent_targets(tracker):
594 """XMPP leaves a target alone once it has the message."""
595
596 pytest.importorskip("slixmpp")
597
598 from apprise.plugins.xmpp import base as xmpp_base
599
600 handed = []
601
602 class _Adapter:
603 def __init__(self, config, **kwargs):
604 handed.append(kwargs.get("targets"))
605
606 def process(self):
607 return True
608
609 with mock.patch.object(xmpp_base, "SlixmppAdapter", _Adapter):
610 obj = _build("xmpps://user:[email protected]/joe/sally")
611 assert obj.send(body="test", title="test") is True
612
613 # Both targets were handed over the first time
614 assert len(handed[0]) == 2
615
616 # ...and neither is offered again
617 assert obj.send(body="test", title="test") is True
618 assert len(handed) == 1
619
620
621 def test_xmpp_retries_targets_after_failure(tracker):
622 """XMPP offers its targets again when the send did not work."""
623
624 pytest.importorskip("slixmpp")
625
626 from apprise.plugins.xmpp import base as xmpp_base
627
628 handed = []
629
630 class _Adapter:
631 def __init__(self, config, **kwargs):
632 handed.append(kwargs.get("targets"))
633
634 def process(self):
635 return False
636
637 with mock.patch.object(xmpp_base, "SlixmppAdapter", _Adapter):
638 obj = _build("xmpps://user:[email protected]/joe/sally")
639 assert obj.send(body="test", title="test") is False
640 assert obj.send(body="test", title="test") is False
641
642 # Nothing was marked, so both attempts carried both targets
643 assert [len(x) for x in handed] == [2, 2]