Debian Codegraph @

tests/test_config_base.py

raw
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28 from datetime import datetime, timezone as _tz, tzinfo
29 from inspect import cleandoc
30
31 # Disable logging for a cleaner testing output
32 import logging
33 from typing import Any
34 from unittest.mock import Mock
35
36 import pytest
37 from pytest_mock import MockerFixture
38 import requests
39 import yaml
40
41 from apprise import Apprise, AppriseAsset, AppriseConfig, ConfigFormat
42 from apprise.config import ConfigBase
43 from apprise.exception import AppriseImproperlyConfigured
44 from apprise.plugins.email import NotifyEmail
45 from apprise.utils.time import zoneinfo
46
47 logging.disable(logging.CRITICAL)
48
49
50 @pytest.fixture
51 def requests_remote_config(mocker: MockerFixture) -> Mock:
52 """
53 Patch requests.post globally.
54
55 The config loader will still go through its normal HTTP logic, but all
56 outbound GETs will receive controlled in-memory responses.
57 """
58
59 def fake_post(url: str, *args: Any, **kwargs: Any) -> requests.Response:
60 if url == "http://localhost:8000/get/test-001":
61 body = cleandoc("""
62 json://localhost
63 form://localhost
64 """)
65 elif url == "http://localhost:8000/get/test-002":
66 body = cleandoc("""
67 xml://localhost
68 """)
69 else:
70 pytest.fail(f"Unexpected URL fetched: {url!r}")
71
72 resp = requests.Response()
73 resp.status_code = requests.codes.ok
74 resp.url = url
75 resp._content = body.encode("utf-8") # type: ignore[attr-defined]
76 resp.encoding = "utf-8"
77 return resp
78
79 # Patch the actual requests.post symbol that ConfigHTTP uses internally
80 mock_post: Mock = mocker.patch("requests.post", side_effect=fake_post)
81 return mock_post
82
83
84 def test_config_base():
85 """
86 API: ConfigBase() object
87
88 """
89
90 # invalid types throw exceptions
91 with pytest.raises(AppriseImproperlyConfigured):
92 ConfigBase(**{"format": "invalid"})
93
94 # Config format types are not the same as ConfigBase ones
95 with pytest.raises(AppriseImproperlyConfigured):
96 ConfigBase(**{"format": "markdown"})
97
98 cb = ConfigBase(**{"format": "yaml"})
99 assert isinstance(cb, ConfigBase)
100
101 cb = ConfigBase(**{"format": "text"})
102 assert isinstance(cb, ConfigBase)
103
104 # Set encoding
105 cb = ConfigBase(encoding="utf-8", format="text")
106 assert isinstance(cb, ConfigBase)
107
108 # read is not supported in the base object; only the children
109 assert cb.read() is None
110
111 # There are no services loaded on a freshly created object
112 assert len(cb.services()) == 0
113
114 # Unsupported URLs are not parsed
115 assert ConfigBase.parse_url(url="invalid://") is None
116
117 # Valid URL & Valid Format
118 results = ConfigBase.parse_url(
119 url="file://relative/path?format=yaml&encoding=latin-1"
120 )
121 assert isinstance(results, dict)
122 # These are moved into the root
123 assert results.get("format") == "yaml"
124 assert results.get("encoding") == "latin-1"
125
126 # But they also exist in the qsd location
127 assert isinstance(results.get("qsd"), dict)
128 assert results["qsd"].get("encoding") == "latin-1"
129 assert results["qsd"].get("format") == "yaml"
130
131 # Valid URL & Invalid Format
132 results = ConfigBase.parse_url(
133 url="file://relative/path?format=invalid&encoding=latin-1"
134 )
135 assert isinstance(results, dict)
136 # Only encoding is moved into the root
137 assert "format" not in results
138 assert results.get("encoding") == "latin-1"
139
140 # But they will always exist in the qsd location
141 assert isinstance(results.get("qsd"), dict)
142 assert results["qsd"].get("encoding") == "latin-1"
143 assert results["qsd"].get("format") == "invalid"
144
145
146 def test_config_base_detect_config_format():
147 """
148 API: ConfigBase.detect_config_format
149
150 """
151
152 # Garbage Handling
153 for garbage in (object(), None, 42):
154 # A response is always correctly returned
155 assert ConfigBase.detect_config_format(garbage) is None
156
157 # Empty files are valid
158 assert ConfigBase.detect_config_format("") is ConfigFormat.TEXT
159
160 # Valid Text Configuration
161 assert (
162 ConfigBase.detect_config_format("""
163 # A comment line over top of a URL
164 mailto://userb:[email protected]
165 """)
166 is ConfigFormat.TEXT
167 )
168
169 # A text file that has semi-colon as comment characters
170 # is valid too
171 assert (
172 ConfigBase.detect_config_format("""
173 ; A comment line over top of a URL
174 mailto://userb:[email protected]
175 """)
176 is ConfigFormat.TEXT
177 )
178
179 # Valid YAML Configuration
180 assert (
181 ConfigBase.detect_config_format("""
182 # A comment line over top of a URL
183 version: 1
184 """)
185 is ConfigFormat.YAML
186 )
187
188 # Just a whole lot of blank lines...
189 assert ConfigBase.detect_config_format("\n\n\n") is ConfigFormat.TEXT
190
191 # A tag group assignment carries tags instead of a URL, but it is still
192 # TEXT format; detection must not stop at the first one it encounters
193 assert (
194 ConfigBase.detect_config_format("""
195 # A group lets one name stand for several others
196 family=me,wife,kids
197 me=mailto://userb:[email protected]
198 """)
199 is ConfigFormat.TEXT
200 )
201
202 # A group assignment that carries a priority prefixed tag
203 assert (
204 ConfigBase.detect_config_format("""
205 1:alerts,me=ntfy://ntfy.sh/chris-phone
206 """)
207 is ConfigFormat.TEXT
208 )
209
210 # A colon in the key still identifies YAML when no URL or tag list
211 # follows it
212 assert (
213 ConfigBase.detect_config_format("""
214 version: 1
215 """)
216 is ConfigFormat.YAML
217 )
218
219 # Invalid Config
220 assert ConfigBase.detect_config_format("3") is None
221
222
223 def test_config_base_config_parse():
224 """
225 API: ConfigBase.config_parse
226
227 """
228
229 # Garbage Handling
230 for garbage in (object(), None, 42):
231 # A response is always correctly returned
232 result = ConfigBase.config_parse(garbage)
233 # response is a tuple...
234 assert isinstance(result, tuple)
235 # containing 2 items (plugins, config)
236 assert len(result) == 2
237 # In the case of garbage in, we get garbage out; both lists are empty
238 assert result == ([], [])
239
240 # Valid Text Configuration
241 result = ConfigBase.config_parse(
242 """
243 # A comment line over top of a URL
244 mailto://userb:[email protected]
245 """,
246 asset=AppriseAsset(),
247 )
248 # We expect to parse 1 entry from the above
249 assert isinstance(result, tuple)
250 assert len(result) == 2
251 # The first element is the number of notification services processed
252 assert len(result[0]) == 1
253 # If we index into the item, we can check to see the tags associate
254 # with it
255 assert len(result[0][0].tags) == 0
256
257 # The second is the number of configuration include lines parsed
258 assert len(result[1]) == 0
259
260 # Valid Configuration
261 result = ConfigBase.config_parse(
262 """
263 # if no version is specified then version 1 is presumed
264 version: 1
265
266 #
267 # Define your notification urls:
268 #
269 urls:
270 - pbul://o.gn5kj6nfhv736I7jC3cj3QLRiyhgl98b
271 - mailto://test:[email protected]
272 - json://localhost:
273 - tag: devops, admin
274 """,
275 asset=AppriseAsset(),
276 )
277
278 # We expect to parse 2 entries from the above
279 assert isinstance(result, tuple)
280 assert len(result) == 2
281 assert isinstance(result[0], list)
282 assert len(result[0]) == 3
283 assert len(result[0][0].tags) == 0
284 assert len(result[0][1].tags) == 0
285 assert len(result[0][2].tags) == 2
286
287 # Test case where we pass in a bad format
288 result = ConfigBase.config_parse(
289 """
290 ; A comment line over top of a URL
291 mailto://userb:[email protected]
292 """,
293 config_format="invalid-format",
294 )
295
296 # This is not parseable despite the valid text
297 assert isinstance(result, tuple)
298 assert isinstance(result[0], list)
299 assert len(result[0]) == 0
300
301 result, _ = ConfigBase.config_parse(
302 """
303 ; A comment line over top of a URL
304 mailto://userb:[email protected]
305 """,
306 config_format=ConfigFormat.TEXT,
307 )
308
309 # Parseable
310 assert isinstance(result, list)
311 assert len(result) == 1
312
313
314 def test_config_base_discord_bug_report_01():
315 """
316 API: ConfigBase.config_parse user feedback
317
318 A Discord report that a tag was not correctly assigned to a URL when
319 presented in the following format
320 urls:
321 - json://myhost:
322 - tag: test
323 userid: test
324 """
325 result, config = ConfigBase.config_parse(
326 """
327 urls:
328 - json://myhost:
329 - tag: test
330 userid: test
331 """,
332 asset=AppriseAsset(),
333 )
334
335 # We expect to parse 4 entries from the above
336 assert isinstance(result, list)
337 assert isinstance(config, list)
338 assert len(result) == 1
339 assert len(result[0].tags) == 1
340 assert "test" in result[0].tags
341
342
343 def test_config_base_config_parse_text():
344 """
345 API: ConfigBase.config_parse_text object
346
347 """
348
349 # Garbage Handling
350 for garbage in (object(), None, 42):
351 # A response is always correctly returned
352 result = ConfigBase.config_parse_text(garbage)
353 # response is a tuple...
354 assert isinstance(result, tuple)
355 # containing 2 items (plugins, config)
356 assert len(result) == 2
357 # In the case of garbage in, we get garbage out; both lists are empty
358 assert result == ([], [])
359
360 # Valid Configuration
361 result, config = ConfigBase.config_parse_text(
362 """
363 # A completely invalid token on json string (it gets ignored)
364 # but the URL is still valid
365 json://localhost?invalid-token=nodashes
366
367 # A comment line over top of a URL
368 mailto://userb:[email protected]
369
370 # Test a URL using it's native format; in this case Ryver
371 https://apprise.ryver.com/application/webhook/ckhrjW8w672m6HG
372
373 # Invalid URL as it's not associated with a plugin
374 # or a native url
375 https://not.a.native.url/
376
377 # A line with mulitiple tag assignments to it
378 taga,tagb=kde://
379
380 # An include statement to Apprise API with trailing spaces:
381 include http://localhost:8080/notify/apprise
382
383 # A relative include statement (with trailing spaces)
384 include apprise.cfg """,
385 asset=AppriseAsset(),
386 )
387
388 # We expect to parse 4 entries from the above
389 assert isinstance(result, list)
390 assert isinstance(config, list)
391 assert len(result) == 4
392 assert len(result[0].tags) == 0
393
394 # Our last element will have 2 tags associated with it
395 assert len(result[-1].tags) == 2
396 assert "taga" in result[-1].tags
397 assert "tagb" in result[-1].tags
398
399 assert len(config) == 2
400 assert "http://localhost:8080/notify/apprise" in config
401 assert "apprise.cfg" in config
402
403 # Here is a similar result set however this one has an invalid line
404 # in it which invalidates the entire file
405 result, config = ConfigBase.config_parse_text("""
406 # A comment line over top of a URL
407 mailto://userc:[email protected]
408
409 # A line with mulitiple tag assignments to it
410 taga,tagb=windows://
411
412 I am an invalid line that does not follow any of the Apprise file rules!
413 """)
414
415 # We expect to parse 0 entries from the above because the invalid line
416 # invalidates the entire configuration file. This is for security reasons;
417 # we don't want to point at files load content in them just because they
418 # resemble an Apprise configuration.
419 assert isinstance(result, list)
420 assert len(result) == 0
421
422 # There were no include entries defined
423 assert len(config) == 0
424
425 # More invalid data
426 result, config = ConfigBase.config_parse_text("""
427 # An invalid URL
428 invalid://user:[email protected]
429
430 # A tag without a url
431 taga=
432
433 # A very poorly structured url
434 sns://:@/
435
436 # Just 1 token provided
437 sns://T1JJ3T3L2/
438
439 # Even with the above invalid entries, we can still
440 # have valid include lines
441 include file:///etc/apprise.cfg
442
443 # An invalid include (nothing specified afterwards)
444 include
445
446 # An include of a config type we don't support
447 include invalid://
448 """)
449
450 # We expect to parse 0 entries from the above
451 assert isinstance(result, list)
452 assert len(result) == 0
453
454 # There were no include entries defined
455 assert len(config) == 0
456
457 # Test case where a comment is on it's own line with nothing else
458 result, config = ConfigBase.config_parse_text("#")
459 # We expect to parse 0 entries from the above
460 assert isinstance(result, list)
461 assert len(result) == 0
462
463 # There were no include entries defined
464 assert len(config) == 0
465
466 # Verify our tagging works when multiple tags are provided
467 result, config = ConfigBase.config_parse_text("""
468 tag1, tag2, tag3=json://user:pass@localhost
469 """)
470
471 assert isinstance(result, list)
472 assert len(result) == 1
473 assert len(result[0].tags) == 3
474 assert "tag1" in result[0].tags
475 assert "tag2" in result[0].tags
476 assert "tag3" in result[0].tags
477
478
479 def test_config_base_config_tag_groups_text():
480 """
481 API: ConfigBase.config_tag_groups_text object
482
483 """
484
485 # Valid Configuration
486 result, config = ConfigBase.config_parse_text(
487 """
488 # Tag assignments
489 groupA, groupB = tagB, tagC
490
491 # groupB doubles down as it takes the entries initialized above
492 # plus the added ones defined below
493 groupB = tagA, tagB, tagD
494 groupC = groupA, groupB, groupC, tagE
495
496 # Tag that recursively looks to more tags
497 groupD = groupC
498
499 # Assigned ourselves
500 groupX = groupX
501
502 # Set up a recursive loop
503 groupE = groupF
504 groupF = groupE
505
506 # Set up a larger recursive loop
507 groupG = groupH
508 groupH = groupI
509 groupI = groupJ
510 groupJ = groupK
511 groupK = groupG
512
513 # Bad assignments
514 groupM = , , ,
515 , , = , , ,
516
517 # int's and floats are okay
518 1 = 2
519 a = 5
520
521 # A comment line over top of a URL
522 4, groupB = mailto://userb:[email protected]
523
524 # Tag Assignments
525 tagA,groupB=json://localhost
526
527 # More Tag Assignments
528 tagC,groupB=xml://localhost
529
530 # More Tag Assignments
531 groupD=form://localhost
532
533 """,
534 asset=AppriseAsset(),
535 )
536
537 # We expect to parse 4 entries from the above
538 assert isinstance(result, list)
539 assert isinstance(config, list)
540 assert len(result) == 4
541
542 # Our first element is our group tags
543 assert len(result[0].tags) == 2
544 assert "groupb" in result[0].tags
545 assert "4" in result[0].tags
546
547 # No additional configuration is loaded
548 assert len(config) == 0
549
550 apobj = Apprise()
551 assert apobj.add(result)
552 # We match against 1 entry
553 assert len(list(apobj.find("tagA"))) == 1
554 assert len(list(apobj.find("tagB"))) == 0
555 assert len(list(apobj.find("groupA"))) == 1
556 assert len(list(apobj.find("groupB"))) == 3
557 assert len(list(apobj.find("groupC"))) == 2
558 assert len(list(apobj.find("groupD"))) == 3
559
560 # Invalid Assignment
561 result, config = ConfigBase.config_parse_text("""
562 # Must have something to equal or it's a bad line
563 group =
564
565 # A tag Assignments that is never gotten to as the line
566 # above is bad
567 groupD=form://localhost
568 """)
569
570 # We expect to parse 0 entries from the above
571 assert isinstance(result, list)
572 assert isinstance(config, list)
573 assert len(result) == 0
574 assert len(config) == 0
575
576 # Invalid Assignment
577 result, config = ConfigBase.config_parse_text("""
578 # Rundant assignment
579 group = group
580
581 # Our group assignment
582 group=windows://
583
584 """)
585
586 # the redundant assignment does us no harm; but it doesn't grant us any
587 # value either
588 assert isinstance(result, list)
589 assert len(result) == 1
590
591 # Our first element is our group tags
592 assert len(result[0].tags) == 1
593 assert "group" in result[0].tags
594
595 # There were no include entries defined
596 assert len(config) == 0
597
598 # More invalid data
599 result, config = ConfigBase.config_parse_text("""
600 # A tag without a url or group assignment
601 taga=
602
603 """)
604
605 # We expect to parse 0 entries from the above
606 assert isinstance(result, list)
607 assert len(result) == 0
608
609 # There were no include entries defined
610 assert len(config) == 0
611
612 result, config = ConfigBase.config_parse_text("""
613 # A tag without a url or group assignment
614 taga= %%INVALID
615 """)
616
617 # We expect to parse 0 entries from the above
618 assert isinstance(result, list)
619 assert len(result) == 0
620
621 # There were no include entries defined
622 assert len(config) == 0
623
624
625 def test_config_base_config_parse_text_with_url():
626 """
627 API: ConfigBase.config_parse_text object_with_url
628
629 """
630 # Here is a similar result set however this one has an invalid line
631 # in it which invalidates the entire file
632 result, config = ConfigBase.config_parse_text("""
633 # Test a URL that has a URL as an argument
634 json://user:pass@localhost?+arg=http://example.com?arg2=1&arg3=3
635 """)
636
637 # No tag is parsed, but our URL successfully parses as is
638
639 assert isinstance(result, list)
640 assert len(result) == 1
641 assert len(result[0].tags) == 0
642
643 # Verify our URL is correctly captured
644 assert "%2Barg=http%3A%2F%2Fexample.com%3Farg2%3D1" in result[0].url()
645 assert "json://user:pass@localhost/" in result[0].url()
646
647 # There were no include entries defined
648 assert len(config) == 0
649
650 # Pass in our configuration again
651 result, config = ConfigBase.config_parse_text(result[0].url())
652
653 # Verify that our results repeat themselves
654 assert isinstance(result, list)
655 assert len(result) == 1
656 assert len(result[0].tags) == 0
657 assert "%2Barg=http%3A%2F%2Fexample.com%3Farg2%3D1" in result[0].url()
658 assert "json://user:pass@localhost/" in result[0].url()
659
660 assert len(config) == 0
661
662
663 def test_config_base_config_parse_yaml():
664 """
665 API: ConfigBase.config_parse_yaml object
666
667 """
668
669 # general reference used below
670 asset = AppriseAsset()
671
672 # Garbage Handling
673 for garbage in (object(), None, "", 42):
674 # A response is always correctly returned
675 result = ConfigBase.config_parse_yaml(garbage)
676 # response is a tuple...
677 assert isinstance(result, tuple)
678 # containing 2 items (plugins, config)
679 assert len(result) == 2
680 # In the case of garbage in, we get garbage out; both lists are empty
681 assert result == ([], [])
682
683 # Invalid Version
684 result, config = ConfigBase.config_parse_yaml("version: 2a", asset=asset)
685
686 # Invalid data gets us an empty result set
687 assert isinstance(result, list)
688 assert len(result) == 0
689
690 # There were no include entries defined
691 assert len(config) == 0
692
693 # Invalid Syntax (throws a ScannerError)
694 result, config = ConfigBase.config_parse_yaml(
695 """
696 # if no version is specified then version 1 is presumed
697 version: 1
698
699 urls
700 """,
701 asset=asset,
702 )
703
704 # Invalid data gets us an empty result set
705 assert isinstance(result, list)
706 assert len(result) == 0
707
708 # There were no include entries defined
709 assert len(config) == 0
710
711 # Missing url token
712 result, config = ConfigBase.config_parse_yaml(
713 """
714 # if no version is specified then version 1 is presumed
715 version: 1
716
717 """,
718 asset=asset,
719 )
720
721 # Invalid data gets us an empty result set
722 assert isinstance(result, list)
723 assert len(result) == 0
724
725 # There were no include entries defined
726 assert len(config) == 0
727
728 # No urls defined
729 result, config = ConfigBase.config_parse_yaml(
730 """
731 # if no version is specified then version 1 is presumed
732 version: 1
733
734 urls:
735 """,
736 asset=asset,
737 )
738
739 # Invalid data gets us an empty result set
740 assert isinstance(result, list)
741 assert len(result) == 0
742
743 # There were no include entries defined
744 assert len(config) == 0
745
746 # Invalid url defined
747 result, config = ConfigBase.config_parse_yaml(
748 """
749 # if no version is specified then version 1 is presumed
750 version: 1
751
752 # Invalid URL definition; yet the answer to life at the same time
753 urls: 43
754 """,
755 asset=asset,
756 )
757
758 # Invalid data gets us an empty result set
759 assert isinstance(result, list)
760 assert len(result) == 0
761
762 # There were no include entries defined
763 assert len(config) == 0
764
765 # Invalid url/schema
766 result, config = ConfigBase.config_parse_yaml(
767 """
768 # if no version is specified then version 1 is presumed
769 version: 1
770
771 urls:
772 - invalid://
773
774 """,
775 asset=asset,
776 )
777
778 # Invalid data gets us an empty result set
779 assert isinstance(result, list)
780 assert len(result) == 0
781
782 # There were no include entries defined
783 assert len(config) == 0
784
785 # Invalid url/schema
786 result, config = ConfigBase.config_parse_yaml(
787 """
788 # if no version is specified then version 1 is presumed
789 version: 1
790
791 urls:
792 - invalid://:
793 - a: b
794
795 """,
796 asset=asset,
797 )
798
799 # Invalid data gets us an empty result set
800 assert isinstance(result, list)
801 assert len(result) == 0
802
803 # There were no include entries defined
804 assert len(config) == 0
805
806 # Invalid url/schema
807 result, config = ConfigBase.config_parse_yaml(
808 """
809 # Include entry with nothing associated with it
810 include:
811
812 urls:
813 - just some free text that isn't valid:
814 - a garbage entry to go with it
815
816 """,
817 asset=asset,
818 )
819
820 # Invalid data gets us an empty result set
821 assert isinstance(result, list)
822 assert len(result) == 0
823
824 # There were no include entries defined
825 assert len(config) == 0
826
827 # Invalid url/schema
828 result, config = ConfigBase.config_parse_yaml(
829 """
830 # if no version is specified then version 1 is presumed
831 version: 1
832
833 urls:
834 - not even a proper url
835
836 """,
837 asset=asset,
838 )
839
840 # Invalid data gets us an empty result set
841 assert isinstance(result, list)
842 assert len(result) == 0
843
844 # There were no include entries defined
845 assert len(config) == 0
846
847 # Invalid url/schema
848 result, config = ConfigBase.config_parse_yaml(
849 """
850 urls:
851 # a very invalid sns entry
852 - sns://T1JJ3T3L2/
853 - sns://:@/:
854 - invalid: test
855 - sns://T1JJ3T3L2/:
856 - invalid: test
857 - _invalid: Token can not start with an underscore
858
859 # some strangeness
860 -
861 -
862 - test
863
864 """,
865 asset=asset,
866 )
867
868 # Invalid data gets us an empty result set
869 assert isinstance(result, list)
870 assert len(result) == 0
871
872 # There were no include entries defined
873 assert len(config) == 0
874
875 # Valid Configuration
876 result, config = ConfigBase.config_parse_yaml(
877 """
878 # if no version is specified then version 1 is presumed
879 version: 1
880
881 # Including by dict
882 include:
883 # File includes
884 - file:///absolute/path/
885 - relative/path
886 # Trailing colon shouldn't disrupt include
887 - http://test.com:
888
889 # invalid (numeric)
890 - 4
891
892 # some strangeness
893 -
894 -
895 - test
896
897 #
898 # Define your notification urls:
899 #
900 urls:
901 - pbul://o.gn5kj6nfhv736I7jC3cj3QLRiyhgl98b
902 - mailto://test:[email protected]
903 - https://apprise.ryver.com/application/webhook/ckhrjW8w672m6HG
904 - https://not.a.native.url/
905
906 # A completely invalid token on json string (it gets ignored)
907 # but the URL is still valid
908 - json://localhost?invalid-token=nodashes
909
910 """,
911 asset=asset,
912 )
913
914 # We expect to parse 4 entries from the above
915 # The Ryver one is in a native form and the 4th one is invalid
916 assert isinstance(result, list)
917 assert len(result) == 4
918 assert len(result[0].tags) == 0
919
920 # There were 3 include entries
921 assert len(config) == 3
922 assert "file:///absolute/path/" in config
923 assert "relative/path" in config
924 assert "http://test.com" in config
925
926 # Valid Configuration
927 result, config = ConfigBase.config_parse_yaml(
928 """
929 # A single line include is supported
930 include: http://localhost:8080/notify/apprise
931
932 urls:
933 # The following generates 1 service
934 - json://localhost:
935 tag: my-custom-tag, my-other-tag
936
937 # The following also generates 1 service
938 - json://localhost:
939 - tag: my-custom-tag, my-other-tag
940
941 # How to stack multiple entries (this generates 2):
942 - mailto://user:[email protected]:
943 - to: [email protected]
944 - to: [email protected]
945
946 # This is an illegal entry; the schema can not be changed
947 schema: json
948
949 # accidently left a colon at the end of the url; no problem
950 # we'll accept it
951 - mailto://oscar:[email protected]:
952
953 # A Ryver URL (using Native format); still accepted
954 - https://apprise.ryver.com/application/webhook/ckhrjW8w672m6HG:
955
956 # An invalid URL with colon (ignored)
957 - https://not.a.native.url/:
958
959 # A telegram entry (returns a None in parse_url())
960 - tgram://invalid
961
962 """,
963 asset=asset,
964 )
965
966 # We expect to parse 6 entries from the above because the tgram:// entry
967 # would have failed to be loaded
968 assert isinstance(result, list)
969 assert len(result) == 6
970 assert len(result[0].tags) == 2
971
972 # Our single line included
973 assert len(config) == 1
974 assert "http://localhost:8080/notify/apprise" in config
975
976 # Global Tags
977 result, config = ConfigBase.config_parse_yaml(
978 """
979 # Global Tags stacked as a list
980 tag:
981 - admin
982 - devops
983
984 urls:
985 - json://localhost
986 - dbus://
987 """,
988 asset=asset,
989 )
990
991 # We expect to parse 2 entries from the above
992 assert isinstance(result, list)
993 assert len(result) == 2
994
995 # There were no include entries defined
996 assert len(config) == 0
997
998 # all entries will have our global tags defined in them
999 for entry in result:
1000 assert "admin" in entry.tags
1001 assert "devops" in entry.tags
1002
1003 # Global Tags
1004 result, config = ConfigBase.config_parse_yaml(
1005 """
1006 # Global Tags
1007 tag: admin, devops
1008
1009 urls:
1010 # The following tags will get added to the global set
1011 - json://localhost:
1012 - tag: string-tag, my-other-tag, text
1013
1014 # Tags can be presented in this list format too:
1015 - dbus://:
1016 - tag:
1017 - list-tag
1018 - dbus
1019 """,
1020 asset=asset,
1021 )
1022
1023 # all entries will have our global tags defined in them
1024 for entry in result:
1025 assert "admin" in entry.tags
1026 assert "devops" in entry.tags
1027
1028 # We expect to parse 2 entries from the above
1029 assert isinstance(result, list)
1030 assert len(result) == 2
1031
1032 # json:// has 2 globals + 3 defined
1033 assert len(result[0].tags) == 5
1034 assert "text" in result[0].tags
1035
1036 # json:// has 2 globals + 2 defined
1037 assert len(result[1].tags) == 4
1038 assert "list-tag" in result[1].tags
1039
1040 # There were no include entries defined
1041 assert len(config) == 0
1042
1043 # An invalid set of entries
1044 result, config = ConfigBase.config_parse_yaml(
1045 """
1046 urls:
1047 # The following tags will get added to the global set
1048 - json://localhost:
1049 -
1050 -
1051 - entry
1052 """,
1053 asset=asset,
1054 )
1055
1056 # We expect to parse 0 entries from the above
1057 assert isinstance(result, list)
1058 assert len(result) == 0
1059
1060 # There were no include entries defined
1061 assert len(config) == 0
1062
1063 # An asset we'll manipulate; set some system flags
1064 asset = AppriseAsset(_uid="abc123", _recursion=1)
1065
1066 # Global Tags
1067 result, config = ConfigBase.config_parse_yaml(
1068 """
1069 # Test the creation of our apprise asset object
1070 asset:
1071 app_id: AppriseTest
1072 app_desc: Apprise Test Notifications
1073 app_url: http://nuxref.com
1074 async_mode: no
1075
1076 # System flags should never get set
1077 _uid: custom_id
1078 _recursion: 100
1079
1080 # Support setting empty values
1081 image_url_mask:
1082 image_url_logo:
1083
1084 image_path_mask: tmp/path
1085
1086 # Timezone (supports tz keyword too)
1087 tz: America/Montreal
1088
1089 # invalid entry
1090 theme:
1091 -
1092 -
1093 - entry
1094
1095 # Now for some invalid entries
1096 invalid: entry
1097 __init__: can't be over-ridden
1098 nolists:
1099 - we don't support these entries
1100 - in the apprise object
1101
1102 urls:
1103 - json://localhost:
1104 """,
1105 asset=asset,
1106 )
1107
1108 # We expect to parse 1 entries from the above
1109 assert isinstance(result, list)
1110 assert len(result) == 1
1111
1112 # There were no include entries defined
1113 assert len(config) == 0
1114
1115 assert asset.app_id == "AppriseTest"
1116 assert asset.app_desc == "Apprise Test Notifications"
1117 assert asset.app_url == "http://nuxref.com"
1118
1119 # Verify our system flags retain only the value they were initialized to
1120 assert asset._uid == "abc123"
1121 assert asset._recursion == 1
1122
1123 # Boolean types stay boolean
1124 assert asset.async_mode is False
1125
1126 # Our TimeZone
1127 assert isinstance(asset.tzinfo, tzinfo)
1128 assert asset.tzinfo.key == zoneinfo("America/Montreal").key
1129
1130 # the theme was not updated and remains the same as it was
1131 assert asset.theme == AppriseAsset().theme
1132
1133 # Empty string assignment
1134 assert isinstance(asset.image_url_mask, str)
1135 assert asset.image_url_mask == ""
1136 assert isinstance(asset.image_url_logo, str)
1137 assert asset.image_url_logo == ""
1138
1139 # For on-lookers looking through this file; here is a perfectly formatted
1140 # YAML configuration file for your reference so you can see it without
1141 # all of the errors like the ones identified above
1142 result, config = ConfigBase.config_parse_yaml(
1143 """
1144 # if no version is specified then version 1 is presumed. Thus this is a
1145 # completely optional field. It's a good idea to just add this line because it
1146 # will help with future ambiguity (if it ever occurs).
1147 version: 1
1148
1149 # Define an Asset object if you wish (Optional)
1150 asset:
1151 app_id: AppriseTest
1152 app_desc: Apprise Test Notifications
1153 app_url: http://nuxref.com
1154
1155 # An invalid timezone
1156 timezone: invalid
1157
1158 # Optionally define some global tags to associate with ALL of your
1159 # urls below.
1160 tag: admin, devops
1161
1162 # Define your URLs (Mandatory!)
1163 urls:
1164 # Either on-line each entry like this:
1165 - json://localhost
1166
1167 # Or add a colon to the end of the URL where you can optionally provide
1168 # over-ride entries. One of the most likely entry to be used here
1169 # is the tag entry. This gets extended to the global tag (if defined)
1170 # above
1171 - xml://localhost:
1172 - tag: customer
1173
1174 # The more elements you specify under a URL the more times the URL will
1175 # get replicated and used. Hence this entry actually could be considered
1176 # 2 URLs being called with just the destination email address changed:
1177 - mailto://george:[email protected]:
1178 - to: [email protected]
1179 - to: [email protected]
1180
1181 # Again... to re-iterate, the above mailto:// would actually fire two (2)
1182 # separate emails each with a different destination address specified.
1183 # Be careful when defining your arguments and differentiating between
1184 # when to use the dash (-) and when not to. Each time you do, you will
1185 # cause another instance to be created.
1186
1187 # Defining more then 1 element to a muti-set is easy, it looks like this:
1188 - mailto://jackson:[email protected]:
1189 - to: [email protected]
1190 tag: jeff, customer
1191
1192 - to: [email protected]
1193 tag: chris, customer
1194 """,
1195 asset=asset,
1196 )
1197
1198 # okay, here is how we get our total based on the above (read top-down)
1199 # +1 json:// entry
1200 # +1 xml:// entry
1201 # +2 mailto:// entry to [email protected] and [email protected]
1202 # +2 mailto:// entry to [email protected] and [email protected]
1203 # = 6
1204 assert len(result) == 6
1205
1206 # all six entries will have our global tags defined in them
1207 for entry in result:
1208 assert "admin" in entry.tags
1209 assert "devops" in entry.tags
1210
1211 # Entries can be directly accessed as they were added
1212
1213 # our json:// had no additional tags added; so just the global ones
1214 # So just 2; admin and devops (these were already validated above in the
1215 # for loop
1216 assert len(result[0].tags) == 2
1217
1218 # our xml:// object has 1 tag added (customer)
1219 assert len(result[1].tags) == 3
1220 assert "customer" in result[1].tags
1221
1222 # You get the idea, here is just a direct mapping to the remaining entries
1223 # in the same order they appear above
1224 assert len(result[2].tags) == 2
1225 assert len(result[3].tags) == 2
1226
1227 assert len(result[4].tags) == 4
1228 assert "customer" in result[4].tags
1229 assert "jeff" in result[4].tags
1230
1231 assert len(result[5].tags) == 4
1232 assert "customer" in result[5].tags
1233 assert "chris" in result[5].tags
1234
1235 # There were no include entries defined
1236 assert len(config) == 0
1237
1238 # Valid Configuration (multi inline configuration entries)
1239 result, config = ConfigBase.config_parse_yaml(
1240 """
1241 # A configuration file that contains 2 includes separated by a comma and/or
1242 # space:
1243 include: http://localhost:8080/notify/apprise, http://localhost/apprise/cfg
1244
1245 """,
1246 asset=asset,
1247 )
1248
1249 # We will have loaded no results
1250 assert isinstance(result, list)
1251 assert len(result) == 0
1252
1253 # But our two configuration files will be present:
1254 assert len(config) == 2
1255 assert "http://localhost:8080/notify/apprise" in config
1256 assert "http://localhost/apprise/cfg" in config
1257
1258 # Valid Configuration (another way of specifying more then one include)
1259 result, config = ConfigBase.config_parse_yaml(
1260 """
1261 # A configuration file that contains 4 includes on their own
1262 # lines beneath the keyword `include`:
1263 include:
1264 http://localhost:8080/notify/apprise
1265 http://localhost/apprise/cfg01
1266 http://localhost/apprise/cfg02
1267 http://localhost/apprise/cfg03
1268
1269 """,
1270 asset=asset,
1271 )
1272
1273 # We will have loaded no results
1274 assert isinstance(result, list)
1275 assert len(result) == 0
1276
1277 # But our 4 configuration files will be present:
1278 assert len(config) == 4
1279 assert "http://localhost:8080/notify/apprise" in config
1280 assert "http://localhost/apprise/cfg01" in config
1281 assert "http://localhost/apprise/cfg02" in config
1282 assert "http://localhost/apprise/cfg03" in config
1283
1284 # Test a configuration with an invalid schema with options
1285 result, config = ConfigBase.config_parse_yaml(
1286 """
1287 urls:
1288 - invalid://:
1289 tag: 'invalid'
1290 :name: 'Testing2'
1291 :body: 'test body2'
1292 :title: 'test title2'
1293 """,
1294 asset=asset,
1295 )
1296
1297 # We will have loaded no results
1298 assert isinstance(result, list)
1299 assert len(result) == 0
1300
1301 # Valid Configuration (we allow comma separated entries for
1302 # each defined bullet)
1303 result, config = ConfigBase.config_parse_yaml(
1304 """
1305 # A configuration file that contains 4 includes on their own
1306 # lines beneath the keyword `include`:
1307 include:
1308 - http://localhost:8080/notify/apprise, http://localhost/apprise/cfg01
1309 http://localhost/apprise/cfg02
1310 - http://localhost/apprise/cfg03
1311
1312 """,
1313 asset=asset,
1314 )
1315
1316 # We will have loaded no results
1317 assert isinstance(result, list)
1318 assert len(result) == 0
1319
1320 # But our 4 configuration files will be present:
1321 assert len(config) == 4
1322 assert "http://localhost:8080/notify/apprise" in config
1323 assert "http://localhost/apprise/cfg01" in config
1324 assert "http://localhost/apprise/cfg02" in config
1325 assert "http://localhost/apprise/cfg03" in config
1326
1327
1328 def test_config_base_yaml_includes(
1329 requests_remote_config: Mock,
1330 ) -> None:
1331 """
1332 API: ConfigBase.config_parse_yaml_includes
1333
1334 Verify that HTTP include entries are fetched via requests.get and that
1335 the remote config bodies are parsed into json:// and xml:// notifiers.
1336 """
1337
1338 # general reference used below
1339 asset = AppriseAsset()
1340
1341 # Initialize our apprise configuration
1342 ac = AppriseConfig(asset=asset, recursion=1)
1343
1344 # Add our entry
1345 ac.add_config(
1346 cleandoc("""
1347 # Include our Apprise Configuration from 2 locations
1348 include:
1349 - http://localhost:8000/get/test-001
1350 - http://localhost:8000/get/test-002
1351
1352 # no further URLs defined
1353 """)
1354 )
1355
1356 # Force a fresh parse and get the loaded plugin
1357 services = ac.services()
1358
1359 # the following will return
1360 assert len(services) == 3
1361
1362 # representation for NotifyBase subclasses.
1363 urls = {n.url() for n in services}
1364
1365 # The *exact* URL string may include extra params depending on defaults,
1366 # so we check using containment instead of strict equality.
1367 assert any(u.startswith("json://localhost") for u in urls)
1368 assert any(u.startswith("xml://localhost") for u in urls)
1369 assert any(u.startswith("form://localhost") for u in urls)
1370
1371
1372 def test_yaml_vs_text_tagging():
1373 """
1374 API: ConfigBase YAML vs TEXT tagging
1375 """
1376
1377 yaml_result, _ = ConfigBase.config_parse_yaml("""
1378 urls:
1379 - mailtos://lead2gold:[email protected]:
1380 tag: mytag
1381 """)
1382 assert yaml_result
1383
1384 text_result, _ = ConfigBase.config_parse_text("""
1385 mytag=mailtos://lead2gold:[email protected]
1386 """)
1387 assert text_result
1388
1389 # Now we compare our results and verify they are the same
1390 assert len(yaml_result) == len(text_result)
1391 assert isinstance(yaml_result[0], NotifyEmail)
1392 assert isinstance(text_result[0], NotifyEmail)
1393 assert "mytag" in text_result[0]
1394 assert "mytag" in yaml_result[0]
1395
1396
1397 def test_config_base_config_tag_groups_yaml_01():
1398 """
1399 API: ConfigBase.config_tag_groups_yaml #1 object
1400
1401 """
1402
1403 # general reference used below
1404 asset = AppriseAsset()
1405
1406 # Valid Configuration
1407 result, config = ConfigBase.config_parse_yaml(
1408 """
1409 # if no version is specified then version 1 is presumed
1410 version: 1
1411
1412 groups:
1413 - group1: tagB, tagC, tagNotAssigned
1414 - group2:
1415 - tagA
1416 - tagC
1417 - group3:
1418 - tagD: optional comment
1419 - tagA: optional comment #2
1420
1421 # No assignment
1422 - group4
1423
1424 # No assignment type 2
1425 - group5:
1426
1427 # Integer assignment
1428 - group6: 3
1429 - group6: 3, 4, 5, test
1430 - group6: 3.5, tagC
1431
1432 # Recursion
1433 - groupA: groupB
1434 - groupB: groupA
1435 # And Again... (just because)
1436 - groupA: groupB
1437 - groupB: groupA
1438
1439 # Self assignment
1440 - groupX: groupX
1441
1442 # Set up a larger recursive loop
1443 - groupG: groupH
1444 - groupH: groupI, groupJ
1445 - groupI: groupJ, groupG
1446 - groupJ: groupK, groupH, groupI
1447 - groupK: groupG
1448
1449 # No tags assigned
1450 - groupK: ",, , ,"
1451 - " , ": ",, , ,"
1452
1453 # Multi Assignments
1454 - groupL, groupM: tagD, tagA
1455 - 4, groupN:
1456 - tagD
1457 - tagE, TagA
1458
1459 # Add one more tag to groupL making it different then GroupM by 1
1460 - groupL: tagB
1461 #
1462 # Define your notification urls:
1463 #
1464 urls:
1465 - form://localhost:
1466 - tag: tagA
1467 - mailto://test:[email protected]:
1468 - tag: tagB
1469 - xml://localhost:
1470 - tag: tagC
1471 - json://localhost:
1472 - tag: tagD, tagA
1473
1474 """,
1475 asset=asset,
1476 )
1477
1478 # We expect to parse 4 entries from the above
1479 assert isinstance(result, list)
1480 assert isinstance(config, list)
1481 assert len(result) == 4
1482
1483 # Our first element is our group tags
1484 assert len(result[0].tags) == 5
1485 assert "group2" in result[0].tags
1486 assert "group3" in result[0].tags
1487 assert "groupl" in result[0].tags
1488 assert "groupm" in result[0].tags
1489 assert "taga" in result[0].tags
1490
1491 # No additional configuration is loaded
1492 assert len(config) == 0
1493
1494 apobj = Apprise()
1495 assert apobj.add(result)
1496 # We match against 1 entry
1497 assert len(list(apobj.find("tagA"))) == 2
1498 assert len(list(apobj.find("tagB"))) == 1
1499 assert len(list(apobj.find("tagC"))) == 1
1500 assert len(list(apobj.find("tagD"))) == 1
1501 assert len(list(apobj.find("group1"))) == 2
1502 assert len(list(apobj.find("group2"))) == 3
1503 assert len(list(apobj.find("group3"))) == 2
1504 assert len(list(apobj.find("group4"))) == 0
1505 assert len(list(apobj.find("group5"))) == 0
1506 # json:// -- group6 -> 4 -> TagA
1507 # xml:// -- group6 -> TagC
1508 assert len(list(apobj.find("group6"))) == 2
1509 assert len(list(apobj.find("4"))) == 1
1510 assert len(list(apobj.find("groupN"))) == 1
1511
1512
1513 def test_config_base_config_tag_groups_yaml_02():
1514 """
1515 API: ConfigBase.config_tag_groups_yaml #2 object
1516
1517 """
1518
1519 # general reference used below
1520 asset = AppriseAsset()
1521
1522 # Valid Configuration
1523 result, config = ConfigBase.config_parse_yaml(
1524 """
1525 # if no version is specified then version 1 is presumed
1526 version: 1
1527
1528 groups:
1529 group1: tagB, tagC, tagNotAssigned
1530 group2:
1531 - tagA
1532 - tagC
1533 group3:
1534 - tagD: optional comment
1535 - tagA: optional comment #2
1536
1537 # No assignment type 2
1538 group5:
1539
1540 # Integer assignment (since it's not a list, the last element prevails
1541 # and replaces the above); '4' does not get appended as it would in
1542 # the event this was a list instead
1543 group6: 3
1544 group6: 3, 4, 5, test
1545 group6: 3.5, tagC
1546
1547 # Recursion
1548 groupA: groupB
1549 groupB: groupA
1550 # And Again... (just because)
1551 groupA: groupB
1552 groupB: groupA
1553
1554 # Self assignment
1555 groupX: groupX
1556
1557 # Set up a larger recursive loop
1558 groupG: groupH
1559 groupH: groupI, groupJ
1560 groupI: groupJ, groupG
1561 groupJ: groupK, groupH, groupI
1562 groupK: groupG
1563
1564 # No tags assigned
1565 groupK: ",, , ,"
1566 " , ": ",, , ,"
1567
1568 # Multi Assignments
1569 groupL, groupM: tagD, tagA
1570 4, groupN:
1571 - tagD
1572 - tagE, TagA
1573
1574 # Add one more tag to groupL making it different then GroupM by 1
1575 groupL: tagB
1576 #
1577 # Define your notification urls:
1578 #
1579 urls:
1580 - form://localhost:
1581 - tag: tagA
1582 - mailto://test:[email protected]:
1583 - tag: tagB
1584 - xml://localhost:
1585 - tag: tagC
1586 - json://localhost:
1587 - tag: tagD, tagA
1588
1589 """,
1590 asset=asset,
1591 )
1592
1593 # We expect to parse 4 entries from the above
1594 assert isinstance(result, list)
1595 assert isinstance(config, list)
1596 assert len(result) == 4
1597
1598 # Our first element is our group tags
1599 assert len(result[0].tags) == 5
1600 assert "group2" in result[0].tags
1601 assert "group3" in result[0].tags
1602 assert "groupl" in result[0].tags
1603 assert "groupm" in result[0].tags
1604 assert "taga" in result[0].tags
1605
1606 # No additional configuration is loaded
1607 assert len(config) == 0
1608
1609 apobj = Apprise()
1610 assert apobj.add(result)
1611 # We match against 1 entry
1612 assert len(list(apobj.find("tagA"))) == 2
1613 assert len(list(apobj.find("tagB"))) == 1
1614 assert len(list(apobj.find("tagC"))) == 1
1615 assert len(list(apobj.find("tagD"))) == 1
1616 assert len(list(apobj.find("group1"))) == 2
1617 assert len(list(apobj.find("group2"))) == 3
1618 assert len(list(apobj.find("group3"))) == 2
1619 assert len(list(apobj.find("group4"))) == 0
1620 assert len(list(apobj.find("group5"))) == 0
1621 # NOT json:// -- group6 -> 4 -> TagA (not appended because dict storage)
1622 # ^
1623 # |
1624 # See: test_config_base_config_tag_groups_yaml_01 (above)
1625 # dict storage (as this tests for) causes last entry to
1626 # prevail; previous assignments are lost
1627 #
1628 # xml:// -- group6 -> TagC
1629 assert len(list(apobj.find("group6"))) == 1
1630 assert len(list(apobj.find("4"))) == 1
1631 assert len(list(apobj.find("groupN"))) == 1
1632 assert len(list(apobj.find("groupK"))) == 0
1633
1634
1635 def test_config_base_config_parse_yaml_globals():
1636 """
1637 API: ConfigBase.config_parse_yaml globals
1638
1639 """
1640
1641 # general reference used below
1642 asset = AppriseAsset()
1643
1644 # Invalid Syntax (throws a ScannerError)
1645 results, config = ConfigBase.config_parse_yaml(
1646 cleandoc("""
1647 urls:
1648 - jsons://localhost1:
1649 - to: [email protected]
1650 tag: jeff, customer
1651 cto: 30
1652 rto: 30
1653 verify: no
1654
1655 - jsons://localhost2?cto=30&rto=30&verify=no:
1656 - to: [email protected]
1657 tag: json, customer
1658 """),
1659 asset=asset,
1660 )
1661
1662 # Invalid data gets us an empty result set
1663 assert isinstance(results, list)
1664
1665 # Our results loaded
1666 assert len(results) == 2
1667 assert len(config) == 0
1668
1669 # Now verify that our global variables correctly initialized
1670 for entry in results:
1671 assert entry.verify_certificate is False
1672 assert entry.socket_read_timeout == 30
1673 assert entry.socket_connect_timeout == 30
1674
1675
1676 # This test fails on CentOS 8.x so it was moved into it's own function
1677 # so it could be bypassed. The ability to use lists in YAML files didn't
1678 # appear to happen until later on; it's certainly not available in v3.12
1679 # which was what shipped with CentOS v8 at the time.
1680 @pytest.mark.skipif(
1681 int(yaml.__version__.split(".")[0]) <= 3,
1682 reason="requires pyaml v4.x or higher.",
1683 )
1684 def test_config_base_config_parse_yaml_list():
1685 """
1686 API: ConfigBase.config_parse_yaml list parsing
1687
1688 """
1689
1690 # general reference used below
1691 asset = AppriseAsset()
1692
1693 # Invalid url/schema
1694 result, config = ConfigBase.config_parse_yaml(
1695 """
1696 # no lists... just no
1697 urls: [milk, pumpkin pie, eggs, juice]
1698
1699 # Including by list is okay
1700 include: [file:///absolute/path/, relative/path, http://test.com]
1701
1702 """,
1703 asset=asset,
1704 )
1705
1706 # Invalid data gets us an empty result set
1707 assert isinstance(result, list)
1708 assert len(result) == 0
1709
1710 # There were 3 include entries
1711 assert len(config) == 3
1712 assert "file:///absolute/path/" in config
1713 assert "relative/path" in config
1714 assert "http://test.com" in config
1715
1716
1717 def test_yaml_asset_timezone_and_asset_tokens(tmpdir):
1718 """
1719 Covers: valid tz, reserved keys, invalid key, bool coercion, None->"",
1720 invalid type for string, and %z formatting path used later by plugins.
1721 """
1722 cfg = tmpdir.join("asset-tz.yml")
1723 cfg.write(
1724 """
1725 version: 1
1726 asset:
1727 tz: " america/toronto " # case-insensitive + whitespace cleanup
1728 _private: "ignored" # reserved (starts with _)
1729 name_: "ignored" # reserved (ends with _)
1730 not_a_field: "ignored" # invalid asset key
1731 secure_logging: "yes" # string -> bool via parse_bool
1732 app_id: null # None becomes empty string
1733 app_desc: [ "list" ] # invalid type for string -> warning path
1734 urls:
1735 - json://localhost
1736 """
1737 )
1738
1739 ac = AppriseConfig(paths=str(cfg))
1740 # Force a fresh parse and get the loaded plugin
1741 services = ac.services()
1742 assert len(services) == 1
1743
1744 plugin = services[0]
1745 asset = plugin.asset
1746
1747 # tz was accepted and normalised
1748 # lower() is required since Mac and Window are not case sensitive and will
1749 # See output as it was passed in and not corrected per IANA
1750 assert getattr(asset.tzinfo, "key", None).lower() == "america/toronto"
1751 # boolean coercion applied
1752 assert asset.secure_logging is True
1753 # None -> ""
1754 assert asset.app_id == ""
1755
1756
1757 def test_yaml_asset_language(tmpdir):
1758 """A YAML asset may set the language Apprise presents strings in."""
1759
1760 def language_for(content):
1761 """Load ``content`` and return the language of its asset."""
1762 cfg = tmpdir.join("asset-lang.yml")
1763 cfg.write(content)
1764 services = AppriseConfig(paths=str(cfg)).services()
1765 assert len(services) == 1
1766 return services[0].asset.language
1767
1768 # Accepted, and stored in its normalized form
1769 assert (
1770 language_for(
1771 """
1772 version: 1
1773 asset:
1774 language: " ES-mx "
1775 urls:
1776 - json://localhost
1777 """
1778 )
1779 == "es_MX"
1780 )
1781
1782 # lang is accepted as well
1783 assert (
1784 language_for(
1785 """
1786 version: 1
1787 asset:
1788 lang: fr
1789 urls:
1790 - json://localhost
1791 """
1792 )
1793 == "fr"
1794 )
1795
1796 # language wins when both are present
1797 assert (
1798 language_for(
1799 """
1800 version: 1
1801 asset:
1802 lang: fr
1803 language: de
1804 urls:
1805 - json://localhost
1806 """
1807 )
1808 == "de"
1809 )
1810
1811 # Anything we can not work with is ignored, leaving the system language
1812 for value in ('"garbage"', "null", "[ a, b ]", "42"):
1813 assert (
1814 language_for(
1815 f"""
1816 version: 1
1817 asset:
1818 lang: {value}
1819 urls:
1820 - json://localhost
1821 """
1822 )
1823 is None
1824 )
1825
1826
1827 def test_yaml_asset_timezone_invalid_and_precedence(tmpdir):
1828 """
1829 If 'timezone' is present but invalid, it takes precedence over 'tz'
1830 and MUST NOT set the asset to the 'tz' value. We assert that London
1831 was not applied. We deliberately avoid asserting the exact fallback,
1832 since environments may surface a system tz (datetime.timezone) that
1833 lacks a `.key` attribute.
1834 """
1835 cfg = tmpdir.join("asset-tz-invalid.yml")
1836 cfg.write(
1837 """
1838 version: 1
1839 asset:
1840 timezone: null # invalid (will be seen as "None")
1841 tz: Europe/London # would be valid, but 'timezone' wins
1842 urls:
1843 - json://localhost
1844 """
1845 )
1846
1847 base_asset = AppriseAsset(timezone="UTC")
1848 ac = AppriseConfig(paths=str(cfg))
1849 services = ac.services(asset=base_asset)
1850 assert len(services) == 1
1851
1852 tzinfo = services[0].asset.tzinfo
1853
1854 # The key assertion: 'tz' MUST NOT have been applied
1855 assert getattr(tzinfo, "key", "").lower() != "europe/london"
1856
1857 # Sanity check that something sensible is set
1858 # Compare offsets at a fixed instant instead of object identity
1859 dt = datetime(2024, 1, 1, 12, 0, tzinfo=_tz.utc)
1860 assert tzinfo.utcoffset(dt) is not None
1861
1862
1863 @pytest.mark.parametrize(
1864 "garbage_yaml",
1865 [
1866 "123",
1867 "3.1415",
1868 "true",
1869 "[UTC]",
1870 "{x: UTC}",
1871 ],
1872 )
1873 def test_yaml_asset_tz_garbage_types_only(tmpdir, garbage_yaml):
1874 """
1875 If only 'tz' is present and it is non-string, it is ignored.
1876 We assert it didn't become a real IANA zone (e.g., Europe/London),
1877 and that the tzinfo is usable.
1878 """
1879 cfg = tmpdir.join("asset-tz-garbage-only.yml")
1880 cfg.write(
1881 f"""
1882 version: 1
1883 asset:
1884 tz: {garbage_yaml} # non-string -> warning path
1885 urls:
1886 - json://localhost
1887 """
1888 )
1889
1890 base_asset = AppriseAsset(timezone="UTC")
1891 ac = AppriseConfig(paths=str(cfg))
1892 services = ac.services(asset=base_asset)
1893 assert len(services) == 1
1894
1895 tzinfo = services[0].asset.tzinfo
1896
1897 # 1) Did not “accidentally” become a valid IANA from elsewhere.
1898 assert getattr(tzinfo, "key", "").lower() != "europe/london"
1899
1900 # 2) tzinfo is usable (offset resolves at a fixed instant).
1901 dt = datetime(2024, 1, 1, 12, 0, tzinfo=_tz.utc)
1902 assert tzinfo.utcoffset(dt) is not None
1903 # also stable tzname resolution
1904 assert isinstance(tzinfo.tzname(dt), str)
1905
1906
1907 def test_config_base_yaml_tag_alias_dict(tmpdir):
1908 """
1909 API: ConfigBase.parse_yaml_file (#5)
1910
1911 Validate `tags` is accepted as an alias of `tag` in the dict form:
1912 - "schema://...":
1913 tags: a-tag
1914
1915 Also implicitly verifies `tags` does not leak into plugin kwargs, because
1916 plugin instantiation would fail if an unexpected kwarg is passed through.
1917 """
1918 t = tmpdir.mkdir("tags-alias-dict-form").join("apprise.yml")
1919 t.write("""urls:
1920 - pover://nsisxnvnqixq39t0cw54pxieyvtdd9@2jevtmstfg5a7hfxndiybasttxxfku:
1921 tags: test1
1922 - pover://rg8ta87qngcrkc6t4qbykxktou0uug@tqs3i88xlufexwl8t4asglt4zp5wfn:
1923 tags: test2
1924 - pover://jcqgnlyq2oetea4qg3iunahj8d5ijm@evalvutkhc8ipmz2lcgc70wtsm0qpb:
1925 tags: test3
1926 """)
1927
1928 ac = AppriseConfig(paths=str(t))
1929
1930 # The number of configuration files that exist
1931 assert len(ac) == 1
1932
1933 # All entries should load
1934 assert len(ac.services()) == 3
1935
1936 a = Apprise()
1937 assert a.add(services=ac) is True
1938 assert len(a) == 3
1939
1940 # Verify tag matching works
1941 assert sum(1 for _ in a.find("no-match")) == 0
1942 assert sum(1 for _ in a.find("all")) == 3
1943 assert sum(1 for _ in a.find("test1")) == 1
1944 assert sum(1 for _ in a.find("test2")) == 1
1945 assert sum(1 for _ in a.find("test3")) == 1
1946 assert sum(1 for _ in a.find("test1, test3")) == 2
1947
1948
1949 def test_config_base_yaml_tag_alias_list(tmpdir):
1950 """
1951 API: ConfigBase.parse_yaml_file (#6)
1952
1953 Validate `tags` is accepted as an alias of `tag` in the list-of-dicts form:
1954 - "schema://...":
1955 - tags: a-tag
1956 - tags: another-tag
1957
1958 Expected behaviour: expands into multiple entries (one per list item),
1959 and each is tagged appropriately.
1960 """
1961 t = tmpdir.mkdir("tags-alias-list-form").join("apprise.yml")
1962 t.write("""urls:
1963 - pover://nsisxnvnqixq39t0cw54pxieyvtdd9@2jevtmstfg5a7hfxndiybasttxxfku:
1964 - tags: test1
1965 - tags: test2
1966 - pover://jcqgnlyq2oetea4qg3iunahj8d5ijm@evalvutkhc8ipmz2lcgc70wtsm0qpb:
1967 - tags: test3
1968 """)
1969
1970 ac = AppriseConfig(paths=str(t))
1971
1972 # The number of configuration files that exist
1973 assert len(ac) == 1
1974
1975 # First URL expands to 2, second expands to 1
1976 assert len(ac.services()) == 3
1977
1978 a = Apprise()
1979 assert a.add(services=ac) is True
1980 assert len(a) == 3
1981
1982 # Verify tag matching works across expanded entries
1983 assert sum(1 for _ in a.find("test1")) == 1
1984 assert sum(1 for _ in a.find("test2")) == 1
1985 assert sum(1 for _ in a.find("test3")) == 1
1986 assert sum(1 for _ in a.find("test1, test2")) == 2
1987
1988
1989 def test_config_base_yaml_tag_priority(tmpdir):
1990 """
1991 API: ConfigBase.parse_yaml_file (#7)
1992
1993 Validate priority: when both `tag` and `tags` are present, `tag` wins.
1994
1995 This must remain true to preserve the original documented behaviour.
1996 """
1997 t = tmpdir.mkdir("tag-priority-over-tags").join("apprise.yml")
1998 t.write("""urls:
1999 - pover://nsisxnvnqixq39t0cw54pxieyvtdd9@2jevtmstfg5a7hfxndiybasttxxfku:
2000 tag: primary
2001 tags: secondary
2002 """)
2003
2004 ac = AppriseConfig(paths=str(t))
2005
2006 # The number of configuration files that exist
2007 assert len(ac) == 1
2008
2009 # Entry should load successfully
2010 assert len(ac.services()) == 1
2011
2012 a = Apprise()
2013 assert a.add(services=ac) is True
2014 assert len(a) == 1
2015
2016 # Tag priority check
2017 assert sum(1 for _ in a.find("primary")) == 1
2018 assert sum(1 for _ in a.find("secondary")) == 0
2019
2020
2021 def test_yaml_sibling_token_overrides_basic():
2022 """
2023 API: ConfigBase - YAML sibling-key token overrides (basic cases).
2024
2025 Keys at the same indentation level as the schema URL key
2026 (sibling form) must behave identically to child-indented tokens.
2027 Both of these forms must load the same plugin with the same attrs:
2028
2029 # sibling form (same indentation)
2030 - mailtos://_:
2031 smtp: smtp.example.com
2032 from: [email protected]
2033
2034 # child form (one level deeper)
2035 - mailtos://_:
2036 smtp: smtp.example.com
2037 from: [email protected]
2038 """
2039 # --- sibling form (the historically broken form) ---
2040 result_sibling, _ = ConfigBase.config_parse_yaml("""
2041 urls:
2042 - mailtos://_:
2043 user: [email protected]
2044 password: secret
2045 smtp: smtp.example.com
2046 from: [email protected]
2047 to: [email protected]
2048 tag: myteam
2049 """)
2050
2051 # --- child form (always worked) ---
2052 result_child, _ = ConfigBase.config_parse_yaml("""
2053 urls:
2054 - mailtos://_:
2055 user: [email protected]
2056 password: secret
2057 smtp: smtp.example.com
2058 from: [email protected]
2059 to: [email protected]
2060 tag: myteam
2061 """)
2062
2063 # Both forms must load exactly one plugin instance
2064 assert len(result_sibling) == 1
2065 assert len(result_child) == 1
2066
2067 # Both results must be NotifyEmail instances
2068 assert isinstance(result_sibling[0], NotifyEmail)
2069 assert isinstance(result_child[0], NotifyEmail)
2070
2071 for obj in (result_sibling[0], result_child[0]):
2072 # SMTP server from sibling/child token
2073 assert obj.smtp_host == "smtp.example.com"
2074
2075 # from: maps to from_addr via template_args
2076 assert obj.from_addr[1] == "[email protected]"
2077
2078 # to: maps to targets
2079 assert any(t[1] == "[email protected]" for t in obj.targets)
2080
2081 # password: sets the credential directly
2082 assert obj.password == "secret"
2083
2084 # tag: applies correctly
2085 assert "myteam" in obj.tags
2086
2087
2088 def test_yaml_sibling_token_priority_over_url():
2089 """
2090 API: ConfigBase - sibling tokens override URL-embedded values.
2091
2092 Priority order (lowest to highest):
2093 3 - URL path (user:pass@host:port)
2094 2 - URL query string (?smtp=...)
2095 1 - YAML sibling/child tokens (highest)
2096 """
2097 # URL embeds one smtp server; sibling token overrides it
2098 result, _ = ConfigBase.config_parse_yaml("""
2099 urls:
2100 - mailtos://[email protected]?smtp=old.smtp.example.com:
2101 smtp: new.smtp.example.com
2102 to: [email protected]
2103 tag: priority-test
2104 """)
2105
2106 assert len(result) == 1
2107 assert isinstance(result[0], NotifyEmail)
2108
2109 # Sibling token must win over the URL query-string value
2110 assert result[0].smtp_host == "new.smtp.example.com"
2111 assert "priority-test" in result[0].tags
2112
2113
2114 def test_yaml_child_token_priority_over_sibling():
2115 """
2116 API: ConfigBase - child tokens (indented) override sibling tokens.
2117
2118 When a URL entry has BOTH a child value (indented under the key)
2119 AND sibling keys, child tokens take priority on a per-key basis.
2120 """
2121 result, _ = ConfigBase.config_parse_yaml("""
2122 urls:
2123 - mailtos://[email protected]:
2124 smtp: child.smtp.example.com
2125 smtp: sibling.smtp.example.com
2126 to: [email protected]
2127 """)
2128
2129 assert len(result) == 1
2130 assert isinstance(result[0], NotifyEmail)
2131
2132 # Child token (child.smtp.example.com) must beat sibling token
2133 assert result[0].smtp_host == "child.smtp.example.com"
2134
2135
2136 def test_yaml_sibling_token_with_multiple_targets():
2137 """
2138 API: ConfigBase - multiple targets via sibling 'to:' token.
2139
2140 'to:' in YAML tokens is a kwarg equivalent to ?to= in a URL.
2141 Multiple recipients must be expressed as a comma-separated string
2142 or as a YAML list under the 'to:' key -- NOT as multiple YAML
2143 entries each containing a separate 'to:' (that would create
2144 multiple plugin instances rather than one plugin with many targets).
2145
2146 Both the comma-separated and YAML-list forms should resolve to a
2147 single plugin instance whose 'targets' list contains all recipients.
2148 """
2149 # Comma-separated form: equivalent to ?to=user1,user2 in the URL
2150 result_csv, _ = ConfigBase.config_parse_yaml("""
2151 urls:
2152 - mailtos://[email protected]:
2153 smtp: smtp.example.com
2154 to: [email protected], [email protected]
2155 tag: shared
2156 """)
2157
2158 # YAML list form: same semantics, different syntax
2159 result_list, _ = ConfigBase.config_parse_yaml("""
2160 urls:
2161 - mailtos://[email protected]:
2162 smtp: smtp.example.com
2163 to:
2164 - [email protected]
2165 - [email protected]
2166 tag: shared
2167 """)
2168
2169 # Each form must load exactly one plugin instance
2170 assert len(result_csv) == 1
2171 assert len(result_list) == 1
2172
2173 for obj in (result_csv[0], result_list[0]):
2174 assert isinstance(obj, NotifyEmail)
2175
2176 # Sibling smtp: applies to the single instance
2177 assert obj.smtp_host == "smtp.example.com"
2178
2179 # Both recipients must appear in targets
2180 assert any(t[1] == "[email protected]" for t in obj.targets)
2181 assert any(t[1] == "[email protected]" for t in obj.targets)
2182
2183 # Sibling tag: applies correctly
2184 assert "shared" in obj.tags
2185
2186
2187 def test_yaml_sibling_token_shared_across_list_expansion():
2188 """
2189 API: ConfigBase - sibling tokens propagate to every list-expansion entry.
2190
2191 When the URL key has a YAML list as its child value (each list item
2192 becomes a separate plugin instance) AND sibling keys supply shared
2193 settings, the sibling tokens are applied as a base to every instance
2194 before per-entry overrides are merged.
2195
2196 This is distinct from 'to: email1, email2' (multiple targets for one
2197 instance) -- here each list entry is an independent plugin instance
2198 with its own per-entry settings, all sharing the sibling tokens.
2199 """
2200 result, _ = ConfigBase.config_parse_yaml("""
2201 urls:
2202 - mailtos://[email protected]:
2203 - to: [email protected]
2204 tag: boss
2205 - to: [email protected]
2206 tag: team
2207 smtp: smtp.example.com
2208 """)
2209
2210 # One plugin instance per list entry
2211 assert len(result) == 2
2212 assert all(isinstance(r, NotifyEmail) for r in result)
2213
2214 # Sibling smtp: must be applied to every instance
2215 assert result[0].smtp_host == "smtp.example.com"
2216 assert result[1].smtp_host == "smtp.example.com"
2217
2218 # Per-entry tags must be respected
2219 assert "boss" in result[0].tags
2220 assert "team" in result[1].tags
2221
2222
2223 def test_yaml_sibling_token_per_entry_overrides_sibling():
2224 """
2225 API: ConfigBase - per-entry tokens override sibling tokens for same key.
2226
2227 When a list-expansion entry defines the same key as a sibling token,
2228 the per-entry value wins for that instance only. Other instances with
2229 no per-entry value for that key still receive the sibling fallback.
2230
2231 Scenario:
2232 - sibling smtp: smtp1.example.com (shared fallback for all entries)
2233 - entry 1: to=manager, tag=boss (no per-entry smtp -> uses sibling)
2234 - entry 2: to=coworker, smtp=smtp2, tag=team (overrides sibling smtp)
2235
2236 Expected result: 2 instances, each with correct smtp and tags.
2237 """
2238 result, _ = ConfigBase.config_parse_yaml("""
2239 urls:
2240 - mailtos://[email protected]:
2241 - to: [email protected]
2242 tag: boss
2243 - to: [email protected]
2244 smtp: smtp2.example.com
2245 tag: team
2246 smtp: smtp1.example.com
2247 """)
2248
2249 # One instance per list entry
2250 assert len(result) == 2
2251 assert all(isinstance(r, NotifyEmail) for r in result)
2252
2253 # Instance 0: no per-entry smtp, so sibling smtp1 is used
2254 assert any(t[1] == "[email protected]" for t in result[0].targets)
2255 assert result[0].smtp_host == "smtp1.example.com"
2256 assert "boss" in result[0].tags
2257
2258 # Instance 1: per-entry smtp2 overrides the sibling smtp1
2259 assert any(t[1] == "[email protected]" for t in result[1].targets)
2260 assert result[1].smtp_host == "smtp2.example.com"
2261 assert "team" in result[1].tags
2262
2263
2264 def test_yaml_sibling_alias_does_not_overwrite_child_canonical():
2265 """
2266 API: ConfigBase - child alias key wins over sibling canonical key.
2267
2268 When a sibling provides a canonical key ('password') and the child dict
2269 provides the URL_TOKEN_ALIASES shorthand for the same key ('pass'), the
2270 child value must win.
2271
2272 Before the fix, both dicts were merged raw before _special_token_handler()
2273 ran the URL_TOKEN_ALIASES step. The combined dict contained both 'pass'
2274 and 'password', so the alias-conflict branch discarded 'pass' and kept
2275 the sibling's 'password' -- the wrong winner.
2276
2277 The fix normalizes sibling and child token dicts separately first, so
2278 each alias is resolved in the context of its own dict only. After
2279 normalization both dicts carry 'password', and the priority merge
2280 (sibling as base, child overrides) produces the correct winner.
2281 """
2282 result, _ = ConfigBase.config_parse_yaml("""
2283 urls:
2284 - mailtos://[email protected]:
2285 pass: child_pass
2286 to: [email protected]
2287 password: sibling_pass
2288 """)
2289
2290 # One instance created
2291 assert len(result) == 1
2292 assert isinstance(result[0], NotifyEmail)
2293
2294 # Child 'pass' (alias) must win over sibling 'password' (canonical)
2295 assert result[0].password == "child_pass"
2296
2297
2298 def test_yaml_alias_populates_null_canonical():
2299 """
2300 API: ConfigBase - alias populates canonical when canonical is null.
2301
2302 """
2303 # canonical 'password:' is null (no value) + alias 'pass: secret'
2304 # alias must win because null == not provided
2305 result, _ = ConfigBase.config_parse_yaml("""
2306 urls:
2307 - json://user@localhost:
2308 pass: secret
2309 password:
2310 """)
2311 assert len(result) == 1
2312 assert result[0].password == "secret"
2313
2314 # Canonical with a real value still wins over the alias
2315 result2, _ = ConfigBase.config_parse_yaml("""
2316 urls:
2317 - json://user@localhost:
2318 pass: alias_val
2319 password: real_val
2320 """)
2321 assert len(result2) == 1
2322 assert result2[0].password == "real_val"
2323
2324
2325 def test_yaml_sibling_token_order_independent():
2326 """
2327 API: ConfigBase - sibling tokens are captured regardless of YAML key order.
2328
2329 YAML does not guarantee mapping key order. If a sibling token appears
2330 before the URL key in the mapping dict (e.g. due to editor or template
2331 quirks), it must still be captured. The old dict(it) approach only
2332 captured items *after* the URL key in the iterator; the fix uses the
2333 full url.items() dict so all non-URL-key items are included.
2334 """
2335 # Write the YAML directly so the key order is explicit and no
2336 # yaml.dump call is required. smtp appears BEFORE the URL key,
2337 # to appears AFTER -- both must be captured as sibling tokens.
2338 content = """
2339 urls:
2340 - smtp: smtp.example.com
2341 mailtos://[email protected]:
2342 to: [email protected]
2343 """
2344
2345 result, _ = ConfigBase.config_parse_yaml(content)
2346
2347 # Both pre-URL (smtp) and post-URL (to) siblings must be applied
2348 assert len(result) == 1
2349 assert isinstance(result[0], NotifyEmail)
2350 assert result[0].smtp_host == "smtp.example.com"
2351 assert any(t[1] == "[email protected]" for t in result[0].targets)
2352
2353
2354 def test_yaml_sibling_password_token():
2355 """
2356 API: ConfigBase - 'password' and 'pass' keys both set plugin password.
2357
2358 YAML tokens bypass parse_url(), so the URL-path shorthand 'pass' must
2359 be normalized to 'password' by URL_TOKEN_ALIASES inside
2360 _special_token_handler. Verify that both spellings work in sibling
2361 and child indentation forms.
2362 """
2363 # --- 'password:' sibling form ---
2364 result_sibling, _ = ConfigBase.config_parse_yaml("""
2365 urls:
2366 - json://testhost:
2367 user: alice
2368 password: s3cr3t
2369 tag: pw-test
2370 """)
2371
2372 # --- 'password:' child form ---
2373 result_child, _ = ConfigBase.config_parse_yaml("""
2374 urls:
2375 - json://testhost:
2376 user: alice
2377 password: s3cr3t
2378 tag: pw-test
2379 """)
2380
2381 # --- 'pass:' sibling form (alias normalization) ---
2382 result_pass_sibling, _ = ConfigBase.config_parse_yaml("""
2383 urls:
2384 - json://testhost:
2385 user: alice
2386 pass: s3cr3t
2387 tag: pw-test
2388 """)
2389
2390 # --- 'pass:' child form (alias normalization) ---
2391 result_pass_child, _ = ConfigBase.config_parse_yaml("""
2392 urls:
2393 - json://testhost:
2394 user: alice
2395 pass: s3cr3t
2396 tag: pw-test
2397 """)
2398
2399 for result in (
2400 result_sibling,
2401 result_child,
2402 result_pass_sibling,
2403 result_pass_child,
2404 ):
2405 assert len(result) == 1
2406
2407 for obj in (
2408 result_sibling[0],
2409 result_child[0],
2410 result_pass_sibling[0],
2411 result_pass_child[0],
2412 ):
2413 assert obj.user == "alice"
2414 assert obj.password == "s3cr3t"
2415 assert "pw-test" in obj.tags
2416
2417 # When both 'pass:' and 'password:' appear, 'password:' (canonical) wins
2418 result_both, _ = ConfigBase.config_parse_yaml("""
2419 urls:
2420 - json://testhost:
2421 user: alice
2422 password: canonical
2423 pass: shorthand
2424 """)
2425 assert len(result_both) == 1
2426 assert result_both[0].password == "canonical"
2427
2428
2429 def test_yaml_sibling_no_silent_drop_on_null_child():
2430 """
2431 API: ConfigBase - sibling tokens are never silently discarded.
2432
2433 Previously, when the URL key had a null child value (the common
2434 case when users used same-level indentation), all sibling keys
2435 were silently ignored and the URL failed to instantiate. Confirm
2436 that the failure mode described in issue #1635 no longer occurs.
2437 """
2438 # Mirrors the bug-report YAML (correcting 'rom' typo to 'from')
2439 result, _ = ConfigBase.config_parse_yaml("""
2440 urls:
2441 - mailtos://_:
2442 user: [email protected]
2443 password: secret
2444 smtp: smtp.example.com
2445 from: [email protected]
2446 to: [email protected]
2447 tag:
2448 - dev
2449 - prod
2450 """)
2451
2452 # Must load successfully (previously raised TypeError and returned [])
2453 assert len(result) == 1
2454 assert isinstance(result[0], NotifyEmail)
2455
2456 obj = result[0]
2457 assert obj.smtp_host == "smtp.example.com"
2458 assert obj.from_addr[1] == "[email protected]"
2459 assert any(t[1] == "[email protected]" for t in obj.targets)
2460 assert "dev" in obj.tags
2461 assert "prod" in obj.tags
2462
2463
2464 def test_yaml_sibling_token_unknown_schema():
2465 """
2466 API: ConfigBase - sibling tokens with an unregistered schema.
2467
2468 When the schema is not in N_MGR the _special_token_handler call
2469 inside the 'elif sibling_tokens' branch is skipped (the False arm
2470 of 'if schema in N_MGR'). The branch still executes fully; it
2471 just applies sibling tokens as-is. Because the schema is unknown
2472 no plugin is instantiated and the result list is empty.
2473 """
2474 # 'xyzunknown' is not a registered Apprise plugin, so the
2475 # 'if schema in N_MGR' guard evaluates to False.
2476 result, _ = ConfigBase.config_parse_yaml("""
2477 urls:
2478 - xyzunknown://placeholder:
2479 mytoken: value
2480 otherkey: data
2481 """)
2482
2483 # The sibling branch ran (no exception), but no plugin loaded
2484 assert isinstance(result, list)
2485 assert len(result) == 0
2486
2487
2488 def test_yaml_child_dict_schema_key_ignored():
2489 """
2490 API: ConfigBase - 'schema' key in a child dict token is stripped.
2491
2492 The schema that determines which plugin is instantiated comes from the
2493 URL key itself. Allowing a child dict to override 'schema' via a
2494 token would cause the wrong plugin constructor to be called with
2495 fields parsed for a different URL type, leading to silent failures.
2496
2497 The list-expansion branch explicitly strips 'schema' from each entry.
2498 This test verifies the single-child-dict branch does the same.
2499 """
2500 result, _ = ConfigBase.config_parse_yaml("""
2501 urls:
2502 - mailtos://[email protected]:
2503 schema: json
2504 to: [email protected]
2505 """)
2506
2507 # The email plugin must load; the child 'schema: json' must be ignored
2508 assert len(result) == 1
2509 assert isinstance(result[0], NotifyEmail)
2510
2511
2512 def test_yaml_sibling_before_url_no_spurious_warning():
2513 """
2514 API: ConfigBase - sibling tokens before the URL key emit no warning.
2515
2516 YAML mappings do not guarantee key order. A sibling token (e.g.
2517 'smtp:') may appear before the URL key in the serialised YAML. The
2518 scan loop that finds the URL key must skip non-schema keys silently;
2519 it must NOT emit an 'Ignored entry' warning because those keys are
2520 collected later as valid sibling tokens.
2521 """
2522 from unittest import mock as _mock
2523
2524 with _mock.patch("apprise.config.base.ConfigBase.logger") as mock_log:
2525 result, _ = ConfigBase.config_parse_yaml("""
2526 urls:
2527 - smtp: smtp.example.com
2528 mailtos://[email protected]:
2529 to: [email protected]
2530 """)
2531
2532 # Both siblings are applied; no spurious "Ignored entry" warning fired
2533 assert len(result) == 1
2534 assert isinstance(result[0], NotifyEmail)
2535 assert result[0].smtp_host == "smtp.example.com"
2536 assert any(t[1] == "[email protected]" for t in result[0].targets)
2537
2538 # Confirm no "Ignored entry" warning was logged
2539 for call_args in mock_log.warning.call_args_list:
2540 assert "Ignored entry" not in str(call_args)
2541
2542
2543 def test_yaml_token_priority_over_qsd():
2544 """
2545 API: ConfigBase - YAML tokens take priority over URL query-string params.
2546
2547 The documented priority is: YAML tokens > ?key=value qsd > URL path.
2548 A second call to post_process_parse_url_results() runs after YAML tokens
2549 are merged. Without stripping qsd first, that call would re-apply qsd
2550 overrides and silently overwrite YAML-token values, breaking the
2551 documented priority.
2552 """
2553 # The URL embeds ?pass= in the query string; the YAML sibling token
2554 # 'password:' should take priority and survive to the plugin.
2555 result, _ = ConfigBase.config_parse_yaml("""
2556 urls:
2557 - json://user:urlpass@localhost?pass=qsdpass:
2558 password: yamlpass
2559 """)
2560 assert len(result) == 1
2561 # YAML token must win over qsd ?pass= and URL-path password
2562 assert result[0].password == "yamlpass"
2563
2564
2565 def test_yaml_token_priority_over_qsd_non_credential_fields():
2566 """
2567 API: ConfigBase - YAML tokens take priority over qsd for non-credential
2568 fields (verify, redirect, etc.).
2569
2570 post_process_parse_url_results() processes not only user/password but
2571 also verify, redirect, rto, cto, and port from qsd. All of these
2572 must honour the same YAML > qsd > URL-path priority rule.
2573
2574 The fix strips ALL qsd (not just credential keys) before the second
2575 post_process call for URLBase-based plugins, so qsd can never
2576 overwrite any YAML-token value regardless of which field it sets.
2577 """
2578 # URL has ?verify=no but the YAML sibling says verify: yes --
2579 # YAML token must win; the plugin should have verify_certificate=True
2580 result, _ = ConfigBase.config_parse_yaml("""
2581 urls:
2582 - json://user:pass@localhost?verify=no:
2583 verify: yes
2584 """)
2585 assert len(result) == 1
2586 assert result[0].verify_certificate is True
2587
2588
2589 def test_yaml_reapply_preserves_tags_and_asset():
2590 """The final YAML pass must not undo values assembled by ConfigBase.
2591
2592 Both spellings of tags are normalized into one set and combined with the
2593 global tags. The asset is supplied by the caller and cannot be replaced by
2594 a same-named YAML option.
2595 """
2596 asset = AppriseAsset()
2597 result, _ = ConfigBase.config_parse_yaml(
2598 "tag: global\n"
2599 "urls:\n"
2600 " - json://localhost/:\n"
2601 " tags: local\n"
2602 " asset: untrusted-value\n",
2603 asset=asset,
2604 )
2605
2606 assert len(result) == 1
2607 assert result[0].tags == {"global", "local"}
2608 assert result[0].asset is asset
2609
2610
2611 def test_yaml_priority_all_urlbase_globals_via_plugin_details():
2612 """
2613 API: ConfigBase - YAML priority verified dynamically for every
2614 URLBase-level global arg via plugin.details().
2615
2616 Verify that the priority sequence (YAML > qsd > URL path)
2617 is respected for every global arg defined.
2618 """
2619 from apprise import plugins
2620 from apprise.config.base import N_MGR
2621 from apprise.url import URLBase
2622
2623 # Discover args via plugin.details() for a minimal URLBase plugin.
2624 # json:// has no required service credentials and is always available.
2625 details = plugins.details(N_MGR["json"])
2626
2627 # Type-driven conflict pairs: (qsd_str, yaml_str).
2628 # YAML should win -- expected value is derived from yaml_str.
2629 type_conflict = {
2630 "bool": ("no", "yes"),
2631 "float": ("5.0", "10.0"),
2632 "int": ("5", "10"),
2633 }
2634
2635 # Intersect plugin.details() args with URLBase.template_args to
2636 # isolate the globals shared by every URLBase plugin.
2637 # _lookup_default is the URLBase instance attribute name for the arg.
2638 urlbase_meta = URLBase.template_args
2639 test_cases = []
2640 for name, arg_meta in details["args"].items():
2641 if name not in urlbase_meta:
2642 continue
2643 arg_type = arg_meta.get("type", "string")
2644 if arg_type not in type_conflict:
2645 continue
2646 attr_name = urlbase_meta[name].get("_lookup_default")
2647 if not attr_name:
2648 continue
2649 qsd_val, yaml_val = type_conflict[arg_type]
2650 test_cases.append((name, attr_name, arg_type, qsd_val, yaml_val))
2651
2652 # Guard: the 4 known URLBase globals must always be discovered.
2653 # If URLBase.template_args loses an entry this fires immediately.
2654 found = {t[0] for t in test_cases}
2655 assert found >= {"cto", "redirect", "rto", "verify"}, (
2656 "Expected URLBase globals cto/redirect/rto/verify in "
2657 "plugin.details(); got: {}".format(sorted(found))
2658 )
2659
2660 # Build a YAML config that sets every global in both qsd AND as a
2661 # YAML sibling token with a conflicting value so the winner is
2662 # unambiguous.
2663 qsd_str = "&".join("{}={}".format(n, qv) for n, _, _, qv, _ in test_cases)
2664 siblings = "\n ".join(
2665 "{}: {}".format(n, yv) for n, _, _, _, yv in test_cases
2666 )
2667 yaml_cfg = (
2668 "urls:\n - json://user:pass@localhost?{qsd}:\n {siblings}\n"
2669 ).format(qsd=qsd_str, siblings=siblings)
2670
2671 result, _ = ConfigBase.config_parse_yaml(yaml_cfg)
2672 assert len(result) == 1
2673 inst = result[0]
2674
2675 # Verify YAML wins for every global.
2676 for name, attr_name, arg_type, qsd_val, yaml_val in test_cases:
2677 actual = getattr(inst, attr_name)
2678 if arg_type == "bool":
2679 expected = True # yaml_val is always "yes"
2680 elif arg_type == "float":
2681 expected = float(yaml_val)
2682 elif arg_type == "int":
2683 expected = int(yaml_val)
2684 else:
2685 expected = yaml_val
2686 assert actual == expected, (
2687 "YAML token '{}' should override qsd "
2688 "(YAML={!r}, qsd={!r}) but got {!r} for '{}'".format(
2689 name, yaml_val, qsd_val, actual, attr_name
2690 )
2691 )
2692
2693
2694 def test_yaml_url_token_map_to():
2695 """ConfigBase maps named URL parts used as YAML keys."""
2696 result, _ = ConfigBase.config_parse_yaml("""
2697 urls:
2698 - discord://1234567890/abcdefghijklmnopqrstuvwxyz/:
2699 - tag: test1
2700 botname: App 1
2701 avatar_url: https://localhost/app1.png
2702 - tag: test2
2703 botname: App 2
2704 avatar_url: https://localhost/app2.png
2705 """)
2706
2707 assert len(result) == 2
2708 assert result[0].user == "App 1"
2709 assert result[0].avatar_url == "https://localhost/app1.png"
2710 assert result[1].user == "App 2"
2711 assert result[1].avatar_url == "https://localhost/app2.png"
2712
2713 # The sibling (non-indented) form works the same way
2714 result, _ = ConfigBase.config_parse_yaml("""
2715 urls:
2716 - discord://1234567890/abcdefghijklmnopqrstuvwxyz/:
2717 botname: App 3
2718 """)
2719
2720 assert len(result) == 1
2721 assert result[0].user == "App 3"
2722
2723 # A YAML key that is neither an argument nor a URL token is left alone
2724 tokens = ConfigBase._special_token_handler(
2725 "discord", {"botname": "App 4", "not-a-token": "ignored"}
2726 )
2727 assert tokens["user"] == "App 4"
2728 assert "botname" not in tokens
2729 assert tokens["not-a-token"] == "ignored"
2730
2731
2732 def test_yaml_token_alias_chains():
2733 """ConfigBase follows YAML aliases to constructor arguments."""
2734 # sogs `key` -> `user` (URL token) -> `public_key` (constructor arg)
2735 tokens = ConfigBase._special_token_handler("sogs", {"key": "abc"})
2736 assert tokens == {"public_key": "abc"}
2737
2738 # The URL token name itself resolves to the same place
2739 tokens = ConfigBase._special_token_handler("sogs", {"user": "abc"})
2740 assert tokens == {"public_key": "abc"}
2741
2742 # ringcentral `from_phone` (URL token) -> `source` (constructor arg)
2743 tokens = ConfigBase._special_token_handler(
2744 "ringc", {"from_phone": "+15551234567"}
2745 )
2746 assert tokens == {"source": "+15551234567"}
2747
2748
2749 def test_yaml_token_multi_alias():
2750 """ConfigBase skips shortcuts that represent several URL values."""
2751 tokens = ConfigBase._special_token_handler(
2752 "slack", {"token": "T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ"}
2753 )
2754 assert tokens == {}
2755
2756 # The same key in a real configuration does not break the parse
2757 result, _ = ConfigBase.config_parse_yaml("""
2758 urls:
2759 - slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/#general:
2760 token: ignored
2761 """)
2762
2763 assert len(result) == 1