Debian Codegraph @

tests/test_apprise_cli.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 from importlib import reload
29 from importlib.metadata import PackageNotFoundError
30 from inspect import cleandoc
31 import json
32
33 # Disable logging for a cleaner testing output
34 import logging
35 import os
36 from os.path import dirname, join
37 import re
38 import sys
39 from typing import ClassVar
40 from unittest import mock
41
42 from click.testing import CliRunner
43 from helpers import environ
44 import pytest
45 import requests
46
47 from apprise import NotificationManager, NotifyBase, cli
48 from apprise.locale import gettext_lazy as _
49 from apprise.plugins.base import RequirementsSpec
50
51 logging.disable(logging.CRITICAL)
52
53 # Grant access to our Notification Manager Singleton
54 N_MGR = NotificationManager()
55
56
57 def test_apprise_cli_nux_env(tmpdir):
58 """
59 CLI: Nux Environment
60
61 """
62
63 class GoodNotification(NotifyBase):
64 def __init__(self, *args, **kwargs):
65 super().__init__(*args, **kwargs)
66
67 def notify(self, **kwargs):
68 # Pretend everything is okay (when passing --disable-async)
69 return True
70
71 async def async_notify(self, **kwargs):
72 # Pretend everything is okay
73 return True
74
75 def url(self, *args, **kwargs):
76 # Support url()
77 return "good://"
78
79 class BadNotification(NotifyBase):
80 def __init__(self, *args, **kwargs):
81 super().__init__(*args, **kwargs)
82
83 async def async_notify(self, **kwargs):
84 # Pretend everything is okay
85 return False
86
87 def url(self, *args, **kwargs):
88 # Support url()
89 return "bad://"
90
91 # Set up our notification types
92 N_MGR["good"] = GoodNotification
93 N_MGR["bad"] = BadNotification
94
95 runner = CliRunner()
96 result = runner.invoke(cli.main)
97 # no servers specified; we return 1 (non-zero)
98 assert result.exit_code == 1
99
100 result = runner.invoke(cli.main, ["-v"])
101 assert result.exit_code == 1
102
103 result = runner.invoke(cli.main, ["-vv"])
104 assert result.exit_code == 1
105
106 result = runner.invoke(cli.main, ["-vvv"])
107 assert result.exit_code == 1
108
109 result = runner.invoke(cli.main, ["-vvvv"])
110 assert result.exit_code == 1
111
112 # Display version information and exit
113 result = runner.invoke(cli.main, ["-V"])
114 assert result.exit_code == 0
115
116 result = runner.invoke(
117 cli.main,
118 [
119 "-t",
120 "test title",
121 "-b",
122 "test body",
123 "good://localhost",
124 ],
125 )
126 assert result.exit_code == 0
127
128 with mock.patch("requests.request") as mock_request:
129 # Prepare Mock
130 mock_request.return_value = requests.Request()
131 mock_request.return_value.status_code = requests.codes.ok
132
133 result = runner.invoke(
134 cli.main,
135 [
136 "-t",
137 "test title",
138 "-b",
139 "test body\\nsNewLine",
140 # Test using interpret escapes
141 "-e",
142 # Use our JSON query
143 "json://localhost",
144 ],
145 )
146 assert result.exit_code == 0
147
148 # Test our call count
149 assert mock_request.call_count == 1
150 details = mock_request.call_args_list[0]
151 assert details[0][0] == "POST"
152
153 # Our string is now escaped correctly
154 assert (
155 json.loads(details[1]["data"]).get("message", "")
156 == "test body\nsNewLine"
157 )
158
159 # Reset
160 mock_request.reset_mock()
161
162 result = runner.invoke(
163 cli.main,
164 [
165 "-t",
166 "test title",
167 "-b",
168 "test body\\nsNewLine",
169 # No -e switch at all (so we don't escape the above)
170 # Use our JSON query
171 "json://localhost",
172 ],
173 )
174 assert result.exit_code == 0
175
176 # Test our call count
177 assert mock_request.call_count == 1
178 details = mock_request.call_args_list[0]
179 assert details[0][0] == "POST"
180
181 # Our string is now escaped correctly
182 assert (
183 json.loads(details[1]["data"]).get("message", "")
184 == "test body\\nsNewLine"
185 )
186
187 # Run in synchronous mode
188 result = runner.invoke(
189 cli.main,
190 [
191 "-t",
192 "test title",
193 "-b",
194 "test body",
195 "good://localhost",
196 "--disable-async",
197 ],
198 )
199 assert result.exit_code == 0
200
201 # Test Debug Mode (--debug)
202 result = runner.invoke(
203 cli.main,
204 [
205 "-t",
206 "test title",
207 "-b",
208 "test body",
209 "good://localhost",
210 "--debug",
211 ],
212 )
213 assert result.exit_code == 0
214
215 # Test Debug Mode (-D)
216 result = runner.invoke(
217 cli.main,
218 [
219 "-t",
220 "test title",
221 "-b",
222 "test body",
223 "good://localhost",
224 "-D",
225 ],
226 )
227 assert result.exit_code == 0
228
229 result = runner.invoke(
230 cli.main,
231 [
232 "-t",
233 "test title",
234 "good://localhost",
235 ],
236 input="test stdin body\n",
237 )
238 assert result.exit_code == 0
239
240 # Run in synchronous mode
241 result = runner.invoke(
242 cli.main,
243 [
244 "-t",
245 "test title",
246 "good://localhost",
247 "--disable-async",
248 ],
249 input="test stdin body\n",
250 )
251 assert result.exit_code == 0
252
253 result = runner.invoke(
254 cli.main,
255 [
256 "-t",
257 "test title",
258 "-b",
259 "test body",
260 "bad://localhost",
261 ],
262 )
263 assert result.exit_code == 1
264
265 # Run in synchronous mode
266 result = runner.invoke(
267 cli.main,
268 [
269 "-t",
270 "test title",
271 "-b",
272 "test body",
273 "bad://localhost",
274 "-Da",
275 ],
276 )
277 assert result.exit_code == 1
278
279 # Testing with the --dry-run flag reveals a successful response since we
280 # don't actually execute the bad:// notification; we only display it
281 result = runner.invoke(
282 cli.main,
283 [
284 "-t",
285 "test title",
286 "-b",
287 "test body",
288 "bad://localhost",
289 "--dry-run",
290 ],
291 )
292 assert result.exit_code == 0
293
294 # Write a simple text based configuration file
295 t = tmpdir.mkdir("apprise-obj").join("apprise")
296 buf = f"""
297 # Include ourselves
298 include {t!s}
299
300 taga,tagb=good://localhost
301 tagc=good://nuxref.com
302 """
303 t.write(buf)
304
305 # This will read our configuration and not send any notices at all
306 # because we assigned tags to all of our urls and didn't identify
307 # a specific match below.
308
309 # 'include' reference in configuration file would have included the file a
310 # second time (since recursion default is 1).
311 result = runner.invoke(
312 cli.main,
313 [
314 "-b",
315 "test config",
316 "--config",
317 str(t),
318 ],
319 )
320 # Even when recursion take place, tags are all honored
321 # so 2 is returned because nothing was notified
322 assert result.exit_code == 3
323
324 # This will send out 1 notification because our tag matches
325 # one of the entries above
326 # translation: has taga
327 result = runner.invoke(
328 cli.main,
329 [
330 "-b",
331 "has taga",
332 "--config",
333 str(t),
334 "--tag",
335 "taga",
336 ],
337 )
338 assert result.exit_code == 0
339
340 # Test recursion
341 result = runner.invoke(
342 cli.main,
343 [
344 "-t",
345 "test title",
346 "-b",
347 "test body",
348 "--config",
349 str(t),
350 "--tag",
351 "tagc",
352 # Invalid entry specified for recursion
353 "-R",
354 "invalid",
355 ],
356 )
357 assert result.exit_code == 2
358
359 result = runner.invoke(
360 cli.main,
361 [
362 "-t",
363 "test title",
364 "-b",
365 "test body",
366 "--config",
367 str(t),
368 "--tag",
369 "tagc",
370 # missing entry specified for recursion
371 "--recursive-depth",
372 ],
373 )
374 assert result.exit_code == 2
375
376 result = runner.invoke(
377 cli.main,
378 [
379 "-t",
380 "test title",
381 "-b",
382 "test body",
383 "--config",
384 str(t),
385 "--tag",
386 "tagc",
387 # Disable recursion (thus inclusion will be ignored)
388 "-R",
389 "0",
390 ],
391 )
392 assert result.exit_code == 0
393
394 # Test recursion
395 result = runner.invoke(
396 cli.main,
397 [
398 "-t",
399 "test title",
400 "-b",
401 "test body",
402 "--config",
403 str(t),
404 "--tag",
405 "tagc",
406 # Recurse up to 5 times
407 "--recursion-depth",
408 "5",
409 ],
410 )
411 assert result.exit_code == 0
412
413 # This will send out 2 notifications because by specifying 2 tag
414 # entries, we 'or' them together:
415 # translation: has taga or tagb or tagd
416 result = runner.invoke(
417 cli.main,
418 [
419 "-b",
420 "has taga OR tagc OR tagd",
421 "--config",
422 str(t),
423 "--tag",
424 "taga",
425 "--tag",
426 "tagc",
427 "--tag",
428 "tagd",
429 ],
430 )
431 assert result.exit_code == 0
432
433 # Write a simple text based configuration file
434 t = tmpdir.mkdir("apprise-obj2").join("apprise-test2")
435 buf = """
436 good://localhost/1
437 good://localhost/2
438 good://localhost/3
439 good://localhost/4
440 good://localhost/5
441 myTag=good://localhost/6
442 """
443 t.write(buf)
444
445 # This will read our configuration and send a notification to
446 # the first 5 entries in the list, but not the one that has
447 # the tag associated with it
448 result = runner.invoke(
449 cli.main,
450 [
451 "-b",
452 "test config",
453 "--config",
454 str(t),
455 ],
456 )
457 assert result.exit_code == 0
458
459 # Test our notification type switch (it defaults to info) so we want to
460 # try it as a different value. Should return without a problem
461 result = runner.invoke(
462 cli.main,
463 [
464 "-b",
465 "# test config",
466 "--config",
467 str(t),
468 "-n",
469 "success",
470 ],
471 )
472 assert result.exit_code == 0
473
474 # Test our notification type switch when set to something unsupported
475 result = runner.invoke(
476 cli.main,
477 [
478 "-b",
479 "test config",
480 "--config",
481 str(t),
482 "--notification-type",
483 "invalid",
484 ],
485 )
486 # An error code of 2 is returned if invalid input is specified on the
487 # command line
488 assert result.exit_code == 2
489
490 # The notification type switch is case-insensitive
491 result = runner.invoke(
492 cli.main,
493 [
494 "-b",
495 "test config",
496 "--config",
497 str(t),
498 "--notification-type",
499 "WARNING",
500 ],
501 )
502 assert result.exit_code == 0
503
504 # Test our formatting switch (it defaults to text) so we want to try it as
505 # a different value. Should return without a problem
506 result = runner.invoke(
507 cli.main,
508 [
509 "-b",
510 "# test config",
511 "--config",
512 str(t),
513 "-i",
514 "markdown",
515 ],
516 )
517 assert result.exit_code == 0
518
519 # Test our formatting switch when set to something unsupported
520 result = runner.invoke(
521 cli.main,
522 [
523 "-b",
524 "test config",
525 "--config",
526 str(t),
527 "--input-format",
528 "invalid",
529 ],
530 )
531 # An error code of 2 is returned if invalid input is specified on the
532 # command line
533 assert result.exit_code == 2
534
535 # The formatting switch is not case sensitive
536 result = runner.invoke(
537 cli.main,
538 [
539 "-b",
540 "# test config",
541 "--config",
542 str(t),
543 "--input-format",
544 "HTML",
545 ],
546 )
547 assert result.exit_code == 0
548
549 # As a way of ensuring we match the first 5 entries, we can run a
550 # --dry-run against the same result set above and verify the output
551 result = runner.invoke(
552 cli.main,
553 [
554 "-b",
555 "test config",
556 "--config",
557 str(t),
558 "--dry-run",
559 ],
560 )
561 assert result.exit_code == 0
562 lines = re.split(r"[\r\n]", result.output.strip())
563 # 5 lines of all good:// entries matched + url id underneath
564 assert len(lines) == 10
565 # Verify we match against the remaining good:// entries
566 for i in range(0, 10, 2):
567 assert lines[i].endswith("good://")
568
569 # Tags are case-insensitive; mytag matches myTag
570 result = runner.invoke(
571 cli.main,
572 [
573 "-b",
574 "has mytag",
575 "--config",
576 str(t),
577 "--tag",
578 "mytag",
579 ],
580 )
581 assert result.exit_code == 0
582
583 # Same command with --dry-run; one entry matches so exit code is 0
584 result = runner.invoke(
585 cli.main,
586 ["-b", "has mytag", "--config", str(t), "--tag", "mytag", "--dry-run"],
587 )
588 assert result.exit_code == 0
589
590 # A tag that does not exist in the config produces no matches; the live
591 # run returns exit code 3 to signal "no services found".
592 result = runner.invoke(
593 cli.main,
594 ["-b", "no match", "--config", str(t), "--tag", "nonexistent"],
595 )
596 assert result.exit_code == 3
597
598 # --dry-run must mirror the live result: a non-matching tag also returns
599 # exit code 3, not 0. This guards against dry-run masking "no services
600 # found" by always reporting success.
601 result = runner.invoke(
602 cli.main,
603 [
604 "-b",
605 "no match",
606 "--config",
607 str(t),
608 "--tag",
609 "nonexistent",
610 "--dry-run",
611 ],
612 )
613 assert result.exit_code == 3
614
615 # Here is a case where we get what was expected; we also attach a file
616 result = runner.invoke(
617 cli.main,
618 [
619 "-b",
620 "has myTag",
621 "--config",
622 str(t),
623 "--attach",
624 join(dirname(__file__), "var", "apprise-test.gif"),
625 "--tag",
626 "myTag",
627 ],
628 )
629 assert result.exit_code == 0
630
631 # Testing with the --dry-run flag reveals the same positive results
632 # because there was at least one match
633 result = runner.invoke(
634 cli.main,
635 [
636 "-b",
637 "has myTag",
638 "--config",
639 str(t),
640 "--tag",
641 "myTag",
642 "--dry-run",
643 ],
644 )
645 assert result.exit_code == 0
646
647 #
648 # Test environment variables
649 #
650 # Write a simple text based configuration file
651 t2 = tmpdir.mkdir("apprise-obj-env").join("apprise")
652 buf = """
653 # A general one
654 good://localhost
655
656 # A failure (if we use the fail tag)
657 fail=bad://localhost
658
659 # A normal one tied to myTag
660 myTag=good://nuxref.com
661 """
662 t2.write(buf)
663
664 with environ(APPRISE_URLS="good://localhost"):
665 # This will load okay because we defined the environment
666 # variable with a valid URL
667 result = runner.invoke(
668 cli.main,
669 [
670 "-b",
671 "test environment",
672 # Test that we ignore our tag
673 "--tag",
674 "mytag",
675 ],
676 )
677 assert result.exit_code == 0
678
679 # Same action but without --tag
680 result = runner.invoke(
681 cli.main,
682 [
683 "-b",
684 "test environment",
685 ],
686 )
687 assert result.exit_code == 0
688
689 with (
690 mock.patch("apprise.cli.DEFAULT_CONFIG_PATHS", []),
691 environ(APPRISE_URLS=" "),
692 ):
693 # An empty string is not valid and therefore not loaded so the below
694 # fails. We override the DEFAULT_CONFIG_PATHS because we don't want to
695 # detect ones loaded on the machine running the unit tests
696 result = runner.invoke(
697 cli.main,
698 [
699 "-b",
700 "test environment",
701 ],
702 )
703 assert result.exit_code == 1
704
705 with environ(APPRISE_URLS="bad://localhost"):
706 result = runner.invoke(
707 cli.main,
708 [
709 "-b",
710 "test environment",
711 ],
712 )
713 assert result.exit_code == 1
714
715 # If we specify an inline URL, it will over-ride the environment
716 # variable
717 result = runner.invoke(
718 cli.main,
719 [
720 "-t",
721 "test title",
722 "-b",
723 "test body",
724 "good://localhost",
725 ],
726 )
727 assert result.exit_code == 0
728
729 # A Config file also over-rides the environment variable if
730 # specified on the command line:
731 result = runner.invoke(
732 cli.main,
733 [
734 "-b",
735 "has myTag",
736 "--config",
737 str(t2),
738 "--tag",
739 "myTag",
740 ],
741 )
742 assert result.exit_code == 0
743
744 with environ(APPRISE_CONFIG=str(t2)):
745 # Deprecated test case
746 result = runner.invoke(
747 cli.main,
748 [
749 "-b",
750 "has myTag",
751 "--tag",
752 "myTag",
753 ],
754 )
755 assert result.exit_code == 0
756
757 with environ(APPRISE_CONFIG_PATH=str(t2)):
758 # Our configuration file will load from our environmment variable
759 result = runner.invoke(
760 cli.main,
761 [
762 "-b",
763 "has myTag",
764 "--tag",
765 "myTag",
766 ],
767 )
768 assert result.exit_code == 0
769
770 with environ(APPRISE_CONFIG_PATH=str(t2) + ";/another/path"):
771 # Our configuration file will load from our environmment variable
772 result = runner.invoke(
773 cli.main,
774 [
775 "-b",
776 "has myTag",
777 "--tag",
778 "myTag",
779 ],
780 )
781 assert result.exit_code == 0
782
783 with (
784 mock.patch("apprise.cli.DEFAULT_CONFIG_PATHS", []),
785 environ(APPRISE_CONFIG=" "),
786 ):
787 # We will fail to send the notification as no path was specified.
788 # We override the DEFAULT_CONFIG_PATHS because we don't want to detect
789 # ones loaded on the machine running the unit tests
790 result = runner.invoke(
791 cli.main,
792 [
793 "-b",
794 "my message",
795 ],
796 )
797 assert result.exit_code == 1
798
799 with environ(APPRISE_CONFIG="garbage/file/path.yaml"):
800 # We will fail to send the notification as the path
801 # specified is not loadable
802 result = runner.invoke(
803 cli.main,
804 [
805 "-b",
806 "my message",
807 ],
808 )
809 assert result.exit_code == 1
810
811 # We can force an over-ride by specifying a config file on the
812 # command line options:
813 result = runner.invoke(
814 cli.main,
815 [
816 "-b",
817 "has myTag",
818 "--config",
819 str(t2),
820 "--tag",
821 "myTag",
822 ],
823 )
824 assert result.exit_code == 0
825
826 # Just a general test; if both the --config and urls are specified
827 # then the the urls trumps all
828 result = runner.invoke(
829 cli.main,
830 [
831 "-b",
832 "has myTag",
833 "--config",
834 str(t2),
835 "good://localhost",
836 "--tag",
837 "fail",
838 ],
839 )
840 # Tags are ignored, URL specified, so it trump config
841 assert result.exit_code == 0
842
843 # we just repeat the test as a proof that it only executes
844 # the urls despite the fact the --config was specified
845 result = runner.invoke(
846 cli.main,
847 [
848 "-b",
849 "reads the url entry only",
850 "--config",
851 str(t2),
852 "good://localhost",
853 "--tag",
854 "fail",
855 ],
856 )
857 # Tags are ignored, URL specified, so it trump config
858 assert result.exit_code == 0
859
860 # once agian, but we call bad://
861 result = runner.invoke(
862 cli.main,
863 [
864 "-b",
865 "reads the url entry only",
866 "--config",
867 str(t2),
868 "bad://localhost",
869 "--tag",
870 "myTag",
871 ],
872 )
873 assert result.exit_code == 1
874
875 # Test Escaping:
876 result = runner.invoke(
877 cli.main,
878 [
879 "-e",
880 "-t",
881 "test\ntitle",
882 "-b",
883 "test\nbody",
884 "good://localhost",
885 ],
886 )
887 assert result.exit_code == 0
888
889 # Test Escaping (without title)
890 result = runner.invoke(
891 cli.main,
892 [
893 "--interpret-escapes",
894 "-b",
895 "test\nbody",
896 "good://localhost",
897 ],
898 )
899 assert result.exit_code == 0
900
901 # Test Emojis:
902 result = runner.invoke(
903 cli.main,
904 [
905 "-j",
906 "-t",
907 ":smile:",
908 "-b",
909 ":grin:",
910 "good://localhost",
911 ],
912 )
913 assert result.exit_code == 0
914
915 result = runner.invoke(
916 cli.main,
917 [
918 "--interpret-emojis",
919 "-t",
920 ":smile:",
921 "-b",
922 ":grin:",
923 "good://localhost",
924 ],
925 )
926 assert result.exit_code == 0
927
928
929 def test_apprise_cli_modules(tmpdir):
930 """
931 CLI: --plugin (-P)
932
933 """
934
935 runner = CliRunner()
936
937 #
938 # Loading of modules works correctly
939 #
940 notify_cmod_base = tmpdir.mkdir("cli_modules")
941 notify_cmod = notify_cmod_base.join("hook.py")
942 notify_cmod.write(
943 cleandoc("""
944 from apprise.decorators import notify
945
946 @notify(on="climod")
947 def mywrapper(body, title, notify_type, *args, **kwargs):
948 pass
949 """)
950 )
951
952 result = runner.invoke(
953 cli.main,
954 [
955 "--plugin-path",
956 str(notify_cmod),
957 "-t",
958 "title",
959 "-b",
960 "body",
961 "climod://",
962 ],
963 )
964
965 assert result.exit_code == 0
966
967 # Test -P
968 result = runner.invoke(
969 cli.main,
970 [
971 "-P",
972 str(notify_cmod),
973 "-t",
974 "title",
975 "-b",
976 "body",
977 "climod://",
978 ],
979 )
980
981 assert result.exit_code == 0
982
983 # Test double hooks
984 notify_cmod2 = notify_cmod_base.join("hook2.py")
985 notify_cmod2.write(
986 cleandoc("""
987 from apprise.decorators import notify
988
989 @notify(on="climod2")
990 def mywrapper(body, title, notify_type, *args, **kwargs):
991 pass
992 """)
993 )
994
995 result = runner.invoke(
996 cli.main,
997 [
998 "--plugin-path",
999 str(notify_cmod),
1000 "--plugin-path",
1001 str(notify_cmod2),
1002 "-t",
1003 "title",
1004 "-b",
1005 "body",
1006 "climod://",
1007 "climod2://",
1008 ],
1009 )
1010
1011 assert result.exit_code == 0
1012
1013 with environ(
1014 APPRISE_PLUGIN_PATH=str(notify_cmod) + ";" + str(notify_cmod2)
1015 ):
1016 # Leverage our environment variables to specify the plugin path
1017 result = runner.invoke(
1018 cli.main,
1019 [
1020 "-b",
1021 "body",
1022 "climod://",
1023 "climod2://",
1024 ],
1025 )
1026
1027 assert result.exit_code == 0
1028
1029
1030 @pytest.mark.skipif(
1031 sys.platform == "win32", reason="Unreliable results to be determined"
1032 )
1033 def test_apprise_cli_persistent_storage(tmpdir):
1034 """
1035 CLI: test persistent storage
1036
1037 """
1038
1039 # This is a made up class that is just used to verify
1040 class NoURLIDNotification(NotifyBase):
1041 """A no URL ID."""
1042
1043 # Update URL identifier
1044 url_identifier = False
1045
1046 def __init__(self, *args, **kwargs):
1047 super().__init__(*args, **kwargs)
1048
1049 def send(self, **kwargs):
1050
1051 # Pretend everything is okay
1052 return True
1053
1054 def url(self, *args, **kwargs):
1055 # Support URL
1056 return "noper://"
1057
1058 def parse_url(self, *args, **kwargs):
1059 # parse our url
1060 return {"schema": "noper"}
1061
1062 # This is a made up class that is just used to verify
1063 class TestNotification(NotifyBase):
1064 """A Testing Script."""
1065
1066 def __init__(self, *args, **kwargs):
1067 super().__init__(*args, **kwargs)
1068
1069 def send(self, **kwargs):
1070
1071 # Test our persistent settings
1072 self.store.set("key", "value")
1073 assert self.store.get("key") == "value"
1074
1075 # Pretend everything is okay
1076 return True
1077
1078 def url(self, *args, **kwargs):
1079 # Support URL
1080 return "test://"
1081
1082 def parse_url(self, *args, **kwargs):
1083 # parse our url
1084 return {"schema": "test"}
1085
1086 # assign test:// to our notification defined above
1087 N_MGR["test"] = TestNotification
1088 N_MGR["noper"] = NoURLIDNotification
1089
1090 # Write a simple text based configuration file
1091 config = tmpdir.join("apprise.cfg")
1092 buf = cleandoc("""
1093 # Create a config file we can source easily
1094 test=test://
1095 noper=noper://
1096
1097 # Define a second test URL that will
1098 two-urls=test://
1099
1100 # Create another entry that has no tag associatd with it
1101 test://?entry=2
1102 """)
1103 config.write(buf)
1104
1105 runner = CliRunner()
1106
1107 # Generate notification that creates persistent data
1108 result = runner.invoke(
1109 cli.main,
1110 [
1111 "--storage-path",
1112 str(tmpdir),
1113 "--config",
1114 str(config),
1115 "storage",
1116 "list",
1117 ],
1118 )
1119 # list our entries
1120 assert result.exit_code == 0
1121
1122 # our persist storage has not been created yet
1123 stdout = result.stdout.strip()
1124
1125 # Click output can wrap based on terminal width, and storage backend
1126 # sizes are not stable across Python/OS variations. Validate semantics.
1127 assert re.search(
1128 r"^1\.\s+[a-z0-9_-]{8}\s+\d+(?:\.\d{2})?[KMGT]?B\s+unused\b",
1129 stdout,
1130 re.MULTILINE,
1131 )
1132 assert re.search(r"(?m)^\s*-\s+test://\s*$", stdout)
1133
1134 # An invalid mode specified
1135 result = runner.invoke(
1136 cli.main,
1137 [
1138 "--storage-path",
1139 str(tmpdir),
1140 "--storage-mode",
1141 "invalid",
1142 "--config",
1143 str(config),
1144 "-g",
1145 "test",
1146 "-t",
1147 "title",
1148 "-b",
1149 "body",
1150 ],
1151 )
1152 # Bad mode specified
1153 assert result.exit_code == 2
1154
1155 # Invalid uid lenth specified
1156 result = runner.invoke(
1157 cli.main,
1158 [
1159 "--storage-path",
1160 str(tmpdir),
1161 "--storage-mode",
1162 "flush",
1163 "--storage-uid-length",
1164 1,
1165 "--config",
1166 str(config),
1167 "-g",
1168 "test",
1169 "-t",
1170 "title",
1171 "-b",
1172 "body",
1173 ],
1174 )
1175 # storage uid length to small
1176 assert result.exit_code == 2
1177
1178 # No files written yet; just config file exists
1179 dir_content = os.listdir(str(tmpdir))
1180 assert len(dir_content) == 1
1181 assert "apprise.cfg" in dir_content
1182
1183 # Generate notification that creates persistent data
1184 result = runner.invoke(
1185 cli.main,
1186 [
1187 "--storage-path",
1188 str(tmpdir),
1189 "--storage-mode",
1190 "flush",
1191 "--config",
1192 str(config),
1193 "-t",
1194 "title",
1195 "-b",
1196 "body",
1197 "-g",
1198 "test",
1199 ],
1200 )
1201 # We parsed our data accordingly
1202 assert result.exit_code == 0
1203
1204 dir_content = os.listdir(str(tmpdir))
1205 assert len(dir_content) == 2
1206 assert "apprise.cfg" in dir_content
1207 assert "ea482db7" in dir_content
1208
1209 # Have a look at our storage listings
1210 result = runner.invoke(
1211 cli.main,
1212 [
1213 "--storage-path",
1214 str(tmpdir),
1215 "--config",
1216 str(config),
1217 "storage",
1218 "list",
1219 ],
1220 )
1221 # list our entries
1222 assert result.exit_code == 0
1223
1224 stdout = result.stdout.strip()
1225 assert re.search(
1226 r"^1\.\s+[a-z0-9_-]{8}\s+\d+(?:\.\d{2})?[KMGT]?B\s+active\b",
1227 stdout,
1228 re.MULTILINE,
1229 )
1230
1231 # keyword list is not required
1232 result = runner.invoke(
1233 cli.main,
1234 [
1235 "--storage-path",
1236 str(tmpdir),
1237 "--config",
1238 str(config),
1239 "storage",
1240 ],
1241 )
1242 # list our entries
1243 assert result.exit_code == 0
1244
1245 stdout = result.stdout.strip()
1246 assert re.search(
1247 r"^1\.\s+[a-z0-9_-]{8}\s+\d+(?:\.\d{2})?[KMGT]?B\s+active\b",
1248 stdout,
1249 re.MULTILINE,
1250 )
1251
1252 # search on something that won't match
1253 result = runner.invoke(
1254 cli.main,
1255 [
1256 "--storage-path",
1257 str(tmpdir),
1258 "--config",
1259 str(config),
1260 "storage",
1261 "list",
1262 "nomatch",
1263 ],
1264 )
1265 # list our entries
1266 assert result.exit_code == 0
1267
1268 assert not result.stdout.strip()
1269
1270 # closest match search
1271 result = runner.invoke(
1272 cli.main,
1273 [
1274 "--storage-path",
1275 str(tmpdir),
1276 "--config",
1277 str(config),
1278 "storage",
1279 "list",
1280 # Closest match will hit a result
1281 "ea",
1282 ],
1283 )
1284 # list our entries
1285 assert result.exit_code == 0
1286
1287 stdout = result.stdout.strip()
1288 assert re.search(
1289 r"^1\.\s+[a-z0-9_-]{8}\s+\d+(?:\.\d{2})?[KMGT]?B\s+active\b",
1290 stdout,
1291 re.MULTILINE,
1292 )
1293
1294 # list is the presumed option if no match
1295 result = runner.invoke(
1296 cli.main,
1297 [
1298 "--storage-path",
1299 str(tmpdir),
1300 "--config",
1301 str(config),
1302 "storage",
1303 # Closest match will hit a result
1304 "ea",
1305 ],
1306 )
1307 # list our entries successfully again..
1308 assert result.exit_code == 0
1309
1310 stdout = result.stdout.strip()
1311 assert re.search(
1312 r"^1\.\s+[a-z0-9_-]{8}\s+\d+(?:\.\d{2})?[KMGT]?B\s+active\b",
1313 stdout,
1314 re.MULTILINE,
1315 )
1316
1317 # Search based on tag
1318 result = runner.invoke(
1319 cli.main,
1320 [
1321 "--storage-path",
1322 str(tmpdir),
1323 "--config",
1324 str(config),
1325 "storage",
1326 "list",
1327 # We can match by tags too
1328 "-g",
1329 "test",
1330 ],
1331 )
1332 # list our entries
1333 assert result.exit_code == 0
1334
1335 stdout = result.stdout.strip()
1336 assert re.search(
1337 r"^1\.\s+[a-z0-9_-]{8}\s+\d+(?:\.\d{2})?[KMGT]?B\s+active\b",
1338 stdout,
1339 re.MULTILINE,
1340 )
1341
1342 # Create a stale 8-char namespace on disk that belongs to a different
1343 # URL — it must NOT appear in the output when filtering by URL.
1344 tmpdir.mkdir("aaaaaaaa")
1345
1346 # Filter by URL directly — no config file required; the URL is loaded
1347 # inline and its uid is used to match storage entries.
1348 result = runner.invoke(
1349 cli.main,
1350 [
1351 "--storage-path",
1352 str(tmpdir),
1353 "storage",
1354 "list",
1355 # Pass the raw URL instead of an 8-char UID prefix
1356 "test://",
1357 ],
1358 )
1359 # Should produce exactly one entry (the url's namespace); the
1360 # unrelated stale directory 'aaaaaaaa' must not bleed into output.
1361 assert result.exit_code == 0
1362
1363 stdout = result.stdout.strip()
1364 assert re.search(
1365 r"^1\.\s+[a-z0-9_-]{8}\s+\d+(?:\.\d{2})?[KMGT]?B\s+active\b",
1366 stdout,
1367 re.MULTILINE,
1368 )
1369 # Confirm only one entry — stale 'aaaaaaaa' must be absent
1370 assert not re.search(r"aaaaaaaa", stdout)
1371
1372 # URL filter alongside --config: URL filters trump all other sources,
1373 # including --config. 'a' is reset and only the URL-filter plugin
1374 # is loaded. Its storage was already created, so exactly one active
1375 # entry should appear.
1376 result = runner.invoke(
1377 cli.main,
1378 [
1379 "--storage-path",
1380 str(tmpdir),
1381 "--config",
1382 str(config),
1383 "storage",
1384 "list",
1385 "test://",
1386 ],
1387 )
1388 assert result.exit_code == 0
1389 stdout = result.stdout.strip()
1390 assert re.search(
1391 r"^1\.\s+[a-z0-9_-]{8}\s+\d+(?:\.\d{2})?[KMGT]?B\s+active\b",
1392 stdout,
1393 re.MULTILINE,
1394 )
1395
1396 # Duplicate URL filter: the same URL specified twice. Both entries
1397 # are added to the fresh Apprise instance; the uids dict groups them
1398 # under one uid key, so only a single storage entry should appear.
1399 result = runner.invoke(
1400 cli.main,
1401 [
1402 "--storage-path",
1403 str(tmpdir),
1404 "storage",
1405 "list",
1406 "test://",
1407 "test://",
1408 ],
1409 )
1410 assert result.exit_code == 0
1411 stdout = result.stdout.strip()
1412 assert re.search(
1413 r"^1\.\s+[a-z0-9_-]{8}\s+\d+(?:\.\d{2})?[KMGT]?B\s+active\b",
1414 stdout,
1415 re.MULTILINE,
1416 )
1417 # Only one numbered entry should appear despite two URL arguments
1418 assert len(re.findall(r"^\d+\.", stdout, re.MULTILINE)) == 1
1419
1420 # URL filter with an unrecognised schema: a.add() silently rejects the
1421 # URL, leaving the Apprise instance empty. With no plugin uids resolved,
1422 # disk_scan is skipped entirely and the output is empty.
1423 result = runner.invoke(
1424 cli.main,
1425 [
1426 "--storage-path",
1427 str(tmpdir),
1428 "storage",
1429 "list",
1430 "nosuchschema://filter",
1431 ],
1432 )
1433 assert result.exit_code == 0
1434 assert not result.stdout.strip()
1435
1436 # URL filter with --tag: URL filter fires rule #1 which clears the tag
1437 # (same as sending a notification — URLs trump all, including tags).
1438 # The test:// plugin's storage is shown; the stale dirs are absent
1439 # because disk_scan is scoped to the URL-filter plugin's uid.
1440 result = runner.invoke(
1441 cli.main,
1442 [
1443 "--storage-path",
1444 str(tmpdir),
1445 "--tag",
1446 "test",
1447 "storage",
1448 "list",
1449 "test://",
1450 ],
1451 )
1452 assert result.exit_code == 0
1453 stdout = result.stdout.strip()
1454 assert re.search(
1455 r"^1\.\s+[a-z0-9_-]{8}\s+\d+(?:\.\d{2})?[KMGT]?B\s+active\b",
1456 stdout,
1457 re.MULTILINE,
1458 )
1459 # Stale dirs must not bleed into output when URL filter is active
1460 assert not re.search(r"aaaaaaaa", stdout)
1461
1462 # URL filter scopes PRUNE too: only the test:// plugin's storage
1463 # directory is eligible; stale dirs like 'aaaaaaaa' are left alone.
1464 # Use --dry-run so we exercise the _had_url_filters namespace-scoping
1465 # branch without actually modifying disk (keeping ea482db7 active for
1466 # the assertions that follow).
1467 result = runner.invoke(
1468 cli.main,
1469 [
1470 "--storage-path",
1471 str(tmpdir),
1472 "--storage-prune-days",
1473 0,
1474 "--dry-run",
1475 "storage",
1476 "prune",
1477 "test://",
1478 ],
1479 )
1480 assert result.exit_code == 0
1481 # The stale 'aaaaaaaa' directory must still exist after the URL-scoped
1482 # prune because it was outside the test:// namespace.
1483 assert os.path.isdir(os.path.join(str(tmpdir), "aaaaaaaa"))
1484
1485 # URL filter scopes CLEAR too: only the test:// plugin's namespace is
1486 # cleared; unrelated stale directories are untouched.
1487 # Use --dry-run so we exercise the _had_url_filters scoping path
1488 # without wiping ea482db7 contents (subsequent tests expect it active).
1489 result = runner.invoke(
1490 cli.main,
1491 [
1492 "--storage-path",
1493 str(tmpdir),
1494 "--dry-run",
1495 "storage",
1496 "clear",
1497 "test://",
1498 ],
1499 )
1500 assert result.exit_code == 0
1501 # 'aaaaaaaa' must still be present — it was outside the cleared scope
1502 assert os.path.isdir(os.path.join(str(tmpdir), "aaaaaaaa"))
1503
1504 # Tag-scoped PRUNE: --tag limits the prune namespace to only the uids
1505 # that matched the tag filter. The stale 'aaaaaaaa' directory is
1506 # outside that namespace and must not be removed.
1507 # Use --dry-run so the test is non-destructive and ea482db7 stays active.
1508 result = runner.invoke(
1509 cli.main,
1510 [
1511 "--storage-path",
1512 str(tmpdir),
1513 "--config",
1514 str(config),
1515 "--tag",
1516 "test",
1517 "--storage-prune-days",
1518 0,
1519 "--dry-run",
1520 "storage",
1521 "prune",
1522 ],
1523 )
1524 assert result.exit_code == 0
1525 # The stale 'aaaaaaaa' directory must be untouched — it was outside the
1526 # tag-scoped prune namespace.
1527 assert os.path.isdir(os.path.join(str(tmpdir), "aaaaaaaa"))
1528
1529 # Tag-scoped CLEAR: same principle — only the tagged plugin's namespace
1530 # is eligible for clearing; everything else is left alone.
1531 # Use --dry-run to keep ea482db7 active for subsequent assertions.
1532 result = runner.invoke(
1533 cli.main,
1534 [
1535 "--storage-path",
1536 str(tmpdir),
1537 "--config",
1538 str(config),
1539 "--tag",
1540 "test",
1541 "--dry-run",
1542 "storage",
1543 "clear",
1544 ],
1545 )
1546 assert result.exit_code == 0
1547 # The stale 'aaaaaaaa' directory must survive — it was not in scope
1548 assert os.path.isdir(os.path.join(str(tmpdir), "aaaaaaaa"))
1549
1550 # When a tag or URL filter is specified but resolves to nothing,
1551 # disk_prune() must NOT be called. The tests below confirm that ea482db7
1552 # survives each no-match check.
1553
1554 # Tag-scoped PRUNE with a tag that matches no loaded plugin: nothing
1555 # resolves so disk_prune() must be skipped entirely.
1556 result = runner.invoke(
1557 cli.main,
1558 [
1559 "--storage-path",
1560 str(tmpdir),
1561 "--config",
1562 str(config),
1563 "--tag",
1564 "no-such-tag",
1565 "--storage-prune-days",
1566 0,
1567 "storage",
1568 "prune",
1569 ],
1570 )
1571 assert result.exit_code == 0
1572 # ea482db7 must be intact -- the no-match prune must not wipe storage
1573 assert os.path.isdir(os.path.join(str(tmpdir), "ea482db7"))
1574
1575 # Tag-scoped CLEAR with the same unmatchable tag: same guard must fire.
1576 result = runner.invoke(
1577 cli.main,
1578 [
1579 "--storage-path",
1580 str(tmpdir),
1581 "--config",
1582 str(config),
1583 "--tag",
1584 "no-such-tag",
1585 "storage",
1586 "clear",
1587 ],
1588 )
1589 assert result.exit_code == 0
1590 # ea482db7 must survive -- a no-match clear must not erase everything
1591 assert os.path.isdir(os.path.join(str(tmpdir), "ea482db7"))
1592
1593 # URL filter that fails to load (unknown schema): _had_url_filters is
1594 # True but no uid resolves, so disk_prune() must not be called.
1595 result = runner.invoke(
1596 cli.main,
1597 [
1598 "--storage-path",
1599 str(tmpdir),
1600 "--storage-prune-days",
1601 0,
1602 "storage",
1603 "prune",
1604 "nosuchschema://",
1605 ],
1606 )
1607 assert result.exit_code == 0
1608 assert os.path.isdir(os.path.join(str(tmpdir), "ea482db7"))
1609
1610 # Same guard applies to clear when the URL filter resolves nothing.
1611 result = runner.invoke(
1612 cli.main,
1613 [
1614 "--storage-path",
1615 str(tmpdir),
1616 "storage",
1617 "clear",
1618 "nosuchschema://",
1619 ],
1620 )
1621 assert result.exit_code == 0
1622 assert os.path.isdir(os.path.join(str(tmpdir), "ea482db7"))
1623
1624 # Prune call but prune-days set incorrectly
1625 result = runner.invoke(
1626 cli.main,
1627 [
1628 "--storage-path",
1629 str(tmpdir),
1630 "--storage-prune-days",
1631 -1,
1632 "storage",
1633 "prune",
1634 ],
1635 )
1636 # storage prune days is invalid
1637 assert result.exit_code == 2
1638
1639 # Create a tmporary namespace
1640 tmpdir.mkdir("namespace")
1641
1642 # Generates another listing
1643 result = runner.invoke(
1644 cli.main,
1645 [
1646 "--storage-path",
1647 str(tmpdir),
1648 "--config",
1649 str(config),
1650 "storage",
1651 ],
1652 )
1653
1654 # list our entries
1655 assert result.exit_code == 0
1656
1657 stdout = result.stdout.strip()
1658 assert re.search(
1659 r"^1\.\s+[a-z0-9_-]{8}\s+\d+(?:\.\d{2})?[KMGT]?B\s+active\b",
1660 stdout,
1661 re.MULTILINE,
1662 )
1663 assert re.match(
1664 r".*\s*[0-9]\.\s+namespace\s+0\.00B\s+stale.*",
1665 stdout,
1666 (re.MULTILINE | re.DOTALL),
1667 )
1668
1669 # Generates another listing but utilize the tag
1670 result = runner.invoke(
1671 cli.main,
1672 [
1673 "--storage-path",
1674 str(tmpdir),
1675 "--config",
1676 str(config),
1677 "--tag",
1678 "test",
1679 "storage",
1680 ],
1681 )
1682
1683 # list our entries
1684 assert result.exit_code == 0
1685
1686 stdout = result.stdout.strip()
1687 assert re.search(
1688 r"^1\.\s+[a-z0-9_-]{8}\s+\d+(?:\.\d{2})?[KMGT]?B\s+active\b",
1689 stdout,
1690 re.MULTILINE,
1691 )
1692 assert (
1693 re.match(
1694 r".*\s*[0-9]\.\s+namespace\s+0\.00B\s+stale.*",
1695 stdout,
1696 (re.MULTILINE | re.DOTALL),
1697 )
1698 is None
1699 )
1700
1701 # Clear all of our accumulated disk space
1702 result = runner.invoke(
1703 cli.main,
1704 [
1705 "--storage-path",
1706 str(tmpdir),
1707 "--config",
1708 str(config),
1709 "storage",
1710 "clear",
1711 ],
1712 )
1713
1714 # successful
1715 assert result.exit_code == 0
1716
1717 # Generate another listing
1718 result = runner.invoke(
1719 cli.main,
1720 [
1721 "--storage-path",
1722 str(tmpdir),
1723 "--config",
1724 str(config),
1725 "storage",
1726 ],
1727 )
1728
1729 # list our entries
1730 assert result.exit_code == 0
1731
1732 stdout = result.stdout.strip()
1733 # back to unused state and 0 bytes
1734 assert re.search(
1735 r"^1\.\s+[a-z0-9_-]{8}\s+\d+(?:\.\d{2})?[KMGT]?B\s+unused\b",
1736 stdout,
1737 re.MULTILINE,
1738 )
1739 # namespace is gone now
1740 assert (
1741 re.match(
1742 r".*\s*[0-9]\.\s+namespace\s+0\.00B\s+stale.*",
1743 stdout,
1744 (re.MULTILINE | re.DOTALL),
1745 )
1746 is None
1747 )
1748
1749 # Provide both tags and uid
1750 result = runner.invoke(
1751 cli.main,
1752 [
1753 "--storage-path",
1754 str(tmpdir),
1755 "--config",
1756 str(config),
1757 "storage",
1758 "ea",
1759 "-g",
1760 "test",
1761 ],
1762 )
1763
1764 # list our entries
1765 assert result.exit_code == 0
1766
1767 stdout = result.stdout.strip()
1768 # back to unused state and 0 bytes
1769 assert re.match(
1770 r"^[0-9]\.\s+[a-z0-9_-]{8}\s+0\.00B\s+unused\s+-\s+test://$",
1771 stdout,
1772 re.MULTILINE,
1773 )
1774
1775 # Generate notification that creates persistent data
1776 result = runner.invoke(
1777 cli.main,
1778 [
1779 "--storage-path",
1780 str(tmpdir),
1781 "--storage-mode",
1782 "flush",
1783 "--config",
1784 str(config),
1785 "-t",
1786 "title",
1787 "-b",
1788 "body",
1789 "-g",
1790 "test",
1791 ],
1792 )
1793 # We parsed our data accordingly
1794 assert result.exit_code == 0
1795
1796 # Have a look at our storage listings
1797 result = runner.invoke(
1798 cli.main,
1799 [
1800 "--storage-path",
1801 str(tmpdir),
1802 "--config",
1803 str(config),
1804 "storage",
1805 "list",
1806 ],
1807 )
1808 # list our entries
1809 assert result.exit_code == 0
1810
1811 stdout = result.stdout.strip()
1812 assert re.search(
1813 r"^1\.\s+[a-z0-9_-]{8}\s+\d+(?:\.\d{2})?[KMGT]?B\s+active\b",
1814 stdout,
1815 re.MULTILINE,
1816 )
1817
1818 # Prune call but prune-days set incorrectly
1819 result = runner.invoke(
1820 cli.main,
1821 [
1822 "--storage-path",
1823 str(tmpdir),
1824 "storage",
1825 "prune",
1826 ],
1827 )
1828
1829 # Run our prune successfully
1830 assert result.exit_code == 0
1831
1832 # Have a look at our storage listings (expected no change in output)
1833 result = runner.invoke(
1834 cli.main,
1835 [
1836 "--storage-path",
1837 str(tmpdir),
1838 "--config",
1839 str(config),
1840 "storage",
1841 "list",
1842 ],
1843 )
1844 # list our entries
1845 assert result.exit_code == 0
1846
1847 stdout = result.stdout.strip()
1848 assert re.search(
1849 r"^1\.\s+[a-z0-9_-]{8}\s+\d+(?:\.\d{2})?[KMGT]?B\s+active\b",
1850 stdout,
1851 re.MULTILINE,
1852 )
1853
1854 # Prune call but prune-days set incorrectly
1855 result = runner.invoke(
1856 cli.main,
1857 [
1858 "--storage-path",
1859 str(tmpdir),
1860 # zero simulates a full clean
1861 "--storage-prune-days",
1862 0,
1863 "storage",
1864 "prune",
1865 ],
1866 )
1867
1868 # Run our prune successfully
1869 assert result.exit_code == 0
1870
1871 # Have a look at our storage listings (expected no change in output)
1872 result = runner.invoke(
1873 cli.main,
1874 [
1875 "--storage-path",
1876 str(tmpdir),
1877 "--config",
1878 str(config),
1879 "storage",
1880 "list",
1881 ],
1882 )
1883 # list our entries
1884 assert result.exit_code == 0
1885
1886 # Note: An prune/expiry of zero gets everything except for MS Windows
1887 # during testing only.
1888 # Until this can be resolved, this is the section of the test that
1889 # caused us to disable it in MS Windows
1890 stdout = result.stdout.strip()
1891 assert re.search(
1892 r"^1\.\s+[a-z0-9_-]{8}\s+\d+(?:\.\d{2})?[KMGT]?B\s+unused\b",
1893 stdout,
1894 re.MULTILINE,
1895 )
1896
1897 # New Temporary namespace
1898 new_persistent_base = tmpdir.mkdir("namespace")
1899 with environ(APPRISE_STORAGE_PATH=str(new_persistent_base)):
1900 # Reload our module
1901 reload(cli)
1902
1903 # Nothing in our directory yet
1904 dir_content = os.listdir(str(new_persistent_base))
1905 assert len(dir_content) == 0
1906
1907 # Generate notification that creates persistent data
1908 # storage path is pulled out of our environment variable
1909 result = runner.invoke(
1910 cli.main,
1911 [
1912 "--storage-mode",
1913 "flush",
1914 "--config",
1915 str(config),
1916 "-t",
1917 "title",
1918 "-b",
1919 "body",
1920 "-g",
1921 "test",
1922 ],
1923 )
1924 # We parsed our data accordingly
1925 assert result.exit_code == 0
1926
1927 # Now content exists
1928 dir_content = os.listdir(str(new_persistent_base))
1929 assert len(dir_content) == 1
1930
1931 # Reload our module with our environment variable gone
1932 reload(cli)
1933
1934 # Clear loaded modules
1935 N_MGR.unload_modules()
1936
1937
1938 def test_apprise_cli_details(tmpdir):
1939 """
1940 CLI: --details (-l)
1941
1942 """
1943
1944 runner = CliRunner()
1945
1946 #
1947 # Testing the printout of our details
1948 # --details or -l
1949 #
1950 result = runner.invoke(
1951 cli.main,
1952 [
1953 "--details",
1954 ],
1955 )
1956 assert result.exit_code == 0
1957
1958 result = runner.invoke(
1959 cli.main,
1960 [
1961 "-l",
1962 ],
1963 )
1964 assert result.exit_code == 0
1965
1966 # Clear loaded modules
1967 N_MGR.unload_modules()
1968
1969 # This is a made up class that is just used to verify
1970 class TestReq01Notification(NotifyBase):
1971 """This class is used to test various requirement configurations."""
1972
1973 # Set some requirements
1974 requirements: ClassVar[RequirementsSpec] = {
1975 "packages_required": [
1976 "cryptography <= 3.4",
1977 "ultrasync",
1978 ],
1979 "packages_recommended": "django",
1980 }
1981
1982 def url(self, **kwargs):
1983 # Support URL
1984 return ""
1985
1986 def send(self, **kwargs):
1987 # Pretend everything is okay (so we don't break other tests)
1988 return True
1989
1990 N_MGR["req01"] = TestReq01Notification
1991
1992 # This is a made up class that is just used to verify
1993 class TestReq02Notification(NotifyBase):
1994 """This class is used to test various requirement configurations."""
1995
1996 # Just not enabled at all
1997 enabled = False
1998
1999 # Set some requirements
2000 requirements: ClassVar[RequirementsSpec] = {
2001 # None and/or [] is implied, but jsut to show that the code won't
2002 # crash if explicitly set this way:
2003 "packages_required": None,
2004 "packages_recommended": [
2005 "cryptography <= 3.4",
2006 ],
2007 }
2008
2009 def url(self, **kwargs):
2010 # Support URL
2011 return ""
2012
2013 def send(self, **kwargs):
2014 # Pretend everything is okay (so we don't break other tests)
2015 return True
2016
2017 N_MGR["req02"] = TestReq02Notification
2018
2019 # This is a made up class that is just used to verify
2020 class TestReq03Notification(NotifyBase):
2021 """This class is used to test various requirement configurations."""
2022
2023 # Set some requirements (but additionally include a details over-ride)
2024 requirements: ClassVar[RequirementsSpec] = {
2025 # We can over-ride the default details assigned to our plugin if
2026 # specified
2027 "details": _("some specified requirement details"),
2028 # We can set a string value as well (it does not have to be a list)
2029 "packages_recommended": "cryptography <= 3.4",
2030 }
2031
2032 def url(self, **kwargs):
2033 # Support URL
2034 return ""
2035
2036 def send(self, **kwargs):
2037 # Pretend everything is okay (so we don't break other tests)
2038 return True
2039
2040 N_MGR["req03"] = TestReq03Notification
2041
2042 # This is a made up class that is just used to verify
2043 class TestReq04Notification(NotifyBase):
2044 """This class is used to test a case where our requirements is fixed to
2045 a None."""
2046
2047 # This is the same as saying there are no requirements
2048 requirements = None
2049
2050 def url(self, **kwargs):
2051 # Support URL
2052 return ""
2053
2054 def send(self, **kwargs):
2055 # Pretend everything is okay (so we don't break other tests)
2056 return True
2057
2058 N_MGR["req04"] = TestReq04Notification
2059
2060 # This is a made up class that is just used to verify
2061 class TestReq05Notification(NotifyBase):
2062 """This class is used to test a case where only packages_recommended is
2063 identified."""
2064
2065 requirements: ClassVar[RequirementsSpec] = {
2066 "packages_recommended": "cryptography <= 3.4"
2067 }
2068
2069 def url(self, **kwargs):
2070 # Support URL
2071 return ""
2072
2073 def send(self, **kwargs):
2074 # Pretend everything is okay (so we don't break other tests)
2075 return True
2076
2077 N_MGR["req05"] = TestReq05Notification
2078
2079 class TestDisabled01Notification(NotifyBase):
2080 """This class is used to test a pre-disabled state."""
2081
2082 # Just flat out disable our service
2083 enabled = False
2084
2085 # we'll use this as a key to make our service easier to find
2086 # in the next part of the testing
2087 service_name = "na01"
2088
2089 def url(self, **kwargs):
2090 # Support URL
2091 return ""
2092
2093 def notify(self, **kwargs):
2094 # Pretend everything is okay (so we don't break other tests)
2095 return True
2096
2097 N_MGR["na01"] = TestDisabled01Notification
2098
2099 class TestDisabled02Notification(NotifyBase):
2100 """This class is used to test a post-disabled state."""
2101
2102 # we'll use this as a key to make our service easier to find
2103 # in the next part of the testing
2104 service_name = "na02"
2105
2106 def __init__(self, *args, **kwargs):
2107 super().__init__(**kwargs)
2108
2109 # enable state changes **AFTER** we initialize
2110 self.enabled = False
2111
2112 def url(self, **kwargs):
2113 # Support URL
2114 return ""
2115
2116 def notify(self, **kwargs):
2117 # Pretend everything is okay (so we don't break other tests)
2118 return True
2119
2120 N_MGR["na02"] = TestDisabled02Notification
2121
2122 # We'll add a good notification to our list
2123 class TesEnabled01Notification(NotifyBase):
2124 """This class is just a simple enabled one."""
2125
2126 # we'll use this as a key to make our service easier to find
2127 # in the next part of the testing
2128 service_name = "good"
2129
2130 def url(self, **kwargs):
2131 # Support URL
2132 return ""
2133
2134 def send(self, **kwargs):
2135 # Pretend everything is okay (so we don't break other tests)
2136 return True
2137
2138 N_MGR["good"] = TesEnabled01Notification
2139
2140 # Verify that we can pass through all of our different details
2141 result = runner.invoke(
2142 cli.main,
2143 [
2144 "--details",
2145 ],
2146 )
2147 assert result.exit_code == 0
2148
2149 result = runner.invoke(
2150 cli.main,
2151 [
2152 "-l",
2153 ],
2154 )
2155 assert result.exit_code == 0
2156
2157 # Clear loaded modules
2158 N_MGR.unload_modules()
2159
2160
2161 def test_apprise_cli_print_help():
2162 """
2163 CLI: --help (-h)
2164
2165 """
2166 runner = CliRunner()
2167
2168 # Clear our working variables so they don't obstruct the next test
2169 # This simulates an actual call from the CLI. Unfortunately through
2170 # testing were occupying the same memory space so our singleton's
2171 # have already been populated
2172 N_MGR._paths_previously_scanned.clear()
2173 N_MGR._custom_module_map.clear()
2174
2175 # Print help and exit
2176 result = runner.invoke(cli.main, ["--help"])
2177 assert result.exit_code == 0
2178
2179 result = runner.invoke(cli.main, ["-h"])
2180 assert result.exit_code == 0
2181
2182
2183 @mock.patch("requests.request")
2184 def test_apprise_cli_plugin_loading(mock_request, tmpdir):
2185 """
2186 CLI: --plugin-path (-P)
2187
2188 """
2189 # Prepare Mock
2190 mock_request.return_value = requests.Request()
2191 mock_request.return_value.status_code = requests.codes.ok
2192
2193 runner = CliRunner()
2194
2195 # Clear our working variables so they don't obstruct the next test
2196 # This simulates an actual call from the CLI. Unfortunately through
2197 # testing were occupying the same memory space so our singleton's
2198 # have already been populated
2199 N_MGR._paths_previously_scanned.clear()
2200 N_MGR._custom_module_map.clear()
2201
2202 # Test a path that has no files to load in it
2203 result = runner.invoke(
2204 cli.main,
2205 [
2206 "--plugin-path",
2207 join(str(tmpdir), "invalid_path"),
2208 "-b",
2209 "test\nbody",
2210 "json://localhost",
2211 ],
2212 )
2213 # The path is silently loaded but fails... it's okay because the
2214 # notification we're choosing to notify does exist
2215 assert result.exit_code == 0
2216
2217 # Directories that don't exist passed in by the CLI aren't even scanned
2218 assert len(N_MGR._paths_previously_scanned) == 0
2219 assert len(N_MGR._custom_module_map) == 0
2220
2221 # Test our current existing path that has no entries in it
2222 result = runner.invoke(
2223 cli.main,
2224 [
2225 "--plugin-path",
2226 str(tmpdir.mkdir("empty")),
2227 "-b",
2228 "test\nbody",
2229 "json://localhost",
2230 ],
2231 )
2232 # The path is silently loaded but fails... it's okay because the
2233 # notification we're choosing to notify does exist
2234 assert result.exit_code == 0
2235 assert len(N_MGR._paths_previously_scanned) == 1
2236 assert join(str(tmpdir), "empty") in N_MGR._paths_previously_scanned
2237
2238 # However there was nothing to load
2239 assert len(N_MGR._custom_module_map) == 0
2240
2241 # Clear our working variables so they don't obstruct the next test
2242 # This simulates an actual call from the CLI. Unfortunately through
2243 # testing were occupying the same memory space so our singleton's
2244 # have already been populated
2245 N_MGR._paths_previously_scanned.clear()
2246 N_MGR._custom_module_map.clear()
2247
2248 # Prepare ourselves a file to work with
2249 notify_hook_a_base = tmpdir.mkdir("random")
2250 notify_hook_a = notify_hook_a_base.join("myhook01.py")
2251 notify_hook_a.write(
2252 cleandoc("""
2253 raise ImportError
2254 """)
2255 )
2256
2257 result = runner.invoke(
2258 cli.main,
2259 [
2260 "--plugin-path",
2261 str(notify_hook_a),
2262 "-b",
2263 "test\nbody",
2264 # A custom hook:
2265 "clihook://",
2266 ],
2267 )
2268 # It doesn't exist so it will fail
2269 # meanwhile we would have failed to load the myhook path
2270 assert result.exit_code == 1
2271
2272 # The path is silently loaded but fails... it's okay because the
2273 # notification we're choosing to notify does exist
2274 assert len(N_MGR._paths_previously_scanned) == 1
2275 assert str(notify_hook_a) in N_MGR._paths_previously_scanned
2276 # However there was nothing to load
2277 assert len(N_MGR._custom_module_map) == 0
2278
2279 # Prepare ourselves a file to work with
2280 notify_hook_aa = notify_hook_a_base.join("myhook02.py")
2281 notify_hook_aa.write(
2282 cleandoc("""
2283 garbage entry
2284 """)
2285 )
2286
2287 N_MGR.plugins()
2288 result = runner.invoke(
2289 cli.main,
2290 [
2291 "--plugin-path",
2292 str(notify_hook_aa),
2293 "-b",
2294 "test\nbody",
2295 # A custom hook:
2296 "clihook://custom",
2297 ],
2298 )
2299 # It doesn't exist so it will fail
2300 # meanwhile we would have failed to load the myhook path
2301 assert result.exit_code == 1
2302
2303 # The path is silently loaded but fails...
2304 # as a result the path stacks with the last
2305 assert len(N_MGR._paths_previously_scanned) == 2
2306 assert str(notify_hook_a) in N_MGR._paths_previously_scanned
2307 assert str(notify_hook_aa) in N_MGR._paths_previously_scanned
2308 # However there was nothing to load
2309 assert len(N_MGR._custom_module_map) == 0
2310
2311 # Clear our working variables so they don't obstruct the next test
2312 # This simulates an actual call from the CLI. Unfortunately through
2313 # testing were occupying the same memory space so our singleton's
2314 # have already been populated
2315 N_MGR._paths_previously_scanned.clear()
2316 N_MGR._custom_module_map.clear()
2317
2318 # Prepare ourselves a file to work with
2319 notify_hook_b = tmpdir.mkdir("goodmodule").join("__init__.py")
2320 notify_hook_b.write(
2321 cleandoc("""
2322 from apprise.decorators import notify
2323
2324 # We want to trigger on anyone who configures a call to clihook://
2325 @notify(on="clihook")
2326 def mywrapper(body, title, notify_type, *args, **kwargs):
2327 # A simple test - print to screen
2328 print("{}: {} - {}".format(notify_type, title, body))
2329
2330 # No return (so a return of None) get's translated to True
2331
2332 # Define another in the same file
2333 @notify(on="clihookA")
2334 def mywrapper(body, title, notify_type, *args, **kwargs):
2335 # A simple test - print to screen
2336 print("!! {}: {} - {}".format(notify_type, title, body))
2337
2338 # No return (so a return of None) get's translated to True
2339 """)
2340 )
2341
2342 result = runner.invoke(
2343 cli.main,
2344 [
2345 "--plugin-path",
2346 str(tmpdir),
2347 "-b",
2348 "test body",
2349 # A custom hook:
2350 "clihook://still/valid",
2351 ],
2352 )
2353
2354 # We can detect the goodmodule (which has an __init__.py in it)
2355 # so we'll load okay
2356 assert result.exit_code == 0
2357
2358 # Let's see how things got loaded:
2359 assert len(N_MGR._paths_previously_scanned) == 2
2360 assert str(tmpdir) in N_MGR._paths_previously_scanned
2361 # absolute path to detected module is also added
2362 assert (
2363 join(str(tmpdir), "goodmodule", "__init__.py")
2364 in N_MGR._paths_previously_scanned
2365 )
2366
2367 # We also loaded our clihook properly
2368 assert len(N_MGR._custom_module_map) == 1
2369
2370 # We can find our new hook loaded in our schema map now...
2371 assert "clihook" in N_MGR
2372
2373 # Capture our key for reference
2374 key = next(iter(N_MGR._custom_module_map.keys()))
2375
2376 # We loaded 2 entries from the same file
2377 assert len(N_MGR._custom_module_map[key]["notify"]) == 2
2378 assert "clihook" in N_MGR._custom_module_map[key]["notify"]
2379 # Converted to lower case
2380 assert "clihooka" in N_MGR._custom_module_map[key]["notify"]
2381
2382 # Our function name
2383 assert (
2384 N_MGR._custom_module_map[key]["notify"]["clihook"]["fn_name"]
2385 == "mywrapper"
2386 )
2387 # What we parsed from the `on` keyword in the @notify decorator
2388 assert (
2389 N_MGR._custom_module_map[key]["notify"]["clihook"]["url"]
2390 == "clihook://"
2391 )
2392 # our default name Assignment. This can be-overridden on the @notify
2393 # decorator by just adding a name= to the parameter list
2394 assert N_MGR["clihook"].service_name == "Custom - clihook"
2395
2396 # Our Base Notification object when initialized:
2397 assert (
2398 len(N_MGR._module_map[N_MGR._custom_module_map[key]["name"]]["plugin"])
2399 == 2
2400 )
2401 for plugin in N_MGR._module_map[N_MGR._custom_module_map[key]["name"]][
2402 "plugin"
2403 ]:
2404 assert isinstance(plugin(), NotifyBase)
2405
2406 # Clear our working variables so they don't obstruct the next test
2407 # This simulates an actual call from the CLI. Unfortunately through
2408 # testing were occupying the same memory space so our singleton's
2409 # have already been populated
2410 N_MGR._paths_previously_scanned.clear()
2411 N_MGR._custom_module_map.clear()
2412 del N_MGR["clihook"]
2413
2414 result = runner.invoke(
2415 cli.main,
2416 [
2417 "--plugin-path",
2418 str(notify_hook_b),
2419 "-b",
2420 "test body",
2421 # A custom hook:
2422 "clihook://",
2423 ],
2424 )
2425
2426 # Absolute path to __init__.py is okay
2427 assert result.exit_code == 0
2428
2429 # we can verify that it prepares our message
2430 assert result.stdout.strip() == "info: - test body"
2431
2432 # Clear our working variables so they don't obstruct the next test
2433 # This simulates an actual call from the CLI. Unfortunately through
2434 # testing were occupying the same memory space so our singleton's
2435 # have already been populated
2436 N_MGR._paths_previously_scanned.clear()
2437 N_MGR._custom_module_map.clear()
2438 del N_MGR["clihook"]
2439
2440 result = runner.invoke(
2441 cli.main,
2442 [
2443 "--plugin-path",
2444 dirname(str(notify_hook_b)),
2445 "-b",
2446 "test body",
2447 # A custom hook:
2448 "clihook://",
2449 ],
2450 )
2451
2452 # Now we succeed to load our module when pointed to it only because
2453 # an __init__.py is found on the inside of it
2454 assert result.exit_code == 0
2455
2456 # we can verify that it prepares our message
2457 assert result.stdout.strip() == "info: - test body"
2458
2459 # Test double paths that are the same; this ensures we only
2460 # load the plugin once
2461 result = runner.invoke(
2462 cli.main,
2463 [
2464 "--plugin-path",
2465 dirname(str(notify_hook_b)),
2466 "--plugin-path",
2467 str(notify_hook_b),
2468 "--details",
2469 ],
2470 )
2471
2472 # Now we succeed to load our module when pointed to it only because
2473 # an __init__.py is found on the inside of it
2474 assert result.exit_code == 0
2475
2476 # Clear our working variables so they don't obstruct the next test
2477 # This simulates an actual call from the CLI. Unfortunately through
2478 # testing were occupying the same memory space so our singleton's
2479 # have already been populated
2480 N_MGR._paths_previously_scanned.clear()
2481 N_MGR._custom_module_map.clear()
2482 del N_MGR["clihook"]
2483
2484 # Prepare ourselves a file to work with
2485 notify_hook_b = tmpdir.mkdir("complex").join("complex.py")
2486 notify_hook_b.write(
2487 cleandoc("""
2488 from apprise.decorators import notify
2489
2490 # We can't over-ride an element that already exists
2491 # in this case json://
2492 @notify(on="json")
2493 def mywrapper_01(body, title, notify_type, *args, **kwargs):
2494 # Return True (same as None)
2495 return True
2496
2497 @notify(on="willfail", name="always failing...")
2498 def mywrapper_02(body, title, notify_type, *args, **kwargs):
2499 # Simply fail
2500 return False
2501
2502 @notify(on="clihook1", name="the original clihook entry")
2503 def mywrapper_03(body, title, notify_type, *args, **kwargs):
2504 # Return True
2505 return True
2506
2507 # This is a duplicate o the entry above, so it can not be
2508 # loaded...
2509 @notify(on="clihook1", name="a duplicate of the clihook entry")
2510 def mywrapper_04(body, title, notify_type, *args, **kwargs):
2511 # Return True
2512 return True
2513
2514 # This is where things get realy cool... we can not only
2515 # define the schema we want to over-ride, but we can define
2516 # some default values to pass into our wrapper function to
2517 # act as a base before whatever was actually passed in is
2518 # applied ontop.... think of it like templating information
2519 @notify(on="clihook2://localhost")
2520 def mywrapper_05(body, title, notify_type, *args, **kwargs):
2521 # Return True
2522 return True
2523
2524
2525 # This can't load because of the defined schema/on definition
2526 @notify(on="", name="an invalid schema was specified")
2527 def mywrapper_06(body, title, notify_type, *args, **kwargs):
2528 return True
2529 """)
2530 )
2531
2532 result = runner.invoke(
2533 cli.main,
2534 [
2535 "--plugin-path",
2536 join(str(tmpdir), "complex"),
2537 "-b",
2538 "test body",
2539 # A custom hook that does not exist
2540 "clihook://",
2541 ],
2542 )
2543
2544 # Since clihook:// isn't in our complex listing, this will fail
2545 assert result.exit_code == 1
2546
2547 # Let's see how things got loaded
2548 assert len(N_MGR._paths_previously_scanned) == 2
2549 # Our path we specified on the CLI...
2550 assert join(str(tmpdir), "complex") in N_MGR._paths_previously_scanned
2551
2552 # absolute path to detected module is also added
2553 assert (
2554 join(str(tmpdir), "complex", "complex.py")
2555 in N_MGR._paths_previously_scanned
2556 )
2557
2558 # We loaded our one module successfuly
2559 assert len(N_MGR._custom_module_map) == 1
2560
2561 # We can find our new hook loaded in our SCHEMA_MAP now...
2562 assert "willfail" in N_MGR
2563 assert "clihook1" in N_MGR
2564 assert "clihook2" in N_MGR
2565
2566 # Capture our key for reference
2567 key = next(iter(N_MGR._custom_module_map.keys()))
2568
2569 assert len(N_MGR._custom_module_map[key]["notify"]) == 3
2570 assert "willfail" in N_MGR._custom_module_map[key]["notify"]
2571 assert "clihook1" in N_MGR._custom_module_map[key]["notify"]
2572 # We only load 1 instance of the clihook2, the second will fail
2573 assert "clihook2" in N_MGR._custom_module_map[key]["notify"]
2574 # We can never load previously created notifications
2575 assert "json" not in N_MGR._custom_module_map[key]["notify"]
2576
2577 result = runner.invoke(
2578 cli.main,
2579 [
2580 "--plugin-path",
2581 join(str(tmpdir), "complex"),
2582 "-b",
2583 "test body",
2584 # A custom notification set up for failure
2585 "willfail://",
2586 ],
2587 )
2588 # Note that the failure of the decorator carries all the way back
2589 # to the CLI
2590 assert result.exit_code == 1
2591
2592 result = runner.invoke(
2593 cli.main,
2594 [
2595 "--plugin-path",
2596 join(str(tmpdir), "complex"),
2597 "-b",
2598 "test body",
2599 # our clihook that returns true
2600 "clihook1://",
2601 # our other loaded clihook
2602 "clihook2://",
2603 ],
2604 )
2605 # Note that the failure of the decorator carries all the way back
2606 # to the CLI
2607 assert result.exit_code == 0
2608
2609 result = runner.invoke(
2610 cli.main,
2611 [
2612 "--plugin-path",
2613 join(str(tmpdir), "complex"),
2614 "--notification-type",
2615 "invalid",
2616 "-b",
2617 "test body",
2618 # our clihook that returns true
2619 "clihook1://",
2620 ],
2621 )
2622 # Bad notification type specified
2623 assert result.exit_code == 2
2624
2625 result = runner.invoke(
2626 cli.main,
2627 [
2628 "--plugin-path",
2629 join(str(tmpdir), "complex"),
2630 "-b",
2631 "-i",
2632 "warningtest body",
2633 # our clihook that returns true
2634 "clihook1://",
2635 ],
2636 )
2637 # Bad notification type specified
2638 assert result.exit_code == 0
2639
2640 result = runner.invoke(
2641 cli.main,
2642 [
2643 "--plugin-path",
2644 join(str(tmpdir), "complex"),
2645 # Print our custom details to the screen
2646 "--details",
2647 ],
2648 )
2649 assert "willfail" in result.stdout
2650 assert "always failing..." in result.stdout
2651
2652 assert "clihook1" in result.stdout
2653 assert "the original clihook entry" in result.stdout
2654 assert "a duplicate of the clihook entry" not in result.stdout
2655
2656 assert "clihook2" in result.stdout
2657 assert "Custom - clihook2" in result.stdout
2658
2659 # Note that the failure of the decorator carries all the way back
2660 # to the CLI
2661 assert result.exit_code == 0
2662
2663
2664 @mock.patch("platform.system")
2665 def test_apprise_cli_windows_env(mock_system):
2666 """
2667 CLI: Windows Environment
2668
2669 """
2670 # Force a windows environment
2671 mock_system.return_value = "Windows"
2672
2673 # Reload our module
2674 reload(cli)
2675
2676
2677 @mock.patch("apprise.cli.NotificationManager")
2678 @mock.patch("importlib.metadata.packages_distributions", create=True)
2679 @mock.patch("importlib.metadata.version")
2680 @mock.patch("apprise.cli.logger")
2681 def test_apprise_cli_runtime_env_skip_when_not_debug(
2682 mock_logger, mock_ver, mock_dist, mock_mgr
2683 ):
2684 """
2685 CLI: _log_runtime_env() exits immediately when not at DEBUG level.
2686 """
2687 # Simulate a logger that is not at DEBUG level
2688 mock_logger.isEnabledFor.return_value = False
2689
2690 cli._log_runtime_env()
2691
2692 # Nothing should be computed or logged
2693 mock_logger.debug.assert_not_called()
2694 mock_mgr.assert_not_called()
2695 mock_dist.assert_not_called()
2696 mock_ver.assert_not_called()
2697
2698
2699 @mock.patch("apprise.cli.NotificationManager")
2700 @mock.patch("importlib.metadata.packages_distributions", create=True)
2701 @mock.patch("importlib.metadata.version")
2702 @mock.patch("apprise.cli.logger")
2703 def test_apprise_cli_runtime_env_logging(
2704 mock_logger, mock_ver, mock_dist, mock_mgr
2705 ):
2706 """
2707 CLI: _log_runtime_env() summary
2708 """
2709 # Simulate a DEBUG-level logger
2710 mock_logger.isEnabledFor.return_value = True
2711
2712 # Plugin whose dep should appear in output
2713 class EnabledPlugin:
2714 enabled = True
2715
2716 @staticmethod
2717 def runtime_deps():
2718 return ("testpkg",)
2719
2720 # Disabled plugin -- its dep must NOT appear in output
2721 class DisabledPlugin:
2722 enabled = False
2723
2724 @staticmethod
2725 def runtime_deps():
2726 return ("disabled-dep",)
2727
2728 # Plugin with no runtime_deps attribute -- silently skipped
2729 class NoRuntimeDepsPlugin:
2730 enabled = True
2731
2732 mock_mgr.return_value = [
2733 {
2734 "plugin": {
2735 EnabledPlugin,
2736 DisabledPlugin,
2737 NoRuntimeDepsPlugin,
2738 },
2739 },
2740 ]
2741 mock_dist.return_value = {"testpkg": ["test-package"]}
2742 mock_ver.return_value = "9.9.9"
2743
2744 cli._log_runtime_env()
2745
2746 # Collect positional-arg tuples from each debug() call
2747 calls = [a for a, _ in mock_logger.debug.call_args_list]
2748
2749 # Environment summary lines must be present
2750 assert any(a[0] == "Apprise: %s" for a in calls)
2751 assert any(a[0] == "Python: %s" for a in calls)
2752 assert any(a[0] == "Platform: %s" for a in calls)
2753 assert any(a[0] == "Encoding: %s" for a in calls)
2754
2755 # Resolved deps emitted as a single inline line
2756 assert any(
2757 a[0] == "Runtime deps: %s" and a[1] == "test-package=9.9.9"
2758 for a in calls
2759 )
2760
2761 # Disabled plugin dep must not be logged
2762 assert not any("disabled-dep" in str(a) for a in calls)
2763
2764
2765 @mock.patch("apprise.cli.NotificationManager")
2766 @mock.patch("importlib.metadata.packages_distributions", create=True)
2767 @mock.patch("importlib.metadata.version")
2768 @mock.patch("apprise.cli.logger")
2769 def test_apprise_cli_runtime_env_no_runtime_deps(
2770 mock_logger, mock_ver, mock_dist, mock_mgr
2771 ):
2772 """
2773 CLI: _log_runtime_env()
2774 """
2775 mock_logger.isEnabledFor.return_value = True
2776
2777 # Plugin that declares no deps
2778 class NoDepsPlugin:
2779 enabled = True
2780
2781 @staticmethod
2782 def runtime_deps():
2783 return ()
2784
2785 mock_mgr.return_value = [{"plugin": {NoDepsPlugin}}]
2786
2787 cli._log_runtime_env()
2788
2789 # Environment header was still logged
2790 calls = [a for a, _ in mock_logger.debug.call_args_list]
2791 assert any(a[0] == "Apprise: %s" for a in calls)
2792
2793 # Package-metadata scan must not have been attempted
2794 mock_dist.assert_not_called()
2795 mock_ver.assert_not_called()
2796
2797 # No " pkg: ver" lines
2798 assert not any(a[0] == "Runtime deps: %s" for a in calls)
2799
2800
2801 @mock.patch("apprise.cli.NotificationManager")
2802 @mock.patch("importlib.metadata.packages_distributions", create=True)
2803 @mock.patch("importlib.metadata.version")
2804 @mock.patch("apprise.cli.logger")
2805 def test_apprise_cli_runtime_env_dist_map_exception(
2806 mock_logger, mock_ver, mock_dist, mock_mgr
2807 ):
2808 """
2809 CLI: _log_runtime_env() handles packages_distributions() failures.
2810 """
2811 mock_logger.isEnabledFor.return_value = True
2812
2813 class DepPlugin:
2814 enabled = True
2815
2816 @staticmethod
2817 def runtime_deps():
2818 return ("somepkg",)
2819
2820 mock_mgr.return_value = [{"plugin": {DepPlugin}}]
2821 mock_dist.side_effect = Exception("metadata unavailable")
2822
2823 # Must not raise
2824 cli._log_runtime_env()
2825
2826 # pkg_version should never be reached
2827 mock_ver.assert_not_called()
2828
2829 # No " pkg: ver" lines
2830 calls = [a for a, _ in mock_logger.debug.call_args_list]
2831 assert not any(a[0] == "Runtime deps: %s" for a in calls)
2832
2833
2834 @mock.patch("apprise.cli.NotificationManager")
2835 @mock.patch("importlib.metadata.packages_distributions", create=True)
2836 @mock.patch("importlib.metadata.version")
2837 @mock.patch("apprise.cli.logger")
2838 def test_apprise_cli_runtime_env_lookup_errors(
2839 mock_logger, mock_ver, mock_dist, mock_mgr
2840 ):
2841 """
2842 CLI: _log_runtime_env() silently skips packages exception raised.
2843 """
2844 mock_logger.isEnabledFor.return_value = True
2845
2846 # Plugin whose runtime_deps() raises
2847 class BrokenPlugin:
2848 enabled = True
2849
2850 @staticmethod
2851 def runtime_deps():
2852 raise RuntimeError("plugin error")
2853
2854 # Plugin whose dep import name is not in the dist map
2855 class UnmappedPlugin:
2856 enabled = True
2857
2858 @staticmethod
2859 def runtime_deps():
2860 return ("notmapped",)
2861
2862 # Plugin whose dep maps to a dist but the version lookup fails
2863 class VersionlessPlugin:
2864 enabled = True
2865
2866 @staticmethod
2867 def runtime_deps():
2868 return ("verpkg",)
2869
2870 mock_mgr.return_value = [
2871 {
2872 "plugin": {
2873 BrokenPlugin,
2874 UnmappedPlugin,
2875 VersionlessPlugin,
2876 },
2877 },
2878 ]
2879
2880 # "notmapped" absent from map; "verpkg" present but ver raises
2881 mock_dist.return_value = {"verpkg": ["ver-package"]}
2882 mock_ver.side_effect = PackageNotFoundError("ver-package")
2883
2884 # Must not raise
2885 cli._log_runtime_env()
2886
2887 # None of the error paths should produce a " pkg: ver" line
2888 calls = [a for a, _ in mock_logger.debug.call_args_list]
2889 assert not any(a[0] == "Runtime deps: %s" for a in calls)
2890
2891
2892 @pytest.mark.skipif(
2893 sys.version_info < (3, 11),
2894 reason="packages_distributions requires Python 3.11+",
2895 )
2896 @mock.patch("apprise.cli.NotificationManager")
2897 @mock.patch("apprise.cli.logger")
2898 def test_apprise_cli_runtime_env_no_packages_distributions(
2899 mock_logger, mock_mgr
2900 ):
2901 """
2902 CLI: _log_runtime_env() gracefully skips dep listing when
2903 packages_distributions() is missing (ImportError path).
2904 Simulates the Python < 3.11 scenario on Python 3.11+ by temporarily
2905 removing packages_distributions from importlib.metadata.
2906 """
2907 import importlib.metadata as _meta
2908
2909 mock_logger.isEnabledFor.return_value = True
2910
2911 class DepPlugin:
2912 enabled = True
2913
2914 @staticmethod
2915 def runtime_deps():
2916 return ("somepkg",)
2917
2918 mock_mgr.return_value = [{"plugin": {DepPlugin}}]
2919
2920 # Temporarily hide packages_distributions to trigger the ImportError
2921 _pd = _meta.packages_distributions
2922 del _meta.packages_distributions
2923 try:
2924 cli._log_runtime_env()
2925 finally:
2926 _meta.packages_distributions = _pd
2927
2928 # Env summary was still logged despite the missing function
2929 calls = [a for a, _ in mock_logger.debug.call_args_list]
2930 assert any(a[0] == "Apprise: %s" for a in calls)
2931
2932 # No dep listing -- packages_distributions was unavailable
2933 assert not any(a[0] == "Runtime deps: %s" for a in calls)
2934
2935
2936 # Remove this test when Python 3.9 support is dropped.
2937 @pytest.mark.skipif(
2938 sys.version_info >= (3, 11),
2939 reason="packages_distributions exists on Python 3.11+",
2940 )
2941 @mock.patch("apprise.cli.NotificationManager")
2942 @mock.patch("apprise.cli.logger")
2943 def test_apprise_cli_runtime_env_py39_no_packages_distributions(
2944 mock_logger, mock_mgr
2945 ):
2946 """
2947 CLI: _log_runtime_env() gracefully skips dep listing on Python < 3.11
2948 where packages_distributions() is genuinely absent.
2949 """
2950 mock_logger.isEnabledFor.return_value = True
2951
2952 class DepPlugin:
2953 enabled = True
2954
2955 @staticmethod
2956 def runtime_deps():
2957 return ("somepkg",)
2958
2959 mock_mgr.return_value = [{"plugin": {DepPlugin}}]
2960
2961 # packages_distributions() absent natively -- no manipulation needed
2962 cli._log_runtime_env()
2963
2964 # Env summary was still logged despite the missing function
2965 calls = [a for a, _ in mock_logger.debug.call_args_list]
2966 assert any(a[0] == "Apprise: %s" for a in calls)
2967
2968 # No dep listing -- packages_distributions unavailable on Python < 3.11
2969 assert not any(a[0] == "Runtime deps: %s" for a in calls)