Debian Codegraph @

tests/test_api.py

raw symbols SCIP
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 Apprise,
47 AppriseAsset,
48 AppriseAttachment,
49 NotificationManager,
50 NotifyBase,
51 NotifyFormat,
52 NotifyImageSize,
53 NotifyType,
54 PrivacyMode,
55 URLBase,
56 __version__,
57 )
58 from apprise.locale import LazyTranslation, gettext_lazy as _
59 from apprise.plugins.base import RequirementsSpec
60 from apprise.utils.parse import parse_list
61
62 logging.disable(logging.CRITICAL)
63
64 # Attachment Directory
65 TEST_VAR_DIR = join(dirname(__file__), "var")
66
67 # Grant access to our Notification Manager Singleton
68 N_MGR = NotificationManager()
69
70
71 def test_apprise_object():
72 """
73 API: Apprise() object
74
75 """
76
77 def do_notify(server, *args, **kwargs):
78 return server.notify(*args, **kwargs)
79
80 apprise_test(do_notify)
81
82
83 def test_apprise_async():
84 """
85 API: Apprise() object asynchronous methods
86
87 """
88 with OuterEventLoop() as loop:
89
90 def do_notify(server, *args, **kwargs):
91 return loop.run_until_complete(
92 server.async_notify(*args, **kwargs)
93 )
94
95 apprise_test(do_notify)
96
97
98 def apprise_test(do_notify):
99 a = Apprise()
100
101 # no items
102 assert len(a) == 0
103
104 # Apprise object can also be directly tested with 'if' keyword
105 # No entries results in a False response
106 assert not a
107
108 # Create an Asset object
109 asset = AppriseAsset(theme="default")
110
111 # We can load the device using our asset
112 a = Apprise(asset=asset)
113
114 # We can load our servers up front as well
115 servers = [
116 "json://myhost",
117 "kodi://kodi.server.local",
118 ]
119
120 a = Apprise(servers=servers)
121
122 # 2 servers loaded
123 assert len(a) == 2
124
125 # Apprise object can also be directly tested with 'if' keyword
126 # At least one entry results in a True response
127 assert a
128
129 # We can retrieve our URLs this way:
130 assert len(a.urls()) == 2
131
132 # We can add another server
133 assert (
134 a.add(
135 "mmosts://mattermost.server.local/3ccdd113474722377935511fc85d3dd4"
136 )
137 is True
138 )
139 assert len(a) == 3
140
141 # Try adding nothing but delimiters
142 assert a.add(",, ,, , , , ,") is False
143
144 # The number of servers added doesn't change
145 assert len(a) == 3
146
147 # We can pop an object off of our stack by it's indexed value:
148 obj = a.pop(0)
149 assert isinstance(obj, NotifyBase) is True
150 assert len(a) == 2
151
152 # We can retrieve elements from our list too by reference:
153 assert isinstance(a[0].url(), str) is True
154
155 # We can iterate over our list too:
156 count = 0
157 for o in a:
158 assert isinstance(o.url(), str) is True
159 count += 1
160 # verify that we did indeed iterate over each element
161 assert len(a) == count
162
163 # We can empty our set
164 a.clear()
165 assert len(a) == 0
166
167 # An invalid schema
168 assert a.add("this is not a parseable url at all") is False
169 assert len(a) == 0
170
171 # An unsupported schema
172 assert a.add("invalid://we.just.do.not.support.this.plugin.type") is False
173 assert len(a) == 0
174
175 # A poorly formatted URL
176 assert a.add("json://user:@@@:bad?no.good") is False
177 assert len(a) == 0
178
179 # Add a server with our asset we created earlier
180 assert (
181 a.add(
182 "mmosts://mattermost.server.local/"
183 "3ccdd113474722377935511fc85d3dd4",
184 asset=asset,
185 )
186 is True
187 )
188
189 # Clear our server listings again
190 a.clear()
191 assert len(a) == 0
192
193 # No servers to notify
194 assert do_notify(a, title="my title", body="my body") is False
195
196 # More Variations of Multiple Adding of URLs
197 a = Apprise()
198 assert a.add(servers)
199 assert len(a) == 2
200 a.clear()
201
202 assert a.add("ntfys://user:pass@host/test, json://localhost")
203 assert len(a) == 2
204 a.clear()
205
206 assert a.add(["ntfys://user:pass@host/test", "json://localhost"])
207 assert len(a) == 2
208 a.clear()
209
210 assert a.add(("ntfys://user:pass@host/test", "json://localhost"))
211 assert len(a) == 2
212 a.clear()
213
214 assert a.add({"ntfys://user:pass@host/test", "json://localhost"})
215 assert len(a) == 2
216 a.clear()
217
218 # Pass a list entry containing 1 string with 2 elements in it
219 # Mimic Home-Assistant core-2024.2.1 Issue:
220 # - https://github.com/home-assistant/core/issues/110242
221 #
222 # In this case, the first one will load, but not the second entry
223 # This is by design; but captured here to illustrate the issue
224 assert a.add(["ntfys://user:pass@host/test, json://localhost"])
225 assert len(a) == 1
226 assert a[0].url().startswith("ntfys://")
227 a.clear()
228
229 # Following thorugh with the problem of providing a list containing
230 # an entry with 2 URLs in it... while the ntfys parsed okay above,
231 # the same can't be said for other combinations. It's important
232 # to always keep strings separately
233 assert a.add(["mailto://user:[email protected], json://localhost"]) is False
234 assert len(a) == 0
235
236 # Showing that the URLs were valid on their own:
237 assert a.add(*["mailto://user:[email protected], json://localhost"])
238 assert len(a) == 2
239 assert a[0].url().startswith("mailto://")
240 assert a[1].url().startswith("json://")
241 a.clear()
242
243 class BadNotification(NotifyBase):
244 def __init__(self, **kwargs):
245 super().__init__(**kwargs)
246
247 # We fail whenever we're initialized
248 raise TypeError()
249
250 @staticmethod
251 def parse_url(url, *args, **kwargs):
252 # always parseable
253 return NotifyBase.parse_url(url, verify_host=False)
254
255 class GoodNotification(NotifyBase):
256 def __init__(self, **kwargs):
257 super().__init__(notify_format=NotifyFormat.HTML, **kwargs)
258
259 def send(self, **kwargs):
260 # Pretend everything is okay
261 return True
262
263 @staticmethod
264 def parse_url(url, *args, **kwargs):
265 # always parseable
266 return NotifyBase.parse_url(url, verify_host=False)
267
268 # Store our bad notification in our schema map
269 N_MGR["bad"] = BadNotification
270
271 # Store our good notification in our schema map
272 N_MGR["good"] = GoodNotification
273
274 # Just to explain what is happening here, we would have parsed the
275 # url properly but failed when we went to go and create an instance
276 # of it.
277 assert a.add("bad://localhost") is False
278 assert len(a) == 0
279
280 # We'll fail because we've got nothing to notify
281 assert do_notify(a, title="my title", body="my body") is False
282
283 # Clear our server listings again
284 a.clear()
285
286 assert a.add("good://localhost") is True
287 assert len(a) == 1
288
289 # Bad Notification Types are not accepted
290 assert (
291 do_notify(a, title="my title", body="my body", notify_type="bad")
292 is False
293 )
294
295 # Notifications of string type are accepted
296 assert (
297 do_notify(a, title="my title", body="my body", notify_type="warning")
298 is True
299 )
300
301 # Notifications of string type are accepted
302 assert (
303 do_notify(a, title="my title", body="my body", notify_type="warning")
304 is True
305 )
306
307 # Notifications of string type are accepted
308 assert (
309 do_notify(a, title="my title", body="my body", notify_type="warning")
310 is True
311 )
312
313 # Notifications where notify_type is of the NotifyType object is the
314 # preferred choice
315 assert (
316 do_notify(
317 a, title="my title", body="my body", notify_type=NotifyType.WARNING
318 )
319 is True
320 )
321
322 # No Title/Body combo's
323 assert do_notify(a, title=None, body=None) is False
324 assert do_notify(a, title="", body=None) is False
325 assert do_notify(a, title=None, body="") is False
326
327 assert do_notify(a, title=5, body=b"bytes") is False
328 assert do_notify(a, title=b"bytes", body=10) is False
329 assert do_notify(a, title=object(), body=b"bytes") is False
330 assert do_notify(a, title=b"bytes", body=object()) is False
331
332 # A Body must be present
333 assert do_notify(a, title="present", body=None) is False
334
335 # Other combinations work fine
336 assert do_notify(a, title=None, body="present") is True
337 assert do_notify(a, title="present", body="present") is True
338
339 # Send Attachment with success
340 attach = join(TEST_VAR_DIR, "apprise-test.gif")
341 assert (
342 do_notify(
343 a,
344 body="body",
345 title="test",
346 notify_type=NotifyType.INFO,
347 attach=attach,
348 )
349 is True
350 )
351
352 # Send the attachment as an AppriseAttachment object
353 assert (
354 do_notify(
355 a,
356 body="body",
357 title="test",
358 notify_type=NotifyType.INFO,
359 attach=AppriseAttachment(attach),
360 )
361 is True
362 )
363
364 # test a invalid attachment
365 assert (
366 do_notify(
367 a,
368 body="body",
369 title="test",
370 notify_type=NotifyType.INFO,
371 attach="invalid://",
372 )
373 is False
374 )
375
376 # Repeat the same tests above...
377 # however do it by directly accessing the object; this grants the similar
378 # results:
379 assert (
380 do_notify(
381 a[0],
382 body="body",
383 title="test",
384 notify_type=NotifyType.INFO,
385 attach=attach,
386 )
387 is True
388 )
389
390 # Send the attachment as an AppriseAttachment object
391 assert (
392 do_notify(
393 a[0],
394 body="body",
395 title="test",
396 notify_type=NotifyType.INFO,
397 attach=AppriseAttachment(attach),
398 )
399 is True
400 )
401
402 # test a invalid attachment
403 assert (
404 do_notify(
405 a[0],
406 body="body",
407 title="test",
408 notify_type=NotifyType.INFO,
409 attach="invalid://",
410 )
411 is False
412 )
413
414 class ThrowNotification(NotifyBase):
415 def notify(self, **kwargs):
416 # Pretend everything is okay
417 raise TypeError()
418
419 async def async_notify(self, **kwargs):
420 # Pretend everything is okay (async)
421 raise TypeError()
422
423 class RuntimeNotification(NotifyBase):
424 def notify(self, **kwargs):
425 # Pretend everything is okay
426 raise RuntimeError()
427
428 async def async_notify(self, **kwargs):
429 # Pretend everything is okay (async)
430 raise TypeError()
431
432 class FailNotification(NotifyBase):
433 def notify(self, **kwargs):
434 # Pretend everything is okay
435 return False
436
437 async def async_notify(self, **kwargs):
438 # Pretend everything is okay (async)
439 raise TypeError()
440
441 # Store our bad notification in our schema map
442 N_MGR["throw"] = ThrowNotification
443
444 # Store our good notification in our schema map
445 N_MGR["fail"] = FailNotification
446
447 # Store our good notification in our schema map
448 N_MGR["runtime"] = RuntimeNotification
449
450 for async_mode in (True, False):
451 # Create an Asset object
452 asset = AppriseAsset(theme="default", async_mode=async_mode)
453
454 # We can load the device using our asset
455 a = Apprise(asset=asset)
456
457 assert a.add("runtime://localhost") is True
458 assert a.add("throw://localhost") is True
459 assert a.add("fail://localhost") is True
460 assert len(a) == 3
461
462 # Test when our notify both throws an exception and or just
463 # simply returns False
464 assert do_notify(a, title="present", body="present") is False
465
466 # Create a Notification that throws an unexected exception
467 class ThrowInstantiateNotification(NotifyBase):
468 def __init__(self, **kwargs):
469 # Pretend everything is okay
470 raise TypeError()
471
472 N_MGR.unload_modules()
473 N_MGR["throw"] = ThrowInstantiateNotification
474
475 # Store our good notification in our schema map
476 N_MGR["good"] = GoodNotification
477
478 # Reset our object
479 a.clear()
480 assert len(a) == 0
481
482 # Test our socket details
483 # rto = Socket Read Timeout
484 # cto = Socket Connect Timeout
485 plugin = a.instantiate("good://localhost?rto=5.1&cto=10")
486 assert isinstance(plugin, NotifyBase)
487 assert plugin.socket_connect_timeout == pytest.approx(10.0)
488 assert plugin.socket_read_timeout == pytest.approx(5.1)
489
490 plugin = a.instantiate("good://localhost?rto=invalid&cto=invalid")
491 assert isinstance(plugin, NotifyBase)
492 assert plugin.socket_connect_timeout == URLBase.socket_connect_timeout
493 assert plugin.socket_read_timeout == URLBase.socket_read_timeout
494
495 # Reset our object
496 a.clear()
497 assert len(a) == 0
498
499 with pytest.raises(ValueError):
500 # Encoding error
501 AppriseAsset(encoding="ascii", storage_salt="ボールト")
502
503 with pytest.raises(ValueError):
504 # Not a valid storage salt (must be str or bytes)
505 AppriseAsset(storage_salt=42)
506
507 # Set our cache to be off
508 plugin = a.instantiate("good://localhost?store=no", asset=asset)
509 assert isinstance(plugin, NotifyBase)
510 assert plugin.url_id(lazy=False) is None
511 # Verify our cache is disabled
512 assert "store=no" in plugin.url()
513
514 with pytest.raises(ValueError):
515 # idlen must be greater then 0
516 AppriseAsset(storage_idlen=-1)
517
518 # Create a larger idlen
519 asset = AppriseAsset(storage_idlen=32)
520 plugin = a.instantiate("good://localhost", asset=asset)
521 assert len(plugin.url_id()) == 32
522
523 # Instantiate a bad object
524 plugin = a.instantiate(object, tag="bad_object")
525 assert plugin is None
526
527 # Instantiate a good object
528 plugin = a.instantiate("good://localhost", tag="good")
529 assert isinstance(plugin, NotifyBase)
530
531 # Test simple tagging inside of the object
532 assert "good" in plugin
533 assert "bad" not in plugin
534
535 # the in (__contains__ override) is based on or'ed content; so although
536 # 'bad' isn't tagged as being in the plugin, 'good' is, so the return
537 # value of this is True
538 assert ["bad", "good"] in plugin
539 assert {"bad", "good"} in plugin
540 assert ("bad", "good") in plugin
541
542 # We an add already substatiated instances into our Apprise object
543 a.add(plugin)
544 assert len(a) == 1
545
546 # We can add entries as a list too (to add more then one)
547 a.add([plugin, plugin, plugin])
548 assert len(a) == 4
549
550 # Reset our object again
551 a.clear()
552 with pytest.raises(TypeError):
553 a.instantiate("throw://localhost", suppress_exceptions=False)
554
555 assert len(a) == 0
556
557 assert a.instantiate("throw://localhost", suppress_exceptions=True) is None
558 assert len(a) == 0
559
560 #
561 # We rince and repeat the same tests as above, however we do them
562 # using the dict version
563 #
564
565 # Reset our object
566 a.clear()
567 assert len(a) == 0
568
569 # Instantiate a good object
570 plugin = a.instantiate({"schema": "good", "host": "localhost"}, tag="good")
571 assert isinstance(plugin, NotifyBase)
572
573 # Test simple tagging inside of the object
574 assert "good" in plugin
575 assert "bad" not in plugin
576
577 # the in (__contains__ override) is based on or'ed content; so although
578 # 'bad' isn't tagged as being in the plugin, 'good' is, so the return
579 # value of this is True
580 assert ["bad", "good"] in plugin
581 assert {"bad", "good"} in plugin
582 assert ("bad", "good") in plugin
583
584 # We an add already substatiated instances into our Apprise object
585 a.add(plugin)
586 assert len(a) == 1
587
588 # We can add entries as a list too (to add more then one)
589 a.add([plugin, plugin, plugin])
590 assert len(a) == 4
591
592 # Reset our object again
593 a.clear()
594 with pytest.raises(TypeError):
595 a.instantiate(
596 {"schema": "throw", "host": "localhost"}, suppress_exceptions=False
597 )
598
599 assert len(a) == 0
600
601 assert (
602 a.instantiate(
603 {"schema": "throw", "host": "localhost"}, suppress_exceptions=True
604 )
605 is None
606 )
607 assert len(a) == 0
608
609
610 def test_apprise_pretty_print():
611 """
612 API: Apprise() Pretty Print tests
613
614 """
615 # Privacy Print
616 # PrivacyMode.Secret always returns the same thing to avoid guessing
617 assert (
618 URLBase.pprint(None, privacy=True, mode=PrivacyMode.Secret) == "****"
619 )
620 assert URLBase.pprint(42, privacy=True, mode=PrivacyMode.Secret) == "****"
621 assert (
622 URLBase.pprint(object, privacy=True, mode=PrivacyMode.Secret) == "****"
623 )
624 assert URLBase.pprint("", privacy=True, mode=PrivacyMode.Secret) == "****"
625 assert URLBase.pprint("a", privacy=True, mode=PrivacyMode.Secret) == "****"
626 assert (
627 URLBase.pprint("ab", privacy=True, mode=PrivacyMode.Secret) == "****"
628 )
629 assert (
630 URLBase.pprint("abcdefghijk", privacy=True, mode=PrivacyMode.Secret)
631 == "****"
632 )
633
634 # PrivacyMode.Outer
635 assert URLBase.pprint(None, privacy=True, mode=PrivacyMode.Outer) == ""
636 assert URLBase.pprint(42, privacy=True, mode=PrivacyMode.Outer) == ""
637 assert URLBase.pprint(object, privacy=True, mode=PrivacyMode.Outer) == ""
638 assert URLBase.pprint("", privacy=True, mode=PrivacyMode.Outer) == ""
639 assert URLBase.pprint("a", privacy=True, mode=PrivacyMode.Outer) == "a...a"
640 assert (
641 URLBase.pprint("ab", privacy=True, mode=PrivacyMode.Outer) == "a...b"
642 )
643 assert (
644 URLBase.pprint("abcdefghijk", privacy=True, mode=PrivacyMode.Outer)
645 == "a...k"
646 )
647
648 # PrivacyMode.Tail
649 assert URLBase.pprint(None, privacy=True, mode=PrivacyMode.Tail) == ""
650 assert URLBase.pprint(42, privacy=True, mode=PrivacyMode.Tail) == ""
651 assert URLBase.pprint(object, privacy=True, mode=PrivacyMode.Tail) == ""
652 assert URLBase.pprint("", privacy=True, mode=PrivacyMode.Tail) == ""
653 assert URLBase.pprint("a", privacy=True, mode=PrivacyMode.Tail) == "...a"
654 assert URLBase.pprint("ab", privacy=True, mode=PrivacyMode.Tail) == "...ab"
655 assert (
656 URLBase.pprint("abcdefghijk", privacy=True, mode=PrivacyMode.Tail)
657 == "...hijk"
658 )
659
660 # Quoting settings
661 assert URLBase.pprint(" ", privacy=False, safe="") == "%20"
662 assert URLBase.pprint(" ", privacy=False, quote=False, safe="") == " "
663
664
665 @mock.patch("requests.request")
666 def test_apprise_tagging(mock_request):
667 """
668 API: Apprise() object tagging functionality
669
670 """
671
672 def do_notify(server, *args, **kwargs):
673 return server.notify(*args, **kwargs)
674
675 apprise_tagging_test(mock_request, do_notify)
676
677
678 @mock.patch("requests.request")
679 def test_apprise_tagging_async(mock_request):
680 """
681 API: Apprise() object tagging functionality asynchronous methods
682
683 """
684 with OuterEventLoop() as loop:
685
686 def do_notify(server, *args, **kwargs):
687 return loop.run_until_complete(
688 server.async_notify(*args, **kwargs)
689 )
690
691 apprise_tagging_test(mock_request, do_notify)
692
693
694 def apprise_tagging_test(mock_request, do_notify):
695 # A request
696 robj = mock.Mock()
697 robj.raw = mock.Mock()
698 # Allow raw.read() calls
699 robj.raw.read.return_value = ""
700 robj.text = ""
701 robj.content = ""
702 mock_request.return_value = robj
703
704 # Simulate a successful notification
705 mock_request.return_value.status_code = requests.codes.ok
706
707 # Create our object
708 a = Apprise()
709
710 # An invalid addition can't add the tag
711 assert a.add("averyinvalidschema://localhost", tag="uhoh") is False
712 assert (
713 a.add(
714 {"schema": "averyinvalidschema", "host": "localhost"}, tag="uhoh"
715 )
716 is False
717 )
718
719 # Add entry and assign it to a tag called 'awesome'
720 assert a.add("json://localhost/path1/", tag="awesome") is True
721 assert (
722 a.add(
723 {"schema": "json", "host": "localhost", "fullpath": "/path1/"},
724 tag="awesome",
725 )
726 is True
727 )
728
729 # Add another notification and assign it to a tag called 'awesome'
730 # and another tag called 'local'
731 assert a.add("json://localhost/path2/", tag=["mmost", "awesome"]) is True
732
733 # notify the awesome tag; this would notify both services behind the
734 # scenes
735 assert (
736 do_notify(a, title="my title", body="my body", tag="awesome") is True
737 )
738
739 # notify all of the tags
740 assert (
741 do_notify(
742 a, title="my title", body="my body", tag=["awesome", "mmost"]
743 )
744 is True
745 )
746
747 # When we query against our loaded notifications for a tag that simply
748 # isn't assigned to anything, we return None. None (different then False)
749 # tells us that we litterally had nothing to query. We didn't fail...
750 # but we also didn't do anything...
751 assert (
752 do_notify(a, title="my title", body="my body", tag="missing") is None
753 )
754
755 # Now to test the ability to and and/or notifications
756 a = Apprise()
757
758 # Add a tag by tuple
759 assert a.add("json://localhost/tagA/", tag=("TagA",)) is True
760 # Add 2 tags by string
761 assert a.add("json://localhost/tagAB/", tag="TagA, TagB") is True
762 # Add a tag using a set
763 assert a.add("json://localhost/tagB/", tag={"TagB"}) is True
764 # Add a tag by string (again)
765 assert a.add("json://localhost/tagC/", tag="TagC") is True
766 # Add 2 tags using a list
767 assert a.add("json://localhost/tagCD/", tag=["TagC", "TagD"]) is True
768 # Add a tag by string (again)
769 assert a.add("json://localhost/tagD/", tag="TagD") is True
770 # add a tag set by set (again)
771 assert (
772 a.add("json://localhost/tagCDE/", tag={"TagC", "TagD", "TagE"}) is True
773 )
774
775 # Expression: TagC and TagD
776 # Matches the following only:
777 # - json://localhost/tagCD/
778 # - json://localhost/tagCDE/
779 assert (
780 do_notify(a, title="my title", body="my body", tag=[("TagC", "TagD")])
781 is True
782 )
783
784 # Expression: (TagY and TagZ) or TagX
785 # Matches nothing, None is returned in this case
786 assert (
787 do_notify(
788 a, title="my title", body="my body", tag=[("TagY", "TagZ"), "TagX"]
789 )
790 is None
791 )
792
793 # Expression: (TagY and TagZ) or TagA
794 # Matches the following only:
795 # - json://localhost/tagAB/
796 assert (
797 do_notify(
798 a, title="my title", body="my body", tag=[("TagY", "TagZ"), "TagA"]
799 )
800 is True
801 )
802
803 # Expression: (TagE and TagD) or TagB
804 # Matches the following only:
805 # - json://localhost/tagCDE/
806 # - json://localhost/tagAB/
807 # - json://localhost/tagB/
808 assert (
809 do_notify(
810 a, title="my title", body="my body", tag=[("TagE", "TagD"), "TagB"]
811 )
812 is True
813 )
814
815 # Garbage Entries in tag field just get stripped out. the below
816 # is the same as notifying no tags at all. Since we have not added
817 # any entries that do not have tags (that we can match against)
818 # we fail. None is returned as a way of letting us know that we
819 # had Notifications to notify, but since none of them matched our tag
820 # none were notified.
821 assert (
822 do_notify(
823 a,
824 title="my title",
825 body="my body",
826 tag=[
827 (object,),
828 ],
829 )
830 is None
831 )
832
833
834 def test_apprise_schemas():
835 """
836 API: Apprise().schema() tests
837
838 """
839 # Clear loaded modules
840 a = Apprise()
841
842 # no items
843 assert len(a) == 0
844
845 class TextNotification(NotifyBase):
846 # set our default notification format
847 notify_format = NotifyFormat.TEXT
848
849 # Garbage Protocol Entries
850 protocol = None
851
852 secure_protocol = (None, object)
853
854 class HtmlNotification(NotifyBase):
855 protocol = ("html", "htm")
856
857 secure_protocol = ("htmls", "htms")
858
859 class MarkDownNotification(NotifyBase):
860 protocol = "markdown"
861
862 secure_protocol = "markdowns"
863
864 schemas = URLBase.schemas(TextNotification)
865 assert isinstance(schemas, set) is True
866 # We didn't define a protocol or secure protocol
867 assert len(schemas) == 0
868
869 # Store our notifications into our schema map
870 N_MGR["text"] = TextNotification
871 N_MGR["html"] = HtmlNotification
872 N_MGR["markdown"] = MarkDownNotification
873
874 schemas = URLBase.schemas(TextNotification)
875 assert isinstance(schemas, set) is True
876 # We didn't define a protocol or secure protocol one
877 # but one got assigned in he above N_MGR call
878 assert len(schemas) == 1
879 assert "text" in schemas
880
881 schemas = URLBase.schemas(HtmlNotification)
882 assert isinstance(schemas, set) is True
883 assert len(schemas) == 4
884 assert "html" in schemas
885 assert "htm" in schemas
886 assert "htmls" in schemas
887 assert "htms" in schemas
888
889 # Invalid entries do not disrupt schema calls
890 for garbage in (object(), None, 42):
891 schemas = URLBase.schemas(garbage)
892 assert isinstance(schemas, set) is True
893 assert len(schemas) == 0
894
895
896 def test_apprise_urlbase_object():
897 """
898 API: Apprise() URLBase object testing
899
900 """
901 results = URLBase.parse_url("https://localhost/path/?cto=3.0&verify=no")
902 assert results.get("user") is None
903 assert results.get("password") is None
904 assert results.get("path") == "/path/"
905 assert results.get("secure") is True
906 assert results.get("verify") is False
907 base = URLBase(**results)
908 assert base.request_timeout == (3.0, 4.0)
909 assert base.request_auth is None
910 assert base.request_url == "https://localhost/path/"
911 assert base.url().startswith("https://localhost/")
912
913 results = URLBase.parse_url(
914 "http://user:pass@localhost:34/path/here?rto=3.0&verify=yes"
915 )
916 assert results.get("user") == "user"
917 assert results.get("password") == "pass"
918 assert results.get("fullpath") == "/path/here"
919 assert results.get("secure") is False
920 assert results.get("verify") is True
921 base = URLBase(**results)
922 assert base.request_timeout == (4.0, 3.0)
923 assert base.request_auth == ("user", "pass")
924 assert base.request_url == "http://localhost:34/path/here"
925 assert base.url().startswith("http://user:pass@localhost:34/path/here")
926
927 results = URLBase.parse_url("http://[email protected]/path/")
928 assert results.get("user") == "user"
929 assert results.get("password") is None
930 assert results.get("fullpath") == "/path/"
931 assert results.get("secure") is False
932 assert results.get("verify") is True
933 base = URLBase(**results)
934 assert base.request_timeout == (4.0, 4.0)
935 assert base.request_auth == ("user", None)
936 assert base.request_url == "http://127.0.0.1/path/"
937 assert base.url().startswith("http://[email protected]/path/")
938
939 # redirect= defaults to True (follows redirects, matching requests default)
940 results = URLBase.parse_url("https://localhost/path/?redirect=yes")
941 assert results.get("redirect") is True
942 base = URLBase(**results)
943 assert base.redirects is True
944 # redirect=yes is the default, so it must not appear in url() output
945 assert "redirect" not in base.url()
946
947 # redirect=no disables redirect following and round-trips in the URL
948 results = URLBase.parse_url(
949 "http://user:pass@localhost:34/path/here?redirect=no"
950 )
951 assert results.get("redirect") is False
952 base = URLBase(**results)
953 assert base.redirects is False
954 assert "redirect=no" in base.url()
955
956 # redirect is absent from results when not specified -- URLBase inherits
957 # the global default from the asset (default asset has http_redirects=True)
958 results = URLBase.parse_url("http://[email protected]/path/")
959 assert "redirect" not in results
960 base = URLBase(**results)
961 assert base.redirects is True
962 assert "redirect" not in base.url()
963
964 # AppriseAsset(http_redirects=False) flows through to every plugin when the
965 # URL does not specify redirect=
966 from apprise import AppriseAsset
967
968 asset_no_redirect = AppriseAsset(http_redirects=False)
969 results = URLBase.parse_url("http://[email protected]/path/")
970 assert "redirect" not in results
971 base = URLBase(**results, asset=asset_no_redirect)
972 assert base.redirects is False # inherited the asset global
973 # redirects matches the asset default -- no override to serialise
974 assert "redirect" not in base.url()
975
976 # URL-level redirect=yes overrides asset http_redirects=False; the
977 # override must be preserved in url() so the round-trip is idempotent
978 results = URLBase.parse_url("http://[email protected]/path/?redirect=yes")
979 assert results.get("redirect") is True
980 base = URLBase(**results, asset=asset_no_redirect)
981 assert base.redirects is True # URL wins over asset
982 assert "redirect=yes" in base.url() # differs from asset default, emitted
983
984 # YAML config path: redirect= provided in the results dict directly
985 # (not via qsd) -- exercises the elif "redirect" in results branch in
986 # post_process_parse_url_results()
987 results = URLBase.parse_url("http://[email protected]/path/")
988 assert "redirect" not in results
989 results["redirect"] = "no"
990 URLBase.post_process_parse_url_results(results)
991 assert results.get("redirect") is False
992
993 results["redirect"] = "yes"
994 URLBase.post_process_parse_url_results(results)
995 assert results.get("redirect") is True
996
997 # URL_TOKEN_ALIASES: 'pass' in top-level results is normalized to
998 # 'password' by post_process_parse_url_results (covers the YAML config
999 # path where a flat dict is passed rather than a parsed URL string)
1000 results = URLBase.parse_url("http://[email protected]/path/")
1001 results["pass"] = "secret"
1002 URLBase.post_process_parse_url_results(results)
1003 assert results.get("password") == "secret"
1004 assert "pass" not in results
1005
1006 # URL_TOKEN_ALIASES: canonical 'password' wins when already set to a
1007 # real value -- 'pass' in top-level results must not overwrite an
1008 # explicitly provided URL-path password; a WARNING is logged so the
1009 # operator knows the alias was present but dropped (no values logged)
1010 results = URLBase.parse_url("http://user:[email protected]/path/")
1011 results["pass"] = "shouldnotwin"
1012 with mock.patch("apprise.url.logger") as mock_log:
1013 URLBase.post_process_parse_url_results(results)
1014 mock_log.warning.assert_called_once()
1015 call_args = mock_log.warning.call_args[0]
1016 # alias and canonical key names appear; actual values must not
1017 assert "pass" in call_args[1]
1018 assert "password" in call_args[2]
1019 assert results.get("password") == "realpass"
1020 assert "pass" not in results
1021
1022 # URL_TOKEN_ALIASES: qsd 'pass=' overrides the URL-path password because
1023 # query-string parameters always take the highest priority
1024 results = URLBase.parse_url(
1025 "http://user:[email protected]/path/?pass=realpass"
1026 )
1027 URLBase.post_process_parse_url_results(results)
1028 assert results.get("password") == "realpass"
1029 assert "pass" not in results
1030
1031 # URL_TOKEN_ALIASES: 'pass' in qsd is also normalized to 'password'
1032 results = URLBase.parse_url("http://[email protected]/path/?pass=qsecret")
1033 URLBase.post_process_parse_url_results(results)
1034 assert results.get("password") == "qsecret"
1035
1036 # Generic initialization
1037 base = URLBase(**{"schema": ""})
1038 assert base.request_timeout == (4.0, 4.0)
1039 assert base.request_auth is None
1040 assert base.request_url == "http:///"
1041 assert base.url().startswith("http:///")
1042
1043 base = URLBase()
1044 assert base.request_timeout == (4.0, 4.0)
1045 assert base.request_auth is None
1046 assert base.request_url == "http:///"
1047 assert base.url().startswith("http:///")
1048
1049 # URLBase.__len__ defaults to 1; subclasses that support multiple
1050 # targets override this to return the actual count.
1051 assert len(base) == 1
1052
1053 # Invalid asset type -- a non-AppriseAsset value must be silently ignored
1054 # and a debug log must tell the caller what happened. The instance must
1055 # still receive a valid default AppriseAsset so nothing downstream breaks.
1056 with mock.patch("apprise.url.logger") as mock_log:
1057 base = URLBase(asset="not-an-asset")
1058 mock_log.debug.assert_called_once()
1059 call_args = mock_log.debug.call_args[0]
1060 # The type name appears in the message so the caller can identify it
1061 assert "str" in call_args[1]
1062
1063 assert isinstance(base.asset, AppriseAsset)
1064
1065
1066 def test_apprise_unique_id():
1067 """
1068 API: Apprise() Input Formats tests
1069
1070 """
1071
1072 # Default testing
1073 obj1 = Apprise.instantiate("json://[email protected]/path")
1074 obj2 = Apprise.instantiate("json://[email protected]/path/?arg=")
1075
1076 assert obj1.url_identifier == obj2.url_identifier
1077 assert obj1.url_id() == obj2.url_id()
1078 # Second call leverages lazy reference (so it's much faster
1079 assert obj1.url_id() == obj2.url_id()
1080 # Disable Lazy Setting
1081 assert obj1.url_id(lazy=False) == obj2.url_id(lazy=False)
1082
1083 # A variation such as providing a password or altering the path makes the
1084 # url_id() different:
1085 obj2 = Apprise.instantiate("json://[email protected]/path2/?arg=") # path
1086 assert obj1.url_id() != obj2.url_id()
1087 obj2 = Apprise.instantiate(
1088 "jsons://[email protected]/path/?arg="
1089 ) # secure flag
1090 assert obj1.url_id() != obj2.url_id()
1091 obj2 = Apprise.instantiate("json://[email protected]/path/?arg=") # user
1092 assert obj1.url_id() != obj2.url_id()
1093 obj2 = Apprise.instantiate("json://[email protected]:8080/path/?arg=") # port
1094 assert obj1.url_id() != obj2.url_id()
1095 obj2 = Apprise.instantiate(
1096 "json://user:[email protected]/path/?arg="
1097 ) # password
1098 assert obj1.url_id() != obj2.url_id()
1099
1100 # Leverage salt setting
1101 asset = AppriseAsset(storage_salt="abcd")
1102
1103 obj2 = Apprise.instantiate("json://[email protected]/path/", asset=asset)
1104 assert obj1.url_id(lazy=False) != obj2.url_id(lazy=False)
1105
1106 asset = AppriseAsset(storage_salt=b"abcd")
1107 # same salt value produces a match again
1108 obj1 = Apprise.instantiate("json://[email protected]/path/", asset=asset)
1109 assert obj1.url_id() == obj2.url_id()
1110
1111 # We'll add a good notification to our list
1112 class TesNoURLID(NotifyBase):
1113 """This class is just sets a use case where we don't return a
1114 url_identifier."""
1115
1116 # we'll use this as a key to make our service easier to find
1117 # in the next part of the testing
1118 service_name = "nourl"
1119
1120 _url_identifier = False
1121
1122 def send(self, **kwargs):
1123 # Pretend everything is okay (so we don't break other tests)
1124 return True
1125
1126 @staticmethod
1127 def parse_url(url):
1128 return NotifyBase.parse_url(url, verify_host=False)
1129
1130 @property
1131 def url_identifier(self):
1132 """No URL Identifier."""
1133 return self._url_identifier
1134
1135 N_MGR["nourl"] = TesNoURLID
1136
1137 # setting URL Identifier to False disables the generator
1138 url = "nourl://"
1139 obj = Apprise.instantiate(url)
1140 # No generation takes place
1141 assert obj.url_id() is None
1142
1143 #
1144 # Dictionary Testing
1145 #
1146 obj._url_identifier = {
1147 "abc": "123",
1148 "def": b"\0",
1149 "hij": 42,
1150 "klm": object,
1151 }
1152 # call uses cached value (from above)
1153 assert obj.url_id() is None
1154 # Tests dictionary key generation
1155 assert obj.url_id(lazy=False) is not None
1156
1157 # List/Set/Tuple Testing
1158 #
1159 obj1 = Apprise.instantiate(url)
1160 obj1._url_identifier = ["123", b"\0", 42, object]
1161 # Tests dictionary key generation
1162 assert obj1.url_id() is not None
1163
1164 obj2 = Apprise.instantiate(url)
1165 obj2._url_identifier = ("123", b"\0", 42, object)
1166 assert obj2.url_id() is not None
1167 assert obj1.url_id() == obj2.url_id()
1168
1169 obj3 = Apprise.instantiate(url)
1170 obj3._url_identifier = {"123", b"\0", 42, object}
1171 assert obj3.url_id() is not None
1172
1173 obj = Apprise.instantiate(url)
1174 obj._url_identifier = b"test"
1175 assert obj.url_id() is not None
1176
1177 obj = Apprise.instantiate(url)
1178 obj._url_identifier = "test"
1179 assert obj.url_id() is not None
1180
1181 # Testing Garbage
1182 for x in (31, object, 43.1):
1183 obj = Apprise.instantiate(url)
1184 obj._url_identifier = x
1185 assert obj.url_id() is not None
1186
1187
1188 def test_apprise_notify_formats():
1189 """
1190 API: Apprise() Input Formats tests
1191
1192 """
1193 # Need to set async_mode=False to call notify() instead of async_notify().
1194 asset = AppriseAsset(async_mode=False)
1195
1196 a = Apprise(asset=asset)
1197
1198 # no items
1199 assert len(a) == 0
1200
1201 class TextNotification(NotifyBase):
1202 # set our default notification format
1203 notify_format = NotifyFormat.TEXT
1204
1205 def __init__(self, **kwargs):
1206 super().__init__(**kwargs)
1207
1208 def notify(self, **kwargs):
1209 # Pretend everything is okay
1210 return True
1211
1212 class HtmlNotification(NotifyBase):
1213 # set our default notification format
1214 notify_format = NotifyFormat.HTML
1215
1216 def __init__(self, **kwargs):
1217 super().__init__(**kwargs)
1218
1219 def notify(self, **kwargs):
1220 # Pretend everything is okay
1221 return True
1222
1223 class MarkDownNotification(NotifyBase):
1224 # set our default notification format
1225 notify_format = NotifyFormat.MARKDOWN
1226
1227 def __init__(self, **kwargs):
1228 super().__init__(**kwargs)
1229
1230 def notify(self, **kwargs):
1231 # Pretend everything is okay
1232 return True
1233
1234 # Store our notifications into our schema map
1235 N_MGR["text"] = TextNotification
1236 N_MGR["html"] = HtmlNotification
1237 N_MGR["markdown"] = MarkDownNotification
1238
1239 # Test Markdown; the above calls the markdown because our good://
1240 # defined plugin above was defined to default to HTML which triggers
1241 # a markdown to take place if the body_format specified on the notify
1242 # call
1243 assert a.add("html://localhost") is True
1244 assert a.add("html://another.server") is True
1245 assert a.add("html://and.another") is True
1246 assert a.add("text://localhost") is True
1247 assert a.add("text://another.server") is True
1248 assert a.add("text://and.another") is True
1249 assert a.add("markdown://localhost") is True
1250 assert a.add("markdown://another.server") is True
1251 assert a.add("markdown://and.another") is True
1252
1253 assert len(a) == 9
1254
1255 assert (
1256 a.notify(
1257 title="markdown",
1258 body="## Testing Markdown",
1259 body_format=NotifyFormat.MARKDOWN,
1260 )
1261 is True
1262 )
1263
1264 assert (
1265 a.notify(
1266 title="text", body="Testing Text", body_format=NotifyFormat.TEXT
1267 )
1268 is True
1269 )
1270
1271 assert (
1272 a.notify(
1273 title="html", body="<b>HTML</b>", body_format=NotifyFormat.HTML
1274 )
1275 is True
1276 )
1277
1278
1279 def test_apprise_asset(tmpdir):
1280 """
1281 API: AppriseAsset() object
1282
1283 """
1284 a = AppriseAsset(theme="light")
1285 # Default theme
1286 assert a.theme == "light"
1287
1288 # Invalid kw handling
1289 with pytest.raises(AttributeError):
1290 AppriseAsset(invalid_kw="value")
1291
1292 a = AppriseAsset(
1293 theme="dark",
1294 image_path_mask="/{THEME}/{TYPE}-{XY}{EXTENSION}",
1295 image_url_mask="http://localhost/{THEME}/{TYPE}-{XY}{EXTENSION}",
1296 )
1297
1298 a.default_html_color = "#abcabc"
1299
1300 assert a.color("invalid", tuple) == (171, 202, 188)
1301 assert a.color(NotifyType.INFO, tuple) == (58, 163, 227)
1302
1303 assert a.color("invalid", int) == 11258556
1304 assert a.color(NotifyType.INFO, int) == 3843043
1305
1306 assert a.color("invalid", None) == "#abcabc"
1307 assert a.color(NotifyType.INFO, None) == "#3AA3E3"
1308 # None is the default
1309 assert a.color(NotifyType.INFO) == "#3AA3E3"
1310
1311 # Invalid Type
1312 with pytest.raises(ValueError):
1313 # The exception we expect since dict is not supported
1314 a.color(NotifyType.INFO, dict)
1315
1316 # Test our ASCII mappings
1317 assert a.ascii("invalid") == "[?]"
1318 assert a.ascii(NotifyType.INFO) == "[i]"
1319 assert a.ascii(NotifyType.SUCCESS) == "[+]"
1320 assert a.ascii(NotifyType.WARNING) == "[~]"
1321 assert a.ascii(NotifyType.FAILURE) == "[!]"
1322
1323 # Invalid Type
1324 with pytest.raises(ValueError):
1325 # The exception we expect since dict is not supported
1326 a.color(NotifyType.INFO, dict)
1327
1328 assert (
1329 a.image_url(NotifyType.INFO, NotifyImageSize.XY_128)
1330 == "http://localhost/dark/info-128x128.png"
1331 )
1332
1333 # Default image size
1334 assert (
1335 a.image_url(NotifyType.INFO)
1336 == "http://localhost/dark/info-256x256.png"
1337 )
1338
1339 assert (
1340 a.image_path(NotifyType.INFO, NotifyImageSize.XY_256, must_exist=False)
1341 == "/dark/info-256x256.png"
1342 )
1343
1344 # This path doesn't exist so image_raw will fail (since we just
1345 # randompyl picked it for testing)
1346 assert a.image_raw(NotifyType.INFO, NotifyImageSize.XY_256) is None
1347
1348 assert (
1349 a.image_path(NotifyType.INFO, NotifyImageSize.XY_256, must_exist=True)
1350 is None
1351 )
1352
1353 # Create a new object (with our default settings)
1354 a = AppriseAsset()
1355
1356 # Our default configuration can access our file
1357 assert (
1358 a.image_path(NotifyType.INFO, NotifyImageSize.XY_256, must_exist=True)
1359 is not None
1360 )
1361
1362 assert a.image_raw(NotifyType.INFO, NotifyImageSize.XY_256) is not None
1363
1364 # Create a temporary directory
1365 sub = tmpdir.mkdir("great.theme")
1366
1367 # Write a file
1368 sub.join(
1369 f"{NotifyType.INFO.value}-{NotifyImageSize.XY_256.value}.png"
1370 ).write("the content doesn't matter for testing.")
1371
1372 # Create an asset that will reference our file we just created
1373 a = AppriseAsset(
1374 theme="great.theme",
1375 image_path_mask=(
1376 f"{dirname(sub.strpath)}/{{THEME}}/{{TYPE}}-{{XY}}.png"
1377 ),
1378 )
1379
1380 # We'll be able to read file we just created
1381 assert a.image_raw(NotifyType.INFO, NotifyImageSize.XY_256) is not None
1382
1383 # We can retrieve the filename at this point even with must_exist set
1384 # to True
1385 assert (
1386 a.image_path(NotifyType.INFO, NotifyImageSize.XY_256, must_exist=True)
1387 is not None
1388 )
1389
1390 # Test case where we can't access the image file
1391 with mock.patch("builtins.open", side_effect=OSError()):
1392 assert a.image_raw(NotifyType.INFO, NotifyImageSize.XY_256) is None
1393
1394 # Our content is retrivable again
1395 assert a.image_raw(NotifyType.INFO, NotifyImageSize.XY_256) is not None
1396
1397 # Disable all image references
1398 a = AppriseAsset(image_path_mask=False, image_url_mask=False)
1399
1400 # We always return none in these calls now
1401 assert a.image_raw(NotifyType.INFO, NotifyImageSize.XY_256) is None
1402 assert a.image_url(NotifyType.INFO, NotifyImageSize.XY_256) is None
1403 assert (
1404 a.image_path(NotifyType.INFO, NotifyImageSize.XY_256, must_exist=False)
1405 is None
1406 )
1407 assert (
1408 a.image_path(NotifyType.INFO, NotifyImageSize.XY_256, must_exist=True)
1409 is None
1410 )
1411
1412 # Test our default extension out
1413 a = AppriseAsset(
1414 image_path_mask="/{THEME}/{TYPE}-{XY}{EXTENSION}",
1415 image_url_mask="http://localhost/{THEME}/{TYPE}-{XY}{EXTENSION}",
1416 default_extension=".jpeg",
1417 )
1418 assert (
1419 a.image_path(NotifyType.INFO, NotifyImageSize.XY_256, must_exist=False)
1420 == "/default/info-256x256.jpeg"
1421 )
1422
1423 assert (
1424 a.image_url(NotifyType.INFO, NotifyImageSize.XY_256)
1425 == "http://localhost/default/info-256x256.jpeg"
1426 )
1427
1428 # extension support
1429 assert (
1430 a.image_path(
1431 NotifyType.INFO,
1432 NotifyImageSize.XY_128,
1433 must_exist=False,
1434 extension=".ico",
1435 )
1436 == "/default/info-128x128.ico"
1437 )
1438
1439 assert (
1440 a.image_url(NotifyType.INFO, NotifyImageSize.XY_256, extension=".test")
1441 == "http://localhost/default/info-256x256.test"
1442 )
1443
1444 a = AppriseAsset(plugin_paths=("/tmp",))
1445 assert a.plugin_paths == ("/tmp",)
1446
1447
1448 def test_apprise_disabled_plugins():
1449 """
1450 API: Apprise() Disabled Plugin States
1451
1452 """
1453 # Ensure there are no other drives loaded
1454 N_MGR.unload_modules(disable_native=True)
1455 assert len(N_MGR) == 0
1456
1457 class TestDisabled01Notification(NotifyBase):
1458 """This class is used to test a pre-disabled state."""
1459
1460 # Just flat out disable our service
1461 enabled = False
1462
1463 # we'll use this as a key to make our service easier to find
1464 # in the next part of the testing
1465 service_name = "na01"
1466
1467 def notify(self, **kwargs):
1468 # Pretend everything is okay (so we don't break other tests)
1469 return True
1470
1471 N_MGR["na01"] = TestDisabled01Notification
1472
1473 class TestDisabled02Notification(NotifyBase):
1474 """This class is used to test a post-disabled state."""
1475
1476 # we'll use this as a key to make our service easier to find
1477 # in the next part of the testing
1478 service_name = "na02"
1479
1480 def __init__(self, *args, **kwargs):
1481 super().__init__(**kwargs)
1482
1483 # enable state changes **AFTER** we initialize
1484 self.enabled = False
1485
1486 def notify(self, **kwargs):
1487 # Pretend everything is okay (so we don't break other tests)
1488 return True
1489
1490 N_MGR["na02"] = TestDisabled02Notification
1491
1492 # Create our Apprise instance
1493 a = Apprise()
1494
1495 result = a.details(lang="ca-en", show_disabled=True)
1496 assert isinstance(result, dict)
1497 assert "schemas" in result
1498 assert len(result["schemas"]) == 2
1499
1500 # our na01 is disabled right from the get-go
1501 entry = next(
1502 (x for x in result["schemas"] if x["service_name"] == "na01"), None
1503 )
1504 assert entry is not None
1505 assert entry["enabled"] is False
1506
1507 plugin = a.instantiate("na01://localhost")
1508 # Object is just flat out disabled... nothing is instatiated
1509 assert plugin is None
1510
1511 # our na02 isn't however until it's initialized; as a result
1512 # it get's returned in our result set
1513 entry = next(
1514 (x for x in result["schemas"] if x["service_name"] == "na02"), None
1515 )
1516 assert entry is not None
1517 assert entry["enabled"] is True
1518
1519 plugin = a.instantiate("na02://localhost")
1520 # Object isn't disabled until the __init__() call. But this is still
1521 # enough to not instantiate the object:
1522 assert plugin is None
1523
1524 # If we choose to filter our disabled, we can't unfortunately filter those
1525 # that go disabled after instantiation, but we do filter out any that are
1526 # already known to not be enabled:
1527 result = a.details(lang="ca-en", show_disabled=False)
1528 assert isinstance(result, dict)
1529 assert "schemas" in result
1530 assert len(result["schemas"]) == 1
1531
1532 # We'll add a good notification to our list
1533 class TesEnabled01Notification(NotifyBase):
1534 """This class is just a simple enabled one."""
1535
1536 # we'll use this as a key to make our service easier to find
1537 # in the next part of the testing
1538 service_name = "good"
1539
1540 def send(self, **kwargs):
1541 # Pretend everything is okay (so we don't break other tests)
1542 return True
1543
1544 N_MGR["good"] = TesEnabled01Notification
1545
1546 # The last thing we'll simulate is a case where the plugin is just
1547 # disabled at a later time long into it's life. this is just to allow
1548 # administrators to stop the flow of their notifications for their own
1549 # given reasons.
1550 plugin = a.instantiate("good://localhost")
1551 assert isinstance(plugin, NotifyBase)
1552
1553 # we'll toggle our state
1554 plugin.enabled = False
1555
1556 # As a result, we can now no longer send a notification:
1557 assert plugin.notify("My Message") is False
1558
1559 # As just a proof of how you can toggle the state back:
1560 plugin.enabled = True
1561
1562 # our notifications will go okay now
1563 assert plugin.notify("My Message") is True
1564
1565 # Restore our modules
1566 N_MGR.unload_modules()
1567
1568
1569 def test_apprise_details():
1570 """
1571 API: Apprise() Details
1572
1573 """
1574
1575 # This is a made up class that is just used to verify
1576 class TestDetailNotification(NotifyBase):
1577 """This class is used to test various configurations supported."""
1578
1579 # Minimum requirements for a plugin to produce details
1580 service_name = "Detail Testing"
1581
1582 # The default simple (insecure) protocol (used by NotifyMail)
1583 protocol = "details"
1584
1585 # Set test_bool flag
1586 always_true = True
1587 always_false = False
1588
1589 # Define object templates
1590 templates = (
1591 "{schema}://{host}",
1592 "{schema}://{host}:{port}",
1593 "{schema}://{user}@{host}:{port}",
1594 "{schema}://{user}:{pass}@{host}:{port}",
1595 )
1596
1597 # Define our tokens; these are the minimum tokens required required to
1598 # be passed into this function (as arguments). The syntax appends any
1599 # previously defined in the base package and builds onto them
1600 template_tokens = dict(
1601 NotifyBase.template_tokens,
1602 **{
1603 "notype": {
1604 # name is a minimum requirement
1605 "name": _("no type"),
1606 },
1607 "regex_test01": {
1608 "name": _("RegexTest"),
1609 "type": "string",
1610 "regex": r"^[A-Z0-9]$",
1611 },
1612 "regex_test02": {
1613 "name": _("RegexTest"),
1614 # Support regex options too
1615 "regex": (r"^[A-Z0-9]$", "i"),
1616 },
1617 "regex_test03": {
1618 "name": _("RegexTest"),
1619 # Support regex option without a second option
1620 "regex": r"^[A-Z0-9]$",
1621 },
1622 "regex_test04": {
1623 # this entry would just end up getting removed
1624 "regex": None,
1625 },
1626 # List without delimiters (causes defaults to kick in)
1627 "mylistA": {
1628 "name": "fruit",
1629 "type": "list:string",
1630 },
1631 # A list with a delimiter list
1632 "mylistB": {
1633 "name": "softdrinks",
1634 "type": "list:string",
1635 "delim": ["|", "-"],
1636 },
1637 },
1638 )
1639
1640 template_args = dict(
1641 NotifyBase.template_args,
1642 **{
1643 # Test _exist_if logic
1644 "test_exists_if_01": {
1645 "name": "Always False",
1646 "type": "bool",
1647 # Provide a default
1648 "default": False,
1649 # Base the existance of this key/value entry on the lookup
1650 # of this class value at runtime. Hence:
1651 # if not NotifyObject.always_false
1652 # del this_entry
1653 #
1654 "_exists_if": "always_false",
1655 },
1656 # Test _exist_if logic
1657 "test_exists_if_02": {
1658 "name": "Always True",
1659 "type": "bool",
1660 # Provide a default
1661 "default": False,
1662 # Base the existance of this key/value entry on the lookup
1663 # of this class value at runtime. Hence:
1664 # if not NotifyObject.always_true
1665 # del this_entry
1666 #
1667 "_exists_if": "always_true",
1668 },
1669 # alias_of testing
1670 "test_alias_of": {"alias_of": "mylistB", "delim": ("-", " ")},
1671 },
1672 )
1673
1674 def send(self, **kwargs):
1675 # Pretend everything is okay (so we don't break other tests)
1676 return True
1677
1678 # Store our good detail notification in our schema map
1679 N_MGR["details"] = TestDetailNotification
1680
1681 # This is a made up class that is just used to verify
1682 class TestReq01Notification(NotifyBase):
1683 """This class is used to test various requirement configurations."""
1684
1685 # Set some requirements
1686 requirements: ClassVar[RequirementsSpec] = {
1687 "packages_required": [
1688 "cryptography <= 3.4",
1689 "ultrasync",
1690 ],
1691 "packages_recommended": "django",
1692 }
1693
1694 def send(self, **kwargs):
1695 # Pretend everything is okay (so we don't break other tests)
1696 return True
1697
1698 N_MGR["req01"] = TestReq01Notification
1699
1700 # This is a made up class that is just used to verify
1701 class TestReq02Notification(NotifyBase):
1702 """This class is used to test various requirement configurations."""
1703
1704 # Just not enabled at all
1705 enabled = False
1706
1707 # Set some requirements
1708 requirements: ClassVar[RequirementsSpec] = {
1709 # None and/or [] is implied, but jsut to show that the code won't
1710 # crash if explicitly set this way:
1711 "packages_required": None,
1712 "packages_recommended": [
1713 "cryptography <= 3.4",
1714 ],
1715 }
1716
1717 def send(self, **kwargs):
1718 # Pretend everything is okay (so we don't break other tests)
1719 return True
1720
1721 N_MGR["req02"] = TestReq02Notification
1722
1723 # This is a made up class that is just used to verify
1724 class TestReq03Notification(NotifyBase):
1725 """This class is used to test various requirement configurations."""
1726
1727 # Set some requirements
1728 requirements: ClassVar[RequirementsSpec] = {
1729 # We can over-ride the default details assigned to our plugin if
1730 # specified
1731 "details": _("some specified requirement details"),
1732 # We can set a string value as well (it does not have to be a list)
1733 "packages_recommended": "cryptography <= 3.4",
1734 }
1735
1736 def send(self, **kwargs):
1737 # Pretend everything is okay (so we don't break other tests)
1738 return True
1739
1740 N_MGR["req03"] = TestReq03Notification
1741
1742 # This is a made up class that is just used to verify
1743 class TestReq04Notification(NotifyBase):
1744 """This class is used to test a case where our requirements is fixed to
1745 a None."""
1746
1747 # This is the same as saying there are no requirements
1748 requirements = None
1749
1750 def send(self, **kwargs):
1751 # Pretend everything is okay (so we don't break other tests)
1752 return True
1753
1754 N_MGR["req04"] = TestReq04Notification
1755
1756 # This is a made up class that is just used to verify
1757 class TestReq05Notification(NotifyBase):
1758 """This class is used to test a case where only packages_recommended is
1759 identified."""
1760
1761 requirements: ClassVar[RequirementsSpec] = {
1762 # We can set a string value as well (it does not have to be a list)
1763 "packages_recommended": "cryptography <= 3.4"
1764 }
1765
1766 def send(self, **kwargs):
1767 # Pretend everything is okay (so we don't break other tests)
1768 return True
1769
1770 N_MGR["req05"] = TestReq05Notification
1771
1772 # Create our Apprise instance
1773 a = Apprise()
1774
1775 # Dictionary response
1776 result = a.details()
1777 assert isinstance(result, dict)
1778
1779 # Test different variations of our call
1780 result = a.details(lang="ca-fr")
1781 assert isinstance(result, dict)
1782 for entry in result["schemas"]:
1783 # Verify our key does not exist because we did not ask for it
1784 assert "enabled" not in entry
1785 assert "requirements" not in entry
1786
1787 result = a.details(lang="us-en", show_requirements=True)
1788 assert isinstance(result, dict)
1789 for entry in result["schemas"]:
1790 # Verify our key does not exist because we did not ask for it
1791 assert "enabled" not in entry
1792
1793 # Requirements are set for display
1794 assert "requirements" in entry
1795 assert "details" in entry["requirements"]
1796 assert "packages_required" in entry["requirements"]
1797 assert "packages_recommended" in entry["requirements"]
1798 assert isinstance(
1799 entry["requirements"]["details"], (str, LazyTranslation)
1800 )
1801 assert isinstance(entry["requirements"]["packages_required"], list)
1802 assert isinstance(entry["requirements"]["packages_recommended"], list)
1803
1804 result = a.details(lang="ca-en", show_disabled=True)
1805 assert isinstance(result, dict)
1806 for entry in result["schemas"]:
1807 # Verify that our plugin state is available to us
1808 assert "enabled" in entry
1809 assert isinstance(entry["enabled"], bool)
1810
1811 # Verify our key does not exist because we did not ask for it
1812 assert "requirements" not in entry
1813
1814 result = a.details(
1815 lang="ca-fr", show_requirements=True, show_disabled=True
1816 )
1817 assert isinstance(result, dict)
1818 for entry in result["schemas"]:
1819 # Plugin States are set for display
1820 assert "enabled" in entry
1821 assert isinstance(entry["enabled"], bool)
1822
1823 # Requirements are set for display
1824 assert "requirements" in entry
1825 assert "details" in entry["requirements"]
1826 assert "packages_required" in entry["requirements"]
1827 assert "packages_recommended" in entry["requirements"]
1828 assert isinstance(
1829 entry["requirements"]["details"], (str, LazyTranslation)
1830 )
1831 assert isinstance(entry["requirements"]["packages_required"], list)
1832 assert isinstance(entry["requirements"]["packages_recommended"], list)
1833
1834
1835 def test_apprise_details_plugin_verification():
1836 """
1837 API: Apprise() Details Plugin Verification
1838
1839 """
1840 # Prepare our object
1841 a = Apprise()
1842
1843 # Details object
1844 details = a.details()
1845
1846 # Dictionary response
1847 assert isinstance(details, dict)
1848
1849 # Details object with language defined:
1850 details = a.details(lang="en")
1851
1852 # Dictionary response
1853 assert isinstance(details, dict)
1854
1855 # Details object with unsupported language:
1856 details = a.details(lang="xx")
1857
1858 # Dictionary response
1859 assert isinstance(details, dict)
1860
1861 # Apprise version
1862 assert "version" in details
1863 assert details.get("version") == __version__
1864
1865 # Defined schemas identify each plugin
1866 assert "schemas" in details
1867 assert isinstance(details.get("schemas"), list)
1868
1869 # We have an entry per defined plugin
1870 assert "asset" in details
1871 assert isinstance(details.get("asset"), dict)
1872 assert "app_id" in details["asset"]
1873 assert "app_desc" in details["asset"]
1874 assert "default_extension" in details["asset"]
1875 assert "theme" in details["asset"]
1876 assert "image_path_mask" in details["asset"]
1877 assert "image_url_mask" in details["asset"]
1878 assert "image_url_logo" in details["asset"]
1879
1880 # Valid Type Regular Expression Checker
1881 # Case Sensitive and MUST match the following:
1882 is_valid_type_re = re.compile(r"((choice|list):)?(string|bool|int|float)")
1883
1884 # match tokens found in templates so we can cross reference them back
1885 # to see if they have a matching argument
1886 template_token_re = re.compile(r"{([^}]+)}[^{]*?(?=$|{)")
1887
1888 # Define acceptable map_to arguments that can be tied in with the
1889 # kwargs function definitions.
1890 valid_kwargs = {
1891 # General Parameters
1892 "user",
1893 "password",
1894 "port",
1895 "host",
1896 "schema",
1897 "fullpath",
1898 # NotifyBase parameters:
1899 "tz",
1900 "format",
1901 "overflow",
1902 "emojis",
1903 "retry",
1904 "wait",
1905 "optional",
1906 # URLBase parameters:
1907 "verify",
1908 "redirect",
1909 "cto",
1910 "rto",
1911 "store",
1912 }
1913
1914 # Valid Schema Entries:
1915 valid_schema_keys = (
1916 "name",
1917 "private",
1918 "required",
1919 "type",
1920 "values",
1921 "min",
1922 "max",
1923 "regex",
1924 "default",
1925 "list",
1926 "delim",
1927 "prefix",
1928 "map_to",
1929 "alias_of",
1930 "group",
1931 )
1932 for entry in details["schemas"]:
1933 # Track the map_to entries (if specified); We need to make sure that
1934 # these properly map back
1935 map_to_entries = set()
1936
1937 # Track the alias_of entries
1938 map_to_aliases = set()
1939
1940 # A Service Name MUST be defined
1941 assert "service_name" in entry
1942 assert isinstance(entry["service_name"], (str, LazyTranslation))
1943
1944 # Acquire our protocols
1945 protocols = parse_list(entry["protocols"], entry["secure_protocols"])
1946
1947 # At least one schema/protocol MUST be defined
1948 assert len(protocols) > 0
1949
1950 # our details
1951 assert "details" in entry
1952 assert isinstance(entry["details"], dict)
1953
1954 # All schema details should include args
1955 for section in ["kwargs", "args", "tokens"]:
1956 assert section in entry["details"]
1957 assert isinstance(entry["details"][section], dict)
1958
1959 for key, arg in entry["details"][section].items():
1960 # Validate keys (case-sensitive)
1961 assert len([k for k in arg if k not in valid_schema_keys]) == 0
1962
1963 # Test our argument
1964 assert isinstance(arg, dict)
1965
1966 if "alias_of" not in arg:
1967 # Minimum requirement of an argument
1968 assert "name" in arg
1969 assert isinstance(arg["name"], str)
1970
1971 assert "type" in arg
1972 assert isinstance(arg["type"], str)
1973 assert is_valid_type_re.match(arg["type"]) is not None
1974
1975 if "min" in arg:
1976 assert arg["type"].endswith("float") or arg[
1977 "type"
1978 ].endswith("int")
1979 assert isinstance(arg["min"], (int, float))
1980
1981 if "max" in arg:
1982 # If a min and max was specified, at least check
1983 # to confirm the min is less then the max
1984 assert arg["min"] < arg["max"]
1985
1986 if "max" in arg:
1987 assert arg["type"].endswith("float") or arg[
1988 "type"
1989 ].endswith("int")
1990 assert isinstance(arg["max"], (int, float))
1991
1992 if "private" in arg:
1993 assert isinstance(arg["private"], bool)
1994
1995 if "required" in arg:
1996 assert isinstance(arg["required"], bool)
1997
1998 if "prefix" in arg:
1999 assert isinstance(arg["prefix"], str)
2000 if section == "kwargs":
2001 # The only acceptable prefix types for kwargs
2002 assert arg["prefix"] in (":", "+", "-")
2003
2004 else:
2005 # kwargs requires that the 'prefix' is defined
2006 assert section != "kwargs"
2007
2008 if "map_to" in arg:
2009 # must be a string
2010 assert isinstance(arg["map_to"], str)
2011 # Track our map_to object
2012 map_to_entries.add(arg["map_to"])
2013
2014 else:
2015 map_to_entries.add(key)
2016
2017 # Some verification
2018 if arg["type"].startswith("choice"):
2019 # choice:bool is redundant and should be swapped to
2020 # just bool
2021 assert not arg["type"].endswith("bool")
2022
2023 # Choices require that a values list is provided
2024 assert "values" in arg
2025 assert isinstance(
2026 arg["values"], (list, tuple, frozenset, set)
2027 )
2028 assert len(arg["values"]) > 0
2029
2030 # Test default
2031 if "default" in arg:
2032 # if a default is provided on a choice object,
2033 # it better be in the list of values
2034 assert arg["default"] in arg["values"]
2035
2036 if arg["type"].startswith("bool"):
2037 # Boolean choices are less restrictive but require a
2038 # default value
2039 assert "default" in arg
2040 assert isinstance(arg["default"], bool)
2041
2042 if "regex" in arg:
2043 # Regex must ALWAYS be in the format (regex, option)
2044 assert isinstance(arg["regex"], (tuple, list))
2045 assert len(arg["regex"]) == 2
2046 assert isinstance(arg["regex"][0], str)
2047 assert arg["regex"][1] is None or isinstance(
2048 arg["regex"][1], str
2049 )
2050
2051 # Compile the regular expression to verify that it is
2052 # valid
2053 try:
2054 re.compile(arg["regex"][0])
2055
2056 except:
2057 assert "{} is an invalid regex".format(
2058 arg["regex"][0]
2059 )
2060
2061 # Regex should always start and/or end with ^/$
2062 assert (
2063 re.match(r"^\^.+?$", arg["regex"][0]) is not None
2064 )
2065 assert (
2066 re.match(r"^.+?\$$", arg["regex"][0]) is not None
2067 )
2068
2069 if arg["type"].startswith("list"):
2070 # Delimiters MUST be defined
2071 assert "delim" in arg
2072 assert isinstance(arg["delim"], (list, tuple))
2073 assert len(arg["delim"]) > 0
2074
2075 else: # alias_of is in the object
2076 # Ensure we're not already in the tokens section
2077 # The alias_of object has no value here
2078 assert section != "tokens"
2079
2080 # must be a string
2081 assert isinstance(arg["alias_of"], (str, list, tuple, set))
2082
2083 aliases = (
2084 [arg["alias_of"]]
2085 if isinstance(arg["alias_of"], str)
2086 else arg["alias_of"]
2087 )
2088
2089 for alias_of in aliases:
2090 # Track our alias_of object
2091 map_to_aliases.add(alias_of)
2092
2093 # We can't be an alias_of ourselves
2094 if key == alias_of:
2095 # This is acceptable as long as we exist in the
2096 # tokens table because that is truely what we map
2097 # back to
2098 assert key in entry["details"]["tokens"]
2099
2100 else:
2101 # Throw the problem into an assert tag for
2102 # debugging purposes... the mapping is not
2103 # acceptable
2104 assert key != alias_of
2105
2106 # alias_of always references back to tokens
2107 assert (
2108 alias_of in entry["details"]["tokens"]
2109 or alias_of in entry["details"]["args"]
2110 )
2111
2112 # Find a list directive in our tokens
2113 t_match = (
2114 entry["details"]["tokens"]
2115 .get(alias_of, {})
2116 .get("type", "")
2117 .startswith("list")
2118 )
2119
2120 a_match = (
2121 entry["details"]["args"]
2122 .get(alias_of, {})
2123 .get("type", "")
2124 .startswith("list")
2125 )
2126
2127 if not (t_match or a_match):
2128 # Ensure the only token we have is the alias_of
2129 # hence record should look like as example):
2130 # {
2131 # 'token': {
2132 # 'alias_of': 'apitoken',
2133 # },
2134 # }
2135 #
2136 # Or if it can represent more then one entry; in
2137 # this case, one must define a name (to define
2138 # grouping).
2139 # {
2140 # 'token': {
2141 # 'name': 'Tokens',
2142 # 'alias_of': ('apitoken', 'webtoken'),
2143 # },
2144 # }
2145 if isinstance(arg["alias_of"], str):
2146 assert len(entry["details"][section][key]) == 1
2147 else: # is tuple,list, or set
2148 assert len(entry["details"][section][key]) == 2
2149 # Must have a name defined to define grouping
2150 assert "name" in entry["details"][section][key]
2151
2152 else:
2153 # We're a list, we allow up to 2 variables
2154 # Obviously we have the alias_of entry; that's why
2155 # were at this part of the code. But we can
2156 # additionally provide a 'delim' over-ride.
2157 assert len(entry["details"][section][key]) <= 2
2158 if len(entry["details"][section][key]) == 2:
2159 # Verify that it is in fact the 'delim' tag
2160 assert (
2161 "delim" in entry["details"][section][key]
2162 )
2163 # If we do have a delim value set, it must be
2164 # of a list/set/tuple type
2165 assert isinstance(
2166 entry["details"][section][key]["delim"],
2167 (tuple, set, list),
2168 )
2169
2170 spec = inspect.getfullargspec(N_MGR._schema_map[protocols[0]].__init__)
2171
2172 function_args = (
2173 (set(parse_list(spec.varkw)) - {"kwargs"})
2174 | (set(spec.args) - {"self"})
2175 | valid_kwargs
2176 )
2177
2178 # Iterate over our map_to_entries and make sure that everything
2179 # maps to a function argument
2180 for arg in map_to_entries:
2181 if arg not in function_args:
2182 # This print statement just makes the error easier to
2183 # troubleshoot
2184 raise AssertionError(
2185 "{}.__init__() expects a {}=None entry according to "
2186 "template configuration".format(
2187 N_MGR._schema_map[protocols[0]].__name__, arg
2188 )
2189 )
2190
2191 # Iterate over all of the function arguments and make sure that
2192 # it maps back to a key
2193 function_args -= valid_kwargs
2194 for arg in function_args:
2195 if arg not in map_to_entries:
2196 err = N_MGR._schema_map[protocols[0]].__name__.__init__(arg)
2197 raise AssertionError(
2198 f"{err} found but not defined in the template "
2199 "configuration"
2200 )
2201
2202 # Iterate over our map_to_aliases and make sure they were defined in
2203 # either the as a token or arg
2204 for arg in map_to_aliases:
2205 assert arg in set(entry["details"]["args"].keys()) | set(
2206 entry["details"]["tokens"].keys()
2207 )
2208
2209 # Template verification
2210 assert "templates" in entry["details"]
2211 assert isinstance(entry["details"]["templates"], (set, tuple, list))
2212
2213 # Iterate over our templates and parse our arguments
2214 for template in entry["details"]["templates"]:
2215 # Ensure we've properly opened and closed all of our tokens
2216 assert template.count("{") == template.count("}")
2217
2218 expected_tokens = template.count("}")
2219 args = template_token_re.findall(template)
2220 assert expected_tokens == len(args)
2221
2222 # Build a cross reference set of our current defined objects
2223 defined_tokens = set()
2224 for key, arg in entry["details"]["tokens"].items():
2225 defined_tokens.add(key)
2226 if "alias_of" in arg:
2227 defined_tokens.add(arg["alias_of"])
2228
2229 # We want to make sure all of our defined tokens have been
2230 # accounted for in at least one defined template
2231 for arg in args:
2232 assert arg in set(entry["details"]["args"].keys()) | set(
2233 entry["details"]["tokens"].keys()
2234 )
2235
2236 # The reverse of the above; make sure that each entry defined
2237 # in the template_tokens is accounted for in at least one of
2238 # the defined templates
2239 assert arg in defined_tokens
2240
2241
2242 def test_apprise_details_plugin_raw_template_tokens():
2243 """
2244 API: Apprise() Raw Template Token Verification
2245
2246 Checks that every plugin's template_tokens and template_args declare
2247 an explicit 'type' field before _sanitize_token can silently back-fill
2248 a default. _sanitize_token adds 'type': 'string' when the field is
2249 missing, so the post-processed details() output always passes -- this
2250 test catches the gap at the source.
2251 """
2252
2253 # Valid Type Regular Expression Checker -- mirrors the one used by
2254 # test_apprise_details_plugin_verification so both tests agree on what
2255 # constitutes a valid type.
2256 is_valid_type_re = re.compile(r"((choice|list):)?(string|bool|int|float)")
2257
2258 for plugin in N_MGR.plugins():
2259 label = plugin.__name__
2260
2261 for section_name, raw in (
2262 ("template_tokens", plugin.template_tokens),
2263 ("template_args", plugin.template_args),
2264 ):
2265 for key, token in raw.items():
2266 # alias_of entries are intentionally type-free; skip them
2267 if "alias_of" in token:
2268 continue
2269
2270 assert "type" in token, (
2271 f"{label}.{section_name}[{key!r}] is missing a"
2272 " 'type' field. Every non-alias token must declare"
2273 " its type explicitly -- _sanitize_token silently"
2274 " fills in 'string' and the omission goes"
2275 " undetected by the post-processed details() checks."
2276 )
2277
2278 assert isinstance(token["type"], str) and (
2279 is_valid_type_re.match(token["type"]) is not None
2280 ), (
2281 f"{label}.{section_name}[{key!r}]['type'] ="
2282 f" {token['type']!r} is not a valid type string."
2283 " Expected one of: string, bool, int, float,"
2284 " choice:string, list:string, etc."
2285 )
2286
2287
2288 @mock.patch("requests.request")
2289 @mock.patch("asyncio.gather", wraps=asyncio.gather)
2290 @mock.patch(
2291 "concurrent.futures.ThreadPoolExecutor",
2292 wraps=concurrent.futures.ThreadPoolExecutor,
2293 )
2294 def test_apprise_async_mode(mock_threadpool, mock_gather, mock_request):
2295 """
2296 API: Apprise() async_mode tests
2297
2298 """
2299 mock_request.return_value.status_code = requests.codes.ok
2300
2301 # Define some servers
2302 servers = [
2303 "xml://localhost",
2304 "json://localhost",
2305 ]
2306
2307 # Default Async Mode is to be enabled
2308 asset = AppriseAsset()
2309 assert asset.async_mode is True
2310
2311 # Load our asset
2312 a = Apprise(asset=asset)
2313
2314 # add our servers
2315 a.add(servers=servers)
2316
2317 # 2 servers loaded
2318 assert len(a) == 2
2319
2320 # Our servers should carry this flag
2321 for server in a:
2322 assert server.asset.async_mode is True
2323
2324 # Send Notifications Asyncronously
2325 assert a.notify("async") is True
2326
2327 # Verify our thread pool was created
2328 assert mock_threadpool.call_count == 1
2329 mock_threadpool.reset_mock()
2330
2331 # Provide an over-ride now
2332 asset = AppriseAsset(async_mode=False)
2333 assert asset.async_mode is False
2334
2335 # Load our asset
2336 a = Apprise(asset=asset)
2337
2338 # Verify our configuration kept
2339 assert a.asset.async_mode is False
2340
2341 # add our servers
2342 a.add(servers=servers)
2343
2344 # 2 servers loaded
2345 assert len(a) == 2
2346
2347 # Our servers should carry this flag
2348 for server in a:
2349 assert server.asset.async_mode is False
2350
2351 # Send Notifications Syncronously
2352 assert a.notify("sync") is True
2353 # Sequential send doesn't require a gather
2354 assert mock_gather.call_count == 0
2355 mock_gather.reset_mock()
2356
2357 # another way of looking a our false set asset configuration
2358 assert a[0].asset.async_mode is False
2359 assert a[1].asset.async_mode is False
2360
2361 # Adjust 1 of the servers async_mode settings
2362 a[0].asset.async_mode = True
2363 assert a[0].asset.async_mode is True
2364
2365 # They all share the same object, so this gets toggled too
2366 assert a[1].asset.async_mode is True
2367
2368 # We'll just change this one
2369 a[1].asset = AppriseAsset(async_mode=False)
2370 assert a[0].asset.async_mode is True
2371 assert a[1].asset.async_mode is False
2372
2373 # Send 1 Notification Syncronously, the other Asyncronously
2374 assert a.notify("a mixed batch") is True
2375
2376 # Verify we didn't use a thread pool for a single notification
2377 assert mock_threadpool.call_count == 0
2378 mock_threadpool.reset_mock()
2379
2380
2381 def test_notify_matrix_dynamic_importing(tmpdir):
2382 """
2383 API: Apprise() Notify Matrix Importing
2384
2385 """
2386
2387 # Make our new path valid
2388 suite = tmpdir.mkdir("apprise_notify_test_suite")
2389 suite.join("__init__.py").write("")
2390
2391 module_name = "badnotify"
2392
2393 # Update our path to point to our new test suite
2394 sys.path.insert(0, str(suite))
2395
2396 # Create a base area to work within
2397 base = suite.mkdir(module_name)
2398 base.join("__init__.py").write("")
2399
2400 # Test no app_id
2401 base.join("NotifyBadFile1.py").write(
2402 cleandoc("""
2403 class NotifyBadFile1:
2404 pass
2405 """)
2406 )
2407
2408 # No class of the same name
2409 base.join("NotifyBadFile2.py").write(
2410 cleandoc("""
2411 class BadClassName:
2412 pass
2413 """)
2414 )
2415
2416 # Exception thrown
2417 base.join("NotifyBadFile3.py").write("""raise ImportError()""")
2418
2419 # Utilizes a schema:// already occupied (as string)
2420 base.join("NotifyGoober.py").write(
2421 cleandoc("""
2422 from apprise import NotifyBase
2423 class NotifyGoober(NotifyBase):
2424 # This class tests the fact we have a new class name, but we're
2425 # trying to over-ride items previously used
2426
2427 # The default simple (insecure) protocol (used by NotifyMail)
2428 protocol = ('mailto', 'goober')
2429
2430 # The default secure protocol (used by NotifyMail)
2431 secure_protocol = 'mailtos'
2432
2433 @staticmethod
2434 def parse_url(url, *args, **kwargs):
2435 # always parseable
2436 return ConfigBase.parse_url(url, verify_host=False)
2437 """)
2438 )
2439
2440 # Utilizes a schema:// already occupied (as tuple)
2441 base.join("NotifyBugger.py").write(
2442 cleandoc("""
2443 from apprise import NotifyBase
2444 class NotifyBugger(NotifyBase):
2445 # This class tests the fact we have a new class name, but we're
2446 # trying to over-ride items previously used
2447
2448 # The default simple (insecure) protocol (used by NotifyMail), the
2449 # other isn't
2450 protocol = ('mailto', 'bugger-test' )
2451
2452 # The default secure protocol (used by NotifyMail), the other isn't
2453 secure_protocol = ('mailtos', ['garbage'])
2454
2455 @staticmethod
2456 def parse_url(url, *args, **kwargs):
2457 # always parseable
2458 return ConfigBase.parse_url(url, verify_host=False)
2459 """)
2460 )
2461
2462 N_MGR.load_modules(path=str(base), name=module_name)