Debian Codegraph @

tests/test_plugin_mobilemessage.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
29 from json import dumps, loads
30
31 # Disable logging for a cleaner testing output
32 import logging
33 import threading
34 from unittest import mock
35 from urllib.parse import urlparse
36
37 from helpers import AppriseURLTester
38 import pytest
39 import requests
40
41 from apprise import Apprise, NotifyType
42 from apprise.exception import AppriseImproperlyConfigured
43 from apprise.plugins.mobilemessage import NotifyMobileMessage
44
45 logging.disable(logging.CRITICAL)
46
47
48 def _ok(count=1):
49 """Build the all-accepted report returned for `count` recipients."""
50 return {
51 "status": "complete",
52 "results": [
53 {"to": f"614000000{index:02d}", "status": "success"}
54 for index in range(count)
55 ],
56 }
57
58
59 # Our Testing URLs
60 apprise_url_tests = (
61 (
62 "mobilemessage://",
63 {
64 # No credentials at all
65 "instance": AppriseImproperlyConfigured,
66 },
67 ),
68 (
69 "mobilemessage://:@/",
70 {
71 # No credentials at all
72 "instance": AppriseImproperlyConfigured,
73 },
74 ),
75 (
76 "mobilemessage://user@ALERTS/0412345678",
77 {
78 # No API password provided
79 "instance": AppriseImproperlyConfigured,
80 },
81 ),
82 (
83 "mobilemessage://user:pass@/0412345678",
84 {
85 # No Sender ID provided
86 "instance": AppriseImproperlyConfigured,
87 },
88 ),
89 (
90 "mobilemessage://user:pass@%20/0412345678",
91 {
92 # A Sender ID of nothing but whitespace
93 "instance": AppriseImproperlyConfigured,
94 },
95 ),
96 (
97 "mobilemessage://user:pass@ALERTS/",
98 {
99 # No targets to notify
100 "instance": NotifyMobileMessage,
101 "requests_response_text": _ok(),
102 "notify_response": False,
103 },
104 ),
105 (
106 "mobilemessage://user:pass@ALERTS/0412345678",
107 {
108 "instance": NotifyMobileMessage,
109 "requests_response_text": _ok(),
110 "privacy_url": "mobilemessage://user:****@ALERTS/61412345678",
111 },
112 ),
113 (
114 "mobilemsg://user:pass@ALERTS/0412345678",
115 {
116 # The shorthand schema normalises back to the full one
117 "instance": NotifyMobileMessage,
118 "requests_response_text": _ok(),
119 "privacy_url": "mobilemessage://user:****@ALERTS/61412345678",
120 },
121 ),
122 (
123 "mobilemessage://user:pass@+61 400 000 000/61412345678",
124 {
125 # A phone number Sender ID is reduced to digits
126 "instance": NotifyMobileMessage,
127 "requests_response_text": _ok(),
128 "privacy_url": (
129 "mobilemessage://user:****@61400000000/61412345678"
130 ),
131 },
132 ),
133 (
134 "mobilemessage://user:pass@ALERTS/0412345678/412345679/61412345680",
135 {
136 # Every accepted way of writing an Australian mobile
137 "instance": NotifyMobileMessage,
138 "requests_response_text": _ok(3),
139 "privacy_url": (
140 "mobilemessage://user:****@ALERTS/61412345678/61412345679"
141 ),
142 },
143 ),
144 (
145 "mobilemessage://user:pass@ALERTS/0412345678/abcd/15551231234",
146 {
147 # Garbage and a non-Australian number are both dropped
148 "instance": NotifyMobileMessage,
149 "requests_response_text": _ok(),
150 "privacy_url": "mobilemessage://user:****@ALERTS/61412345678",
151 },
152 ),
153 (
154 "mobilemessage://user:pass@ALERTS/15551231234",
155 {
156 # Nothing is left to notify once the US number is dropped
157 "instance": NotifyMobileMessage,
158 "requests_response_text": _ok(),
159 "notify_response": False,
160 },
161 ),
162 (
163 "mobilemessage://user:pass@ALERTS/0412345678?max_parts=invalid",
164 {
165 # max_parts must be a number
166 "instance": AppriseImproperlyConfigured,
167 },
168 ),
169 (
170 "mobilemessage://user:pass@ALERTS/0412345678?max_parts=0",
171 {
172 # max_parts is below the accepted range
173 "instance": AppriseImproperlyConfigured,
174 },
175 ),
176 (
177 "mobilemessage://user:pass@ALERTS/0412345678?max_parts=100",
178 {
179 # max_parts is above the accepted range
180 "instance": AppriseImproperlyConfigured,
181 },
182 ),
183 (
184 "mobilemessage://user:pass@ALERTS/0412345678"
185 "?unicode=yes&batch=no&max_parts=2&ref=nightly",
186 {
187 # Every option at once
188 "instance": NotifyMobileMessage,
189 "requests_response_text": _ok(),
190 "privacy_url": "mobilemessage://user:****@ALERTS/61412345678",
191 },
192 ),
193 (
194 "mobilemessage://user:pass@0412345678/?from=ALERTS",
195 {
196 # With from=, the hostname becomes a target
197 "instance": NotifyMobileMessage,
198 "requests_response_text": _ok(),
199 "privacy_url": "mobilemessage://user:****@ALERTS/61412345678",
200 },
201 ),
202 (
203 "mobilemessage://user:pass@ALERTS/?to=0412345678,0498765432",
204 {
205 "instance": NotifyMobileMessage,
206 "requests_response_text": _ok(2),
207 "privacy_url": (
208 "mobilemessage://user:****@ALERTS/61412345678/61498765432"
209 ),
210 },
211 ),
212 (
213 "mobilemessage://user:pass@ALERTS/0412345678",
214 {
215 "instance": NotifyMobileMessage,
216 "requests_response_text": _ok(),
217 # A failure from the upstream server
218 "response": False,
219 "requests_response_code": requests.codes.internal_server_error,
220 },
221 ),
222 (
223 "mobilemessage://user:pass@ALERTS/0412345678",
224 {
225 "instance": NotifyMobileMessage,
226 "requests_response_text": _ok(),
227 # An unknown status code has no mapped description
228 "response": False,
229 "requests_response_code": 999,
230 },
231 ),
232 (
233 "mobilemessage://user:pass@ALERTS/0412345678",
234 {
235 "instance": NotifyMobileMessage,
236 "requests_response_text": _ok(),
237 # Exercise request exception handling
238 "test_requests_exceptions": True,
239 },
240 ),
241 )
242
243
244 def _mk_resp(payload, code=requests.codes.ok):
245 """Build a mocked requests response carrying the given payload."""
246 response = mock.Mock()
247 response.status_code = code
248 response.content = dumps(payload).encode("utf-8")
249 return response
250
251
252 def test_plugin_mobilemessage_urls():
253 """NotifyMobileMessage() Apprise URLs."""
254
255 # Run our general tests
256 AppriseURLTester(tests=apprise_url_tests).run_all()
257
258
259 def test_plugin_mobilemessage_init():
260 """NotifyMobileMessage() initialisation."""
261
262 # An API username and password are both mandatory
263 with pytest.raises(AppriseImproperlyConfigured):
264 NotifyMobileMessage(source="ALERTS", targets="0412345678")
265
266 with pytest.raises(AppriseImproperlyConfigured):
267 NotifyMobileMessage(user="user", source="ALERTS", targets="0412345678")
268
269 # A Sender ID is mandatory
270 with pytest.raises(AppriseImproperlyConfigured):
271 NotifyMobileMessage(user="user", password="pass", targets="0412345678")
272
273 # A valid object
274 obj = NotifyMobileMessage(
275 user="user",
276 password="pass",
277 source="ALERTS",
278 targets="0412345678",
279 )
280 assert obj.targets == ["61412345678"]
281 assert obj.unicode is False
282 assert obj.batch is True
283 assert obj.max_parts == 10
284 assert obj.ref is None
285 assert len(obj) == 1
286
287 # An object with no targets still counts as one notification
288 obj = NotifyMobileMessage(user="user", password="pass", source="ALERTS")
289 assert obj.targets == []
290 assert len(obj) == 1
291
292 # Batch mode turned off counts every target separately
293 obj = NotifyMobileMessage(
294 user="user",
295 password="pass",
296 source="ALERTS",
297 targets=["0412345678", "0498765432"],
298 batch=False,
299 )
300 assert len(obj) == 2
301
302 # Our identity does not change when the targets do
303 other = NotifyMobileMessage(
304 user="user",
305 password="pass",
306 source="ALERTS",
307 targets="0411111111",
308 )
309 assert obj.url_identifier == other.url_identifier
310
311
312 def test_plugin_mobilemessage_max_parts():
313 """NotifyMobileMessage() max_parts handling."""
314
315 # A value that is not a number at all
316 with pytest.raises(AppriseImproperlyConfigured):
317 NotifyMobileMessage(
318 user="user",
319 password="pass",
320 source="ALERTS",
321 targets="0412345678",
322 max_parts="invalid",
323 )
324
325 # Below and above the accepted range
326 for value in (0, 100):
327 with pytest.raises(AppriseImproperlyConfigured):
328 NotifyMobileMessage(
329 user="user",
330 password="pass",
331 source="ALERTS",
332 targets="0412345678",
333 max_parts=value,
334 )
335
336 # The body limit follows the part count and the encoding
337 obj = NotifyMobileMessage(
338 user="user",
339 password="pass",
340 source="ALERTS",
341 targets="0412345678",
342 )
343 assert obj.body_maxlen == 1530
344
345 obj = NotifyMobileMessage(
346 user="user",
347 password="pass",
348 source="ALERTS",
349 targets="0412345678",
350 unicode=True,
351 )
352 assert obj.body_maxlen == 670
353
354 obj = NotifyMobileMessage(
355 user="user",
356 password="pass",
357 source="ALERTS",
358 targets="0412345678",
359 unicode=True,
360 max_parts=3,
361 )
362 assert obj.body_maxlen == 201
363
364
365 def test_plugin_mobilemessage_targets():
366 """NotifyMobileMessage() target handling."""
367
368 obj = NotifyMobileMessage(
369 user="user",
370 password="pass",
371 source="ALERTS",
372 targets=[
373 # Local format
374 "0412345678",
375 # Leading zero left off
376 "412345679",
377 # International format
378 "61412345680",
379 # Nicely formatted international
380 "+61 412 345 681",
381 # Not a phone number at all
382 "abcd",
383 # Too short to be anything
384 "123",
385 # A United States number
386 "15551231234",
387 # An Australian landline, not a mobile
388 "0298765432",
389 ],
390 )
391
392 assert obj.targets == [
393 "61412345678",
394 "61412345679",
395 "61412345680",
396 "61412345681",
397 ]
398
399
400 @mock.patch("requests.post")
401 def test_plugin_mobilemessage_send(mock_post):
402 """NotifyMobileMessage() send handling."""
403
404 # Every recipient was accepted
405 mock_post.return_value = _mk_resp(
406 {
407 "status": "complete",
408 "results": [{"to": "61412345678", "status": "success"}],
409 }
410 )
411
412 obj = Apprise.instantiate(
413 "mobilemessage://user:pass@ALERTS/0412345678?ref=nightly"
414 )
415 assert obj.notify(body="body", notify_type=NotifyType.INFO) is True
416
417 assert mock_post.call_count == 1
418 call = mock_post.call_args_list[0]
419
420 # We reached the documented endpoint
421 assert urlparse(call[0][0]).hostname == "api.mobilemessage.com.au"
422
423 # Basic authentication carries our API key pair
424 assert call[1]["auth"] == ("user", "pass")
425
426 # Our payload holds one entry per recipient
427 payload = loads(call[1]["data"])
428 assert payload["messages"] == [
429 {
430 "to": "61412345678",
431 "message": "body",
432 "sender": "ALERTS",
433 "custom_ref": "nightly",
434 }
435 ]
436 assert payload["enable_unicode"] is False
437 assert payload["max_parts"] == 10
438
439 # Every request carries its own idempotency key
440 assert len(call[1]["headers"]["Idempotency-Key"]) > 0
441
442
443 @mock.patch("requests.post")
444 def test_plugin_mobilemessage_batch(mock_post):
445 """NotifyMobileMessage() batch handling."""
446
447 mock_post.return_value = _mk_resp(_ok(2))
448
449 # Batch mode is on by default, so both recipients share one request
450 obj = Apprise.instantiate(
451 "mobilemessage://user:pass@ALERTS/0412345678/0498765432"
452 )
453 assert obj.notify(body="body") is True
454 assert mock_post.call_count == 1
455
456 payload = loads(mock_post.call_args_list[0][1]["data"])
457 assert len(payload["messages"]) == 2
458
459 # Turning batch mode off gives each recipient its own request, so each
460 # response reports on just the one it carried
461 mock_post.reset_mock()
462 mock_post.return_value = _mk_resp(_ok(1))
463 obj = Apprise.instantiate(
464 "mobilemessage://user:pass@ALERTS/0412345678/0498765432?batch=no"
465 )
466 assert obj.notify(body="body") is True
467 assert mock_post.call_count == 2
468
469 # Each request gets a key of its own
470 keys = {
471 call[1]["headers"]["Idempotency-Key"]
472 for call in mock_post.call_args_list
473 }
474 assert len(keys) == 2
475
476
477 @mock.patch("requests.post")
478 def test_plugin_mobilemessage_results(mock_post):
479 """NotifyMobileMessage() per recipient result handling."""
480
481 obj = Apprise.instantiate(
482 "mobilemessage://user:pass@ALERTS/0412345678/0498765432"
483 )
484
485 # A recipient the service refused fails the notification
486 mock_post.return_value = _mk_resp(
487 {
488 "status": "complete",
489 "results": [
490 {"to": "61412345678", "status": "success"},
491 {
492 "to": "61498765432",
493 "status": "blocked",
494 "error": "Recipient has unsubscribed",
495 },
496 ],
497 }
498 )
499 assert obj.notify(body="body") is False
500
501 # An entry with nothing useful in it still fails
502 mock_post.return_value = _mk_resp(
503 {
504 "status": "complete",
505 "results": [
506 {"to": "61412345678", "status": "success"},
507 {"status": "error"},
508 ],
509 }
510 )
511 assert obj.notify(body="body") is False
512
513 # An entry we can not read confirms nothing, so it counts as refused
514 mock_post.return_value = _mk_resp(
515 {
516 "status": "complete",
517 "results": [
518 {"to": "61412345678", "status": "success"},
519 "unexpected",
520 ],
521 }
522 )
523 assert obj.notify(body="body") is False
524
525 # Every recipient accepted
526 mock_post.return_value = _mk_resp(_ok(2))
527 assert obj.notify(body="body") is True
528
529
530 @mock.patch("apprise.plugins.base.time.sleep")
531 @mock.patch("requests.post")
532 def test_plugin_mobilemessage_timeout_reuses_key(mock_post, mock_sleep):
533 """A resend after a timeout carries the key of the attempt that hung."""
534
535 # Nothing comes back from the first attempt, so there is no way to know
536 # whether the service took the batch or not
537 mock_post.side_effect = [
538 requests.ConnectionError("timed out"),
539 _mk_resp(_ok(2)),
540 ]
541
542 aobj = Apprise()
543 assert aobj.add(
544 "mobilemessage://user:pass@ALERTS/0412345678/0498765432?retry=1&wait=0"
545 )
546 assert bool(aobj.notify(body="body")) is True
547 assert mock_post.call_count == 2
548
549 keys = [
550 call[1]["headers"]["Idempotency-Key"]
551 for call in mock_post.call_args_list
552 ]
553
554 # Same key, so the service recognises the resend and only charges once
555 assert keys[0] == keys[1]
556
557 # The same content in a fresh notification still needs a fresh key.
558 mock_post.reset_mock()
559 mock_post.side_effect = None
560 mock_post.return_value = _mk_resp(_ok(2))
561 assert bool(aobj.notify(body="body")) is True
562 assert (
563 mock_post.call_args_list[0][1]["headers"]["Idempotency-Key"]
564 not in keys
565 )
566
567
568 @mock.patch("apprise.plugins.base.time.sleep")
569 @mock.patch("requests.post")
570 def test_plugin_mobilemessage_server_error_key(mock_post, mock_sleep):
571 """A retry after a server error carries the key that produced it."""
572
573 # A 5xx leaves it unclear whether the batch was processed at all
574 mock_post.side_effect = [
575 _mk_resp({}, code=requests.codes.internal_server_error),
576 _mk_resp(_ok(2)),
577 ]
578
579 aobj = Apprise()
580 assert aobj.add(
581 "mobilemessage://user:pass@ALERTS/0412345678/0498765432?retry=1&wait=0"
582 )
583 assert bool(aobj.notify(body="body")) is True
584 assert mock_post.call_count == 2
585
586 keys = [
587 call[1]["headers"]["Idempotency-Key"]
588 for call in mock_post.call_args_list
589 ]
590 assert keys[0] == keys[1]
591
592
593 @mock.patch("requests.post")
594 def test_plugin_mobilemessage_key_not_inherited(mock_post):
595 """A later notification never picks up a key left by an earlier one."""
596
597 # Retries are off, so the first send has no second attempt to hand its
598 # key to. Leaving it behind would have the service answer the next
599 # alert from its cache instead of sending it.
600 mock_post.side_effect = [
601 requests.ConnectionError("timed out"),
602 _mk_resp(_ok()),
603 ]
604
605 aobj = Apprise()
606 assert aobj.add("mobilemessage://user:pass@ALERTS/0412345678")
607 assert bool(aobj.notify(body="Disk full")) is False
608 assert bool(aobj.notify(body="Disk full")) is True
609
610 keys = [
611 call[1]["headers"]["Idempotency-Key"]
612 for call in mock_post.call_args_list
613 ]
614 assert keys[0] != keys[1]
615
616
617 @mock.patch("apprise.plugins.base.time.sleep")
618 @mock.patch("requests.post")
619 def test_plugin_mobilemessage_key_expires(mock_post, mock_sleep):
620 """A used up retry chain does not lend its key to the next alert."""
621
622 # Both attempts hang, then a separate notification sends the same text
623 mock_post.side_effect = [
624 requests.ConnectionError("timed out"),
625 requests.ConnectionError("timed out"),
626 _mk_resp(_ok()),
627 ]
628
629 aobj = Apprise()
630 assert aobj.add(
631 "mobilemessage://user:pass@ALERTS/0412345678?retry=1&wait=0"
632 )
633 assert bool(aobj.notify(body="Disk full")) is False
634 assert bool(aobj.notify(body="Disk full")) is True
635
636 keys = [
637 call[1]["headers"]["Idempotency-Key"]
638 for call in mock_post.call_args_list
639 ]
640
641 # Shared by the two attempts of the first notification ...
642 assert keys[0] == keys[1]
643
644 # ... and not by the notification that followed it
645 assert keys[2] != keys[0]
646
647
648 @mock.patch("requests.post")
649 def test_plugin_mobilemessage_overlapping_keys(mock_post):
650 """Two notifications in flight at once each get their own key."""
651
652 aobj = Apprise()
653 assert aobj.add("mobilemessage://user:pass@ALERTS/0412345678")
654
655 # Send the same text again from inside the first send's own request,
656 # so the two notifications genuinely overlap on one plugin instance
657 def handler(*args, **kwargs):
658 if mock_post.call_count == 1:
659 aobj.notify(body="Disk full")
660
661 return _mk_resp(_ok())
662
663 mock_post.side_effect = handler
664 assert bool(aobj.notify(body="Disk full")) is True
665 assert mock_post.call_count == 2
666
667 keys = [
668 call[1]["headers"]["Idempotency-Key"]
669 for call in mock_post.call_args_list
670 ]
671 assert keys[0] != keys[1]
672
673
674 @mock.patch("apprise.plugins.base.time.sleep")
675 @mock.patch("requests.post")
676 def test_plugin_mobilemessage_identical_pieces(mock_post, mock_sleep):
677 """Two pieces of one message never share a key, alike or not.
678
679 A long body splits into pieces that can come out byte for byte the
680 same. Each is still its own request, so handing the second the
681 first's key would have the service replay it and never deliver.
682 """
683
684 def handler(*args, **kwargs):
685 sent = loads(kwargs["data"])["messages"]
686 return _mk_resp(
687 {
688 "status": "complete",
689 "results": [{"status": "success"}] * len(sent),
690 }
691 )
692
693 mock_post.side_effect = handler
694
695 aobj = Apprise()
696 assert aobj.add(
697 "mobilemessage://user:pass@ALERTS/0412345678"
698 "?overflow=split&retry=1&wait=0"
699 )
700
701 # Splits into two pieces holding exactly the same text
702 assert bool(aobj.notify(body="A" * 3060)) is True
703 assert mock_post.call_count == 2
704
705 pieces = [
706 loads(call[1]["data"])["messages"][0]["message"]
707 for call in mock_post.call_args_list
708 ]
709 assert pieces[0] == pieces[1]
710
711 keys = [
712 call[1]["headers"]["Idempotency-Key"]
713 for call in mock_post.call_args_list
714 ]
715 assert keys[0] != keys[1]
716
717
718 @mock.patch("apprise.dispatch.time.sleep")
719 @mock.patch("apprise.plugins.base.time.sleep")
720 @mock.patch("requests.post")
721 def test_plugin_mobilemessage_piece_retry_key(
722 mock_post, mock_sleep, mock_wait
723 ):
724 """A piece that has to be resent still carries its own first key."""
725
726 calls = []
727
728 def handler(*args, **kwargs):
729 # The two pieces are told apart by the character they end on
730 message = loads(kwargs["data"])["messages"][0]["message"]
731 calls.append((message[-1], kwargs["headers"]["Idempotency-Key"]))
732
733 if len(calls) == 1:
734 # The opening piece hangs and has to be sent again
735 raise requests.ConnectionError("timed out")
736
737 return _mk_resp(
738 {
739 "status": "complete",
740 "results": [{"status": "success"}],
741 }
742 )
743
744 mock_post.side_effect = handler
745
746 aobj = Apprise()
747 assert aobj.add(
748 "mobilemessage://user:pass@ALERTS/0412345678"
749 "?overflow=split&retry=1&wait=0"
750 )
751 aobj.notify(body="A" * 2000 + "B" * 1060)
752
753 # The first piece, the second piece, then the first one again
754 assert [tail for tail, _ in calls] == ["A", "B", "A"]
755
756 # The resent piece carries the key it opened with
757 assert calls[0][1] == calls[2][1]
758
759 # The piece that got through has its own
760 assert calls[1][1] != calls[0][1]
761
762
763 @mock.patch("apprise.plugins.base.time.sleep")
764 @mock.patch("requests.post")
765 def test_plugin_mobilemessage_concurrent_keys(mock_post, mock_sleep):
766 """Parallel notifications keep separate keys across their retries."""
767
768 aobj = Apprise()
769 assert aobj.add(
770 "mobilemessage://user:pass@ALERTS/0412345678?retry=1&wait=0"
771 )
772
773 seen = set()
774 guard = threading.Lock()
775 keys = []
776
777 def handler(*args, **kwargs):
778 key = kwargs["headers"]["Idempotency-Key"]
779 with guard:
780 keys.append(key)
781 opening = key not in seen
782 seen.add(key)
783
784 if opening:
785 # Every chain's first attempt hangs, whichever order they
786 # happen to run in
787 raise requests.ConnectionError("first attempt hangs")
788
789 return _mk_resp(_ok())
790
791 mock_post.side_effect = handler
792
793 threads = [
794 threading.Thread(target=aobj.notify, kwargs={"body": "Disk full"})
795 for _ in range(2)
796 ]
797 for thread in threads:
798 thread.start()
799
800 for thread in threads:
801 thread.join(timeout=30)
802 assert not thread.is_alive()
803
804 # Two chains, each of which retried once
805 assert len(keys) == 4
806
807 # A key of their own, and each one used by both of its attempts.
808 # Order is left alone; the threads may interleave any way they like.
809 assert len(set(keys)) == 2
810 assert all(keys.count(key) == 2 for key in set(keys))
811
812
813 @mock.patch("apprise.plugins.base.time.sleep")
814 @mock.patch("requests.post")
815 def test_plugin_mobilemessage_overlapping_chains(mock_post, mock_sleep):
816 """An overlapping notification cannot take another's key away."""
817
818 aobj = Apprise()
819 assert aobj.add(
820 "mobilemessage://user:pass@ALERTS/0412345678?retry=1&wait=0"
821 )
822
823 # While the first request is open, an identical notification runs to
824 # completion on the same instance. Its key is its own, and clearing it
825 # must not disturb the one the first notification is still relying on.
826 def handler(*args, **kwargs):
827 if mock_post.call_count == 1:
828 aobj.notify(body="Disk full")
829 raise requests.ConnectionError("first request hangs")
830
831 return _mk_resp(_ok())
832
833 mock_post.side_effect = handler
834 aobj.notify(body="Disk full")
835
836 keys = [
837 call[1]["headers"]["Idempotency-Key"]
838 for call in mock_post.call_args_list
839 ]
840
841 # First attempt, the overlapping notification, then the first's retry
842 assert len(keys) == 3
843 assert keys[0] != keys[1]
844 assert keys[2] == keys[0]
845
846
847 @mock.patch("apprise.plugins.base.time.sleep")
848 @mock.patch("requests.post")
849 def test_plugin_mobilemessage_batch_boundaries(mock_post, mock_sleep):
850 """A batch whose outcome is unknown is resent exactly as it was."""
851
852 # Two batches of one. The first is answered and taken, the second
853 # never comes back, so only the second should go out again -- and it
854 # has to look identical, key included, or the resend is charged twice.
855 mock_post.side_effect = [
856 _mk_resp(
857 {
858 "status": "complete",
859 "results": [{"to": "61412345678", "status": "success"}],
860 }
861 ),
862 requests.ConnectionError("timed out"),
863 _mk_resp(
864 {
865 "status": "complete",
866 "results": [{"to": "61498765432", "status": "success"}],
867 }
868 ),
869 ]
870
871 aobj = Apprise()
872 assert aobj.add(
873 "mobilemessage://user:pass@ALERTS/0412345678/0498765432"
874 "?batch=no&retry=1&wait=0"
875 )
876 assert bool(aobj.notify(body="body")) is True
877
878 # The recipient that was taken is not contacted again
879 assert mock_post.call_count == 3
880 sent = [
881 [entry["to"] for entry in loads(call[1]["data"])["messages"]]
882 for call in mock_post.call_args_list
883 ]
884 assert sent == [["61412345678"], ["61498765432"], ["61498765432"]]
885
886 # The resend of the unanswered batch carries its original key
887 keys = [
888 call[1]["headers"]["Idempotency-Key"]
889 for call in mock_post.call_args_list
890 ]
891 assert keys[1] == keys[2]
892 assert keys[0] != keys[1]
893
894
895 @mock.patch("apprise.plugins.base.time.sleep")
896 @mock.patch("requests.post")
897 def test_plugin_mobilemessage_unreadable_ok_key(mock_post, mock_sleep):
898 """A 200 we cannot read keeps its key, because nothing is settled."""
899
900 # A valid answer accounts for every message; this one accounts for
901 # none, so there is no telling what the service did with the batch
902 unreadable = mock.Mock()
903 unreadable.status_code = requests.codes.ok
904 unreadable.content = b"<html>not json</html>"
905
906 mock_post.side_effect = [unreadable, _mk_resp(_ok(2))]
907
908 aobj = Apprise()
909 assert aobj.add(
910 "mobilemessage://user:pass@ALERTS/0412345678/0498765432?retry=1&wait=0"
911 )
912 assert bool(aobj.notify(body="body")) is True
913 assert mock_post.call_count == 2
914
915 keys = [
916 call[1]["headers"]["Idempotency-Key"]
917 for call in mock_post.call_args_list
918 ]
919 assert keys[0] == keys[1]
920
921
922 @mock.patch("requests.post")
923 def test_plugin_mobilemessage_key_per_notification(mock_post):
924 """Each notification sends under a key of its very own."""
925
926 obj = Apprise.instantiate("mobilemessage://user:pass@ALERTS/0412345678")
927
928 # The outcome of the first send makes no difference here
929 mock_post.return_value = _mk_resp(
930 {"error": "Unauthorized"}, code=requests.codes.unauthorized
931 )
932 assert obj.notify(body="body") is False
933
934 # The same text going out again is a new message, not a repeat
935 mock_post.return_value = _mk_resp(_ok())
936 assert obj.notify(body="body") is True
937
938 keys = [
939 call[1]["headers"]["Idempotency-Key"]
940 for call in mock_post.call_args_list
941 ]
942 assert keys[0] != keys[1]
943
944
945 @mock.patch("apprise.plugins.base.time.sleep")
946 @mock.patch("requests.post")
947 def test_plugin_mobilemessage_retry_skips_accepted(mock_post, mock_sleep):
948 """A retry carries only the recipients the service has not taken."""
949
950 # The first attempt gets one recipient through and has the other
951 # refused; the retry should then be left with just the refused one.
952 mock_post.side_effect = [
953 _mk_resp(
954 {
955 "status": "complete",
956 "results": [
957 {"to": "61412345678", "status": "success"},
958 {
959 "to": "61498765432",
960 "status": "blocked",
961 "error": "Recipient has unsubscribed",
962 },
963 ],
964 }
965 ),
966 _mk_resp(
967 {
968 "status": "complete",
969 "results": [{"to": "61498765432", "status": "blocked"}],
970 }
971 ),
972 ]
973
974 aobj = Apprise()
975 assert aobj.add(
976 "mobilemessage://user:pass@ALERTS/0412345678/0498765432?retry=1&wait=0"
977 )
978 assert bool(aobj.notify(body="body")) is False
979
980 # Both attempts were made
981 assert mock_post.call_count == 2
982
983 def recipients(call):
984 return [entry["to"] for entry in loads(call[1]["data"])["messages"]]
985
986 # Everyone on the way out, then only the one still outstanding
987 assert recipients(mock_post.call_args_list[0]) == [
988 "61412345678",
989 "61498765432",
990 ]
991 assert recipients(mock_post.call_args_list[1]) == ["61498765432"]
992
993
994 @mock.patch("requests.post")
995 def test_plugin_mobilemessage_unconfirmed(mock_post):
996 """NotifyMobileMessage() responses that confirm nothing."""
997
998 obj = Apprise.instantiate(
999 "mobilemessage://user:pass@ALERTS/0412345678/0498765432"
1000 )
1001
1002 # The service always reports on every message it processed, so a
1003 # response without that list leaves the send unconfirmed
1004 for payload in (
1005 # No results field at all
1006 {"status": "complete"},
1007 # Present but the wrong shape
1008 {"status": "complete", "results": "unexpected"},
1009 # Present but empty
1010 {"status": "complete", "results": []},
1011 # One report short of the two recipients we sent to
1012 {
1013 "status": "complete",
1014 "results": [{"to": "61412345678", "status": "success"}],
1015 },
1016 # More reports than we sent messages
1017 {
1018 "status": "complete",
1019 "results": [{"status": "success"}] * 3,
1020 },
1021 # The envelope never said the batch finished
1022 {"results": [{"status": "success"}] * 2},
1023 # An envelope status we do not recognise
1024 {"status": "queued", "results": [{"status": "success"}] * 2},
1025 # Not an object at the top level
1026 None,
1027 ):
1028 mock_post.return_value = _mk_resp(payload)
1029 assert obj.notify(body="body") is False
1030
1031 # A body that is not JSON at all
1032 response = mock.Mock()
1033 response.status_code = requests.codes.ok
1034 response.content = b"<html>not json</html>"
1035 mock_post.return_value = response
1036 assert obj.notify(body="body") is False
1037
1038
1039 @mock.patch("requests.post")
1040 def test_plugin_mobilemessage_errors(mock_post):
1041 """NotifyMobileMessage() error handling."""
1042
1043 obj = Apprise.instantiate(
1044 "mobilemessage://user:pass@ALERTS/0412345678/0498765432?batch=no"
1045 )
1046
1047 # A documented error code
1048 mock_post.return_value = _mk_resp(
1049 {"error": "Unauthorized"}, code=requests.codes.unauthorized
1050 )
1051 assert obj.notify(body="body") is False
1052
1053 # A code we have no message for
1054 mock_post.return_value = _mk_resp({}, code=999)
1055 assert obj.notify(body="body") is False
1056
1057 # The connection never got anywhere
1058 mock_post.side_effect = requests.ConnectionError(
1059 0, "requests.ConnectionError() not handled"
1060 )
1061 assert obj.notify(body="body") is False
1062
1063
1064 def test_plugin_mobilemessage_url_parsing():
1065 """NotifyMobileMessage() URL parsing."""
1066
1067 # Every supported query argument
1068 results = NotifyMobileMessage.parse_url(
1069 "mobilemessage://user:pass@ALERTS/0412345678"
1070 "?unicode=yes&batch=no&max_parts=4&ref=nightly&to=0498765432"
1071 )
1072 assert results["source"] == "ALERTS"
1073 assert results["targets"] == ["0412345678", "0498765432"]
1074 assert results["unicode"] is True
1075 assert results["batch"] is False
1076 assert results["max_parts"] == "4"
1077 assert results["ref"] == "nightly"
1078
1079 # With from=, the hostname becomes a target
1080 results = NotifyMobileMessage.parse_url(
1081 "mobilemessage://user:pass@0412345678/0498765432?from=ALERTS"
1082 )
1083 assert results["source"] == "ALERTS"
1084 assert results["targets"] == ["0412345678", "0498765432"]
1085
1086 # A URL we cannot make sense of at all
1087 assert NotifyMobileMessage.parse_url("mobilemessage://") is not None
1088 assert NotifyMobileMessage.parse_url(None) is None
1089
1090
1091 @mock.patch("requests.post")
1092 def test_plugin_mobilemessage_apprise_integration(mock_post):
1093 """NotifyMobileMessage() Apprise integration."""
1094
1095 mock_post.return_value = _mk_resp(_ok())
1096
1097 aobj = Apprise()
1098 assert aobj.add("mobilemessage://user:pass@ALERTS/0412345678")
1099 assert aobj.add("mobilemsg://user:pass@61400000000/0498765432")
1100 assert len(aobj) == 2
1101 assert bool(aobj.notify(title="title", body="body")) is True
1102 assert mock_post.call_count == 2
1103
1104 # The title is folded into the body because SMS has no title field
1105 payload = loads(mock_post.call_args_list[0][1]["data"])
1106 assert payload["messages"][0]["message"] == "title\r\nbody"