Debian Codegraph @

tests/test_delivery_tracking_retry.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 """Ensure a second attempt does not repeat completed deliveries.
29
30 Each service runs twice against one tracker. The first pass delivers;
31 the second may repeat setup work but must not deliver again.
32 """
33
34 # Disable logging for a cleaner testing output
35 import contextlib
36 from json import dumps, loads
37 import logging
38 import socket
39 from unittest import mock
40
41 from helpers import ATTACHMENT, OK_BODY, delivery_marks
42 import pytest
43 import requests
44
45 from apprise import Apprise, AppriseAttachment, NotifyType
46 from apprise.plugins.base import _delivery_tracker
47
48 logging.disable(logging.CRITICAL)
49
50 # What a particular service needs to see before it calls a delivery a
51 # success. "body" is merged over OK_BODY, "status" replaces the HTTP
52 # code, and "raw" replaces the response text outright.
53 # AWS answers in XML rather than JSON.
54 SNS_XML = (
55 '<CreateTopicResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">'
56 "<CreateTopicResult>"
57 "<TopicArn>arn:aws:sns:us-east-1:000000000000:MyTopic</TopicArn>"
58 "</CreateTopicResult><ResponseMetadata>"
59 "<RequestId>604bef0f-369c-50c5-a7a4-bbd474c83d6a</RequestId>"
60 "<MessageId>1</MessageId>"
61 "</ResponseMetadata></CreateTopicResponse>"
62 )
63
64 # A couple of services only act on certain notification types; the
65 # default would leave them with nothing to do.
66 NOTIFY_TYPES = {
67 "jira": NotifyType.FAILURE,
68 "opsgenie": NotifyType.FAILURE,
69 }
70
71 RESPONSES = {
72 "dapnet": {"status": 201},
73 "kook": {
74 "body": {
75 "code": 0,
76 "url": "https://cdn.example/x",
77 "data": {"url": "https://cdn.example/x", "id": "1"},
78 }
79 },
80 "octopush": {"status": 201},
81 "smseagle": {"body": {"result": {"status": "ok"}}},
82 "pushplus": {"body": {"code": 200}},
83 "pushsafer": {"body": {"status": 1}},
84 "sns": {"raw": SNS_XML},
85 "viber": {"body": {"status": 0}},
86 }
87
88 # One URL per service that records its deliveries. Each carries at
89 # least one target so the loop under test actually runs.
90 TRACKED = {
91 "africas_talking": "atalk://user@apikey/33333333333/+44444444444",
92 "aprs": "aprs://DF1ABC:12345@DF1DEF/DF1GHI",
93 "bark": "bark://192.168.0.6:8081/device_key",
94 "brevo": "brevo://abcd:[email protected]/[email protected]",
95 "bulksms": "bulksms://aaaaa:bbbbbbbbbb@123/33333333333/abcd/",
96 "bulkvs": "bulkvs://uuuuuuuuuu:pppppppppp@1111111111/15551234567",
97 "burstsms": (
98 "burstsms://ffffffff:gggggggggggggggg@33333333333/15551234567"
99 ),
100 "clickatell": (
101 "clickatell://_?apikey=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
102 "&from=1111111111&to=15551230001,15551239999"
103 ),
104 "clicksend": "clicksend://user:pass@33333333333333?batch=no",
105 "d7networks": "d7sms://token1@33333333333333?batch=no",
106 "dapnet": "dapnet://user:pass@localhost/DL0001/DL9999",
107 "eight00com": "eight00com://tttttttttt@8888888888/55555555555",
108 "email": "mailto://user:pass@localhost/[email protected]/[email protected]",
109 "emby": "emby://user:pass@localhost",
110 "evolution": (
111 "evolution://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@localhost/inst/"
112 "12125550001/12125559999"
113 ),
114 "exotel": (
115 "exotel://sid:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@12125550000/"
116 "12125550001/12125559999"
117 ),
118 "fcm": "fcm://apikey/#topic1/device/",
119 "flock": "flock://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/u:0001/u:9999",
120 "fortysixelks": "46elks://user:pass@sender/12125550001/12125559999",
121 "google_chat": "gchat://workspace/key/token",
122 "home_assistant": "hassio://localhost/prefix/path/long.lived.token",
123 "httpsms": (
124 "httpsms://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@12125550000/"
125 "12125550001/12125559999"
126 ),
127 "humhub": "humhubs://mytoken@hostname/1/2/3",
128 "ifttt": "ifttt://WebHookID@EventID/EventID2/",
129 "jira": "jira://apikey/[email protected]/#team/",
130 "join": "join://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/device0001",
131 "kavenegar": "kavenegar://12125550000/12125550001/12125559999",
132 "kook": "kook://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/1234567890",
133 "line": "line://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/target0001",
134 "mailersend": (
135 "mailersend://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:[email protected]/"
136 "[email protected]"
137 ),
138 "mailgun": (
139 "mailgun://[email protected]/"
140 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bbbbbbbb-cccccccc/"
141 "[email protected]?batch=no"
142 ),
143 "matrix": "matrix://user:pass@localhost/#room1/#room2",
144 "mattermost": (
145 "mmost://user@localhost/3ccdd113474722377935511fc85d3dd4?channel=test"
146 ),
147 "messagebird": "msgbird://aaaaaaaaaaaaaaaaaaaaaaaaa/12125550000/",
148 "mqtt": "mqtt://localhost/topic1/topic2",
149 "nextcloud": "ncloud://user@localhost?to=user1,user2",
150 "nextcloudtalk": "nctalk://user:pass@localhost/room1",
151 "notifiarr": "notifiarr://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/#1001",
152 "ntfy": "ntfy://localhost/topic0001/topic9999",
153 "octopush": (
154 "octopush://sender:[email protected]/apikey/1111111111/"
155 "33333333333/?batch=no"
156 ),
157 "office365": (
158 "o365://tenant/ab-cd-ef-gh/abcd/123/3343/@jack/test/[email protected]"
159 ),
160 "one_signal": "onesignal://appid@apikey/playerid",
161 "opsgenie": "opsgenie://apikey/[email protected]/",
162 "pingram": "pingram://pingram_sk_abc123/12125550001",
163 "plivo": (
164 "plivo://15551232123?id=aaaaaaaaaaaaaaaaaaaaaaaaa"
165 "&token=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
166 "&from=15551233000&to=15551232000"
167 ),
168 "postmark": (
169 "postmark://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:[email protected]/"
170 "[email protected]"
171 ),
172 "pushbullet": "pbul://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/#chan1",
173 "pushed": (
174 "pushed://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/"
175 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/#chan0001/@user0001"
176 ),
177 "pushover": (
178 "pover://uuuuuuuuuuuuuuuuuuuuuuuuuuuuuu@"
179 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DEVICE1/"
180 ),
181 "pushplus": "pushplus://abc123def456ghi789jkl012mno345pq/group1",
182 "pushsafer": "psafer://eeeeeeeeeeeeeeeeeeee/12",
183 "pushy": "pushy://_/@device/#topic?key=apikey",
184 "reddit": (
185 "reddit://user:pass@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/"
186 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/sub0001"
187 ),
188 "resend": (
189 "resend://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:[email protected]/"
190 "[email protected]"
191 ),
192 "revolt": "revolt://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/chan0001",
193 "ringcentral": (
194 "ringc://18005554321:jwtcccccccccccccccccccccccccccccccccc"
195 "cccccccccccccccccccccccccc@client_id/secret/1555123456?mode=jwt"
196 ),
197 "rocketchat": "rocket://user:pass@localhost/#chan0001",
198 "sendgrid": (
199 "sendgrid://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:[email protected]/"
200 "[email protected]"
201 ),
202 "sendpulse": (
203 "sendpulse://[email protected]/client_id/cs9/[email protected]/"
204 "[email protected]"
205 ),
206 "serwersms": "serwersms://user:pass@SenderA/+48123456789",
207 "ses": (
208 "ses://[email protected]/T1JJ3TD4JD/TIiajkdnlazk7FQ/us-west-2/"
209 "[email protected]?batch=no"
210 ),
211 "seven": "seven://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/12125550001",
212 "sfr": "sfr://user:pass@spaceid/12125550001",
213 "signal_api": "signal://localhost/+12125550000/+12125550001",
214 "signalgrid": "signalgrid://CLIENTKEY/CHANNEL1/CHANNEL2",
215 "sinch": (
216 "sinch://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:"
217 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb@15551230000/15551234567"
218 ),
219 "slack": ("slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/#chan1"),
220 "smpp": "smpp://user:pass@localhost:2775/12125550000/12125550001",
221 "smseagle": "smseagle://token@localhost/12512222222/@contact/%23group",
222 "smsmanager": "smsmgr://zzzzzzzzzz@123/33333333333/+44444444444",
223 "smtp2go": (
224 "smtp2go://[email protected]/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/"
225 "[email protected]"
226 ),
227 "sns": (
228 "sns://aaaaaaaaaaaaaaaaaaaa/"
229 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/us-east-1/"
230 "12125550001/MyTopic"
231 ),
232 "sogs": (
233 "sessions://"
234 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb:"
235 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@"
236 "open.getsession.org/test-room"
237 ),
238 "sparkpost": (
239 "sparkpost://[email protected]/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/"
240 "[email protected]?batch=no"
241 ),
242 "telegram": (
243 "tgram://123456789:ABCdefGHIjklMNOpqrSTUvwxYZ1234567890/111/"
244 ),
245 "telnyx": (
246 "telnyx://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@12125550000/12125550001"
247 ),
248 "threema": (
249 "threema://*GATEWAY@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/user0001"
250 ),
251 "trigv": (
252 "trigvs://trgv_a1b2c3d4_0123456789abcdef0123456789abcdef/alerts/ops"
253 ),
254 "twilio": (
255 "twilio://ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:"
256 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb@12125550000/12125550001"
257 ),
258 "twist": "twist://password:[email protected]",
259 "twitter": "twitter://consumer_key/consumer_secret/atoken2/asecret/user1",
260 "vapid": "vapid://[email protected]/abc123",
261 "viber": "viber://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/t0001?from=Bot",
262 "voipms": "voipms://pass:[email protected]/12125550000/12125550001",
263 "vonage": (
264 "vonage://ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:"
265 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb@12125550000/12125550001"
266 ),
267 "webexteams": "wxteams://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/room0001",
268 "whatsapp": (
269 "whatsapp://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@12125550000/12125550001"
270 ),
271 "wpush": "wpush://WPUSHaaaaaaaaaaaaaaaaaaaaaaaaaaa",
272 "zulip": "zulip://botname@apprise/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/chan1",
273 }
274
275 # These need more of their service emulated than a shared fixture can
276 # offer: a signed handshake, a stored key pair, a session or channel
277 # listing, or a multi-step upload. Their delivery tracking is exercised
278 # by test_delivery_tracking_paths.py, and their own suites cover the
279 # rest of their behaviour.
280 NEEDS_ITS_OWN_SERVICE = {
281 "aprs": "needs an APRS-IS login handshake",
282 "emby": "needs a live session listing",
283 "jira": "needs a stored request id from a previous call",
284 "opsgenie": "needs a stored request id from a previous call",
285 "pushbullet": "needs a recipient lookup answer",
286 "slack": "needs the multi-step file upload exchange",
287 "sogs": "needs a signed Session handshake",
288 "twist": "needs a workspace and channel listing",
289 "twitter": "needs a user lookup answer",
290 "vapid": "needs a stored key pair and subscription file",
291 }
292
293 TRACKED_IDS = sorted(TRACKED)
294
295
296 class _Work:
297 """Counts everything a plugin does that reaches the outside world."""
298
299 def __init__(self, spec=None):
300 self.count = 0
301 spec = spec or {}
302 self.status = spec.get("status", requests.codes.ok)
303 self.handler = spec.get("handler")
304 if "raw" in spec:
305 self.payload = spec["raw"]
306
307 else:
308 merged = dict(loads(OK_BODY))
309 merged.update(spec.get("body", {}))
310 self.payload = dumps(merged)
311
312 def http(self, *args, **kwargs):
313 self.count += 1
314 status, text = self.status, self.payload
315 if self.handler is not None:
316 # A service that needs its answer shaped to the request
317 # supplies its own.
318 shaped = self.handler(args[0] if args else "", kwargs)
319 if shaped is not None:
320 status, text = shaped
321
322 response = requests.Request()
323 response.status_code = status
324 response.content = text
325 response.text = text
326 response.headers = {"Content-Type": "application/json"}
327 return response
328
329 def plain(self, *args, **kwargs):
330 self.count += 1
331 return True
332
333
334 # Services that speak their own protocol need their client stubbed out
335 # rather than their socket; a bare socket leaves them waiting for a
336 # handshake that never comes.
337 def _protocol_stubs(work):
338 """Return extra patches needed by non-HTTP services."""
339 stubs = []
340
341 try:
342 import paho.mqtt.client # noqa: F401
343
344 published = mock.Mock(**{"rc": 0, "is_published.return_value": True})
345
346 def publish(*args, **kwargs):
347 """Count the call and hand back a published message."""
348 work.plain()
349 return published
350
351 client = mock.Mock(
352 **{
353 "connect.return_value": 0,
354 "reconnect.return_value": 0,
355 "is_connected.return_value": True,
356 "publish.side_effect": publish,
357 }
358 )
359 stubs.append(
360 mock.patch("paho.mqtt.client.Client", return_value=client)
361 )
362
363 except ImportError:
364 pass
365
366 try:
367 import smpplib.client # noqa: F401
368
369 stubs.append(
370 mock.patch(
371 "smpplib.client.Client.send_message",
372 side_effect=work.plain,
373 )
374 )
375 stubs.append(mock.patch("smpplib.client.Client.connect"))
376 stubs.append(mock.patch("smpplib.client.Client.bind_transmitter"))
377 stubs.append(mock.patch("smpplib.client.Client.unbind"))
378 stubs.append(mock.patch("smpplib.client.Client.disconnect"))
379
380 except ImportError:
381 pass
382
383 return stubs
384
385
386 @contextlib.contextmanager
387 def _watched(work):
388 """Run with every outbound path replaced by a counter."""
389 sent = mock.MagicMock(side_effect=work.plain)
390 with (
391 mock.patch("requests.post", side_effect=work.http),
392 mock.patch("requests.get", side_effect=work.http),
393 mock.patch("requests.put", side_effect=work.http),
394 mock.patch("requests.patch", side_effect=work.http),
395 mock.patch("apprise.plugins.base.time.sleep"),
396 # Socket and mail based services never leave the machine
397 mock.patch.object(socket.socket, "connect"),
398 mock.patch.object(socket.socket, "sendall", sent),
399 mock.patch.object(socket.socket, "send", sent),
400 mock.patch.object(socket.socket, "recv", return_value=b""),
401 mock.patch("smtplib.SMTP") as smtp,
402 mock.patch("smtplib.SMTP_SSL") as smtps,
403 contextlib.ExitStack() as extra,
404 ):
405
406 def sendmail(*args, **kwargs):
407 """Count the call; an empty mapping means everything arrived."""
408 work.plain()
409 return {}
410
411 # sendmail() reports the addresses it could NOT reach, so an
412 # empty mapping is what success looks like.
413 for server in (smtp, smtps):
414 session = server.return_value.__enter__.return_value
415 session.sendmail.side_effect = sendmail
416 server.return_value.sendmail.side_effect = sendmail
417
418 for stub in _protocol_stubs(work):
419 extra.enter_context(stub)
420
421 yield
422
423
424 def _deliver(obj, work, notify_type=NotifyType.INFO):
425 """Deliver once; report whether it worked and what it cost."""
426 before = work.count
427 outcome = obj.send(
428 body="test",
429 title="test",
430 notify_type=notify_type,
431 attach=AppriseAttachment(ATTACHMENT),
432 )
433
434 return bool(outcome), work.count - before
435
436
437 @pytest.mark.filterwarnings("ignore::ResourceWarning")
438 @pytest.mark.parametrize("name", TRACKED_IDS)
439 def test_retry_does_not_repeat_delivery(name):
440 """A retry only picks up what the first attempt did not finish."""
441
442 if name in NEEDS_ITS_OWN_SERVICE:
443 pytest.skip(f"{name}: {NEEDS_ITS_OWN_SERVICE[name]}")
444
445 work = _Work(RESPONSES.get(name))
446 token = _delivery_tracker.set(set())
447 try:
448 with _watched(work):
449 # Built inside the patches; a service that opens its own
450 # client in __init__ has to pick up the stub, not a real one.
451 obj = Apprise.instantiate(TRACKED[name], suppress_exceptions=True)
452 if obj is None:
453 # The service needs a package this build does not have
454 pytest.skip(f"{name}: not available in this build")
455
456 kind = NOTIFY_TYPES.get(name, NotifyType.INFO)
457 delivered, first = _deliver(obj, work, kind)
458
459 # Watch what the second pass records; the first one already
460 # delivered everything, so it should record nothing at all.
461 with delivery_marks() as repeated:
462 still_ok, second = _deliver(obj, work, kind)
463
464 finally:
465 _delivery_tracker.reset(token)
466
467 # The first pass has to actually deliver something, otherwise this
468 # case proves nothing at all.
469 assert first > 0, (
470 f"{name}: nothing was delivered on the first attempt, so this"
471 " case cannot show whether a retry repeats itself"
472 )
473
474 # A first pass that failed leaves nothing recorded, and repeating it
475 # is the whole point of a retry. The case only means something when
476 # the first pass worked.
477 assert delivered, (
478 f"{name}: the first attempt reported failure, so this case"
479 " cannot show whether a retry repeats itself"
480 )
481
482 # Skipping what already arrived is still a success. A service
483 # that reports failure here would turn a healthy retry into an
484 # error the caller never had before.
485 assert still_ok, (
486 f"{name}: the second attempt reported failure even though"
487 " everything had already been delivered"
488 )
489
490 # Whatever work is left on the second pass, it is not a delivery.
491 # A recorded target means that target heard from us twice.
492 assert not repeated, (
493 f"{name}: the second attempt delivered to {repeated[0]!r} again"
494 )
495
496 # Everything the first pass sent is recorded, so the second pass has
497 # less to do. Equal counts mean the message went out twice.
498 assert second < first, (
499 f"{name}: the second attempt did the same work as the first"
500 f" ({second} of {first}); a retry would deliver twice"
501 )