Debian Codegraph @

tests/test_api.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 import asyncio
29 import concurrent.futures
30 import inspect
31 from inspect import cleandoc
32
33 # Disable logging for a cleaner testing output
34 import logging
35 from os.path import dirname, join
36 import re
37 import sys
38 from typing import ClassVar
39 from unittest import mock
40
41 from helpers import OuterEventLoop
42 import pytest
43 import requests
44
45 from apprise import (
46 LOGGER_NAME,
47 NOTIFY_FORMATS,
48 Apprise,
49 AppriseAsset,
50 AppriseAttachment,
51 AppriseResultStatus,
52 NotificationManager,
53 NotifyBase,
54 NotifyFormat,
55 NotifyImageSize,
56 NotifyType,
57 PersistentStoreMode,
58 PrivacyMode,
59 URLBase,
60 __version__,
61 plugins,
62 )
63 from apprise.locale import LazyTranslation, gettext_lazy as _
64 from apprise.plugins.base import RequirementsSpec
65 from apprise.utils.parse import parse_list
66
67 logging.disable(logging.CRITICAL)
68
69 # Attachment Directory
70 TEST_VAR_DIR = join(dirname(__file__), "var")
71
72 # Grant access to our Notification Manager Singleton
73 N_MGR = NotificationManager()
74
75
76 def test_apprise_object():
77 """
78 API: Apprise() object
79
80 """
81
82 def do_notify(service, *args, **kwargs):
83 return service.notify(*args, **kwargs)
84
85 apprise_test(do_notify)
86
87
88 def test_apprise_async():
89 """
90 API: Apprise() object asynchronous methods
91
92 """
93 with OuterEventLoop() as loop:
94
95 def do_notify(service, *args, **kwargs):
96 return loop.run_until_complete(
97 service.async_notify(*args, **kwargs)
98 )
99
100 apprise_test(do_notify)
101
102
103 def apprise_test(do_notify):
104 """Exercise the core Apprise container and notification behavior."""
105 a = Apprise()
106
107 # no items
108 assert len(a) == 0
109
110 # Apprise object can also be directly tested with 'if' keyword
111 # No entries results in a False response
112 assert not a
113
114 # Create an Asset object
115 asset = AppriseAsset(theme="default")
116
117 # We can load the device using our asset
118 a = Apprise(asset=asset)
119
120 # We can load our services up front as well
121 services = [
122 "json://myhost",
123 "kodi://kodi.server.local",
124 ]
125
126 a = Apprise(services=services)
127
128 # 2 services loaded
129 assert len(a) == 2
130
131 # Apprise object can also be directly tested with 'if' keyword
132 # At least one entry results in a True response
133 assert a
134
135 # We can retrieve our URLs this way:
136 assert len(a.urls()) == 2
137
138 # We can add another service
139 assert (
140 a.add(
141 "mmosts://mattermost.server.local/3ccdd113474722377935511fc85d3dd4"
142 )
143 is True
144 )
145 assert len(a) == 3
146
147 # Try adding nothing but delimiters
148 assert a.add(",, ,, , , , ,") is False
149
150 # The number of services added doesn't change
151 assert len(a) == 3
152
153 # We can pop an object off of our stack by it's indexed value:
154 obj = a.pop(0)
155 assert isinstance(obj, NotifyBase) is True
156 assert len(a) == 2
157
158 # We can retrieve elements from our list too by reference:
159 assert isinstance(a[0].url(), str) is True
160
161 # We can iterate over our list too:
162 count = 0
163 for o in a:
164 assert isinstance(o.url(), str) is True
165 count += 1
166 # verify that we did indeed iterate over each element
167 assert len(a) == count
168
169 # We can empty our set
170 a.clear()
171 assert len(a) == 0
172
173 # An invalid schema
174 assert a.add("this is not a parseable url at all") is False
175 assert len(a) == 0
176
177 # An unsupported schema
178 assert a.add("invalid://we.just.do.not.support.this.plugin.type") is False
179 assert len(a) == 0
180
181 # A poorly formatted URL
182 assert a.add("json://user:@@@:bad?no.good") is False
183 assert len(a) == 0
184
185 # Add a service with our asset we created earlier
186 assert (
187 a.add(
188 "mmosts://mattermost.server.local/"
189 "3ccdd113474722377935511fc85d3dd4",
190 asset=asset,
191 )
192 is True
193 )
194
195 # Clear our service listings again
196 a.clear()
197 assert len(a) == 0
198
199 # No services to notify
200 assert bool(do_notify(a, title="my title", body="my body")) is False
201
202 # More Variations of Multiple Adding of URLs
203 a = Apprise()
204 assert a.add(services)
205 assert len(a) == 2
206 a.clear()
207
208 assert a.add("ntfys://user:pass@host/test, json://localhost")
209 assert len(a) == 2
210 a.clear()
211
212 assert a.add(["ntfys://user:pass@host/test", "json://localhost"])
213 assert len(a) == 2
214 a.clear()
215
216 assert a.add(("ntfys://user:pass@host/test", "json://localhost"))
217 assert len(a) == 2
218 a.clear()
219
220 assert a.add({"ntfys://user:pass@host/test", "json://localhost"})
221 assert len(a) == 2
222 a.clear()
223
224 # Pass a list entry containing 1 string with 2 elements in it
225 # Mimic Home-Assistant core-2024.2.1 Issue:
226 # - https://github.com/home-assistant/core/issues/110242
227 #
228 # In this case, the first one will load, but not the second entry
229 # This is by design; but captured here to illustrate the issue
230 assert a.add(["ntfys://user:pass@host/test, json://localhost"])
231 assert len(a) == 1
232 assert a[0].url().startswith("ntfys://")
233 a.clear()
234
235 # Following thorugh with the problem of providing a list containing
236 # an entry with 2 URLs in it... while the ntfys parsed okay above,
237 # the same can't be said for other combinations. It's important
238 # to always keep strings separately
239 assert a.add(["mailto://user:[email protected], json://localhost"]) is False
240 assert len(a) == 0
241
242 # Showing that the URLs were valid on their own:
243 assert a.add(*["mailto://user:[email protected], json://localhost"])
244 assert len(a) == 2
245 assert a[0].url().startswith("mailto://")
246 assert a[1].url().startswith("json://")
247 a.clear()
248
249 class BadNotification(NotifyBase):
250 def __init__(self, **kwargs):
251 super().__init__(**kwargs)
252
253 # We fail whenever we're initialized
254 raise TypeError()
255
256 @staticmethod
257 def parse_url(url, *args, **kwargs):
258 # always parseable
259 return NotifyBase.parse_url(url, verify_host=False)
260
261 class GoodNotification(NotifyBase):
262 def __init__(self, **kwargs):
263 super().__init__(notify_format=NotifyFormat.HTML, **kwargs)
264
265 def send(self, **kwargs):
266 # Pretend everything is okay
267 return True
268
269 @staticmethod
270 def parse_url(url, *args, **kwargs):
271 # always parseable
272 return NotifyBase.parse_url(url, verify_host=False)
273
274 # Store our bad notification in our schema map
275 N_MGR["bad"] = BadNotification
276
277 # Store our good notification in our schema map
278 N_MGR["good"] = GoodNotification
279
280 # Just to explain what is happening here, we would have parsed the
281 # url properly but failed when we went to go and create an instance
282 # of it.
283 assert a.add("bad://localhost") is False
284 assert len(a) == 0
285
286 # We'll fail because we've got nothing to notify
287 assert bool(do_notify(a, title="my title", body="my body")) is False
288
289 # Clear our service listings again
290 a.clear()
291
292 assert a.add("good://localhost") is True
293 assert len(a) == 1
294
295 # Bad Notification Types are not accepted
296 assert (
297 bool(do_notify(a, title="my title", body="my body", notify_type="bad"))
298 is False
299 )
300
301 # Notifications of string type are accepted
302 assert (
303 bool(
304 do_notify(
305 a, title="my title", body="my body", notify_type="warning"
306 )
307 )
308 is True
309 )
310
311 # Notifications of string type are accepted
312 assert (
313 bool(
314 do_notify(
315 a, title="my title", body="my body", notify_type="warning"
316 )
317 )
318 is True
319 )
320
321 # Notifications of string type are accepted
322 assert (
323 bool(
324 do_notify(
325 a, title="my title", body="my body", notify_type="warning"
326 )
327 )
328 is True
329 )
330
331 # Notifications where notify_type is of the NotifyType object is the
332 # preferred choice
333 assert (
334 bool(
335 do_notify(
336 a,
337 title="my title",
338 body="my body",
339 notify_type=NotifyType.WARNING,
340 )
341 )
342 is True
343 )
344
345 # No Title/Body combo's
346 assert bool(do_notify(a, title=None, body=None)) is False
347 assert bool(do_notify(a, title="", body=None)) is False
348 assert bool(do_notify(a, title=None, body="")) is False
349
350 assert bool(do_notify(a, title=5, body=b"bytes")) is False
351 assert bool(do_notify(a, title=b"bytes", body=10)) is False
352 assert bool(do_notify(a, title=object(), body=b"bytes")) is False
353 assert bool(do_notify(a, title=b"bytes", body=object())) is False
354
355 # A Body must be present
356 assert bool(do_notify(a, title="present", body=None)) is False
357
358 # Other combinations work fine
359 assert bool(do_notify(a, title=None, body="present")) is True
360 assert bool(do_notify(a, title="present", body="present")) is True
361
362 # Send Attachment with success
363 attach = join(TEST_VAR_DIR, "apprise-test.gif")
364 assert (
365 bool(
366 do_notify(
367 a,
368 body="body",
369 title="test",
370 notify_type=NotifyType.INFO,
371 attach=attach,
372 )
373 )
374 is True
375 )
376
377 # Send the attachment as an AppriseAttachment object
378 assert (
379 bool(
380 do_notify(
381 a,
382 body="body",
383 title="test",
384 notify_type=NotifyType.INFO,
385 attach=AppriseAttachment(attach),
386 )
387 )
388 is True
389 )
390
391 # test a invalid attachment
392 assert (
393 bool(
394 do_notify(
395 a,
396 body="body",
397 title="test",
398 notify_type=NotifyType.INFO,
399 attach="invalid://",
400 )
401 )
402 is False
403 )
404
405 # Repeat the same tests above...
406 # however do it by directly accessing the object; this grants the similar
407 # results:
408 assert (
409 bool(
410 do_notify(
411 a[0],
412 body="body",
413 title="test",
414 notify_type=NotifyType.INFO,
415 attach=attach,
416 )
417 )
418 is True
419 )
420
421 # Send the attachment as an AppriseAttachment object
422 assert (
423 bool(
424 do_notify(
425 a[0],
426 body="body",
427 title="test",
428 notify_type=NotifyType.INFO,
429 attach=AppriseAttachment(attach),
430 )
431 )
432 is True
433 )
434
435 # test a invalid attachment
436 assert (
437 bool(
438 do_notify(
439 a[0],
440 body="body",
441 title="test",
442 notify_type=NotifyType.INFO,
443 attach="invalid://",
444 )
445 )
446 is False
447 )
448
449 class ThrowNotification(NotifyBase):
450 def notify(self, **kwargs):
451 # Pretend everything is okay
452 raise TypeError()
453
454 async def async_notify(self, **kwargs):
455 # Pretend everything is okay (async)
456 raise TypeError()
457
458 class RuntimeNotification(NotifyBase):
459 def notify(self, **kwargs):
460 # Pretend everything is okay
461 raise RuntimeError()
462
463 async def async_notify(self, **kwargs):
464 # Pretend everything is okay (async)
465 raise TypeError()
466
467 class FailNotification(NotifyBase):
468 def notify(self, **kwargs):
469 # Pretend everything is okay
470 return False
471
472 async def async_notify(self, **kwargs):
473 # Pretend everything is okay (async)
474 raise TypeError()
475
476 # Store our bad notification in our schema map
477 N_MGR["throw"] = ThrowNotification
478
479 # Store our good notification in our schema map
480 N_MGR["fail"] = FailNotification
481
482 # Store our good notification in our schema map
483 N_MGR["runtime"] = RuntimeNotification
484
485 for async_mode in (True, False):
486 # Create an Asset object
487 asset = AppriseAsset(theme="default", async_mode=async_mode)
488
489 # We can load the device using our asset
490 a = Apprise(asset=asset)
491
492 assert a.add("runtime://localhost") is True
493 assert a.add("throw://localhost") is True
494 assert a.add("fail://localhost") is True
495 assert len(a) == 3
496
497 # Test when our notify both throws an exception and or just
498 # simply returns False
499 assert bool(do_notify(a, title="present", body="present")) is False
500
501 # Create a Notification that throws an unexected exception
502 class ThrowInstantiateNotification(NotifyBase):
503 def __init__(self, **kwargs):
504 # Pretend everything is okay
505 raise TypeError()
506
507 N_MGR.unload_modules()
508 N_MGR["throw"] = ThrowInstantiateNotification
509
510 # Store our good notification in our schema map
511 N_MGR["good"] = GoodNotification
512
513 # Reset our object
514 a.clear()
515 assert len(a) == 0
516
517 # Test our socket details
518 # rto = Socket Read Timeout
519 # cto = Socket Connect Timeout
520 plugin = a.instantiate("good://localhost?rto=5.1&cto=10")
521 assert isinstance(plugin, NotifyBase)
522 assert plugin.socket_connect_timeout == pytest.approx(10.0)
523 assert plugin.socket_read_timeout == pytest.approx(5.1)
524
525 plugin = a.instantiate("good://localhost?rto=invalid&cto=invalid")
526 assert isinstance(plugin, NotifyBase)
527 assert plugin.socket_connect_timeout == URLBase.socket_connect_timeout
528 assert plugin.socket_read_timeout == URLBase.socket_read_timeout
529
530 # Reset our object
531 a.clear()
532 assert len(a) == 0
533
534 with pytest.raises(ValueError):
535 # Encoding error
536 AppriseAsset(encoding="ascii", storage_salt="ボールト")
537
538 with pytest.raises(ValueError):
539 # Not a valid storage salt (must be str or bytes)
540 AppriseAsset(storage_salt=42)
541
542 # Set our cache to be off
543 plugin = a.instantiate("good://localhost?store=no", asset=asset)
544 assert isinstance(plugin, NotifyBase)
545 # The identifier still works; turning storage off only stops anything
546 # being written to disk for it
547 assert plugin.url_id(lazy=False)
548 assert plugin.store.mode is PersistentStoreMode.MEMORY
549 # Verify our cache is disabled
550 assert "store=no" in plugin.url()
551
552 with pytest.raises(ValueError):
553 # idlen must be greater then 0
554 AppriseAsset(storage_idlen=-1)
555
556 # Create a larger idlen
557 asset = AppriseAsset(storage_idlen=32)
558 plugin = a.instantiate("good://localhost", asset=asset)
559 assert len(plugin.url_id()) == 32
560
561 # Instantiate a bad object
562 plugin = a.instantiate(object, tag="bad_object")
563 assert plugin is None
564
565 # Instantiate a good object
566 plugin = a.instantiate("good://localhost", tag="good")
567 assert isinstance(plugin, NotifyBase)
568
569 # Test simple tagging inside of the object
570 assert "good" in plugin
571 assert "bad" not in plugin
572
573 # the in (__contains__ override) is based on or'ed content; so although
574 # 'bad' isn't tagged as being in the plugin, 'good' is, so the return
575 # value of this is True
576 assert ["bad", "good"] in plugin
577 assert {"bad", "good"} in plugin
578 assert ("bad", "good") in plugin
579
580 # We an add already substatiated instances into our Apprise object
581 a.add(plugin)
582 assert len(a) == 1
583
584 # We can add entries as a list too (to add more then one)
585 a.add([plugin, plugin, plugin])
586 assert len(a) == 4
587
588 # Reset our object again
589 a.clear()
590 with pytest.raises(TypeError):
591 a.instantiate("throw://localhost", suppress_exceptions=False)
592
593 assert len(a) == 0
594
595 assert a.instantiate("throw://localhost", suppress_exceptions=True) is None
596 assert len(a) == 0
597
598 #
599 # We rince and repeat the same tests as above, however we do them
600 # using the dict version
601 #
602
603 # Reset our object
604 a.clear()
605 assert len(a) == 0
606
607 # Instantiate a good object
608 plugin = a.instantiate({"schema": "good", "host": "localhost"}, tag="good")
609 assert isinstance(plugin, NotifyBase)
610
611 # Test simple tagging inside of the object
612 assert "good" in plugin
613 assert "bad" not in plugin
614
615 # the in (__contains__ override) is based on or'ed content; so although
616 # 'bad' isn't tagged as being in the plugin, 'good' is, so the return
617 # value of this is True
618 assert ["bad", "good"] in plugin
619 assert {"bad", "good"} in plugin
620 assert ("bad", "good") in plugin
621
622 # We an add already substatiated instances into our Apprise object
623 a.add(plugin)
624 assert len(a) == 1
625
626 # We can add entries as a list too (to add more then one)
627 a.add([plugin, plugin, plugin])
628 assert len(a) == 4
629
630 # Reset our object again
631 a.clear()
632 with pytest.raises(TypeError):
633 a.instantiate(
634 {"schema": "throw", "host": "localhost"}, suppress_exceptions=False
635 )
636
637 assert len(a) == 0
638
639 assert (
640 a.instantiate(
641 {"schema": "throw", "host": "localhost"}, suppress_exceptions=True
642 )
643 is None
644 )
645 assert len(a) == 0
646
647
648 def test_apprise_pretty_print():
649 """
650 API: Apprise() Pretty Print tests
651
652 """
653 # Privacy Print
654 # PrivacyMode.Secret always returns the same thing to avoid guessing
655 assert (
656 URLBase.pprint(None, privacy=True, mode=PrivacyMode.Secret) == "****"
657 )
658 assert URLBase.pprint(42, privacy=True, mode=PrivacyMode.Secret) == "****"
659 assert (
660 URLBase.pprint(object, privacy=True, mode=PrivacyMode.Secret) == "****"
661 )
662 assert URLBase.pprint("", privacy=True, mode=PrivacyMode.Secret) == "****"
663 assert URLBase.pprint("a", privacy=True, mode=PrivacyMode.Secret) == "****"
664 assert (
665 URLBase.pprint("ab", privacy=True, mode=PrivacyMode.Secret) == "****"
666 )
667 assert (
668 URLBase.pprint("abcdefghijk", privacy=True, mode=PrivacyMode.Secret)
669 == "****"
670 )
671
672 # PrivacyMode.Outer
673 assert URLBase.pprint(None, privacy=True, mode=PrivacyMode.Outer) == ""
674 assert URLBase.pprint(42, privacy=True, mode=PrivacyMode.Outer) == ""
675 assert URLBase.pprint(object, privacy=True, mode=PrivacyMode.Outer) == ""
676 assert URLBase.pprint("", privacy=True, mode=PrivacyMode.Outer) == ""
677 assert URLBase.pprint("a", privacy=True, mode=PrivacyMode.Outer) == "a...a"
678 assert (
679 URLBase.pprint("ab", privacy=True, mode=PrivacyMode.Outer) == "a...b"
680 )
681 assert (
682 URLBase.pprint("abcdefghijk", privacy=True, mode=PrivacyMode.Outer)
683 == "a...k"
684 )
685
686 # PrivacyMode.Tail
687 assert URLBase.pprint(None, privacy=True, mode=PrivacyMode.Tail) == ""
688 assert URLBase.pprint(42, privacy=True, mode=PrivacyMode.Tail) == ""
689 assert URLBase.pprint(object, privacy=True, mode=PrivacyMode.Tail) == ""
690 assert URLBase.pprint("", privacy=True, mode=PrivacyMode.Tail) == ""
691 assert URLBase.pprint("a", privacy=True, mode=PrivacyMode.Tail) == "...a"
692 assert URLBase.pprint("ab", privacy=True, mode=PrivacyMode.Tail) == "...ab"
693 assert (
694 URLBase.pprint("abcdefghijk", privacy=True, mode=PrivacyMode.Tail)
695 == "...hijk"
696 )
697
698 # Quoting settings
699 assert URLBase.pprint(" ", privacy=False, safe="") == "%20"
700 assert URLBase.pprint(" ", privacy=False, quote=False, safe="") == " "
701
702
703 @mock.patch("requests.request")
704 def test_apprise_tagging(mock_request):
705 """
706 API: Apprise() object tagging functionality
707
708 """
709
710 def do_notify(service, *args, **kwargs):
711 return service.notify(*args, **kwargs)
712
713 apprise_tagging_test(mock_request, do_notify)
714
715
716 @mock.patch("requests.request")
717 def test_apprise_tagging_async(mock_request):
718 """
719 API: Apprise() object tagging functionality asynchronous methods
720
721 """
722 with OuterEventLoop() as loop:
723
724 def do_notify(service, *args, **kwargs):
725 return loop.run_until_complete(
726 service.async_notify(*args, **kwargs)
727 )
728
729 apprise_tagging_test(mock_request, do_notify)
730
731
732 def apprise_tagging_test(mock_request, do_notify):
733 """Exercise tag filtering and grouped notification behavior."""
734 # A request
735 robj = mock.Mock()
736 robj.raw = mock.Mock()
737 # Allow raw.read() calls
738 robj.raw.read.return_value = ""
739 robj.text = ""
740 robj.content = ""
741 mock_request.return_value = robj
742
743 # Simulate a successful notification
744 mock_request.return_value.status_code = requests.codes.ok
745
746 # Create our object
747 a = Apprise()
748
749 # An invalid addition can't add the tag
750 assert a.add("averyinvalidschema://localhost", tag="uhoh") is False
751 assert (
752 a.add(
753 {"schema": "averyinvalidschema", "host": "localhost"}, tag="uhoh"
754 )
755 is False
756 )
757
758 # Add entry and assign it to a tag called 'awesome'
759 assert a.add("json://localhost/path1/", tag="awesome") is True
760 assert (
761 a.add(
762 {"schema": "json", "host": "localhost", "fullpath": "/path1/"},
763 tag="awesome",
764 )
765 is True
766 )
767
768 # Add another notification and assign it to a tag called 'awesome'
769 # and another tag called 'local'
770 assert a.add("json://localhost/path2/", tag=["mmost", "awesome"]) is True
771
772 # notify the awesome tag; this would notify both services behind the
773 # scenes
774 assert (
775 bool(do_notify(a, title="my title", body="my body", tag="awesome"))
776 is True
777 )
778
779 # notify all of the tags
780 assert (
781 bool(
782 do_notify(
783 a, title="my title", body="my body", tag=["awesome", "mmost"]
784 )
785 )
786 is True
787 )
788
789 # When we query against our loaded notifications for a tag that simply
790 # isn't assigned to anything, we return NOMATCH. NOMATCH (different
791 # then FAILURE) tells us that we litterally had nothing to query. We
792 # didn't fail... but we also didn't do anything...
793 assert (
794 do_notify(a, title="my title", body="my body", tag="missing").status
795 == AppriseResultStatus.NOMATCH
796 )
797
798 # Now to test the ability to and and/or notifications
799 a = Apprise()
800
801 # Add a tag by tuple
802 assert a.add("json://localhost/tagA/", tag=("TagA",)) is True
803 # Add 2 tags by string
804 assert a.add("json://localhost/tagAB/", tag="TagA, TagB") is True
805 # Add a tag using a set
806 assert a.add("json://localhost/tagB/", tag={"TagB"}) is True
807 # Add a tag by string (again)
808 assert a.add("json://localhost/tagC/", tag="TagC") is True
809 # Add 2 tags using a list
810 assert a.add("json://localhost/tagCD/", tag=["TagC", "TagD"]) is True
811 # Add a tag by string (again)
812 assert a.add("json://localhost/tagD/", tag="TagD") is True
813 # add a tag set by set (again)
814 assert (
815 a.add("json://localhost/tagCDE/", tag={"TagC", "TagD", "TagE"}) is True
816 )
817
818 # Expression: TagC and TagD
819 # Matches the following only:
820 # - json://localhost/tagCD/
821 # - json://localhost/tagCDE/
822 assert (
823 bool(
824 do_notify(
825 a,
826 title="my title",
827 body="my body",
828 tag=[("TagC", "TagD")],
829 )
830 )
831 is True
832 )
833
834 # Expression: (TagY and TagZ) or TagX
835 # Matches nothing, NOMATCH is returned in this case
836 assert (
837 do_notify(
838 a, title="my title", body="my body", tag=[("TagY", "TagZ"), "TagX"]
839 ).status
840 == AppriseResultStatus.NOMATCH
841 )
842
843 # Expression: (TagY and TagZ) or TagA
844 # Matches the following only:
845 # - json://localhost/tagAB/
846 assert (
847 bool(
848 do_notify(
849 a,
850 title="my title",
851 body="my body",
852 tag=[("TagY", "TagZ"), "TagA"],
853 )
854 )
855 is True
856 )
857
858 # Expression: (TagE and TagD) or TagB
859 # Matches the following only:
860 # - json://localhost/tagCDE/
861 # - json://localhost/tagAB/
862 # - json://localhost/tagB/
863 assert (
864 bool(
865 do_notify(
866 a,
867 title="my title",
868 body="my body",
869 tag=[("TagE", "TagD"), "TagB"],
870 )
871 )
872 is True
873 )
874
875 # Garbage Entries in tag field just get stripped out. the below
876 # is the same as notifying no tags at all. Since we have not added
877 # any entries that do not have tags (that we can match against)
878 # we fail. NOMATCH is returned as a way of letting us know that we
879 # had Notifications to notify, but since none of them matched our tag
880 # none were notified.
881 assert (
882 do_notify(
883 a,
884 title="my title",
885 body="my body",
886 tag=[
887 (object,),
888 ],
889 ).status
890 == AppriseResultStatus.NOMATCH
891 )
892
893
894 def test_apprise_schemas():
895 """
896 API: Apprise().schema() tests
897
898 """
899 # Clear loaded modules
900 a = Apprise()
901
902 # no items
903 assert len(a) == 0
904
905 class TextNotification(NotifyBase):
906 # set our default notification format
907 notify_format = NotifyFormat.TEXT
908
909 # Garbage Protocol Entries
910 protocol = None
911
912 secure_protocol = (None, object)
913
914 class HtmlNotification(NotifyBase):
915 protocol = ("html", "htm")
916
917 secure_protocol = ("htmls", "htms")
918
919 class MarkDownNotification(NotifyBase):
920 protocol = "markdown"
921
922 secure_protocol = "markdowns"
923
924 schemas = URLBase.schemas(TextNotification)
925 assert isinstance(schemas, set) is True
926 # We didn't define a protocol or secure protocol
927 assert len(schemas) == 0
928
929 # Store our notifications into our schema map
930 N_MGR["text"] = TextNotification
931 N_MGR["html"] = HtmlNotification
932 N_MGR["markdown"] = MarkDownNotification
933
934 schemas = URLBase.schemas(TextNotification)
935 assert isinstance(schemas, set) is True
936 # We didn't define a protocol or secure protocol one
937 # but one got assigned in he above N_MGR call
938 assert len(schemas) == 1
939 assert "text" in schemas
940
941 schemas = URLBase.schemas(HtmlNotification)
942 assert isinstance(schemas, set) is True
943 assert len(schemas) == 4
944 assert "html" in schemas
945 assert "htm" in schemas
946 assert "htmls" in schemas
947 assert "htms" in schemas
948
949 # Invalid entries do not disrupt schema calls
950 for garbage in (object(), None, 42):
951 schemas = URLBase.schemas(garbage)
952 assert isinstance(schemas, set) is True
953 assert len(schemas) == 0
954
955
956 def test_apprise_urlbase_object():
957 """
958 API: Apprise() URLBase object testing
959
960 """
961 results = URLBase.parse_url("https://localhost/path/?cto=3.0&verify=no")
962 assert results.get("user") is None
963 assert results.get("password") is None
964 assert results.get("path") == "/path/"
965 assert results.get("secure") is True
966 assert results.get("verify") is False
967 base = URLBase(**results)
968 assert base.request_timeout == (3.0, 4.0)
969 assert base.request_auth is None
970 assert base.request_url == "https://localhost/path/"
971 assert base.url().startswith("https://localhost/")
972
973 results = URLBase.parse_url(
974 "http://user:pass@localhost:34/path/here?rto=3.0&verify=yes"
975 )
976 assert results.get("user") == "user"
977 assert results.get("password") == "pass"
978 assert results.get("fullpath") == "/path/here"
979 assert results.get("secure") is False
980 assert results.get("verify") is True
981 base = URLBase(**results)
982 assert base.request_timeout == (4.0, 3.0)
983 assert base.request_auth == ("user", "pass")
984 assert base.request_url == "http://localhost:34/path/here"
985 assert base.url().startswith("http://user:pass@localhost:34/path/here")
986
987 results = URLBase.parse_url("http://[email protected]/path/")
988 assert results.get("user") == "user"
989 assert results.get("password") is None
990 assert results.get("fullpath") == "/path/"
991 assert results.get("secure") is False
992 assert results.get("verify") is True
993 base = URLBase(**results)
994 assert base.request_timeout == (4.0, 4.0)
995 assert base.request_auth == ("user", None)
996 assert base.request_url == "http://127.0.0.1/path/"
997 assert base.url().startswith("http://[email protected]/path/")
998
999 # redirect= defaults to True (follows redirects, matching requests default)
1000 results = URLBase.parse_url("https://localhost/path/?redirect=yes")
1001 assert results.get("redirect") is True
1002 base = URLBase(**results)
1003 assert base.redirects is True
1004 # redirect=yes is the default, so it must not appear in url() output
1005 assert "redirect" not in base.url()
1006
1007 # redirect=no disables redirect following and round-trips in the URL
1008 results = URLBase.parse_url(
1009 "http://user:pass@localhost:34/path/here?redirect=no"
1010 )
1011 assert results.get("redirect") is False
1012 base = URLBase(**results)
1013 assert base.redirects is False
1014 assert "redirect=no" in base.url()
1015
1016 # redirect is absent from results when not specified -- URLBase inherits
1017 # the global default from the asset (default asset has http_redirects=True)
1018 results = URLBase.parse_url("http://[email protected]/path/")
1019 assert "redirect" not in results
1020 base = URLBase(**results)
1021 assert base.redirects is True
1022 assert "redirect" not in base.url()
1023
1024 # AppriseAsset(http_redirects=False) flows through to every plugin when the
1025 # URL does not specify redirect=
1026 from apprise import AppriseAsset
1027
1028 asset_no_redirect = AppriseAsset(http_redirects=False)
1029 results = URLBase.parse_url("http://[email protected]/path/")
1030 assert "redirect" not in results
1031 base = URLBase(**results, asset=asset_no_redirect)
1032 assert base.redirects is False # inherited the asset global
1033 # redirects matches the asset default -- no override to serialise
1034 assert "redirect" not in base.url()
1035
1036 # URL-level redirect=yes overrides asset http_redirects=False; the
1037 # override must be preserved in url() so the round-trip is idempotent
1038 results = URLBase.parse_url("http://[email protected]/path/?redirect=yes")
1039 assert results.get("redirect") is True
1040 base = URLBase(**results, asset=asset_no_redirect)
1041 assert base.redirects is True # URL wins over asset
1042 assert "redirect=yes" in base.url() # differs from asset default, emitted
1043
1044 # YAML config path: redirect= provided in the results dict directly
1045 # (not via qsd) -- exercises the elif "redirect" in results branch in
1046 # post_process_parse_url_results()
1047 results = URLBase.parse_url("http://[email protected]/path/")
1048 assert "redirect" not in results
1049 results["redirect"] = "no"
1050 URLBase.post_process_parse_url_results(results)
1051 assert results.get("redirect") is False
1052
1053 results["redirect"] = "yes"
1054 URLBase.post_process_parse_url_results(results)
1055 assert results.get("redirect") is True
1056
1057 # URL_TOKEN_ALIASES: 'pass' in top-level results is normalized to
1058 # 'password' by post_process_parse_url_results (covers the YAML config
1059 # path where a flat dict is passed rather than a parsed URL string)
1060 results = URLBase.parse_url("http://[email protected]/path/")
1061 results["pass"] = "secret"
1062 URLBase.post_process_parse_url_results(results)
1063 assert results.get("password") == "secret"
1064 assert "pass" not in results
1065
1066 # URL_TOKEN_ALIASES: canonical 'password' wins when already set to a
1067 # real value -- 'pass' in top-level results must not overwrite an
1068 # explicitly provided URL-path password; a WARNING is logged so the
1069 # operator knows the alias was present but dropped (no values logged)
1070 results = URLBase.parse_url("http://user:[email protected]/path/")
1071 results["pass"] = "shouldnotwin"
1072 with mock.patch("apprise.url.logger") as mock_log:
1073 URLBase.post_process_parse_url_results(results)
1074 mock_log.warning.assert_called_once()
1075 call_args = mock_log.warning.call_args[0]
1076 # alias and canonical key names appear; actual values must not
1077 assert "pass" in call_args[1]
1078 assert "password" in call_args[2]
1079 assert results.get("password") == "realpass"
1080 assert "pass" not in results
1081
1082 # URL_TOKEN_ALIASES: qsd 'pass=' overrides the URL-path password because
1083 # query-string parameters always take the highest priority
1084 results = URLBase.parse_url(
1085 "http://user:[email protected]/path/?pass=realpass"
1086 )
1087 URLBase.post_process_parse_url_results(results)
1088 assert results.get("password") == "realpass"
1089 assert "pass" not in results
1090
1091 # URL_TOKEN_ALIASES: 'pass' in qsd is also normalized to 'password'
1092 results = URLBase.parse_url("http://[email protected]/path/?pass=qsecret")
1093 URLBase.post_process_parse_url_results(results)
1094 assert results.get("password") == "qsecret"
1095
1096 # Generic initialization
1097 base = URLBase(**{"schema": ""})
1098 assert base.request_timeout == (4.0, 4.0)
1099 assert base.request_auth is None
1100 assert base.request_url == "http:///"
1101 assert base.url().startswith("http:///")
1102
1103 base = URLBase()
1104 assert base.request_timeout == (4.0, 4.0)
1105 assert base.request_auth is None
1106 assert base.request_url == "http:///"
1107 assert base.url().startswith("http:///")
1108
1109 # URLBase.__len__ defaults to 1; subclasses that support multiple
1110 # targets override this to return the actual count.
1111 assert len(base) == 1
1112
1113 # Invalid asset type -- a non-AppriseAsset value must be silently ignored
1114 # and a debug log must tell the caller what happened. The instance must
1115 # still receive a valid default AppriseAsset so nothing downstream breaks.
1116 with mock.patch("apprise.url.logger") as mock_log:
1117 base = URLBase(asset="not-an-asset")
1118 mock_log.debug.assert_called_once()
1119 call_args = mock_log.debug.call_args[0]
1120 # The type name appears in the message so the caller can identify it
1121 assert "str" in call_args[1]
1122
1123 assert isinstance(base.asset, AppriseAsset)
1124
1125
1126 def test_apprise_unique_id():
1127 """
1128 API: Apprise() Input Formats tests
1129
1130 """
1131
1132 # Default testing
1133 obj1 = Apprise.instantiate("json://[email protected]/path")
1134 obj2 = Apprise.instantiate("json://[email protected]/path/?arg=")
1135
1136 assert obj1.url_identifier == obj2.url_identifier
1137 assert obj1.url_id() == obj2.url_id()
1138 # Second call leverages lazy reference (so it's much faster
1139 assert obj1.url_id() == obj2.url_id()
1140 # Disable Lazy Setting
1141 assert obj1.url_id(lazy=False) == obj2.url_id(lazy=False)
1142
1143 # A variation such as providing a password or altering the path makes the
1144 # url_id() different:
1145 obj2 = Apprise.instantiate("json://[email protected]/path2/?arg=") # path
1146 assert obj1.url_id() != obj2.url_id()
1147 obj2 = Apprise.instantiate(
1148 "jsons://[email protected]/path/?arg="
1149 ) # secure flag
1150 assert obj1.url_id() != obj2.url_id()
1151 obj2 = Apprise.instantiate("json://[email protected]/path/?arg=") # user
1152 assert obj1.url_id() != obj2.url_id()
1153 obj2 = Apprise.instantiate("json://[email protected]:8080/path/?arg=") # port
1154 assert obj1.url_id() != obj2.url_id()
1155 obj2 = Apprise.instantiate(
1156 "json://user:[email protected]/path/?arg="
1157 ) # password
1158 assert obj1.url_id() != obj2.url_id()
1159
1160 # Leverage salt setting
1161 asset = AppriseAsset(storage_salt="abcd")
1162
1163 obj2 = Apprise.instantiate("json://[email protected]/path/", asset=asset)
1164 assert obj1.url_id(lazy=False) != obj2.url_id(lazy=False)
1165
1166 asset = AppriseAsset(storage_salt=b"abcd")
1167 # same salt value produces a match again
1168 obj1 = Apprise.instantiate("json://[email protected]/path/", asset=asset)
1169 assert obj1.url_id() == obj2.url_id()
1170
1171 # We'll add a good notification to our list
1172 class TesNoURLID(NotifyBase):
1173 """This class is just sets a use case where we don't return a
1174 url_identifier."""
1175
1176 # we'll use this as a key to make our service easier to find
1177 # in the next part of the testing
1178 service_name = "nourl"
1179
1180 _url_identifier = False
1181
1182 def send(self, **kwargs):
1183 # Pretend everything is okay (so we don't break other tests)
1184 return True
1185
1186 @staticmethod
1187 def parse_url(url):
1188 return NotifyBase.parse_url(url, verify_host=False)
1189
1190 @property
1191 def url_identifier(self):
1192 """No URL Identifier."""
1193 return self._url_identifier
1194
1195 N_MGR["nourl"] = TesNoURLID
1196
1197 # setting URL Identifier to False disables the generator
1198 url = "nourl://"
1199 obj = Apprise.instantiate(url)
1200 # No generation takes place
1201 assert obj.url_id() is None
1202
1203 #
1204 # Dictionary Testing
1205 #
1206 obj._url_identifier = {
1207 "abc": "123",
1208 "def": b"\0",
1209 "hij": 42,
1210 "klm": object,
1211 }
1212 # call uses cached value (from above)
1213 assert obj.url_id() is None
1214 # Tests dictionary key generation
1215 assert obj.url_id(lazy=False) is not None
1216
1217 # List/Set/Tuple Testing
1218 #
1219 obj1 = Apprise.instantiate(url)
1220 obj1._url_identifier = ["123", b"\0", 42, object]
1221 # Tests dictionary key generation
1222 assert obj1.url_id() is not None
1223
1224 obj2 = Apprise.instantiate(url)
1225 obj2._url_identifier = ("123", b"\0", 42, object)
1226 assert obj2.url_id() is not None
1227 assert obj1.url_id() == obj2.url_id()
1228
1229 obj3 = Apprise.instantiate(url)
1230 obj3._url_identifier = {"123", b"\0", 42, object}
1231 assert obj3.url_id() is not None
1232
1233 obj = Apprise.instantiate(url)
1234 obj._url_identifier = b"test"
1235 assert obj.url_id() is not None
1236
1237 obj = Apprise.instantiate(url)
1238 obj._url_identifier = "test"
1239 assert obj.url_id() is not None
1240
1241 # Testing Garbage
1242 for x in (31, object, 43.1):
1243 obj = Apprise.instantiate(url)
1244 obj._url_identifier = x
1245 assert obj.url_id() is not None
1246
1247
1248 def test_apprise_notify_formats():
1249 """
1250 API: Apprise() Input Formats tests
1251
1252 """
1253 # Need to set async_mode=False to call notify() instead of async_notify().
1254 asset = AppriseAsset(async_mode=False)
1255
1256 a = Apprise(asset=asset)
1257
1258 # no items
1259 assert len(a) == 0
1260
1261 class TextNotification(NotifyBase):
1262 # set our default notification format
1263 notify_format = NotifyFormat.TEXT
1264
1265 def __init__(self, **kwargs):
1266 super().__init__(**kwargs)
1267
1268 def notify(self, **kwargs):
1269 # Pretend everything is okay
1270 return True
1271
1272 class HtmlNotification(NotifyBase):
1273 # set our default notification format
1274 notify_format = NotifyFormat.HTML
1275
1276 def __init__(self, **kwargs):
1277 super().__init__(**kwargs)
1278
1279 def notify(self, **kwargs):
1280 # Pretend everything is okay
1281 return True
1282
1283 class MarkDownNotification(NotifyBase):
1284 # set our default notification format
1285 notify_format = NotifyFormat.MARKDOWN
1286
1287 def __init__(self, **kwargs):
1288 super().__init__(**kwargs)
1289
1290 def notify(self, **kwargs):
1291 # Pretend everything is okay
1292 return True
1293
1294 # Store our notifications into our schema map
1295 N_MGR["text"] = TextNotification
1296 N_MGR["html"] = HtmlNotification
1297 N_MGR["markdown"] = MarkDownNotification
1298
1299 # Test Markdown; the above calls the markdown because our good://
1300 # defined plugin above was defined to default to HTML which triggers
1301 # a markdown to take place if the body_format specified on the notify
1302 # call
1303 assert a.add("html://localhost") is True
1304 assert a.add("html://another.server") is True
1305 assert a.add("html://and.another") is True
1306 assert a.add("text://localhost") is True
1307 assert a.add("text://another.server") is True
1308 assert a.add("text://and.another") is True
1309 assert a.add("markdown://localhost") is True
1310 assert a.add("markdown://another.server") is True
1311 assert a.add("markdown://and.another") is True
1312
1313 assert len(a) == 9
1314
1315 assert (
1316 bool(
1317 a.notify(
1318 title="markdown",
1319 body="## Testing Markdown",
1320 body_format=NotifyFormat.MARKDOWN,
1321 )
1322 )
1323 is True
1324 )
1325
1326 assert (
1327 bool(
1328 a.notify(
1329 title="text",
1330 body="Testing Text",
1331 body_format=NotifyFormat.TEXT,
1332 )
1333 )
1334 is True
1335 )
1336
1337 assert (
1338 bool(
1339 a.notify(
1340 title="html", body="<b>HTML</b>", body_format=NotifyFormat.HTML
1341 )
1342 )
1343 is True
1344 )
1345
1346
1347 def test_apprise_multi_format_resolution(caplog):
1348 """
1349 API: multi-format notify_format resolution
1350
1351 """
1352 # Older pytest versions may leave logging disabled after set_level().
1353 # Override that state only when needed, then restore it below.
1354 caplog.set_level(logging.DEBUG, logger=LOGGER_NAME)
1355 manual_override = not logging.getLogger(LOGGER_NAME).isEnabledFor(
1356 logging.DEBUG
1357 )
1358 if manual_override:
1359 logging.disable(logging.NOTSET)
1360
1361 try:
1362
1363 class SingleFormatNotification(NotifyBase):
1364 """Test plugin that resolves to one fixed format."""
1365
1366 # Single-format plugins always use their declared format.
1367 notify_format = NotifyFormat.HTML
1368
1369 def send(self, body, title="", notify_type=None, **kwargs):
1370 """Accept the prepared body without doing network work."""
1371 return True
1372
1373 class MultiFormatNotification(NotifyBase):
1374 """Test plugin that can render either HTML or Markdown."""
1375
1376 # Declares more than one supported format, index[0] is default
1377 notify_format = (NotifyFormat.HTML, NotifyFormat.MARKDOWN)
1378
1379 received = []
1380
1381 def send(self, body, title="", notify_type=None, **kwargs):
1382 """Record fallback sends with no format-specific hook."""
1383 self.received.append(("send", body))
1384 return True
1385
1386 def send_markdown(
1387 self, body, title="", notify_type=None, **kwargs
1388 ):
1389 """Record Markdown-specific dispatch."""
1390 self.received.append(("send_markdown", body))
1391 return True
1392
1393 # Single-format plugin: _formats()/resolve_format() resolve to the
1394 # one declared format no matter what is passed in.
1395 single = SingleFormatNotification(host="localhost")
1396 assert single._formats() == (NotifyFormat.HTML,)
1397 assert single.resolve_format(None) == NotifyFormat.HTML
1398 assert single.resolve_format(NotifyFormat.TEXT) == NotifyFormat.HTML
1399 assert (
1400 single.resolve_format(NotifyFormat.MARKDOWN) == NotifyFormat.HTML
1401 )
1402
1403 # A plain string is accepted
1404 assert single.resolve_format("text") == NotifyFormat.HTML
1405
1406 # Multi-format plugin, no override, no matching input: default wins
1407 multi = MultiFormatNotification(host="localhost")
1408 assert multi._formats() == (NotifyFormat.HTML, NotifyFormat.MARKDOWN)
1409 assert multi.resolve_format(None) == NotifyFormat.HTML
1410 assert multi.resolve_format(NotifyFormat.TEXT) == NotifyFormat.HTML
1411
1412 # Multi-format plugin, no override, input aligns to a declared format
1413 assert (
1414 multi.resolve_format(NotifyFormat.MARKDOWN)
1415 == NotifyFormat.MARKDOWN
1416 )
1417
1418 # A plain string is supported
1419 resolved = multi.resolve_format("markdown")
1420 assert resolved == NotifyFormat.MARKDOWN
1421 assert isinstance(resolved, NotifyFormat)
1422
1423 # Multi-format plugin, explicit ?format= override in the declared set
1424 multi_override = MultiFormatNotification(
1425 host="localhost", format="markdown"
1426 )
1427 assert multi_override._format_override == NotifyFormat.MARKDOWN
1428 assert multi_override.resolve_format(NotifyFormat.HTML) == (
1429 NotifyFormat.MARKDOWN
1430 )
1431
1432 # Multi-format plugin, ?format= override NOT in the declared set falls
1433 # back through to input alignment, then default, with a debug message.
1434 multi_bad_override = MultiFormatNotification(
1435 host="localhost", format="text"
1436 )
1437 assert multi_bad_override._format_override == NotifyFormat.TEXT
1438 caplog.clear()
1439 assert multi_bad_override.resolve_format(NotifyFormat.MARKDOWN) == (
1440 NotifyFormat.MARKDOWN
1441 )
1442 assert "does not support format" in caplog.text
1443 assert "DEBUG" in caplog.text
1444
1445 # No declared source format: same fallback, but silent -- matches
1446 # the historical no-noise conversion behavior.
1447 caplog.clear()
1448 assert multi_bad_override.resolve_format(None) == NotifyFormat.HTML
1449 assert "does not support format" not in caplog.text
1450
1451 # send_{type}() dispatch: send_markdown() defined, used when resolved
1452 multi.received.clear()
1453 assert (
1454 multi.notify(body="# hi", body_format=NotifyFormat.MARKDOWN)
1455 is True
1456 )
1457 assert multi.received == [("send_markdown", "# hi")]
1458
1459 # send_{type}() dispatch: no send_html() defined, falls back to send()
1460 multi.received.clear()
1461 assert multi.notify(body="hi", body_format=NotifyFormat.HTML) is True
1462 assert multi.received == [("send", "hi")]
1463 finally:
1464 if manual_override:
1465 logging.disable(logging.CRITICAL)
1466
1467
1468 def test_apprise_multi_format_conversion_cache():
1469 """
1470 API: multi-format resolution reuses one converted body per resolved
1471 target, same as the existing single-format conversion cache.
1472
1473 """
1474 asset = AppriseAsset(async_mode=False)
1475 a = Apprise(asset=asset)
1476
1477 class HtmlOnlyNotification(NotifyBase):
1478 """Test plugin that resolves to HTML."""
1479
1480 notify_format = NotifyFormat.HTML
1481
1482 def send(self, body, title="", notify_type=None, **kwargs):
1483 """Accept the prepared body without doing network work."""
1484 return True
1485
1486 class MultiFormatNotification(NotifyBase):
1487 """Test plugin that also resolves to HTML by default."""
1488
1489 # Resolves to HTML by default, same target as HtmlOnlyNotification
1490 notify_format = (NotifyFormat.HTML, NotifyFormat.MARKDOWN)
1491
1492 def send(self, body, title="", notify_type=None, **kwargs):
1493 """Accept the prepared body without doing network work."""
1494 return True
1495
1496 N_MGR["htmlonly"] = HtmlOnlyNotification
1497 N_MGR["multi"] = MultiFormatNotification
1498
1499 assert a.add("htmlonly://localhost") is True
1500 assert a.add("multi://localhost") is True
1501 assert len(a) == 2
1502
1503 with mock.patch(
1504 "apprise.apprise.convert_between",
1505 side_effect=lambda *a, **k: "converted",
1506 ) as mock_convert:
1507 assert (
1508 bool(a.notify(body="hello", body_format=NotifyFormat.TEXT)) is True
1509 )
1510 # Both services resolve to HTML; the body should only be converted
1511 # once and reused, exactly like the single-format cache today.
1512 assert mock_convert.call_count == 1
1513
1514
1515 def test_apprise_payload_max_size_enforced_before_conversion():
1516 """API: Apply the payload cap before conversion and title merging."""
1517 asset = AppriseAsset(async_mode=False, payload_max_size=20)
1518 a = Apprise(asset=asset)
1519
1520 class TitlelessNotification(NotifyBase):
1521 """Test plugin with no native title field."""
1522
1523 title_maxlen = 0
1524
1525 def __init__(self, *args, **kwargs):
1526 super().__init__(**kwargs)
1527 self.sent = []
1528
1529 def send(self, body, title="", notify_type=None, **kwargs):
1530 """Record what would have gone out over the wire."""
1531 self.sent.append((title, body))
1532 return True
1533
1534 N_MGR["titleless"] = TitlelessNotification
1535
1536 obj = TitlelessNotification(host="localhost", asset=asset)
1537 assert a.add(obj) is True
1538
1539 title = "T" * 100
1540 body = "B" * 1000
1541
1542 with mock.patch(
1543 "apprise.apprise.convert_between",
1544 side_effect=lambda src, dst, content: content,
1545 ) as mock_convert:
1546 assert bool(a.notify(title=title, body=body)) is True
1547
1548 # Conversion only receives content that already fits the input cap.
1549 for call in mock_convert.call_args_list:
1550 assert len(call.kwargs["content"]) <= 20
1551
1552 # Title markup may add a few characters after the input cap is applied.
1553 assert len(obj.sent) == 1
1554 delivered_title, delivered_body = obj.sent[0]
1555 assert delivered_title == ""
1556 assert len(delivered_body) < 30
1557
1558
1559 def test_apprise_payload_max_size_not_reapplied_after_conversion():
1560 """API: Cap source text once without truncating converted markup."""
1561
1562 class HTMLNotification(NotifyBase):
1563 """Test plugin whose declared format is HTML."""
1564
1565 notify_format = NotifyFormat.HTML
1566 title_maxlen = 0
1567
1568 def __init__(self, *args, **kwargs):
1569 super().__init__(**kwargs)
1570 self.sent = []
1571
1572 def send(self, body, title="", notify_type=None, **kwargs):
1573 """Record what would have gone out over the wire."""
1574 self.sent.append((title, body))
1575 return True
1576
1577 N_MGR["htmltest"] = HTMLNotification
1578
1579 # The five-character source fits, although its HTML conversion is longer.
1580 asset = AppriseAsset(async_mode=False, payload_max_size=5)
1581 a = Apprise(asset=asset)
1582 obj = HTMLNotification(host="localhost", asset=asset)
1583 assert a.add(obj) is True
1584
1585 result = a.notify(
1586 title="", body="**x**", body_format=NotifyFormat.MARKDOWN
1587 )
1588 assert bool(result) is True
1589
1590 assert len(obj.sent) == 1
1591 _, delivered_body = obj.sent[0]
1592 assert delivered_body == "<p><strong>x</strong></p>"
1593
1594 # Direct plugin calls still enforce the cap because no earlier step did.
1595 obj.sent.clear()
1596 assert obj.notify(title="", body="B" * 100) is True
1597 assert len(obj.sent) == 1
1598 _, direct_body = obj.sent[0]
1599 assert len(direct_body) <= 5
1600
1601 # The old public keyword is ignored, so direct callers cannot use it to
1602 # bypass the cap.
1603 obj.sent.clear()
1604 assert obj.notify(title="", body="B" * 100, payload_precapped=True) is True
1605 assert len(obj.sent) == 1
1606 _, guessed_kwarg_body = obj.sent[0]
1607 assert len(guessed_kwarg_body) <= 5
1608
1609
1610 def test_apprise_payload_max_size_uses_service_asset_limit():
1611 """API: Apply each service's asset cap before conversion.
1612
1613 The service limit still applies when the top-level asset has no cap.
1614 """
1615
1616 class TitlelessNotification(NotifyBase):
1617 """Test plugin with no native title field."""
1618
1619 title_maxlen = 0
1620
1621 def __init__(self, *args, **kwargs):
1622 super().__init__(**kwargs)
1623 self.sent = []
1624
1625 def send(self, body, title="", notify_type=None, **kwargs):
1626 """Record what would have gone out over the wire."""
1627 self.sent.append((title, body))
1628 return True
1629
1630 N_MGR["titleless"] = TitlelessNotification
1631
1632 # The top-level asset used by Apprise() itself has the cap disabled.
1633 global_asset = AppriseAsset(async_mode=False, payload_max_size=0)
1634 a = Apprise(asset=global_asset)
1635
1636 # Give this service a separate asset with its own cap.
1637 service_asset = AppriseAsset(async_mode=False, payload_max_size=20)
1638 obj = TitlelessNotification(host="localhost", asset=service_asset)
1639 assert a.add(obj) is True
1640
1641 title = "T" * 100
1642 body = "B" * 1000
1643
1644 with mock.patch(
1645 "apprise.apprise.convert_between",
1646 side_effect=lambda src, dst, content: content,
1647 ) as mock_convert:
1648 assert bool(a.notify(title=title, body=body)) is True
1649
1650 # Conversion receives content trimmed to the service's own cap.
1651 for call in mock_convert.call_args_list:
1652 assert len(call.kwargs["content"]) <= 20
1653
1654 assert len(obj.sent) == 1
1655 delivered_title, delivered_body = obj.sent[0]
1656 assert len(delivered_title) + len(delivered_body) < 30
1657
1658
1659 def test_apprise_payload_max_size_cache_key_includes_buffer_settings():
1660 """API: Services with different payload settings use separate caches."""
1661
1662 class TitlelessNotification(NotifyBase):
1663 """Test plugin with no native title field."""
1664
1665 title_maxlen = 0
1666
1667 def __init__(self, *args, **kwargs):
1668 super().__init__(**kwargs)
1669 self.sent = []
1670
1671 def send(self, body, title="", notify_type=None, **kwargs):
1672 """Record what would have gone out over the wire."""
1673 self.sent.append((title, body))
1674 return True
1675
1676 N_MGR["titleless"] = TitlelessNotification
1677
1678 global_asset = AppriseAsset(async_mode=False)
1679 a = Apprise(asset=global_asset)
1680
1681 # The second service disables the short-side rule.
1682 asset1 = AppriseAsset(async_mode=False, payload_max_size=35)
1683 obj1 = TitlelessNotification(host="host1", asset=asset1)
1684 assert a.add(obj1) is True
1685
1686 asset2 = AppriseAsset(
1687 async_mode=False, payload_max_size=35, payload_buffer_threshold=0
1688 )
1689 obj2 = TitlelessNotification(host="host2", asset=asset2)
1690 assert a.add(obj2) is True
1691
1692 title = "T" * 9
1693 body = "B" * 33
1694
1695 with mock.patch(
1696 "apprise.apprise.convert_between",
1697 side_effect=lambda src, dst, content: content,
1698 ):
1699 assert bool(a.notify(title=title, body=body)) is True
1700
1701 assert len(obj1.sent) == 1
1702 assert len(obj2.sent) == 1
1703
1704 # With no title field, the different allocations appear in each body.
1705 delivered1 = obj1.sent[0][1]
1706 delivered2 = obj2.sent[0][1]
1707 assert delivered1 != delivered2
1708
1709
1710 def test_apprise_payload_trim_warning(caplog):
1711 """API: Log a warning only when a service cap trims the input."""
1712 # Older pytest versions may leave logging disabled after set_level().
1713 # Override that state only when needed, then restore it below.
1714 caplog.set_level(logging.WARNING, logger=LOGGER_NAME)
1715 manual_override = not logging.getLogger(LOGGER_NAME).isEnabledFor(
1716 logging.WARNING
1717 )
1718 if manual_override:
1719 logging.disable(logging.NOTSET)
1720
1721 try:
1722
1723 class PlainNotification(NotifyBase):
1724 title_maxlen = 10
1725
1726 def send(self, body, title="", notify_type=None, **kwargs):
1727 return True
1728
1729 N_MGR["plain"] = PlainNotification
1730
1731 asset = AppriseAsset(async_mode=False, payload_max_size=5)
1732 a = Apprise(asset=asset)
1733 obj = PlainNotification(host="localhost", asset=asset)
1734 assert a.add(obj) is True
1735
1736 caplog.clear()
1737 assert bool(a.notify(title="", body="x" * 100)) is True
1738 assert "payload_max_size" in caplog.text
1739
1740 # A body that already fits the cap logs no warning at all.
1741 caplog.clear()
1742 assert bool(a.notify(title="", body="x")) is True
1743 assert "payload_max_size" not in caplog.text
1744 finally:
1745 if manual_override:
1746 logging.disable(logging.CRITICAL)
1747
1748
1749 def test_apprise_multi_format_details():
1750 """
1751 API: Apprise() Details reflect a plugin's real supported formats
1752
1753 """
1754
1755 class SingleFormatNotification(NotifyBase):
1756 """Test plugin whose public details should stay broad."""
1757
1758 service_name = "Single Format Testing"
1759 protocol = "singlefmt"
1760 notify_format = NotifyFormat.HTML
1761
1762 templates = ("{schema}://{host}",)
1763
1764 def send(self, body, title="", notify_type=None, **kwargs):
1765 """Accept the prepared body without doing network work."""
1766 return True
1767
1768 class MultiFormatNotification(NotifyBase):
1769 """Test plugin whose public details expose supported formats."""
1770
1771 service_name = "Multi Format Testing"
1772 protocol = "multifmtdetails"
1773 # Declaration order matters: markdown is the default (index[0])
1774 notify_format = (NotifyFormat.MARKDOWN, NotifyFormat.HTML)
1775
1776 templates = ("{schema}://{host}",)
1777
1778 def send(self, body, title="", notify_type=None, **kwargs):
1779 """Accept the prepared body without doing network work."""
1780 return True
1781
1782 # values/default remain broad for every plugin so consumers that only
1783 # know those fields keep seeing the standard Apprise ?format= choices.
1784 # The additive `supported` field carries the narrower native subset.
1785 single_details = plugins.details(SingleFormatNotification)
1786 assert single_details["args"]["format"]["values"] == NOTIFY_FORMATS
1787 assert single_details["args"]["format"]["default"] == "html"
1788 # `supported` names the subset this plugin actually renders natively:
1789 # one entry for a single-format plugin.
1790 assert single_details["args"]["format"]["supported"] == ["html"]
1791
1792 multi_details = plugins.details(MultiFormatNotification)
1793 assert multi_details["args"]["format"]["values"] == NOTIFY_FORMATS
1794 assert multi_details["args"]["format"]["default"] == "markdown"
1795 # Declaration order preserved, not alphabetically re-sorted
1796 assert multi_details["args"]["format"]["supported"] == [
1797 "markdown",
1798 "html",
1799 ]
1800
1801
1802 def test_apprise_asset(tmpdir):
1803 """
1804 API: AppriseAsset() object
1805
1806 """
1807 a = AppriseAsset(theme="light")
1808 # Default theme
1809 assert a.theme == "light"
1810
1811 # Invalid kw handling
1812 with pytest.raises(AttributeError):
1813 AppriseAsset(invalid_kw="value")
1814
1815 a = AppriseAsset(
1816 theme="dark",
1817 image_path_mask="/{THEME}/{TYPE}-{XY}{EXTENSION}",
1818 image_url_mask="http://localhost/{THEME}/{TYPE}-{XY}{EXTENSION}",
1819 )
1820
1821 a.default_html_color = "#abcabc"
1822
1823 assert a.color("invalid", tuple) == (171, 202, 188)
1824 assert a.color(NotifyType.INFO, tuple) == (58, 163, 227)
1825
1826 assert a.color("invalid", int) == 11258556
1827 assert a.color(NotifyType.INFO, int) == 3843043
1828
1829 assert a.color("invalid", None) == "#abcabc"
1830 assert a.color(NotifyType.INFO, None) == "#3AA3E3"
1831 # None is the default
1832 assert a.color(NotifyType.INFO) == "#3AA3E3"
1833
1834 # Invalid Type
1835 with pytest.raises(ValueError):
1836 # The exception we expect since dict is not supported
1837 a.color(NotifyType.INFO, dict)
1838
1839 # Test our ASCII mappings
1840 assert a.ascii("invalid") == "[?]"
1841 assert a.ascii(NotifyType.INFO) == "[i]"
1842 assert a.ascii(NotifyType.SUCCESS) == "[+]"
1843 assert a.ascii(NotifyType.WARNING) == "[~]"
1844 assert a.ascii(NotifyType.FAILURE) == "[!]"
1845
1846 # Invalid Type
1847 with pytest.raises(ValueError):
1848 # The exception we expect since dict is not supported
1849 a.color(NotifyType.INFO, dict)
1850
1851 assert (
1852 a.image_url(NotifyType.INFO, NotifyImageSize.XY_128)
1853 == "http://localhost/dark/info-128x128.png"
1854 )
1855
1856 # Default image size
1857 assert (
1858 a.image_url(NotifyType.INFO)
1859 == "http://localhost/dark/info-256x256.png"
1860 )
1861
1862 assert (
1863 a.image_path(NotifyType.INFO, NotifyImageSize.XY_256, must_exist=False)
1864 == "/dark/info-256x256.png"
1865 )
1866
1867 # This path doesn't exist so image_raw will fail (since we just
1868 # randompyl picked it for testing)
1869 assert a.image_raw(NotifyType.INFO, NotifyImageSize.XY_256) is None
1870
1871 assert (
1872 a.image_path(NotifyType.INFO, NotifyImageSize.XY_256, must_exist=True)
1873 is None
1874 )
1875
1876 # Create a new object (with our default settings)
1877 a = AppriseAsset()
1878
1879 # Our default configuration can access our file
1880 assert (
1881 a.image_path(NotifyType.INFO, NotifyImageSize.XY_256, must_exist=True)
1882 is not None
1883 )
1884
1885 assert a.image_raw(NotifyType.INFO, NotifyImageSize.XY_256) is not None
1886
1887 # Create a temporary directory
1888 sub = tmpdir.mkdir("great.theme")
1889
1890 # Write a file
1891 sub.join(
1892 f"{NotifyType.INFO.value}-{NotifyImageSize.XY_256.value}.png"
1893 ).write("the content doesn't matter for testing.")
1894
1895 # Create an asset that will reference our file we just created
1896 a = AppriseAsset(
1897 theme="great.theme",
1898 image_path_mask=(
1899 f"{dirname(sub.strpath)}/{{THEME}}/{{TYPE}}-{{XY}}.png"
1900 ),
1901 )
1902
1903 # We'll be able to read file we just created
1904 assert a.image_raw(NotifyType.INFO, NotifyImageSize.XY_256) is not None
1905
1906 # We can retrieve the filename at this point even with must_exist set
1907 # to True
1908 assert (
1909 a.image_path(NotifyType.INFO, NotifyImageSize.XY_256, must_exist=True)
1910 is not None
1911 )
1912
1913 # Test case where we can't access the image file
1914 with mock.patch("builtins.open", side_effect=OSError()):
1915 assert a.image_raw(NotifyType.INFO, NotifyImageSize.XY_256) is None
1916
1917 # Our content is retrivable again
1918 assert a.image_raw(NotifyType.INFO, NotifyImageSize.XY_256) is not None
1919
1920 # Disable all image references
1921 a = AppriseAsset(image_path_mask=False, image_url_mask=False)
1922
1923 # We always return none in these calls now
1924 assert a.image_raw(NotifyType.INFO, NotifyImageSize.XY_256) is None
1925 assert a.image_url(NotifyType.INFO, NotifyImageSize.XY_256) is None
1926 assert (
1927 a.image_path(NotifyType.INFO, NotifyImageSize.XY_256, must_exist=False)
1928 is None
1929 )
1930 assert (
1931 a.image_path(NotifyType.INFO, NotifyImageSize.XY_256, must_exist=True)
1932 is None
1933 )
1934
1935 # Test our default extension out
1936 a = AppriseAsset(
1937 image_path_mask="/{THEME}/{TYPE}-{XY}{EXTENSION}",
1938 image_url_mask="http://localhost/{THEME}/{TYPE}-{XY}{EXTENSION}",
1939 default_extension=".jpeg",
1940 )
1941 assert (
1942 a.image_path(NotifyType.INFO, NotifyImageSize.XY_256, must_exist=False)
1943 == "/default/info-256x256.jpeg"
1944 )
1945
1946 assert (
1947 a.image_url(NotifyType.INFO, NotifyImageSize.XY_256)
1948 == "http://localhost/default/info-256x256.jpeg"
1949 )
1950
1951 # extension support
1952 assert (
1953 a.image_path(
1954 NotifyType.INFO,
1955 NotifyImageSize.XY_128,
1956 must_exist=False,
1957 extension=".ico",
1958 )
1959 == "/default/info-128x128.ico"
1960 )
1961
1962 assert (
1963 a.image_url(NotifyType.INFO, NotifyImageSize.XY_256, extension=".test")
1964 == "http://localhost/default/info-256x256.test"
1965 )
1966
1967 a = AppriseAsset(plugin_paths=("/tmp",))
1968 assert a.plugin_paths == ("/tmp",)
1969
1970
1971 def test_apprise_disabled_plugins():
1972 """
1973 API: Apprise() Disabled Plugin States
1974
1975 """
1976 # Ensure there are no other drives loaded
1977 N_MGR.unload_modules(disable_native=True)
1978 assert len(N_MGR) == 0
1979
1980 class TestDisabled01Notification(NotifyBase):
1981 """This class is used to test a pre-disabled state."""
1982
1983 # Just flat out disable our service
1984 enabled = False
1985
1986 # we'll use this as a key to make our service easier to find
1987 # in the next part of the testing
1988 service_name = "na01"
1989
1990 def notify(self, **kwargs):
1991 # Pretend everything is okay (so we don't break other tests)
1992 return True
1993
1994 N_MGR["na01"] = TestDisabled01Notification
1995
1996 class TestDisabled02Notification(NotifyBase):
1997 """This class is used to test a post-disabled state."""
1998
1999 # we'll use this as a key to make our service easier to find
2000 # in the next part of the testing
2001 service_name = "na02"
2002
2003 def __init__(self, *args, **kwargs):
2004 super().__init__(**kwargs)
2005
2006 # enable state changes **AFTER** we initialize
2007 self.enabled = False
2008
2009 def notify(self, **kwargs):
2010 # Pretend everything is okay (so we don't break other tests)
2011 return True
2012
2013 N_MGR["na02"] = TestDisabled02Notification
2014
2015 # Create our Apprise instance
2016 a = Apprise()
2017
2018 result = a.details(lang="ca-en", show_disabled=True)
2019 assert isinstance(result, dict)
2020 assert "schemas" in result
2021 assert len(result["schemas"]) == 2
2022
2023 # our na01 is disabled right from the get-go
2024 entry = next(
2025 (x for x in result["schemas"] if x["service_name"] == "na01"), None
2026 )
2027 assert entry is not None
2028 assert entry["enabled"] is False
2029
2030 plugin = a.instantiate("na01://localhost")
2031 # Object is just flat out disabled... nothing is instatiated
2032 assert plugin is None
2033
2034 # our na02 isn't however until it's initialized; as a result
2035 # it get's returned in our result set
2036 entry = next(
2037 (x for x in result["schemas"] if x["service_name"] == "na02"), None
2038 )
2039 assert entry is not None
2040 assert entry["enabled"] is True
2041
2042 plugin = a.instantiate("na02://localhost")
2043 # Object isn't disabled until the __init__() call. But this is still
2044 # enough to not instantiate the object:
2045 assert plugin is None
2046
2047 # If we choose to filter our disabled, we can't unfortunately filter those
2048 # that go disabled after instantiation, but we do filter out any that are
2049 # already known to not be enabled:
2050 result = a.details(lang="ca-en", show_disabled=False)
2051 assert isinstance(result, dict)
2052 assert "schemas" in result
2053 assert len(result["schemas"]) == 1
2054
2055 # We'll add a good notification to our list
2056 class TesEnabled01Notification(NotifyBase):
2057 """This class is just a simple enabled one."""
2058
2059 # we'll use this as a key to make our service easier to find
2060 # in the next part of the testing
2061 service_name = "good"
2062
2063 def send(self, **kwargs):
2064 # Pretend everything is okay (so we don't break other tests)
2065 return True
2066
2067 N_MGR["good"] = TesEnabled01Notification
2068
2069 # The last thing we'll simulate is a case where the plugin is just
2070 # disabled at a later time long into it's life. this is just to allow
2071 # administrators to stop the flow of their notifications for their own
2072 # given reasons.
2073 plugin = a.instantiate("good://localhost")
2074 assert isinstance(plugin, NotifyBase)
2075
2076 # we'll toggle our state
2077 plugin.enabled = False
2078
2079 # As a result, we can now no longer send a notification:
2080 assert bool(plugin.notify("My Message")) is False
2081
2082 # As just a proof of how you can toggle the state back:
2083 plugin.enabled = True
2084
2085 # our notifications will go okay now
2086 assert bool(plugin.notify("My Message")) is True
2087
2088 # Restore our modules
2089 N_MGR.unload_modules()
2090
2091
2092 def test_apprise_details():
2093 """
2094 API: Apprise() Details
2095
2096 """
2097
2098 # This is a made up class that is just used to verify
2099 class TestDetailNotification(NotifyBase):
2100 """This class is used to test various configurations supported."""
2101
2102 # Minimum requirements for a plugin to produce details
2103 service_name = "Detail Testing"
2104
2105 # The default simple (insecure) protocol (used by NotifyMail)
2106 protocol = "details"
2107
2108 # Set test_bool flag
2109 always_true = True
2110 always_false = False
2111
2112 # Define object templates
2113 templates = (
2114 "{schema}://{host}",
2115 "{schema}://{host}:{port}",
2116 "{schema}://{user}@{host}:{port}",
2117 "{schema}://{user}:{pass}@{host}:{port}",
2118 )
2119
2120 # Define our tokens; these are the minimum tokens required required to
2121 # be passed into this function (as arguments). The syntax appends any
2122 # previously defined in the base package and builds onto them
2123 template_tokens = dict(
2124 NotifyBase.template_tokens,
2125 **{
2126 "notype": {
2127 # name is a minimum requirement
2128 "name": _("no type"),
2129 },
2130 "regex_test01": {
2131 "name": _("RegexTest"),
2132 "type": "string",
2133 "regex": r"^[A-Z0-9]$",
2134 },
2135 "regex_test02": {
2136 "name": _("RegexTest"),
2137 # Support regex options too
2138 "regex": (r"^[A-Z0-9]$", "i"),
2139 },
2140 "regex_test03": {
2141 "name": _("RegexTest"),
2142 # Support regex option without a second option
2143 "regex": r"^[A-Z0-9]$",
2144 },
2145 "regex_test04": {
2146 # this entry would just end up getting removed
2147 "regex": None,
2148 },
2149 # List without delimiters (causes defaults to kick in)
2150 "mylistA": {
2151 "name": "fruit",
2152 "type": "list:string",
2153 },
2154 # A list with a delimiter list
2155 "mylistB": {
2156 "name": "softdrinks",
2157 "type": "list:string",
2158 "delim": ["|", "-"],
2159 },
2160 },
2161 )
2162
2163 template_args = dict(
2164 NotifyBase.template_args,
2165 **{
2166 # Test _exist_if logic
2167 "test_exists_if_01": {
2168 "name": "Always False",
2169 "type": "bool",
2170 # Provide a default
2171 "default": False,
2172 # Base the existance of this key/value entry on the lookup
2173 # of this class value at runtime. Hence:
2174 # if not NotifyObject.always_false
2175 # del this_entry
2176 #
2177 "_exists_if": "always_false",
2178 },
2179 # Test _exist_if logic
2180 "test_exists_if_02": {
2181 "name": "Always True",
2182 "type": "bool",
2183 # Provide a default
2184 "default": False,
2185 # Base the existance of this key/value entry on the lookup
2186 # of this class value at runtime. Hence:
2187 # if not NotifyObject.always_true
2188 # del this_entry
2189 #
2190 "_exists_if": "always_true",
2191 },
2192 # alias_of testing
2193 "test_alias_of": {"alias_of": "mylistB", "delim": ("-", " ")},
2194 },
2195 )
2196
2197 def send(self, **kwargs):
2198 # Pretend everything is okay (so we don't break other tests)
2199 return True
2200
2201 # Store our good detail notification in our schema map
2202 N_MGR["details"] = TestDetailNotification
2203
2204 # This is a made up class that is just used to verify
2205 class TestReq01Notification(NotifyBase):
2206 """This class is used to test various requirement configurations."""
2207
2208 # Set some requirements
2209 requirements: ClassVar[RequirementsSpec] = {
2210 "packages_required": [
2211 "cryptography <= 3.4",
2212 "ultrasync",
2213 ],
2214 "packages_recommended": "django",
2215 }
2216
2217 def send(self, **kwargs):
2218 # Pretend everything is okay (so we don't break other tests)
2219 return True
2220
2221 N_MGR["req01"] = TestReq01Notification
2222
2223 # This is a made up class that is just used to verify
2224 class TestReq02Notification(NotifyBase):
2225 """This class is used to test various requirement configurations."""
2226
2227 # Just not enabled at all
2228 enabled = False
2229
2230 # Set some requirements
2231 requirements: ClassVar[RequirementsSpec] = {
2232 # None and/or [] is implied, but jsut to show that the code won't
2233 # crash if explicitly set this way:
2234 "packages_required": None,
2235 "packages_recommended": [
2236 "cryptography <= 3.4",
2237 ],
2238 }
2239
2240 def send(self, **kwargs):
2241 # Pretend everything is okay (so we don't break other tests)
2242 return True
2243
2244 N_MGR["req02"] = TestReq02Notification
2245
2246 # This is a made up class that is just used to verify
2247 class TestReq03Notification(NotifyBase):
2248 """This class is used to test various requirement configurations."""
2249
2250 # Set some requirements
2251 requirements: ClassVar[RequirementsSpec] = {
2252 # We can over-ride the default details assigned to our plugin if
2253 # specified
2254 "details": _("some specified requirement details"),
2255 # We can set a string value as well (it does not have to be a list)
2256 "packages_recommended": "cryptography <= 3.4",
2257 }
2258
2259 def send(self, **kwargs):
2260 # Pretend everything is okay (so we don't break other tests)
2261 return True
2262
2263 N_MGR["req03"] = TestReq03Notification
2264
2265 # This is a made up class that is just used to verify
2266 class TestReq04Notification(NotifyBase):
2267 """This class is used to test a case where our requirements is fixed to
2268 a None."""
2269
2270 # This is the same as saying there are no requirements
2271 requirements = None
2272
2273 def send(self, **kwargs):
2274 # Pretend everything is okay (so we don't break other tests)
2275 return True
2276
2277 N_MGR["req04"] = TestReq04Notification
2278
2279 # This is a made up class that is just used to verify
2280 class TestReq05Notification(NotifyBase):
2281 """This class is used to test a case where only packages_recommended is
2282 identified."""
2283
2284 requirements: ClassVar[RequirementsSpec] = {
2285 # We can set a string value as well (it does not have to be a list)
2286 "packages_recommended": "cryptography <= 3.4"
2287 }
2288
2289 def send(self, **kwargs):
2290 # Pretend everything is okay (so we don't break other tests)
2291 return True
2292
2293 N_MGR["req05"] = TestReq05Notification
2294
2295 # Create our Apprise instance
2296 a = Apprise()
2297
2298 # Dictionary response
2299 result = a.details()
2300 assert isinstance(result, dict)
2301
2302 # Test different variations of our call
2303 result = a.details(lang="ca-fr")
2304 assert isinstance(result, dict)
2305 for entry in result["schemas"]:
2306 # Verify our key does not exist because we did not ask for it
2307 assert "enabled" not in entry
2308 assert "requirements" not in entry
2309
2310 result = a.details(lang="us-en", show_requirements=True)
2311 assert isinstance(result, dict)
2312 for entry in result["schemas"]:
2313 # Verify our key does not exist because we did not ask for it
2314 assert "enabled" not in entry
2315
2316 # Requirements are set for display
2317 assert "requirements" in entry
2318 assert "details" in entry["requirements"]
2319 assert "packages_required" in entry["requirements"]
2320 assert "packages_recommended" in entry["requirements"]
2321 assert isinstance(
2322 entry["requirements"]["details"], (str, LazyTranslation)
2323 )
2324 assert isinstance(entry["requirements"]["packages_required"], list)
2325 assert isinstance(entry["requirements"]["packages_recommended"], list)
2326
2327 result = a.details(lang="ca-en", show_disabled=True)
2328 assert isinstance(result, dict)
2329 for entry in result["schemas"]:
2330 # Verify that our plugin state is available to us
2331 assert "enabled" in entry
2332 assert isinstance(entry["enabled"], bool)
2333
2334 # Verify our key does not exist because we did not ask for it
2335 assert "requirements" not in entry
2336
2337 result = a.details(
2338 lang="ca-fr", show_requirements=True, show_disabled=True
2339 )
2340 assert isinstance(result, dict)
2341 for entry in result["schemas"]:
2342 # Plugin States are set for display
2343 assert "enabled" in entry
2344 assert isinstance(entry["enabled"], bool)
2345
2346 # Requirements are set for display
2347 assert "requirements" in entry
2348 assert "details" in entry["requirements"]
2349 assert "packages_required" in entry["requirements"]
2350 assert "packages_recommended" in entry["requirements"]
2351 assert isinstance(
2352 entry["requirements"]["details"], (str, LazyTranslation)
2353 )
2354 assert isinstance(entry["requirements"]["packages_required"], list)
2355 assert isinstance(entry["requirements"]["packages_recommended"], list)
2356
2357
2358 def test_apprise_details_plugin_verification():
2359 """
2360 API: Apprise() Details Plugin Verification
2361
2362 """
2363 # Prepare our object
2364 a = Apprise()
2365
2366 # Details object
2367 details = a.details()
2368
2369 # Dictionary response
2370 assert isinstance(details, dict)
2371
2372 # Details object with language defined:
2373 details = a.details(lang="en")
2374
2375 # Dictionary response
2376 assert isinstance(details, dict)
2377
2378 # Details object with unsupported language:
2379 details = a.details(lang="xx")
2380
2381 # Dictionary response
2382 assert isinstance(details, dict)
2383
2384 # Apprise version
2385 assert "version" in details
2386 assert details.get("version") == __version__
2387
2388 # Defined schemas identify each plugin
2389 assert "schemas" in details
2390 assert isinstance(details.get("schemas"), list)
2391
2392 # We have an entry per defined plugin
2393 assert "asset" in details
2394 assert isinstance(details.get("asset"), dict)
2395 assert "app_id" in details["asset"]
2396 assert "app_desc" in details["asset"]
2397 assert "default_extension" in details["asset"]
2398 assert "theme" in details["asset"]
2399 assert "image_path_mask" in details["asset"]
2400 assert "image_url_mask" in details["asset"]
2401 assert "image_url_logo" in details["asset"]
2402
2403 # Valid Type Regular Expression Checker
2404 # Case Sensitive and MUST match the following:
2405 is_valid_type_re = re.compile(
2406 r"((choice|list):)?(string|bool|int|float|email)"
2407 )
2408
2409 # match tokens found in templates so we can cross reference them back
2410 # to see if they have a matching argument
2411 template_token_re = re.compile(r"{([^}]+)}[^{]*?(?=$|{)")
2412
2413 # Define acceptable map_to arguments that can be tied in with the
2414 # kwargs function definitions.
2415 valid_kwargs = {
2416 # General Parameters
2417 "user",
2418 "password",
2419 "port",
2420 "host",
2421 "schema",
2422 "fullpath",
2423 # NotifyBase parameters:
2424 "tz",
2425 "format",
2426 "overflow",
2427 "emojis",
2428 "retry",
2429 "wait",
2430 "optional",
2431 # URLBase parameters:
2432 "verify",
2433 "redirect",
2434 "cto",
2435 "rto",
2436 "store",
2437 }
2438
2439 # Valid Schema Entries:
2440 valid_schema_keys = (
2441 "name",
2442 "private",
2443 "required",
2444 "type",
2445 "values",
2446 # The subset of `values` this specific plugin actually renders
2447 # natively; only meaningfully narrower than `values` for a
2448 # multi-format plugin. See NotifyBase.resolve_format().
2449 "supported",
2450 "min",
2451 "max",
2452 "regex",
2453 "default",
2454 "list",
2455 "delim",
2456 "prefix",
2457 "map_to",
2458 "alias_of",
2459 "group",
2460 )
2461 for entry in details["schemas"]:
2462 # Track the map_to entries (if specified); We need to make sure that
2463 # these properly map back
2464 map_to_entries = set()
2465
2466 # Track the alias_of entries
2467 map_to_aliases = set()
2468
2469 # A Service Name MUST be defined
2470 assert "service_name" in entry
2471 assert isinstance(entry["service_name"], (str, LazyTranslation))
2472
2473 # Acquire our protocols
2474 protocols = parse_list(entry["protocols"], entry["secure_protocols"])
2475
2476 # At least one schema/protocol MUST be defined
2477 assert len(protocols) > 0
2478
2479 # our details
2480 assert "details" in entry
2481 assert isinstance(entry["details"], dict)
2482
2483 # All schema details should include args
2484 for section in ["kwargs", "args", "tokens"]:
2485 assert section in entry["details"]
2486 assert isinstance(entry["details"][section], dict)
2487
2488 for key, arg in entry["details"][section].items():
2489 # Validate keys (case-sensitive)
2490 assert len([k for k in arg if k not in valid_schema_keys]) == 0
2491
2492 # Test our argument
2493 assert isinstance(arg, dict)
2494
2495 if "alias_of" not in arg:
2496 # Minimum requirement of an argument
2497 assert "name" in arg
2498 assert isinstance(arg["name"], str)
2499
2500 assert "type" in arg
2501 assert isinstance(arg["type"], str)
2502 assert is_valid_type_re.match(arg["type"]) is not None
2503
2504 if "min" in arg:
2505 assert arg["type"].endswith("float") or arg[
2506 "type"
2507 ].endswith("int")
2508 assert isinstance(arg["min"], (int, float))
2509
2510 if "max" in arg:
2511 # If a min and max was specified, at least check
2512 # to confirm the min is less then the max
2513 assert arg["min"] < arg["max"]
2514
2515 if "max" in arg:
2516 assert arg["type"].endswith("float") or arg[
2517 "type"
2518 ].endswith("int")
2519 assert isinstance(arg["max"], (int, float))
2520
2521 if "private" in arg:
2522 assert isinstance(arg["private"], bool)
2523
2524 if "required" in arg:
2525 assert isinstance(arg["required"], bool)
2526
2527 if "prefix" in arg:
2528 assert isinstance(arg["prefix"], str)
2529 if section == "kwargs":
2530 # The only acceptable prefix types for kwargs
2531 assert arg["prefix"] in (":", "+", "-")
2532
2533 else:
2534 # kwargs requires that the 'prefix' is defined
2535 assert section != "kwargs"
2536
2537 if "map_to" in arg:
2538 # must be a string
2539 assert isinstance(arg["map_to"], str)
2540 # Track our map_to object
2541 map_to_entries.add(arg["map_to"])
2542
2543 else:
2544 map_to_entries.add(key)
2545
2546 # Some verification
2547 if arg["type"].startswith("choice"):
2548 # choice:bool is redundant and should be swapped to
2549 # just bool
2550 assert not arg["type"].endswith("bool")
2551
2552 # Choices require that a values list is provided
2553 assert "values" in arg
2554 assert isinstance(
2555 arg["values"], (list, tuple, frozenset, set)
2556 )
2557 assert len(arg["values"]) > 0
2558
2559 # Test default
2560 if "default" in arg:
2561 # if a default is provided on a choice object,
2562 # it better be in the list of values
2563 assert arg["default"] in arg["values"]
2564
2565 if arg["type"].startswith("bool"):
2566 # Boolean choices are less restrictive but require a
2567 # default value
2568 assert "default" in arg
2569 assert isinstance(arg["default"], bool)
2570
2571 if "regex" in arg:
2572 # Regex must ALWAYS be in the format (regex, option)
2573 assert isinstance(arg["regex"], (tuple, list))
2574 assert len(arg["regex"]) == 2
2575 assert isinstance(arg["regex"][0], str)
2576 assert arg["regex"][1] is None or isinstance(
2577 arg["regex"][1], str
2578 )
2579
2580 # Compile the regular expression to verify that it is
2581 # valid
2582 try:
2583 re.compile(arg["regex"][0])
2584
2585 except Exception as e:
2586 # Treat any compilation failure as invalid.
2587 pytest.fail(
2588 "{} is an invalid regex ({}: {})".format(
2589 arg["regex"][0], type(e).__name__, e
2590 )
2591 )
2592
2593 # Regex should always start and/or end with ^/$
2594 assert (
2595 re.match(r"^\^.+?$", arg["regex"][0]) is not None
2596 )
2597 assert (
2598 re.match(r"^.+?\$$", arg["regex"][0]) is not None
2599 )
2600
2601 if arg["type"].startswith("list"):
2602 # Delimiters MUST be defined
2603 assert "delim" in arg
2604 assert isinstance(arg["delim"], (list, tuple))
2605 assert len(arg["delim"]) > 0
2606
2607 else: # alias_of is in the object
2608 # Ensure we're not already in the tokens section
2609 # The alias_of object has no value here
2610 assert section != "tokens"
2611
2612 # must be a string
2613 assert isinstance(arg["alias_of"], (str, list, tuple, set))
2614
2615 aliases = (
2616 [arg["alias_of"]]
2617 if isinstance(arg["alias_of"], str)
2618 else arg["alias_of"]
2619 )
2620
2621 for alias_of in aliases:
2622 # Track our alias_of object
2623 map_to_aliases.add(alias_of)
2624
2625 # We can't be an alias_of ourselves
2626 if key == alias_of:
2627 # This is acceptable as long as we exist in the
2628 # tokens table because that is truely what we map
2629 # back to
2630 assert key in entry["details"]["tokens"]
2631
2632 else:
2633 # Throw the problem into an assert tag for
2634 # debugging purposes... the mapping is not
2635 # acceptable
2636 assert key != alias_of
2637
2638 # alias_of always references back to tokens
2639 assert (
2640 alias_of in entry["details"]["tokens"]
2641 or alias_of in entry["details"]["args"]
2642 )
2643
2644 # Find a list directive in our tokens
2645 t_match = (
2646 entry["details"]["tokens"]
2647 .get(alias_of, {})
2648 .get("type", "")
2649 .startswith("list")
2650 )
2651
2652 a_match = (
2653 entry["details"]["args"]
2654 .get(alias_of, {})
2655 .get("type", "")
2656 .startswith("list")
2657 )
2658
2659 if not (t_match or a_match):
2660 # Ensure the only token we have is the alias_of
2661 # hence record should look like as example):
2662 # {
2663 # 'token': {
2664 # 'alias_of': 'apitoken',
2665 # },
2666 # }
2667 #
2668 # Or if it can represent more then one entry; in
2669 # this case, one must define a name (to define
2670 # grouping).
2671 # {
2672 # 'token': {
2673 # 'name': 'Tokens',
2674 # 'alias_of': ('apitoken', 'webtoken'),
2675 # },
2676 # }
2677 if isinstance(arg["alias_of"], str):
2678 assert len(entry["details"][section][key]) == 1
2679 else: # is tuple,list, or set
2680 assert len(entry["details"][section][key]) == 2
2681 # Must have a name defined to define grouping
2682 assert "name" in entry["details"][section][key]
2683
2684 else:
2685 # We're a list, we allow up to 2 variables
2686 # Obviously we have the alias_of entry; that's why
2687 # were at this part of the code. But we can
2688 # additionally provide a 'delim' over-ride.
2689 assert len(entry["details"][section][key]) <= 2
2690 if len(entry["details"][section][key]) == 2:
2691 # Verify that it is in fact the 'delim' tag
2692 assert (
2693 "delim" in entry["details"][section][key]
2694 )
2695 # If we do have a delim value set, it must be
2696 # of a list/set/tuple type
2697 assert isinstance(
2698 entry["details"][section][key]["delim"],
2699 (tuple, set, list),
2700 )
2701
2702 spec = inspect.getfullargspec(N_MGR._schema_map[protocols[0]].__init__)
2703
2704 function_args = (
2705 (set(parse_list(spec.varkw)) - {"kwargs"})
2706 | (set(spec.args) - {"self"})
2707 | valid_kwargs
2708 )
2709
2710 # Iterate over our map_to_entries and make sure that everything
2711 # maps to a function argument
2712 for arg in map_to_entries:
2713 if arg not in function_args:
2714 # This print statement just makes the error easier to
2715 # troubleshoot
2716 raise AssertionError(
2717 "{}.__init__() expects a {}=None entry according to "
2718 "template configuration".format(
2719 N_MGR._schema_map[protocols[0]].__name__, arg
2720 )
2721 )
2722
2723 # Iterate over all of the function arguments and make sure that
2724 # it maps back to a key
2725 function_args -= valid_kwargs
2726 for arg in function_args:
2727 if arg not in map_to_entries:
2728 err = N_MGR._schema_map[protocols[0]].__name__.__init__(arg)
2729 raise AssertionError(
2730 f"{err} found but not defined in the template "
2731 "configuration"
2732 )
2733
2734 # Iterate over our map_to_aliases and make sure they were defined in
2735 # either the as a token or arg
2736 for arg in map_to_aliases:
2737 assert arg in set(entry["details"]["args"].keys()) | set(
2738 entry["details"]["tokens"].keys()
2739 )
2740
2741 # Template verification
2742 assert "templates" in entry["details"]
2743 assert isinstance(entry["details"]["templates"], (set, tuple, list))
2744
2745 # Iterate over our templates and parse our arguments
2746 for template in entry["details"]["templates"]:
2747 # Ensure we've properly opened and closed all of our tokens
2748 assert template.count("{") == template.count("}")
2749
2750 expected_tokens = template.count("}")
2751 args = template_token_re.findall(template)
2752 assert expected_tokens == len(args)
2753
2754 # Build a cross reference set of our current defined objects
2755 defined_tokens = set()
2756 for key, arg in entry["details"]["tokens"].items():
2757 defined_tokens.add(key)
2758 if "alias_of" in arg:
2759 defined_tokens.add(arg["alias_of"])
2760
2761 # We want to make sure all of our defined tokens have been
2762 # accounted for in at least one defined template
2763 for arg in args:
2764 assert arg in set(entry["details"]["args"].keys()) | set(
2765 entry["details"]["tokens"].keys()
2766 )
2767
2768 # The reverse of the above; make sure that each entry defined
2769 # in the template_tokens is accounted for in at least one of
2770 # the defined templates
2771 assert arg in defined_tokens
2772
2773
2774 def test_apprise_details_plugin_raw_template_tokens():
2775 """Require an explicit type in every raw plugin template token.
2776
2777 Sanitizing supplies a missing ``string`` default, so this checks the raw
2778 declarations first.
2779 """
2780
2781 # Use the same valid token types as the plugin verification test.
2782 is_valid_type_re = re.compile(
2783 r"((choice|list):)?(string|bool|int|float|email)"
2784 )
2785
2786 for plugin in N_MGR.plugins():
2787 label = plugin.__name__
2788
2789 for section_name, raw in (
2790 ("template_tokens", plugin.template_tokens),
2791 ("template_args", plugin.template_args),
2792 ):
2793 for key, token in raw.items():
2794 # alias_of entries are intentionally type-free; skip them
2795 if "alias_of" in token:
2796 continue
2797
2798 assert "type" in token, (
2799 f"{label}.{section_name}[{key!r}] is missing a"
2800 " 'type' field. Every non-alias token must declare"
2801 " its type explicitly -- _sanitize_token silently"
2802 " fills in 'string' and the omission goes"
2803 " undetected by the post-processed details() checks."
2804 )
2805
2806 assert isinstance(token["type"], str) and (
2807 is_valid_type_re.match(token["type"]) is not None
2808 ), (
2809 f"{label}.{section_name}[{key!r}]['type'] ="
2810 f" {token['type']!r} is not a valid type string."
2811 " Expected one of: string, bool, int, float,"
2812 " choice:string, list:string, etc."
2813 )
2814
2815
2816 def test_apprise_details_email_token_types():
2817 """Ensure URL email fields declare their token type as ``email``.
2818
2819 Code that builds URLs from this metadata must leave ``@`` unescaped.
2820 Add fields only after confirming that behavior in the plugin's ``url()``
2821 method; a field name alone is not enough.
2822 """
2823 # (plugin class name, template_tokens key)
2824 expected_email_tokens = {
2825 ("NotifySES", "from_email"),
2826 ("NotifyPostmark", "from_email"),
2827 ("NotifyPostmark", "target_email"),
2828 ("NotifyResend", "from_addr"),
2829 ("NotifyResend", "target_email"),
2830 ("NotifyMailerSend", "from_email"),
2831 ("NotifyMailerSend", "target_email"),
2832 ("NotifyOffice365", "target_email"),
2833 ("NotifyOctopush", "api_login"),
2834 ("NotifyThreema", "target_email"),
2835 ("NotifyBrevo", "from_email"),
2836 ("NotifyBrevo", "target_email"),
2837 ("NotifySendGrid", "from_email"),
2838 ("NotifySendGrid", "target_email"),
2839 ("NotifyMailgun", "target_email"),
2840 ("NotifyOneSignal", "target_email"),
2841 ("NotifyPingram", "target_email"),
2842 ("NotifyPushBullet", "target_email"),
2843 ("NotifySendPulse", "target_email"),
2844 ("NotifySlack", "target_email"),
2845 ("NotifyTwist", "email"),
2846 ("NotifyVoipms", "email"),
2847 ("NotifyZulip", "target_user"),
2848 }
2849
2850 plugins_by_name = {plugin.__name__: plugin for plugin in N_MGR.plugins()}
2851 found = set()
2852 for plugin_name, token_key in expected_email_tokens:
2853 assert plugin_name in plugins_by_name, (
2854 f"{plugin_name} was not found -- has it been renamed/removed?"
2855 " Update expected_email_tokens to match."
2856 )
2857 plugin = plugins_by_name[plugin_name]
2858 assert token_key in plugin.template_tokens, (
2859 f"{plugin_name}.template_tokens no longer defines"
2860 f" {token_key!r} -- update expected_email_tokens to match."
2861 )
2862 assert plugin.template_tokens[token_key]["type"] == "email", (
2863 f"{plugin_name}.template_tokens[{token_key!r}]['type'] must"
2864 " stay 'email' -- this field's own url() preserves a literal"
2865 " '@' when rebuilding the URL, so a client keying off this"
2866 " metadata needs the same signal."
2867 )
2868 found.add((plugin_name, token_key))
2869
2870 # Scan all declared email tokens so new fields must join the allowlist.
2871 for plugin in N_MGR.plugins():
2872 for key, token in plugin.template_tokens.items():
2873 if token.get("type") == "email":
2874 assert (plugin.__name__, key) in found, (
2875 f"{plugin.__name__}.template_tokens[{key!r}] is tagged"
2876 " 'email' but isn't listed in expected_email_tokens --"
2877 " add it there (after confirming this field's own"
2878 " url() actually needs it, per this test's docstring)."
2879 )
2880
2881
2882 def test_apprise_send_format_handlers_match_notify_format():
2883 """
2884 API: send_text()/send_html()/send_markdown() vs notify_format sanity
2885
2886 A format-specific send_<format>() method must be reachable through
2887 the plugin's notify_format declaration.
2888 """
2889
2890 for plugin in N_MGR.plugins():
2891 label = plugin.__name__
2892
2893 # Only consider format-specific methods defined directly on this
2894 # class (not merely inherited), so a subclass that narrows
2895 # notify_format isn't blamed for a handler its parent defined.
2896 declared_handlers = {
2897 fmt for fmt in NOTIFY_FORMATS if f"send_{fmt}" in vars(plugin)
2898 }
2899
2900 if not declared_handlers:
2901 continue
2902
2903 # notify_format may be a single NotifyFormat or a tuple; resolve
2904 # it the same way NotifyBase._formats() does.
2905 supported = set(parse_list(plugin.notify_format, sort=False))
2906
2907 missing = declared_handlers - supported
2908 assert not missing, (
2909 f"{label} defines send_{next(iter(missing))}() but "
2910 f"{next(iter(missing))!r} is not declared in its "
2911 f"notify_format {plugin.notify_format!r}; the handler can "
2912 "never be reached."
2913 )
2914
2915
2916 def test_apprise_multi_format_plugins_no_scalar_comparison():
2917 """Multi-format plugins must resolve before scalar comparisons."""
2918
2919 scalar_compare_re = re.compile(r"self\.notify_format\s*==")
2920
2921 for plugin in N_MGR.plugins():
2922 formats = parse_list(plugin.notify_format, sort=False)
2923 if len(formats) <= 1:
2924 # Single-format plugins can compare their scalar directly.
2925 continue
2926
2927 try:
2928 source = inspect.getsource(plugin)
2929 except (OSError, TypeError):
2930 # Dynamic plugins have no source file to inspect.
2931 continue
2932
2933 assert not scalar_compare_re.search(source), (
2934 f"{plugin.__name__} declares a multi-format notify_format "
2935 f"{plugin.notify_format!r} but compares self.notify_format "
2936 "directly somewhere in its source; use "
2937 "self.resolve_format(body_format) instead, since a tuple "
2938 "never equals a scalar and the comparison can never be "
2939 "True."
2940 )
2941
2942
2943 @mock.patch("requests.request")
2944 @mock.patch("asyncio.gather", wraps=asyncio.gather)
2945 @mock.patch(
2946 "concurrent.futures.ThreadPoolExecutor",
2947 wraps=concurrent.futures.ThreadPoolExecutor,
2948 )
2949 def test_apprise_async_mode(mock_threadpool, mock_gather, mock_request):
2950 """
2951 API: Apprise() async_mode tests
2952
2953 """
2954 mock_request.return_value.status_code = requests.codes.ok
2955
2956 # Define some services
2957 services = [
2958 "xml://localhost",
2959 "json://localhost",
2960 ]
2961
2962 # Services use asynchronous mode by default.
2963 asset = AppriseAsset()
2964 assert asset.async_mode is True
2965
2966 # Build an Apprise object with that shared asset.
2967 a = Apprise(asset=asset)
2968
2969 # Add both test services.
2970 a.add(services=services)
2971
2972 # Both service URLs should load.
2973 assert len(a) == 2
2974
2975 # Both services share the asset's asynchronous setting.
2976 for service in a:
2977 assert service.asset.async_mode is True
2978
2979 # Reset the process-wide pool so this test observes its first creation.
2980 # mock.patch restores any pool that an earlier test created.
2981 with mock.patch("apprise.apprise._shared_executor", None):
2982 # Send both notifications asynchronously.
2983 assert bool(a.notify("async")) is True
2984
2985 # The first send creates the shared worker pool once.
2986 assert mock_threadpool.call_count == 1
2987 mock_threadpool.reset_mock()
2988
2989 # Repeat the test with asynchronous mode disabled.
2990 asset = AppriseAsset(async_mode=False)
2991 assert asset.async_mode is False
2992
2993 # Build a fresh Apprise object with the new asset.
2994 a = Apprise(asset=asset)
2995
2996 # The new object keeps the disabled setting.
2997 assert a.asset.async_mode is False
2998
2999 # Add both test services again.
3000 a.add(services=services)
3001
3002 # Both service URLs should load.
3003 assert len(a) == 2
3004
3005 # Both services now use ordered delivery.
3006 for service in a:
3007 assert service.asset.async_mode is False
3008
3009 # Send both notifications one at a time.
3010 assert bool(a.notify("sync")) is True
3011 # Ordered delivery does not need asyncio.gather().
3012 assert mock_gather.call_count == 0
3013 mock_gather.reset_mock()
3014
3015 # Each loaded service exposes the same disabled setting.
3016 assert a[0].asset.async_mode is False
3017 assert a[1].asset.async_mode is False
3018
3019 # Changing the shared asset through one service affects both.
3020 a[0].asset.async_mode = True
3021 assert a[0].asset.async_mode is True
3022
3023 # The second service sees the same shared asset change.
3024 assert a[1].asset.async_mode is True
3025
3026 # Give only the second service its own asset.
3027 a[1].asset = AppriseAsset(async_mode=False)
3028 assert a[0].asset.async_mode is True
3029 assert a[1].asset.async_mode is False
3030
3031 # Send one service each way in the same batch.
3032 assert bool(a.notify("a mixed batch")) is True
3033
3034 # The single async-mode service still goes through the thread
3035 # pool even though it's alone in its batch: AppriseAsset.
3036 # service_timeout defaults to 60s, so a deadline applies, and
3037 # only a thread-pool dispatch can abandon a service that runs
3038 # past its deadline. No NEW executor is constructed though --
3039 # the one from the first dispatch above is shared and reused.
3040 assert mock_threadpool.call_count == 0
3041
3042 # Disable this service's own timeout budget entirely -- with no
3043 # deadline of any kind in effect, a single async-mode service has
3044 # nothing that could ever need abandoning, so the thread-pool
3045 # shortcut applies again (no executor use at all, shared or not).
3046 a[0].asset = AppriseAsset(async_mode=True, service_timeout=0)
3047 a[1].asset = AppriseAsset(async_mode=False)
3048 assert bool(a.notify("a mixed batch, no timeout")) is True
3049 assert mock_threadpool.call_count == 0
3050
3051 # Shut down the executor constructed inside this patched block
3052 # before it's discarded -- otherwise its worker threads would
3053 # sit idle forever with nothing left referencing them once
3054 # mock.patch restores apprise.apprise._shared_executor below.
3055 import apprise.apprise as apprise_module
3056
3057 if apprise_module._shared_executor is not None:
3058 apprise_module._shared_executor.shutdown(wait=False)
3059
3060
3061 def test_notify_matrix_dynamic_importing(tmpdir):
3062 """
3063 API: Apprise() Notify Matrix Importing
3064
3065 """
3066
3067 # Make our new path valid
3068 suite = tmpdir.mkdir("apprise_notify_test_suite")
3069 suite.join("__init__.py").write("")
3070
3071 module_name = "badnotify"
3072
3073 # Update our path to point to our new test suite
3074 sys.path.insert(0, str(suite))
3075
3076 # Create a base area to work within
3077 base = suite.mkdir(module_name)
3078 base.join("__init__.py").write("")
3079
3080 # Test no app_id
3081 base.join("NotifyBadFile1.py").write(
3082 cleandoc("""
3083 class NotifyBadFile1:
3084 pass
3085 """)
3086 )
3087
3088 # No class of the same name
3089 base.join("NotifyBadFile2.py").write(
3090 cleandoc("""
3091 class BadClassName:
3092 pass
3093 """)
3094 )
3095
3096 # Exception thrown
3097 base.join("NotifyBadFile3.py").write("""raise ImportError()""")
3098
3099 # Utilizes a schema:// already occupied (as string)
3100 base.join("NotifyGoober.py").write(
3101 cleandoc("""
3102 from apprise import NotifyBase
3103 class NotifyGoober(NotifyBase):
3104 # This class tests the fact we have a new class name, but we're
3105 # trying to over-ride items previously used
3106
3107 # The default simple (insecure) protocol (used by NotifyMail)
3108 protocol = ('mailto', 'goober')
3109
3110 # The default secure protocol (used by NotifyMail)
3111 secure_protocol = 'mailtos'
3112
3113 @staticmethod
3114 def parse_url(url, *args, **kwargs):
3115 # always parseable
3116 return ConfigBase.parse_url(url, verify_host=False)
3117 """)
3118 )
3119
3120 # Utilizes a schema:// already occupied (as tuple)
3121 base.join("NotifyBugger.py").write(
3122 cleandoc("""
3123 from apprise import NotifyBase
3124 class NotifyBugger(NotifyBase):
3125 # This class tests the fact we have a new class name, but we're
3126 # trying to over-ride items previously used
3127
3128 # The default simple (insecure) protocol (used by NotifyMail), the
3129 # other isn't
3130 protocol = ('mailto', 'bugger-test' )
3131
3132 # The default secure protocol (used by NotifyMail), the other isn't
3133 secure_protocol = ('mailtos', ['garbage'])
3134
3135 @staticmethod
3136 def parse_url(url, *args, **kwargs):
3137 # always parseable
3138 return ConfigBase.parse_url(url, verify_host=False)
3139 """)
3140 )
3141
3142 N_MGR.load_modules(path=str(base), name=module_name)
3143
3144
3145 def test_apprise_ipv6_host_preserved():
3146 """
3147 API: an IPv6 host in a URL reaches the plugin intact
3148
3149 """
3150 # Compressed IPv6 addresses
3151 for url, host in (
3152 ("json://[2001:db8::1]:8080/path", "[2001:db8::1]"),
3153 ("json://[fd00::5]:8080/path", "[fd00::5]"),
3154 ("json://[::1]:8080/path", "[::1]"),
3155 (
3156 "form://[2001:db8:85a3::8a2e:370:7334]/p",
3157 "[2001:db8:85a3::8a2e:370:7334]",
3158 ),
3159 (
3160 "xml://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]/p",
3161 "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
3162 ),
3163 ):
3164 obj = Apprise.instantiate(url, suppress_exceptions=False)
3165 assert obj is not None
3166 assert obj.host == host
3167
3168 # The generated url carries the same address, so re-loading it keeps
3169 # pointing at the same place
3170 assert host in obj.url()
3171
3172 reloaded = Apprise.instantiate(obj.url(), suppress_exceptions=False)
3173 assert reloaded.host == host
3174 assert reloaded.url() == obj.url()
3175
3176
3177 def test_apprise_ipv6_host_invalid():
3178 """
3179 API: a malformed IPv6 host in a URL is refused
3180
3181 """
3182 # More than one :: is not a valid address, so there is nothing sensible
3183 # to deliver to
3184 for url in (
3185 "json://[2001:db8::1::2]:8080/path",
3186 "json://[2001:db8::12345]/path",
3187 "json://[not:an:address]/path",
3188 ):
3189 assert Apprise.instantiate(url, suppress_exceptions=True) is None