Debian Codegraph @

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