Debian Codegraph @

tests/test_apprise_template.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 """Tests for template variables end to end.
28
29 Where a variable may be written, and what each placement can reach, is
30 covered separately in ``test_apprise_template_placement.py``.
31 """
32
33 # Disable logging for a cleaner testing output
34 from collections import UserDict
35 import logging
36 import os
37 from types import MappingProxyType
38 from unittest import mock
39
40 import pytest
41 import requests
42
43 from apprise import Apprise, AppriseAsset, AppriseConfig, NotifyTemplate
44 from apprise.config import ConfigBase
45 from apprise.exception import AppriseTemplateError
46 from apprise.result import AppriseResultStatus
47
48
49 def parse(content):
50 """Return the services a YAML configuration produces."""
51 return ConfigBase.config_parse_yaml(content)[0]
52
53
54 def load(content):
55 """Build an Apprise object around a YAML configuration."""
56 apobj = Apprise()
57 config = AppriseConfig()
58 assert config.add_config(content, format="yaml")
59 assert apobj.add(config)
60 return apobj
61
62
63 @pytest.fixture
64 def logging_enabled():
65 """Enable logging while tests inspect captured records."""
66 previous = logging.root.manager.disable
67 logging.disable(logging.NOTSET)
68 yield
69 logging.disable(previous)
70
71
72 @pytest.fixture
73 def sent():
74 """Accept every outbound request so delivery reports success."""
75 with mock.patch("requests.request") as request:
76 response = mock.Mock()
77 response.status_code = requests.codes.ok
78 response.content = ""
79 response.headers = {}
80 request.return_value = response
81 yield request
82
83
84 def test_apprise_template_deferred_entry():
85 """The service cannot be built while a value is missing."""
86 services = parse(
87 "template:\n - target\nurls:\n - json://localhost/?to=${TARGET}\n"
88 )
89 assert len(services) == 1
90 assert isinstance(services[0], NotifyTemplate)
91 assert services[0].template_names == ("target",)
92 assert services[0].template_required == ("target",)
93 assert services[0].url_id() is None
94
95
96 def test_apprise_template_text_config():
97 """TEXT configurations keep ${...} as literal text."""
98 services, _ = ConfigBase.config_parse_text(
99 "json://user:${NOT_A_VAR}@localhost"
100 )
101 assert len(services) == 1
102 assert "$" in services[0].password
103
104
105 @pytest.mark.parametrize(
106 "entry",
107 (
108 "json://localhost/?tag=${T}",
109 "json://localhost/?tags=${T}",
110 "json://localhost/?+tag=${T}",
111 "json://localhost/?-tag=${T}",
112 "json://localhost/?:tag=${T}",
113 "json://localhost/:\n - tag: ${T}",
114 "json://localhost/:\n - tags: ${T}",
115 ),
116 )
117 def test_apprise_template_rejects_tag_variable(entry, logging_enabled, caplog):
118 """Query, singular, and plural tags all stay fixed."""
119 with caplog.at_level(logging.ERROR):
120 assert parse("template:\n - t\nurls:\n - {}\n".format(entry)) == []
121
122 assert "not permitted in tag/tags" in caplog.text
123
124
125 @pytest.mark.parametrize(
126 "tags",
127 ("tag: ${T}", "tags: ${T}", 'tags: [fixed, "${T}"]'),
128 )
129 def test_apprise_template_rejects_global_tag_variable(
130 tags, logging_enabled, caplog
131 ):
132 """Global routing tags must also be known before resolution."""
133 with caplog.at_level(logging.ERROR):
134 services = parse(
135 f"template:\n - t\n{tags}\nurls:\n - json://localhost/\n"
136 )
137
138 assert services == []
139 assert "not permitted in tag/tags" in caplog.text
140
141
142 def test_apprise_template_disabled_keeps_global_tag_marker():
143 """A tag marker is ordinary text when template support is disabled."""
144 services, _ = ConfigBase.config_parse_yaml(
145 "template:\n - t\ntag: ${T}\nurls:\n - json://localhost/\n",
146 asset=AppriseAsset(allow_templates=False),
147 )
148
149 assert len(services) == 1
150 assert {str(tag) for tag in services[0].tags} == {"${t}"}
151
152
153 def test_apprise_template_keeps_undeclared_global_tag_marker():
154 """Only declared variables are forbidden in routing tags."""
155 services = parse(
156 "template:\n - other\ntag: ${T}\nurls:\n - json://localhost/\n"
157 )
158
159 assert len(services) == 1
160 assert {str(tag) for tag in services[0].tags} == {"${t}"}
161
162
163 def test_apprise_template_fills_marker_after_schema():
164 """Every marker past :// is filled in, wherever it was written."""
165 entry = parse(
166 "template:\n - t\nurls:\n - json://localhost/?+${T}=1&+X=${T}\n"
167 )[0]
168
169 assert isinstance(entry, NotifyTemplate)
170 assert entry.template_names == ("t",)
171
172 # The parameter name and the value both take the supplied value
173 service = entry.resolve({"t": "REAL"})
174 assert service.headers == {"REAL": "1", "X": "REAL"}
175
176
177 def test_apprise_template_preserves_yaml_setting_name():
178 """A marker written as a YAML setting name is not a variable.
179
180 Only values are replaced underneath a URL, so the name stays as the
181 configuration spelled it and Apprise reads it the usual way.
182 """
183 entry = parse(
184 "template:\n - t\n"
185 "urls:\n - json://localhost/:\n"
186 " '+${T}': 1\n '+X': ${T}\n"
187 )[0]
188
189 service = entry.resolve({"t": "REAL"})
190 assert service.headers == {"${T}": "1", "X": "REAL"}
191
192
193 def test_apprise_template_bad_entry_isolated():
194 """One refused entry leaves the rest of the file usable."""
195 services = parse(
196 "template:\n - t\n"
197 "urls:\n - mailto://u:[email protected]:${T}\n - json://other/\n"
198 )
199 assert len(services) == 1
200 assert not isinstance(services[0], NotifyTemplate)
201
202
203 def test_apprise_template_rejects_yaml_loop(logging_enabled, caplog):
204 """A recursive YAML value rejects its entry without escaping an error."""
205 with caplog.at_level(logging.ERROR):
206 services = parse(
207 "template:\n - t\n"
208 "urls:\n - json://user:${T}@localhost/:\n"
209 " - headers: &loop [*loop]\n"
210 " - json://localhost/\n"
211 )
212
213 assert len(services) == 1
214 assert "Looping structure" in caplog.text
215
216
217 @pytest.mark.parametrize(
218 "url",
219 [
220 "json://${T}/path",
221 "json://host/${T}",
222 "json://user:${T}@host/",
223 "json://${T}:pass@host/",
224 "json://host/?to=${T}",
225 ],
226 )
227 def test_apprise_template_url_fields(url):
228 """Host, path, credentials and parameters all accept one."""
229 services = parse(f"template:\n - t\nurls:\n - {url}\n")
230 assert len(services) == 1
231 assert isinstance(services[0], NotifyTemplate)
232
233
234 def test_apprise_template_yaml_setting():
235 """A setting written under the URL may be templated too."""
236 services = parse(
237 "template:\n - t\n"
238 "urls:\n - json://localhost/:\n - to: ${T}\n tag: work\n"
239 )
240 assert len(services) == 1
241 assert services[0].template_names == ("t",)
242 assert {str(t) for t in services[0].tags} == {"work"}
243
244
245 def test_apprise_template_yaml_url_key():
246 """The mapping form is supported as well as the plain form."""
247 services = parse(
248 "template:\n - t\n"
249 "urls:\n - json://localhost/${T}:\n - tag: work\n"
250 )
251 assert len(services) == 1
252 assert isinstance(services[0], NotifyTemplate)
253
254
255 def test_apprise_template_value_encoding(sent):
256 """Credential punctuation reaches the parsed password field unchanged."""
257 apobj = load("template:\n - t\nurls:\n - json://user:${T}@localhost/\n")
258 hostile = "a b&c=d?e/f@g"
259 assert apobj.notify(body="x", template={"t": hostile})
260
261 service = next(apobj.find(template={"t": hostile}))
262
263 # The value survives untouched
264 assert service.password == hostile
265
266 # The plugin escapes that field if it later renders a URL.
267 rendered = service.url()
268 assert "%26" in rendered
269 assert "a b&c" not in rendered
270
271
272 def test_apprise_template_undeclared_marker_literal():
273 """``${NAME}`` only means something when it was declared.
274
275 Anything else is ordinary text, and the entry is not treated as
276 templated at all.
277 """
278 services = parse(
279 "template:\n - t\nurls:\n - json://user:${NOT_DECLARED}@localhost/\n"
280 )
281
282 assert len(services) == 1
283 # It loaded straight away; nothing is waiting on a value
284 assert not isinstance(services[0], NotifyTemplate)
285 assert services[0].password == "${NOT_DECLARED}"
286
287
288 def test_apprise_template_undeclared_marker_not_pending(sent):
289 """The URL is sent exactly as written."""
290 apobj = load(
291 "template:\n - t\nurls:\n - json://user:${NOPE}@localhost/\n"
292 )
293
294 assert apobj.template_vars() == {}
295 assert apobj.notify(body="x").status == AppriseResultStatus.SUCCESS
296
297
298 def test_apprise_template_success_status(sent):
299 """A complete set of values delivers as normal."""
300 apobj = load(
301 "template:\n - t\n"
302 "urls:\n - json://localhost/?:x=${T}\n - json://other/\n"
303 )
304 result = apobj.notify(body="x", template={"t": "value"})
305 assert result.status == AppriseResultStatus.SUCCESS
306 assert len(list(result)) == 2
307
308
309 def test_apprise_template_partial_status(sent):
310 """A skipped entry must not read as a clean success."""
311 apobj = load(
312 "template:\n - t\n"
313 "urls:\n - json://localhost/?:x=${T}\n - json://other/\n"
314 )
315 result = apobj.notify(body="x")
316 assert result.status == AppriseResultStatus.PARTIAL
317 assert len(list(result)) == 1
318
319
320 def test_apprise_template_missing_all_status(sent):
321 """Every match being held back is a failure, not a no-match."""
322 apobj = load("template:\n - t\nurls:\n - json://localhost/?:x=${T}\n")
323 assert apobj.notify(body="x").status == AppriseResultStatus.FAILURE
324
325
326 def test_apprise_template_environment_value(sent, monkeypatch):
327 """A deployment can supply values without touching the config."""
328 monkeypatch.setenv("APPRISE_TEMPLATE_T", "from-env")
329 apobj = load("template:\n - t\nurls:\n - json://user:${T}@localhost/\n")
330 assert apobj.notify(body="x").status == AppriseResultStatus.SUCCESS
331 assert next(apobj.find()).password == "from-env"
332
333
334 def test_apprise_template_tag_matching(sent):
335 """Tags are known up front, so filtering is unaffected."""
336 apobj = load(
337 "template:\n - t\n"
338 "urls:\n - json://user:${T}@localhost/:\n - tag: work\n"
339 " - json://other/:\n - tag: home\n"
340 )
341 matched = list(apobj.find(tag="work", template={"t": "x"}))
342 assert len(matched) == 1
343 assert matched[0].password == "x"
344
345
346 def test_apprise_template_pending_url_display():
347 """Introspection reveals which values are still wanted."""
348 apobj = load("template:\n - t\nurls:\n - json://host/${T}\n")
349 assert "${T}" in apobj.urls()[0]
350 assert "${T}" in apobj.urls(privacy=True)[0]
351
352
353 def test_apprise_template_secret_masking():
354 """A variable name is safe to show; a password is not."""
355 apobj = load(
356 "template:\n - t\nurls:\n - json://user:hunter2secret@host/${T}\n"
357 )
358 shown = apobj.urls(privacy=True)[0]
359 assert "${T}" in shown
360 assert "hunter2secret" not in shown
361
362
363 def test_apprise_template_service_reuse(sent):
364 """Anything the service remembers survives between calls."""
365 entry = parse(
366 "template:\n - t\nurls:\n - json://user:${T}@localhost/\n"
367 )[0]
368 first = entry.resolve({"t": "x"})
369 assert entry.resolve({"t": "x"}) is first
370 assert entry.resolve({"t": "y"}) is not first
371
372 # ...and an identifier only exists once it has been built
373 assert entry.url_id() is None
374 assert first.url_id()
375
376
377 def test_apprise_template_cache_limit():
378 """A caller sending new values each time cannot grow it."""
379 from apprise.template import MAX_RESOLVE_CACHE
380
381 entry = parse(
382 "template:\n - t\nurls:\n - json://user:${T}@localhost/\n"
383 )[0]
384 for i in range(MAX_RESOLVE_CACHE + 10):
385 entry.resolve({"t": f"value{i}"})
386
387 assert len(entry._cache) <= MAX_RESOLVE_CACHE
388
389
390 def test_apprise_template_vars_summary():
391 """Callers can ask what a configuration expects."""
392 apobj = load(
393 "template:\n - needed\n - other: a-default\n"
394 "urls:\n - json://host/${NEEDED}/${OTHER}\n"
395 )
396 report = apobj.template_vars()
397
398 # No default means the call or environment needs to fill the name.
399 assert report["needed"]["default"] is None
400
401 # ...otherwise the default itself is reported
402 assert report["other"]["default"] == "a-default"
403
404 assert report["needed"]["services"] == 1
405
406
407 def test_apprise_template_missing_name_not_captured(sent, logging_enabled):
408 """Keep missing names out of logs returned to API callers."""
409 captured = []
410 apobj = load(
411 "template:\n - super_secret_name\n"
412 "urls:\n - json://localhost/?:x=${SUPER_SECRET_NAME}\n"
413 " - json://other/\n"
414 )
415 result = apobj.notify(
416 body="x",
417 log_callback=lambda entry, service: captured.append(entry),
418 log_level=logging.DEBUG,
419 )
420
421 assert result.status == AppriseResultStatus.PARTIAL
422
423 blob = " ".join(entry.message for entry in captured).lower()
424 assert "super_secret_name" not in blob
425 assert "${" not in blob
426
427 # The operator is still told that something was left out
428 assert "skipped" in blob
429
430
431 def test_apprise_template_config_not_captured(sent, logging_enabled):
432 """A capture must never carry the configuration body."""
433 captured = []
434 apobj = load(
435 "template:\n - t\n"
436 "urls:\n - json://user:hunter2secret@localhost/?:x=${T}\n"
437 )
438 apobj.notify(
439 body="x",
440 log_callback=lambda entry, service: captured.append(entry),
441 log_level=logging.DEBUG,
442 )
443
444 blob = " ".join(entry.message for entry in captured)
445 assert "hunter2secret" not in blob
446
447
448 def test_apprise_template_log_capture_opt_out(logging_enabled):
449 """The flag the template code relies on works on its own."""
450 from apprise.logger import _ServiceLogCapture, logger
451
452 captured = []
453 with _ServiceLogCapture(
454 service=None,
455 log_callback=lambda entry, service: captured.append(entry),
456 level=logging.DEBUG,
457 ):
458 logger.error("PUBLIC-MARKER")
459 logger.error("PRIVATE-MARKER", extra={"apprise_capture": False})
460
461 blob = " ".join(entry.message for entry in captured)
462 assert "PUBLIC-MARKER" in blob
463 assert "PRIVATE-MARKER" not in blob
464
465
466 def test_apprise_template_included_declarations(sent, tmpdir):
467 """Each file declares what it uses; values reach them all."""
468 child = tmpdir.join("child.yml")
469 child.write(
470 "template:\n - shared\nurls:\n - json://user:${SHARED}@child-host/\n"
471 )
472 parent = tmpdir.join("parent.yml")
473 parent.write(
474 "template:\n - shared\n"
475 f"include:\n - {child!s}\n"
476 "urls:\n - json://user:${SHARED}@parent-host/\n"
477 )
478
479 apobj = Apprise()
480 config = AppriseConfig(recursion=1)
481 assert config.add(str(parent))
482 assert apobj.add(config)
483
484 # One value supplied once reaches both files
485 built = list(apobj.find(template={"shared": "one-value"}))
486 assert len(built) == 2
487 assert {service.password for service in built} == {"one-value"}
488
489
490 def test_apprise_template_shared_yaml_block(sent):
491 """A YAML anchor used twice does not confuse the parser."""
492 apobj = load(
493 "template:\n - t\n"
494 "shared: &shared\n to: ${T}\n"
495 "urls:\n - json://first/:\n <<: *shared\n"
496 " - json://second/:\n <<: *shared\n"
497 )
498 assert len(list(apobj.find(template={"t": "x"}))) == 2
499
500
501 def test_apprise_template_cli_value(tmpdir, sent):
502 """--template supplies a value for a run."""
503 from click.testing import CliRunner
504
505 from apprise import cli
506
507 config = tmpdir.join("apprise.yml")
508 config.write("template:\n - t\nurls:\n - json://user:${T}@localhost/\n")
509
510 result = CliRunner().invoke(
511 cli.main,
512 ["-b", "x", f"--config={config!s}", "--template-var", "t=supplied"],
513 )
514 assert result.exit_code == 0
515
516
517 def test_apprise_template_cli_invalid_value(tmpdir):
518 """A --template entry has to read as NAME=VALUE."""
519 from click.testing import CliRunner
520
521 from apprise import cli
522
523 config = tmpdir.join("apprise.yml")
524 config.write("urls:\n - json://localhost\n")
525
526 result = CliRunner().invoke(
527 cli.main,
528 ["-b", "x", f"--config={config!s}", "-tv", "no-equals-sign"],
529 )
530 assert result.exit_code == 2
531 assert "NAME=VALUE" in result.output
532
533
534 def test_apprise_template_cli_dry_run(tmpdir):
535 """The written form and the required names are both listed."""
536 from click.testing import CliRunner
537
538 from apprise import cli
539
540 config = tmpdir.join("apprise.yml")
541 config.write(
542 "template:\n - t\n - other: a-default\n"
543 "urls:\n - json://host/${T}/${OTHER}\n"
544 )
545
546 result = CliRunner().invoke(
547 cli.main, ["-b", "x", f"--config={config!s}", "--dry-run"]
548 )
549 assert "${T}" in result.output
550 assert "t (required)" in result.output
551 assert "other (has default)" in result.output
552
553
554 def test_apprise_template_pending_repr():
555 """It stands in for a service, so it answers the same questions."""
556 entry = parse(
557 "template:\n - t\n"
558 "urls:\n - json://user:${T}@localhost/:\n"
559 " - tag: work\n retry: 2\n"
560 )[0]
561
562 assert entry.schema == "json"
563 assert entry.service_name == "JSON"
564 assert entry.enabled is True
565 assert entry.retry == 2
566 assert entry.optional is None
567 assert "json" in repr(entry)
568 assert "${T}" in str(entry)
569
570
571 def test_apprise_template_unknown_service_metadata():
572 """A schema we do not carry is answered for safely."""
573 entry = parse(
574 "template:\n - t\nurls:\n - json://user:${T}@localhost/\n"
575 )[0]
576 entry.results["schema"] = "not-a-real-schema"
577
578 assert entry._plugin is None
579 assert entry.service_name is None
580 assert entry.enabled is True
581
582
583 def test_apprise_template_setting_display():
584 """A setting is listed so it is clear a value is wanted."""
585 apobj = load(
586 "template:\n - t\n"
587 "urls:\n - mailto://user:[email protected]:\n - to: ${T}\n"
588 )
589 shown = apobj.urls()[0]
590 assert "${T}" in shown
591 # ...and it survives being escaped for the URL
592 assert "%24%7B" not in shown
593
594
595 def test_apprise_template_repeated_name(sent):
596 """A variable may be written as many times as you like."""
597 apobj = load(
598 "template:\n - t\n"
599 "urls:\n - json://user:${T}@localhost/${T}/:\n - to: ${T}\n"
600 )
601
602 service = next(apobj.find(template={"t": "same"}))
603 assert service.password == "same"
604 assert "/same/" in service.url()
605
606
607 def test_apprise_template_url_size_limit(monkeypatch, logging_enabled, caplog):
608 """A built URL is capped no matter what values arrive."""
609 import apprise.template as template_module
610
611 entry = parse(
612 "template:\n - t\nurls:\n - json://user:${T}@localhost/\n"
613 )[0]
614 monkeypatch.setattr(template_module, "MAX_RESOLVED_URL_LEN", 10)
615
616 with caplog.at_level(logging.ERROR):
617 assert entry.resolve({"t": "a-value-well-over-ten-characters"}) is None
618
619 # The message says which lines of the file to go and look at
620 assert "YAML entry #1, item #1" in caplog.text
621
622
623 def test_apprise_template_build_failure(logging_enabled, caplog):
624 """A value the service rejects skips the entry, not the run."""
625 entry = parse(
626 "template:\n - t\nurls:\n - json://user:${T}@localhost/\n"
627 )[0]
628
629 from apprise.template import N_MGR
630
631 with (
632 mock.patch.object(
633 type(N_MGR),
634 "__getitem__",
635 side_effect=TypeError("the value was refused"),
636 ),
637 caplog.at_level(logging.ERROR),
638 ):
639 assert entry.resolve({"t": "x"}) is None
640
641 assert "YAML entry #1, item #1" in caplog.text
642
643
644 def test_apprise_template_substitution_failure(logging_enabled, caplog):
645 """A failure while filling values in is handled quietly."""
646 entry = parse(
647 "template:\n - t\nurls:\n - json://user:${T}@localhost/\n"
648 )[0]
649
650 with (
651 mock.patch.object(
652 entry.placeholders, "substitute", side_effect=RuntimeError("nope")
653 ),
654 caplog.at_level(logging.ERROR),
655 ):
656 assert entry.resolve({"t": "x"}) is None
657
658 assert "YAML entry #1, item #1" in caplog.text
659
660
661 def test_apprise_template_exception_detail_is_never_captured(
662 logging_enabled, caplog
663 ):
664 """A rejected value is not handed back through the result log."""
665 apobj = Apprise()
666 config = AppriseConfig()
667 config.add_config(
668 "template:\n - key\n"
669 "urls:\n - sendgrid://${KEY}:[email protected]/[email protected]\n",
670 format="yaml",
671 )
672 apobj.add(config)
673
674 captured = []
675
676 with caplog.at_level(logging.DEBUG, logger="apprise"):
677 apobj.notify(
678 body="x",
679 # Refused by the service, which names it in the error it raises
680 template={"key": "SECRET!!!KEY"},
681 log_callback=lambda entry, plugin: captured.append(entry),
682 log_level=logging.DEBUG,
683 )
684
685 messages = [str(getattr(entry, "message", entry)) for entry in captured]
686
687 # The entry was skipped, and said so without naming the value
688 assert any("Could not load" in m for m in messages)
689
690 # The service's own exception text never reaches the caller
691 assert not [m for m in messages if "Loading Exception" in m]
692
693
694 def test_apprise_template_location_counts_each_expansion():
695 """One URL block that becomes several services numbers them apart."""
696 services = parse(
697 "template:\n - t\n"
698 "urls:\n - mailto://user:[email protected]:\n"
699 " - to: [email protected]\n cc: ${T}\n"
700 " - to: [email protected]\n cc: ${T}\n"
701 )
702
703 # Both came from the first block under urls:, as separate items
704 assert [s.location for s in services] == [
705 "YAML entry #1, item #1",
706 "YAML entry #1, item #2",
707 ]
708
709
710 def test_apprise_template_adjacent_text_masking():
711 """Only the variable name is safe to show; the rest is not."""
712 entry = parse(
713 "template:\n - t\n"
714 "urls:\n - json://user:prefix${T}suffix@localhost/\n"
715 )[0]
716
717 shown = entry.url(privacy=True)
718 assert "${T}" in shown
719 assert "prefix" not in shown
720 assert "suffix" not in shown
721
722 # Without privacy the whole thing reads back as written
723 assert "prefix${T}suffix" in entry.url()
724
725
726 def test_apprise_template_query_display():
727 """A parameter waiting on a value is visible in the URL."""
728 entry = parse(
729 "template:\n - t\nurls:\n - json://localhost/?:custom=${T}\n"
730 )[0]
731 assert "${T}" in entry.url()
732
733
734 def test_apprise_template_parse_time_validation(logging_enabled, caplog):
735 """Report services that must validate a field while parsing."""
736 with caplog.at_level(logging.ERROR):
737 services = parse(
738 "template:\n - t\n"
739 "urls:\n - sendgrid://SG.abcdefghij:${T}/[email protected]\n"
740 )
741
742 assert services == []
743 assert "template variable can not be used at this position" in (
744 caplog.text.lower()
745 )
746
747
748 def test_apprise_template_valid_service_position():
749 """The limitation is the position, not the service."""
750 services = parse(
751 "template:\n - t\n"
752 "urls:\n - sendgrid://${T}:[email protected]/[email protected]\n"
753 )
754 assert len(services) == 1
755 assert isinstance(services[0], NotifyTemplate)
756
757
758 def test_apprise_template_service_coverage():
759 """A spot check across a few differently shaped URLs."""
760 for url in (
761 "discord://${T}/${T}",
762 "slack://${T}/${T}/${T}",
763 "mailtos://user:[email protected]/[email protected]?smtp=${T}",
764 "twilio://sid:token@${T}/+15551234567",
765 "tgram://123456789:${T}/-1001234567890",
766 ):
767 services = parse(f"template:\n - t\nurls:\n - {url}\n")
768 assert len(services) == 1, url
769 assert isinstance(services[0], NotifyTemplate), url
770
771
772 def test_apprise_template_many_url_variables(sent):
773 """There is no cap on how many are used in one URL."""
774 names = [f"v{i}" for i in range(60)]
775 declared = "\n".join(f" - {name}" for name in names)
776 path = "/".join("${{{}}}".format(name.upper()) for name in names)
777
778 apobj = load(f"template:\n{declared}\nurls:\n - json://host/{path}\n")
779 values = {name: f"val{i}" for i, name in enumerate(names)}
780
781 service = next(apobj.find(template=values))
782 for i in range(60):
783 assert f"val{i}" in service.url()
784
785
786 def test_apprise_template_shared_url_setting(sent):
787 """One name can fill the URL and a setting below it."""
788 apobj = load(
789 "template:\n - t\n"
790 "urls:\n - json://user:${T}@localhost/:\n"
791 " - to: ${T}\n tag: work\n"
792 )
793 service = next(apobj.find(template={"t": "shared"}))
794 assert service.password == "shared"
795
796
797 def test_apprise_template_query_value_is_not_reparsed(sent):
798 """A parsed query value is not reparsed as more query settings."""
799 apobj = load(
800 "template:\n - v\nurls:\n - json://localhost/?:custom=${V}\n"
801 )
802 control = load("template:\n - v\nurls:\n - json://localhost/?:c=${V}\n")
803
804 evil = next(
805 apobj.find(template={"v": "x&method=GET&[email protected]"})
806 )
807 clean = next(control.find(template={"v": "x"}))
808
809 # The marker occupied one parsed value, so its punctuation stays there.
810 assert evil.method == clean.method == "POST"
811
812
813 def test_apprise_template_path_punctuation(sent):
814 """Path fields preserve punctuation selected by the config author."""
815 apobj = load("template:\n - v\nurls:\n - json://h/${V}/x\n")
816 service = next(apobj.find(template={"v": "seg/ment?x=1&y=2#z"}))
817 assert service.fullpath == "/seg/ment?x=1&y=2#z/x"
818
819
820 def test_apprise_template_service_validates_value(sent):
821 """Garbage is handed to the service to make sense of."""
822 apobj = load("template:\n - v\nurls:\n - json://${V}/\n")
823 for value in ("ok.example.com", "evil.com/p", "not a host", "a@b"):
824 assert next(apobj.find(template={"v": value}), None) is not None
825
826
827 def test_apprise_template_embedded_host_is_preserved(sent):
828 """A partial hostname keeps author-supplied URL punctuation."""
829 apobj = load("template:\n - v\nurls:\n - json://trusted-${V}/\n")
830 service = next(
831 apobj.find(template={"v": "[email protected]:80/path?x=1#part"})
832 )
833
834 assert service.host == "[email protected]:80/path?x=1#part"
835 assert service.fullpath == "/"
836
837
838 @pytest.mark.parametrize(
839 "entry",
840 [
841 # Written on its own
842 "${V}://host/",
843 # Written as a YAML key with settings under it
844 "${V}://host/:\n - tag: work",
845 # A marker standing in for the schema and its separator
846 "${V}user:pass@host/",
847 # Trailing text after the marker, as in a secure variant
848 "${V}s://host/",
849 # Leading text before the marker
850 "json${V}://host/",
851 # ...and the same the other way around
852 "${V}json://host/",
853 # Buried in the middle of an otherwise real schema
854 "js${V}on://host/",
855 # A secure variant built from both
856 "mailto${V}s://host/",
857 # No separator at all
858 "${V}",
859 # A separator that is not quite one
860 "${V}//host/",
861 # A later separator does not hide a variable in the schema position
862 "${V}/path://later",
863 # The mapping form must make the same decision
864 "${V}/path://later:\n - tag: work",
865 # A URL hidden in a query value cannot provide the schema boundary
866 "${V}localhost/?url=http://bad.actor.com",
867 # A backslash before :// does not make a variable schema acceptable
868 r"abc${V}s\://localhost",
869 ],
870 )
871 def test_apprise_template_rejects_schema_variable(
872 entry, logging_enabled, caplog
873 ):
874 """Nothing before :// can be a template variable.
875
876 The schema decides which service reads the URL, and that is settled
877 long before a value is known, so this is a configuration error rather
878 than an unresolved notification service.
879 """
880 with caplog.at_level(logging.ERROR):
881 assert parse("template:\n - v\nurls:\n - {}\n".format(entry)) == []
882
883 assert "not permitted in URL schemas" in caplog.text
884
885
886 def test_apprise_template_dollar_is_literal():
887 """A "$" before a marker is just a "$".
888
889 There is no escape syntax. To keep a ${NAME} literal, simply do not
890 declare that name.
891 """
892 entry = parse("template:\n - t\nurls:\n - json://l/?+X=$${T}\n")[0]
893
894 service = entry.resolve({"t": "abc"})
895 assert service.headers == {"X": "$abc"}
896
897
898 def test_apprise_template_default_marker_is_literal():
899 """A default is used exactly as written, markers and all.
900
901 One declaration never builds on another. ``key`` below is the text
902 ``${value}``, not ``34``. Assemble values in the URL instead.
903 """
904 apobj = load(
905 "template:\n value: 34\n key: ${value}\n"
906 "urls:\n - json://l/?+K=${KEY}&+V=${VALUE}\n"
907 )
908
909 # K keeps the marker; V shows that 'value' really does resolve to 34
910 assert next(apobj.find()).headers == {"K": "${value}", "V": "34"}
911
912
913 def test_apprise_template_supplied_marker_is_literal():
914 """A value handed in for one call is not looked at again either."""
915 apobj = load(
916 "template:\n value: 34\n key:\n"
917 "urls:\n - json://l/?+K=${KEY}&+V=${VALUE}\n"
918 )
919 service = next(apobj.find(template={"key": "${value}"}))
920
921 assert service.headers == {"K": "${value}", "V": "34"}
922
923
924 def test_apprise_template_environment_marker_is_literal():
925 """An environment value is taken as written in the same way."""
926 with mock.patch.dict(os.environ, {"APPRISE_TEMPLATE_KEY": "${value}"}):
927 apobj = load(
928 "template:\n value: 34\n key:\n"
929 "urls:\n - json://l/?+K=${KEY}&+V=${VALUE}\n"
930 )
931 assert next(apobj.find()).headers == {"K": "${value}", "V": "34"}
932
933
934 def test_apprise_template_bad_schema_isolated(sent):
935 """One bad entry leaves the rest of the file usable."""
936 services = parse(
937 "template:\n - v\nurls:\n - ${V}://host/\n - json://ok/\n"
938 )
939 assert len(services) == 1
940 assert not isinstance(services[0], NotifyTemplate)
941
942
943 def test_apprise_template_credential_separators(sent):
944 """Ordinary password punctuation is kept unchanged."""
945 apobj = load("template:\n - v\nurls:\n - json://u:${V}@host/\n")
946 service = next(apobj.find(template={"v": "p/a?s&s"}))
947 assert service.password == "p/a?s&s"
948
949
950 @pytest.mark.parametrize("credentials", ("user", "user:pass"))
951 def test_apprise_template_combined_credentials(credentials, sent):
952 """A user field may carry either supported credential form."""
953 apobj = load("template:\n - creds\nurls:\n - json://${CREDS}@host/\n")
954 service = next(apobj.find(template={"creds": credentials}))
955 user, separator, password = credentials.partition(":")
956 assert service.user == user
957 assert service.password == (password if separator else None)
958 assert service.host == "host"
959
960
961 def test_apprise_template_email_authority(sent):
962 """A service may accept an email as its complete authority value."""
963 apobj = load(
964 "template:\n - email\n"
965 "urls:\n"
966 " - ses://${EMAIL}/T1JJ3T3L2/A1BRTD4JD/"
967 "TIiajkdnlazkcevi7FQ/us-west-2/[email protected]\n"
968 )
969 service = next(apobj.find(template={"email": "[email protected]"}))
970 assert service.from_addr == "[email protected]"
971
972
973 # The characters that separate one part of a URL from the next, and a few
974 # everyday ones that have to survive untouched.
975 SEPARATORS = ("/", "&", "@")
976
977 VALUES = (
978 "plain-value",
979 "a/b",
980 "a&b",
981 "a@b",
982 "user:pass",
983 "one,two",
984 "a/b&c@d",
985 "b64/secret+value==",
986 )
987
988
989 @pytest.mark.parametrize("value", VALUES)
990 def test_apprise_template_url_value_is_preserved(value, sent):
991 """A value written into a URL fills the one spot it was written in."""
992 apobj = load("template:\n - v\nurls:\n - json://user:${V}@host/\n")
993 service = next(apobj.find(template={"v": value}))
994
995 # The service still talks to the host the author wrote
996 assert service.host == "host"
997 assert service.user == "user"
998
999 # ...and the value arrives whole, however it was written
1000 assert service.password == value
1001
1002
1003 @pytest.mark.parametrize("value", VALUES)
1004 def test_apprise_template_setting_value_is_left_alone(value, sent):
1005 """A setting under the URL already says what its value is for."""
1006 apobj = load(
1007 "template:\n - v\n"
1008 "urls:\n - json://user:pass@host/:\n - to: ${V}\n"
1009 )
1010 service = next(apobj.find(template={"v": value}))
1011
1012 assert service.host == "host"
1013 assert service.password == "pass"
1014
1015
1016 @pytest.mark.parametrize("value", VALUES)
1017 def test_apprise_template_query_value_adds_no_parameter(value, sent):
1018 """An "&" in a value cannot become another parameter."""
1019 apobj = load("template:\n - v\nurls:\n - json://host/?:custom=${V}\n")
1020 control = load("template:\n - v\nurls:\n - json://host/?:custom=${V}\n")
1021
1022 service = next(apobj.find(template={"v": value}))
1023 clean = next(control.find(template={"v": "plain"}))
1024
1025 # Nothing the value carried changed how the service was set up
1026 assert service.method == clean.method
1027 assert service.host == clean.host == "host"
1028
1029
1030 @pytest.mark.parametrize(
1031 "address", ["[::1]", "::1", "2001:db8::1", "127.0.0.1", "host.example"]
1032 )
1033 def test_apprise_template_real_addresses_survive(address, sent):
1034 """A genuine address is written through untouched."""
1035 apobj = load("template:\n - v\nurls:\n - json://${V}/\n")
1036 assert next(apobj.find(template={"v": address})).host == address
1037
1038
1039 @pytest.mark.parametrize("hostile", VALUES)
1040 def test_apprise_template_email_setting_keeps_server(hostile, sent):
1041 """A named email setting cannot change the configured mail server."""
1042 apobj = load(
1043 "template:\n - v\n"
1044 "urls:\n - mailtos://user:[email protected]/:\n - bcc: ${V}\n"
1045 )
1046 service = next(apobj.find(template={"v": hostile}))
1047
1048 # The server being talked to is still the one the author wrote
1049 assert service.host == "example.com"
1050 assert service.user == "user"
1051 assert service.password == "pass"
1052
1053
1054 def two_configurations():
1055 """Two separately loaded configurations, each with its own variable."""
1056 apobj = Apprise()
1057 for name in ("alpha", "beta"):
1058 config = AppriseConfig()
1059 assert config.add_config(
1060 f"template:\n - {name}\n"
1061 f"urls:\n - json://user:${{{name.upper()}}}@{name}-host/\n",
1062 format="yaml",
1063 )
1064 assert apobj.add(config)
1065 return apobj
1066
1067
1068 def test_apprise_template_values_span_configurations(sent):
1069 """One set of values covers everything that is loaded.
1070
1071 Each entry passes over the names belonging to the other
1072 configuration rather than refusing them.
1073 """
1074 built = list(
1075 two_configurations().find(template={"alpha": "1", "beta": "2"})
1076 )
1077 assert sorted(service.host for service in built) == [
1078 "alpha-host",
1079 "beta-host",
1080 ]
1081 assert sorted(service.password for service in built) == ["1", "2"]
1082
1083
1084 def test_apprise_template_case_is_ignored_end_to_end(sent):
1085 """Declaration, marker, and supplied key casing may all differ."""
1086 apobj = Apprise()
1087 config = AppriseConfig()
1088 assert config.add_config(
1089 "template:\n - MiXeD\nurls:\n - json://user:${mIxEd}@localhost/\n",
1090 format="yaml",
1091 )
1092 assert apobj.add(config)
1093
1094 service = next(apobj.find(template={"MIXED": "value"}))
1095 assert service.password == "value"
1096
1097
1098 def test_apprise_template_partial_values_span_configurations(sent):
1099 """Supplying one still delivers to the one it belongs to."""
1100 built = list(two_configurations().find(template={"alpha": "1"}))
1101 assert [service.host for service in built] == ["alpha-host"]
1102
1103
1104 def test_apprise_template_unknown_name_is_ignored(sent):
1105 """A name no loaded configuration uses does not block delivery."""
1106 built = list(
1107 two_configurations().find(template={"alpha": "1", "nowhere": "x"})
1108 )
1109 assert [service.host for service in built] == ["alpha-host"]
1110
1111
1112 def test_apprise_template_unknown_name_does_not_change_status(sent):
1113 """An unused name does not turn a successful send into a partial one."""
1114 apobj = Apprise()
1115 assert apobj.add("json://untemplated/")
1116
1117 result = apobj.notify(body="x", template={"nowhere": "x"})
1118
1119 assert result.status == AppriseResultStatus.SUCCESS
1120
1121
1122 def test_apprise_template_hides_unknown_name_from_capture(
1123 sent, logging_enabled
1124 ):
1125 """The names must not reach whoever asked for the notification."""
1126 captured = []
1127 two_configurations().notify(
1128 body="x",
1129 template={"a_secret_name": "x"},
1130 log_callback=lambda entry, service: captured.append(entry),
1131 log_level=logging.DEBUG,
1132 )
1133
1134 blob = " ".join(entry.message for entry in captured).lower()
1135 assert "a_secret_name" not in blob
1136
1137
1138 def test_apprise_template_logs_unknown_name_locally(
1139 sent, logging_enabled, caplog
1140 ):
1141 """The local debug log names unused inputs without logging values."""
1142 with caplog.at_level(logging.DEBUG):
1143 list(
1144 two_configurations().find(
1145 template={"NoWhErE": "do-not-log-this-value"}
1146 )
1147 )
1148
1149 assert "nowhere" in caplog.text
1150 assert "supplied but not used" in caplog.text
1151 assert "do-not-log-this-value" not in caplog.text
1152
1153
1154 def test_apprise_template_unused_name_log_is_bounded(logging_enabled, caplog):
1155 """A large unused mapping cannot create an equally large log entry."""
1156 values = {"name{}".format(i): "secret{}".format(i) for i in range(25)}
1157
1158 with caplog.at_level(logging.DEBUG):
1159 list(Apprise().find(template=values))
1160
1161 assert "(+5 more)" in caplog.text
1162 assert "name19" in caplog.text
1163 assert "name20" not in caplog.text
1164 assert "secret" not in caplog.text
1165
1166
1167 def test_apprise_template_can_be_switched_off(sent):
1168 """The configuration is then read as it was before templates.
1169
1170 Nothing is held back, nothing is read from the environment, and the
1171 markers stay exactly as they were written.
1172 """
1173 content = "template:\n - v\nurls:\n - json://user:${V}@localhost/\n"
1174 asset = AppriseAsset(allow_templates=False)
1175
1176 apobj = Apprise(asset=asset)
1177 config = AppriseConfig(asset=asset)
1178 assert config.add_config(content, format="yaml")
1179 assert apobj.add(config)
1180
1181 service = next(apobj.find())
1182 assert not isinstance(service, NotifyTemplate)
1183 assert service.password == "${V}"
1184 assert apobj.template_vars() == {}
1185
1186
1187 def test_apprise_template_disabled_ignores_environment(sent, monkeypatch):
1188 """A value in the environment must not quietly take effect."""
1189 monkeypatch.setenv("APPRISE_TEMPLATE_V", "from-env")
1190 asset = AppriseAsset(allow_templates=False)
1191
1192 apobj = Apprise(asset=asset)
1193 config = AppriseConfig(asset=asset)
1194 assert config.add_config(
1195 "template:\n - v\nurls:\n - json://user:${V}@localhost/\n",
1196 format="yaml",
1197 )
1198 assert apobj.add(config)
1199
1200 assert next(apobj.find()).password == "${V}"
1201
1202
1203 def test_apprise_template_duplicate_setting_uses_last_value():
1204 """PyYAML's normal last-value behavior applies below root sections."""
1205 services = parse(
1206 "urls:\n - json://localhost/:\n"
1207 " - method: GET\n method: POST\n"
1208 )
1209
1210 assert len(services) == 1
1211 assert services[0].method == "POST"
1212
1213
1214 def test_config_yaml_duplicate_section_uses_last_value():
1215 """Repeated root sections retain PyYAML's last-value behavior."""
1216 services = parse("urls:\n - json://first/\nurls:\n - json://second/\n")
1217
1218 assert len(services) == 1
1219 assert services[0].host == "second"
1220
1221
1222 def test_apprise_template_late_declaration_is_recognized(
1223 logging_enabled, caplog
1224 ):
1225 """A declaration may follow the service that uses it."""
1226 with caplog.at_level(logging.DEBUG):
1227 services = parse(
1228 "urls:\n - json://user:${LATE}@localhost/\ntemplate:\n - late\n"
1229 )
1230
1231 assert len(services) == 1
1232 assert isinstance(services[0], NotifyTemplate)
1233 assert "not defined" not in caplog.text
1234
1235
1236 def test_apprise_template_keeps_undeclared_marker(logging_enabled, caplog):
1237 """An undeclared marker remains literal and receives a debug hint."""
1238 with caplog.at_level(logging.DEBUG):
1239 services = parse("urls:\n - json://user:${MISSING}@localhost/\n")
1240
1241 assert services[0].password == "${MISSING}"
1242 assert "'missing' is not defined" in caplog.text
1243 assert "kept as written" in caplog.text
1244 assert not [r for r in caplog.records if r.levelno >= logging.WARNING]
1245
1246
1247 def test_apprise_template_keeps_undeclared_marker_beside_declared_one(
1248 logging_enabled, caplog
1249 ):
1250 """Declaring one marker does not activate other marker-like text."""
1251 with caplog.at_level(logging.DEBUG):
1252 services = parse(
1253 "template:\n - used\n"
1254 "urls:\n - json://user:${MISSING}@localhost/?to=${USED}\n"
1255 )
1256
1257 assert services[0].results["password"] == "${MISSING}"
1258 assert "'missing' is not defined" in caplog.text
1259
1260
1261 def test_apprise_template_reports_unused_declaration(logging_enabled, caplog):
1262 """Debug inspection warns about declarations unused by service entries."""
1263 with caplog.at_level(logging.DEBUG):
1264 services = parse(
1265 "template:\n - unused\nurls:\n - json://localhost/\n"
1266 )
1267
1268 assert len(services) == 1
1269 assert "'unused' is defined but not referenced" in caplog.text
1270 assert any(
1271 record.levelno == logging.WARNING
1272 and "'unused' is defined but not referenced" in record.message
1273 for record in caplog.records
1274 )
1275
1276
1277 def test_apprise_template_yaml_value_counts_as_reference(
1278 logging_enabled, caplog
1279 ):
1280 """A marker in a YAML option value counts as a real use."""
1281 with caplog.at_level(logging.DEBUG):
1282 services = parse(
1283 "template:\n - used\n"
1284 "urls:\n - json://localhost/:\n"
1285 " headers:\n X-Test: ${USED}\n"
1286 )
1287
1288 assert len(services) == 1
1289 assert isinstance(services[0], NotifyTemplate)
1290 assert "not referenced" not in caplog.text
1291
1292
1293 def test_apprise_template_yaml_name_is_not_a_reference(
1294 logging_enabled, caplog
1295 ):
1296 """YAML setting names stay literal and do not count as variable use."""
1297 with caplog.at_level(logging.DEBUG):
1298 services = parse(
1299 "template:\n - unused\n"
1300 "urls:\n - json://localhost/:\n"
1301 " '+${UNUSED}': literal\n"
1302 )
1303
1304 assert len(services) == 1
1305 assert "'unused' is defined but not referenced" in caplog.text
1306
1307
1308 def test_apprise_template_skips_reference_scan_without_debug(
1309 logging_enabled, caplog
1310 ):
1311 """Reference discovery adds no work when debug logging is disabled."""
1312 with (
1313 mock.patch(
1314 "apprise.config.base.template_references",
1315 side_effect=AssertionError("unexpected template scan"),
1316 ),
1317 caplog.at_level(logging.INFO),
1318 ):
1319 services = parse(
1320 "template:\n - unused\nurls:\n - json://localhost/\n"
1321 )
1322
1323 assert len(services) == 1
1324
1325
1326 def test_apprise_template_supports_shared_yaml_anchor():
1327 """A YAML anchor may reuse an entry containing a template marker."""
1328 services = parse(
1329 "template:\n - t\n"
1330 "urls:\n - &shared json://localhost/?to=${T}\n - *shared\n"
1331 )
1332
1333 # Both entries load and both still wait on the same value
1334 assert len(services) == 2
1335 assert all(isinstance(s, NotifyTemplate) for s in services)
1336
1337
1338 def test_apprise_template_disabled_marker_is_left_alone(
1339 logging_enabled, caplog
1340 ):
1341 """Disabled templates neither inspect nor change marker-like text."""
1342 asset = AppriseAsset(allow_templates=False)
1343 with caplog.at_level(logging.DEBUG):
1344 services, _ = ConfigBase.config_parse_yaml(
1345 "template:\n - unused\nurls:\n - json://user:${V}@localhost/\n",
1346 asset=asset,
1347 )
1348
1349 assert services[0].password == "${V}"
1350 assert "not defined" not in caplog.text
1351 assert "not referenced" not in caplog.text
1352
1353
1354 @pytest.mark.parametrize(
1355 ("label", "content"),
1356 [
1357 (
1358 "marker used as a query name",
1359 "template:\n - t\nurls:\n - json://localhost/?+${T}=1\n",
1360 ),
1361 (
1362 "marker used as a value",
1363 "template:\n - t\nurls:\n - json://localhost/?+X=${T}\n",
1364 ),
1365 (
1366 "marker used as a YAML setting name",
1367 "template:\n - t\n"
1368 "urls:\n - json://localhost/:\n '+${T}': 1\n",
1369 ),
1370 (
1371 "marker in the credentials",
1372 "template:\n - t\nurls:\n - json://user:${T}@localhost/\n",
1373 ),
1374 (
1375 "no template section at all",
1376 "urls:\n - json://localhost/?+X=${T}\n",
1377 ),
1378 ],
1379 )
1380 def test_apprise_template_disabled_matches_no_section(label, content):
1381 """Disabled templates leave declared markers as literal text."""
1382 asset = AppriseAsset(allow_templates=False)
1383 services, _ = ConfigBase.config_parse_yaml(content, asset=asset)
1384
1385 assert len(services) == 1
1386
1387 # A real service, never an entry waiting on a value
1388 assert not isinstance(services[0], NotifyTemplate)
1389
1390
1391 def test_apprise_template_disabled_ignores_the_environment(monkeypatch):
1392 """A disabled file never reads APPRISE_TEMPLATE_ values."""
1393 monkeypatch.setenv("APPRISE_TEMPLATE_T", "from-the-environment")
1394 content = "template:\n - t\nurls:\n - json://user:${T}@localhost/\n"
1395
1396 services, _ = ConfigBase.config_parse_yaml(
1397 content, asset=AppriseAsset(allow_templates=False)
1398 )
1399 assert services[0].password == "${T}"
1400
1401 # With the feature on, the same file uses that value
1402 assert next(load(content).find()).password == "from-the-environment"
1403
1404
1405 def test_apprise_template_disabled_ignores_repeated_sections():
1406 """A disabled template table follows PyYAML's last-value behavior."""
1407 asset = AppriseAsset(allow_templates=False)
1408 services, _ = ConfigBase.config_parse_yaml(
1409 "template:\n first: one\n first: two\n"
1410 "urls:\n - json://localhost/\n"
1411 "template:\n - second\n",
1412 asset=asset,
1413 )
1414
1415 assert len(services) == 1
1416
1417
1418 def test_apprise_template_url_handles_a_non_text_setting():
1419 """A setting that is not text has no marker to show."""
1420 entry = parse(
1421 "template:\n - t\n"
1422 "urls:\n - json://user:${T}@localhost/:\n"
1423 " - verify: no\n retry: 2\n"
1424 )[0]
1425
1426 # It renders without complaint, and the marker still shows
1427 assert "${T}" in entry.url()
1428
1429
1430 @pytest.mark.parametrize("declaration", ("", "template:\n - t\n"))
1431 def test_config_skips_non_text_sibling_before_url(declaration):
1432 """A non-text sibling cannot be mistaken for the URL key."""
1433 services = parse(
1434 declaration + "urls:\n - 1: ignored\n json://localhost/:\n"
1435 )
1436 assert len(services) == 1
1437
1438
1439 def test_apprise_template_url_shows_every_field_using_a_name():
1440 """Show a shared marker in every field that uses it.
1441
1442 A marker identifies where the caller's value goes. Leaving it out of
1443 one field would hide a setting the notification still uses.
1444 """
1445 entry = parse(
1446 "template:\n - t\n"
1447 "urls:\n - mailto://user:${T}@gmail.com:\n"
1448 " - to: ${T}\n cc: ${T}\n"
1449 )[0]
1450
1451 url = entry.url()
1452 assert "user:${T}@" in url
1453 assert "to=${T}" in url
1454 assert "cc=${T}" in url
1455
1456
1457 def test_apprise_template_url_without_a_path():
1458 """Not every URL has a path to render."""
1459 entry = parse("template:\n - t\nurls:\n - json://${T}\n")[0]
1460 assert "${T}" in entry.url()
1461
1462
1463 def test_apprise_template_invalid_declaration_refuses_file(
1464 logging_enabled, caplog
1465 ):
1466 """An unreadable template section stops the whole file."""
1467 with caplog.at_level(logging.ERROR):
1468 services = parse(
1469 "template:\n - name\n - NAME\nurls:\n - json://localhost/\n"
1470 )
1471
1472 assert services == []
1473 assert "template section" in caplog.text.lower()
1474
1475
1476 def test_apprise_template_unusable_placeholder_prefix(logging_enabled, caplog):
1477 """Giving up on a placeholder prefix stops the whole file."""
1478 taken = "0" * 16
1479 with (
1480 mock.patch(
1481 "apprise.utils.template.secrets.token_hex", return_value=taken
1482 ),
1483 caplog.at_level(logging.ERROR),
1484 ):
1485 # The prefix it keeps choosing already appears in the file
1486 services = parse(
1487 f"template:\n - v\nurls:\n - json://a{taken}/${{V}}\n"
1488 )
1489
1490 assert services == []
1491
1492
1493 def test_apprise_template_mapping_form_setting_name(logging_enabled, caplog):
1494 """A marker naming a YAML setting is left to the usual token check.
1495
1496 Apprise already refuses a setting name it does not recognise, so the
1497 marker takes the same path any other unusable name would.
1498 """
1499 with caplog.at_level(logging.WARNING):
1500 services = parse(
1501 "template:\n - t\n"
1502 "urls:\n - json://localhost/:\n - ${T}: value\n"
1503 )
1504
1505 assert len(services) == 1
1506 assert "Ignoring invalid token (${T})" in caplog.text
1507
1508 # A file that never declared the name is treated the same way
1509 with caplog.at_level(logging.WARNING):
1510 plain = parse("urls:\n - json://localhost/:\n - ${T}: value\n")
1511
1512 assert len(plain) == 1
1513 assert "Ignoring invalid token (${T})" in caplog.text
1514
1515
1516 def test_apprise_template_mapping_form_bad_position(logging_enabled, caplog):
1517 """The positional refusal also covers the mapping form."""
1518 with caplog.at_level(logging.ERROR):
1519 services = parse(
1520 "template:\n - t\n"
1521 "urls:\n - sendgrid://SG.abcdefghij:${T}/[email protected]:\n"
1522 " - tag: work\n"
1523 )
1524
1525 assert services == []
1526 assert "can not be used at this position" in caplog.text
1527
1528
1529 def test_apprise_template_vars_reports_a_disagreement(sent):
1530 """Two configurations may not agree on a default."""
1531 apobj = Apprise()
1532 for default in ("first-default", "second-default"):
1533 config = AppriseConfig()
1534 assert config.add_config(
1535 f"template:\n - shared: {default}\n"
1536 "urls:\n - json://user:${SHARED}@host/\n",
1537 format="yaml",
1538 )
1539 assert apobj.add(config)
1540
1541 # Neither default is assumed; use a call or environment value instead.
1542 assert apobj.template_vars()["shared"]["default"] is None
1543
1544
1545 def test_apprise_template_status_other_outcomes():
1546 """Only a clean run and a no-match are reworded."""
1547 from apprise.dispatch import template_status
1548
1549 for status in (
1550 AppriseResultStatus.FAILURE,
1551 AppriseResultStatus.PARTIAL,
1552 AppriseResultStatus.TIMEOUT,
1553 ):
1554 assert template_status(status, ["skipped"]) == status
1555
1556
1557 def test_apprise_asset_allow_templates_must_be_a_flag():
1558 """It is a yes or no answer, not a piece of text."""
1559 from apprise.exception import AppriseImproperlyConfigured
1560
1561 with pytest.raises(AppriseImproperlyConfigured):
1562 AppriseAsset(allow_templates="yes")
1563
1564
1565 def schema_for(*names):
1566 """A declared schema to check a URL's service choice against."""
1567 from apprise.utils.template import TemplateSchema
1568
1569 return TemplateSchema.parse(list(names))
1570
1571
1572 @pytest.mark.parametrize(
1573 "section", ["template:", "template: []", "template: {}"]
1574 )
1575 def test_apprise_template_empty_section_changes_nothing(section, sent):
1576 """A template section that declares nothing is simply empty.
1577
1578 Nothing was declared, so every marker is ordinary text and each URL
1579 loads straight away.
1580 """
1581 services = parse(f"{section}\nurls:\n - json://user:${{T}}@localhost/\n")
1582
1583 assert len(services) == 1
1584 assert not isinstance(services[0], NotifyTemplate)
1585 assert services[0].password == "${T}"
1586
1587
1588 def test_apprise_template_vars_counts_agreeing_configurations(sent):
1589 """Two configurations may declare the same variable the same way."""
1590 apobj = Apprise()
1591 for host in ("first", "second"):
1592 config = AppriseConfig()
1593 assert config.add_config(
1594 "template:\n - shared: agreed\n"
1595 f"urls:\n - json://user:${{SHARED}}@{host}/\n",
1596 format="yaml",
1597 )
1598 assert apobj.add(config)
1599
1600 report = apobj.template_vars()
1601
1602 # They agree, so the default stands and both entries are counted
1603 assert report["shared"]["default"] == "agreed"
1604 assert report["shared"]["services"] == 2
1605
1606
1607 @pytest.mark.parametrize(
1608 "url",
1609 [
1610 "mailtos://user:[email protected]/${EMAIL}",
1611 "sendgrid://SG.abcdefghij:[email protected]/${EMAIL}",
1612 ],
1613 )
1614 def test_apprise_template_email_address_value_works(url, sent):
1615 """A whole email address is a perfectly ordinary value.
1616
1617 Some services are written as ``schema://{email}/...``, where the value
1618 really is ``user@host``. Escaping must not stand in the way of that.
1619 """
1620 apobj = load(f"template:\n - email\nurls:\n - {url}\n")
1621 service = next(apobj.find(template={"email": "[email protected]"}))
1622
1623 assert "[email protected]" in [
1624 target[1] if isinstance(target, tuple) else target
1625 for target in service.targets
1626 ]
1627
1628
1629 def test_apprise_template_email_address_as_a_setting(sent):
1630 """The same address written against a setting instead."""
1631 apobj = load(
1632 "template:\n - email\n"
1633 "urls:\n - mailtos://user:[email protected]/:\n - to: ${EMAIL}\n"
1634 )
1635 service = next(apobj.find(template={"email": "[email protected]"}))
1636
1637 assert [target[1] for target in service.targets] == ["[email protected]"]
1638
1639
1640 def test_config_yaml_rejects_an_unusable_key():
1641 """Reject a YAML key that cannot be looked up."""
1642 # A list written as a key; there is nothing to index a mapping by
1643 assert ConfigBase.config_parse_yaml("? [a, b]\n: value\n") == ([], [])
1644
1645
1646 def test_config_query_tag_check_without_templates():
1647 """With nothing templated there is no query to examine."""
1648 from apprise.utils.yaml import templated_tag
1649
1650 assert templated_tag({"qsd": {}}, None) is False
1651 assert templated_tag("not a mapping", None) is False
1652
1653
1654 def test_config_query_tag_check_skips_unusable_buckets(sent):
1655 """A query bucket that is not a mapping is passed over."""
1656 from apprise.utils.template import TemplatePlaceholderMap, TemplateSchema
1657 from apprise.utils.yaml import templated_tag
1658
1659 placeholders = TemplatePlaceholderMap(TemplateSchema.parse(["t"]), "")
1660 results = {"qsd": None, "qsd+": {}, "qsd-": {}, "qsd:": {}}
1661 assert templated_tag(results, placeholders) is False
1662
1663
1664 def test_apprise_template_rejects_invalid_supplied_name(sent):
1665 """A name that is not text is refused rather than guessed at.
1666
1667 Nothing can be looked up by it, so the request is turned down
1668 instead of being filled in from a malformed mapping.
1669 """
1670 apobj = load("template:\n - t\nurls:\n - json://user:${T}@host/\n")
1671
1672 with pytest.raises(AppriseTemplateError):
1673 list(apobj.find(template={"t": "value", 7: "ignored"}))
1674
1675
1676 def run_cli(tmpdir, content, *args):
1677 """Run a dry run against a configuration written to disk."""
1678 from click.testing import CliRunner
1679
1680 from apprise import cli
1681
1682 config = tmpdir.join("apprise.yml")
1683 config.write(content)
1684 return CliRunner().invoke(
1685 cli.main, ["-b", "x", f"--config={config!s}", "--dry-run", *args]
1686 )
1687
1688
1689 def test_apprise_cli_dry_run_supplied_value(tmpdir):
1690 """A value given on the command line is filled in for the preview."""
1691 result = run_cli(
1692 tmpdir,
1693 "template:\n - t\nurls:\n - json://user:${T}@localhost/\n",
1694 "--template-var",
1695 "t=supplied",
1696 )
1697
1698 # The entry resolved, so it has a real identifier rather than a notice
1699 assert "missing value(s)" not in result.output
1700 assert "- n/a -" not in result.output
1701 assert result.exit_code == AppriseResultStatus.SUCCESS
1702
1703
1704 def test_apprise_cli_dry_run_reports_no_identifier(tmpdir):
1705 """A service that keeps no stored data has no identifier to show."""
1706 from apprise.plugins.custom_json import NotifyJSON
1707
1708 with mock.patch.object(NotifyJSON, "url_id", return_value=None):
1709 result = run_cli(tmpdir, "urls:\n - json://localhost/\n")
1710
1711 assert "- n/a -" in result.output
1712 assert result.exit_code == AppriseResultStatus.SUCCESS
1713
1714
1715 def test_apprise_cli_dry_run_partial(tmpdir):
1716 """Some entries are ready and some are still waiting on a value."""
1717 result = run_cli(
1718 tmpdir,
1719 "template:\n - t\n"
1720 "urls:\n - json://user:${T}@localhost/\n - json://ready/\n",
1721 )
1722
1723 assert "could not be resolved" in result.output
1724 assert "1 of 2" in result.output
1725
1726 # The same outcome a real run would report
1727 assert result.exit_code == AppriseResultStatus.PARTIAL
1728
1729
1730 def test_apprise_cli_dry_run_failure(tmpdir):
1731 """Every entry is waiting on a value, so nothing would be sent."""
1732 result = run_cli(
1733 tmpdir, "template:\n - t\nurls:\n - json://user:${T}@localhost/\n"
1734 )
1735
1736 assert result.exit_code == AppriseResultStatus.FAILURE
1737
1738
1739 def test_config_yaml_loader_failure_is_reported():
1740 """A YAML loader failure returns an empty configuration."""
1741 with mock.patch(
1742 "apprise.config.base.yaml.load",
1743 side_effect=AttributeError("no loader"),
1744 ):
1745 assert ConfigBase.config_parse_yaml("urls:\n - json://a/\n") == (
1746 [],
1747 [],
1748 )
1749
1750
1751 def test_apprise_cli_details_lists_required_packages():
1752 """A service that is switched off explains what it needs."""
1753 from click.testing import CliRunner
1754
1755 from apprise import cli
1756
1757 entry = {
1758 "service_name": "Example",
1759 "service_url": "https://example.ca",
1760 "setup_url": None,
1761 "enabled": False,
1762 "details": {"templates": ("{schema}://example",)},
1763 "category": "native",
1764 "attachment_support": False,
1765 "protocols": ("example",),
1766 "secure_protocols": None,
1767 "requirements": {
1768 "details": "Needs an extra package",
1769 "packages_required": ["examplelib"],
1770 "packages_recommended": [],
1771 },
1772 }
1773
1774 with mock.patch(
1775 "apprise.Apprise.details",
1776 return_value={"version": "1.0", "asset": {}, "schemas": [entry]},
1777 ):
1778 result = CliRunner().invoke(cli.main, ["--details"])
1779
1780 assert "Python Packages Required" in result.output
1781 assert "examplelib" in result.output
1782
1783
1784 @pytest.mark.parametrize("supplied", ["a=b", ["a"], 7, ("a", "b")])
1785 def test_apprise_template_rejects_a_non_mapping(supplied):
1786 """Values must arrive as name/value pairs."""
1787 apobj = load("template:\n - t\nurls:\n - json://user:${T}@host/\n")
1788
1789 with pytest.raises(AppriseTemplateError):
1790 list(apobj.find(template=supplied))
1791
1792
1793 def test_apprise_notify_failure_for_non_mapping():
1794 """A bad value table fails the call instead of raising."""
1795 apobj = load("template:\n - t\nurls:\n - json://user:${T}@host/\n")
1796
1797 result = apobj.notify(body="x", template="a=b")
1798 assert not result
1799 assert result.status == AppriseResultStatus.FAILURE
1800
1801
1802 def test_apprise_template_rejects_a_repeated_name():
1803 """Two spellings of one name leave no way to tell which was meant."""
1804 apobj = load("template:\n - t\nurls:\n - json://user:${T}@host/\n")
1805
1806 with pytest.raises(AppriseTemplateError):
1807 list(apobj.find(template={"t": "one", "T": "two"}))
1808
1809
1810 def test_apprise_template_name_not_captured(logging_enabled, caplog):
1811 """An unusable name is turned down before anything is written out."""
1812 apobj = load("template:\n - t\nurls:\n - json://user:${T}@host/\n")
1813
1814 with caplog.at_level(logging.DEBUG), pytest.raises(AppriseTemplateError):
1815 list(apobj.find(template={"t": "value", "unused\nwrite": "x"}))
1816
1817 assert "\nwrite" not in caplog.text
1818
1819
1820 def test_apprise_template_empty_environment_value(monkeypatch, sent):
1821 """An empty environment value never replaces a real one.
1822
1823 Whitespace is not a value, and a default written in the configuration
1824 outranks the environment in any case.
1825 """
1826 monkeypatch.setenv("APPRISE_TEMPLATE_T", " ")
1827 apobj = load(
1828 "template:\n t: fallback\nurls:\n - json://user:${T}@localhost/\n"
1829 )
1830
1831 service = next(apobj.find())
1832 assert service.password == "fallback"
1833
1834
1835 @pytest.mark.parametrize("entry", ["bad name=x", "=x", "a\nb=x", "a-b=x"])
1836 def test_apprise_template_cli_unusable_name(tmpdir, entry):
1837 """A --template-var name has to look like a variable name."""
1838 from click.testing import CliRunner
1839
1840 from apprise import cli
1841
1842 config = tmpdir.join("apprise.yml")
1843 config.write("urls:\n - json://localhost\n")
1844
1845 result = CliRunner().invoke(
1846 cli.main, ["-b", "x", f"--config={config!s}", "-tv", entry]
1847 )
1848 assert result.exit_code == 2
1849 assert "NAME=VALUE" in result.output
1850
1851
1852 def test_apprise_template_cli_repeated_name(tmpdir):
1853 """The same name twice leaves no way to tell which value was meant."""
1854 from click.testing import CliRunner
1855
1856 from apprise import cli
1857
1858 config = tmpdir.join("apprise.yml")
1859 config.write("template:\n - t\nurls:\n - json://user:${T}@localhost/\n")
1860
1861 result = CliRunner().invoke(
1862 cli.main,
1863 ["-b", "x", f"--config={config!s}", "-tv", "t=one", "-tv", "T=two"],
1864 )
1865 assert result.exit_code == 2
1866 assert "more than once" in result.output
1867
1868
1869 def test_apprise_template_reads_a_configuration_once():
1870 """One find() visits each configuration source a single time."""
1871 apobj = Apprise()
1872 config = AppriseConfig(cache=False)
1873 assert config.add_config(
1874 "template:\n - t\nurls:\n - json://localhost/?to=${T}\n",
1875 format="yaml",
1876 )
1877 assert apobj.add(config)
1878
1879 source = config[0]
1880 reads = []
1881 original = source.read
1882
1883 def counted(*args, **kwargs):
1884 reads.append(1)
1885 return original(*args, **kwargs)
1886
1887 source.read = counted
1888 assert len(list(apobj.find(template={"t": "x"}))) == 1
1889 assert len(reads) == 1
1890
1891
1892 @pytest.mark.parametrize(
1893 "supplied",
1894 [
1895 MappingProxyType({"t": "value"}),
1896 UserDict({"t": "value"}),
1897 ],
1898 )
1899 def test_apprise_template_accepts_any_mapping(supplied, sent):
1900 """Any mapping is usable, not only a plain dictionary."""
1901 apobj = load("template:\n - t\nurls:\n - json://localhost/?to=${T}\n")
1902
1903 service = next(apobj.find(template=supplied))
1904 assert service is not None
1905
1906
1907 def test_apprise_template_cli_error_hides_value(tmpdir):
1908 """A refused entry must not echo whatever followed the equals sign."""
1909 from click.testing import CliRunner
1910
1911 from apprise import cli
1912
1913 config = tmpdir.join("apprise.yml")
1914 config.write("urls:\n - json://localhost\n")
1915
1916 result = CliRunner().invoke(
1917 cli.main,
1918 ["-b", "x", f"--config={config!s}", "-tv", "bad name=super-secret"],
1919 )
1920 assert result.exit_code == 2
1921 assert "super-secret" not in result.output
1922 assert "bad name" in result.output
1923
1924
1925 def test_apprise_template_url_shows_a_list_setting():
1926 """Keep markers in list settings, such as email recipients.
1927
1928 Email recipients are stored as a list. A listing that only checks text
1929 fields would silently lose their markers.
1930 """
1931 entry = parse(
1932 "template:\n - t\n"
1933 "urls:\n - mailto://user:[email protected]:\n to: ${T}\n"
1934 )[0]
1935
1936 assert "to=${T}" in entry.url()
1937
1938
1939 def test_apprise_template_url_lists_all_members():
1940 """A list mixing a marker with fixed members keeps them all."""
1941 entry = parse(
1942 "template:\n - t\n"
1943 "urls:\n - mailto://user:[email protected]:\n"
1944 " to:\n - ${T}\n - [email protected]\n"
1945 )[0]
1946
1947 # Members come back the way a URL supplies a list: comma separated
1948 url = entry.url()
1949 assert "${T}" in url
1950 assert "fixed%40example.com" in url
1951
1952
1953 def test_apprise_template_url_uses_the_argument_a_url_accepts():
1954 """Show YAML ``smtp:`` as the URL argument ``smtp=``.
1955
1956 The YAML value is stored as ``smtp_host`` inside the service, but a URL
1957 must use ``smtp=`` to set that same field when read back.
1958 """
1959 entry = parse(
1960 "template:\n - t\n"
1961 "urls:\n - mailto://user:[email protected]:\n smtp: ${T}\n"
1962 )[0]
1963
1964 url = entry.url()
1965 assert "smtp=${T}" in url
1966 assert "smtp_host" not in url
1967
1968 service = Apprise.instantiate(url.replace("${T}", "mail.example.com"))
1969 assert service.smtp_host == "mail.example.com"
1970
1971
1972 def test_apprise_template_url_shows_a_grouped_setting():
1973 """A header waiting on a value is shown with its URL prefix."""
1974 entry = parse(
1975 "template:\n - t\n"
1976 "urls:\n - json://localhost:\n '+X-Token': ${T}\n"
1977 )[0]
1978
1979 url = entry.url()
1980 assert "${T}" in url
1981
1982 service = Apprise.instantiate(url.replace("${T}", "abc123"))
1983 assert service.headers == {"X-Token": "abc123"}
1984
1985
1986 def test_apprise_template_url_skips_non_string_group_key():
1987 """Skip grouped settings whose YAML keys are not strings.
1988
1989 YAML parses a bare ``1:`` as a number, which cannot name a URL header.
1990 """
1991 entry = parse(
1992 "template:\n - t\n"
1993 "urls:\n - json://localhost:\n"
1994 " headers:\n 1: fixed\n X-Token: ${T}\n"
1995 )[0]
1996
1997 url = entry.url()
1998 assert "X-Token=${T}" in url
1999 assert "fixed" not in url
2000
2001
2002 def test_apprise_template_url_deduplicates_header():
2003 """A header written in the URL is listed once, not twice."""
2004 entry = parse(
2005 "template:\n - t\nurls:\n - json://localhost/?+X-Token=${T}\n"
2006 )[0]
2007
2008 assert entry.url().lower().count("x-token") == 1
2009
2010
2011 def test_apprise_template_url_shows_a_port_waiting_on_a_value():
2012 """A port setting shows its marker, not the internal stand-in."""
2013 entry = parse(
2014 "template:\n - t\n"
2015 "urls:\n - mailto://user:[email protected]:\n port: ${T}\n"
2016 )[0]
2017
2018 for url in (entry.url(), entry.url(privacy=True)):
2019 assert ":${T}" in url
2020 assert entry.placeholders.pattern.search(url) is None
2021
2022
2023 def test_apprise_template_url_never_escapes_a_marker():
2024 """Markers stay literal so they can be found and replaced.
2025
2026 A marker is not a value yet, so escaping it would leave a caller with
2027 nothing to search for.
2028 """
2029 entry = parse(
2030 "template:\n - t\n"
2031 "urls:\n - mailto://user:${T}@${T}.example/:\n"
2032 " to: ${T}\n smtp: ${T}\n"
2033 )[0]
2034
2035 for url in (entry.url(), entry.url(privacy=True)):
2036 assert "%24%7B" not in url
2037 assert url.count("${T}") == 4
2038
2039
2040 def test_apprise_template_url_masks_around_a_marker_only():
2041 """Privacy hides stored text but never the marker itself."""
2042 entry = parse(
2043 "template:\n - t\n"
2044 "urls:\n - mailto://user:[email protected]:\n"
2045 " smtp: secretserver.${T}\n"
2046 )[0]
2047
2048 shown = entry.url(privacy=True)
2049 assert "${T}" in shown
2050 assert "secretserver" not in shown
2051
2052
2053 def test_apprise_template_url_rejects_unparsed_marker(logging_enabled, caplog):
2054 """Reject a URL when a port marker disappears during parsing.
2055
2056 A port is parsed as a number, so a marker there may vanish along with
2057 part of the hostname. Do not load the resulting broken entry.
2058 """
2059 entries = (
2060 # Written on its own
2061 "urls:\n - mailto://user:[email protected]:${T}\n",
2062 # Written with settings underneath it
2063 "urls:\n - mailto://user:[email protected]:${T}:\n"
2064 " to: [email protected]\n",
2065 )
2066
2067 for entry in entries:
2068 caplog.clear()
2069 with caplog.at_level(logging.ERROR):
2070 services = parse("template:\n - t\n" + entry)
2071
2072 assert services == []
2073 assert "can not be used at this position" in caplog.text
2074
2075
2076 def test_apprise_template_url_omits_a_setting_no_url_can_set():
2077 """Do not show ``to=`` for ``json://``, which has no such option.
2078
2079 A setting the service cannot use changes nothing when sending. Adding
2080 it to the listed URL would suggest the value goes somewhere it does not.
2081 """
2082 entry = parse(
2083 "template:\n - t\n"
2084 "urls:\n - json://user:pass@localhost/:\n to: ${T}\n"
2085 )[0]
2086
2087 url = entry.url()
2088 assert "to=" not in url
2089
2090 # The same setting on a service that does have it is still shown
2091 entry = parse(
2092 "template:\n - t\n"
2093 "urls:\n - mailto://user:[email protected]:\n to: ${T}\n"
2094 )[0]
2095 assert "to=${T}" in entry.url()
2096
2097
2098 def test_apprise_template_url_grouped_setting_replaces_the_group():
2099 """A header written under the URL replaces the URL's whole group.
2100
2101 Apprise treats a group such as headers as one setting, so writing any
2102 of them under the URL drops the ones the URL carried.
2103 """
2104 entry = parse(
2105 "template:\n - t\n"
2106 "urls:\n - json://localhost/?+X-Token=unused:\n"
2107 " '+Other': ${T}\n"
2108 )[0]
2109
2110 url = entry.url()
2111 assert "${T}" in url
2112 assert "unused" not in url
2113
2114
2115 @pytest.mark.parametrize(
2116 ("placement", "entry"),
2117 [
2118 ("host", "json://${V}/"),
2119 ("part of a host", "json://api.${V}.net/"),
2120 ("user", "json://${V}:pass@localhost/"),
2121 ("password", "json://user:${V}@localhost/"),
2122 ("path", "json://localhost/${V}/end"),
2123 ("query value", "json://localhost/?:custom=${V}"),
2124 ("header", "json://localhost/?+X-Tok=${V}"),
2125 ("setting", "mailto://u:[email protected]:\n smtp: ${V}\n"),
2126 ("port", "mailto://u:[email protected]:\n port: ${V}\n"),
2127 (
2128 "list setting",
2129 "mailto://u:[email protected]:\n to:\n"
2130 " - ${V}\n - [email protected]\n",
2131 ),
2132 (
2133 "beside other text",
2134 "mailto://u:[email protected]:\n smtp: a-${V}-b\n",
2135 ),
2136 ],
2137 )
2138 def test_apprise_template_marker_is_never_escaped(placement, entry):
2139 """A marker reads back as written wherever it was put.
2140
2141 Escaping is right for everything else a URL carries, but a marker is
2142 not a value yet. It has to stay something a reader can spot and a
2143 caller can search for and replace, in both privacy modes.
2144 """
2145 suffix = "" if entry.endswith("\n") else "\n"
2146 services = parse("template:\n - v\nurls:\n - " + entry + suffix)
2147 entry_obj = services[0]
2148
2149 for url in (entry_obj.url(), entry_obj.url(privacy=True)):
2150 assert "${V}" in url
2151 assert "%24%7B" not in url
2152
2153
2154 def test_apprise_template_undeclared_marker_stays_readable():
2155 """A name left out of the template section is still shown as written.
2156
2157 It is not a variable and no value is ever filled into it, but leaving
2158 it readable is what shows the author why the entry never asks for it.
2159 """
2160 entry = parse(
2161 "template:\n - v\n"
2162 "urls:\n - json://localhost/?a=${undeclared}&b=${V}\n"
2163 )[0]
2164
2165 url = entry.url()
2166 assert "b=${V}" in url
2167 assert "a=${undeclared}" in url
2168
2169 # ...but only the declared name is something to supply a value for
2170 assert entry.template_names == ("v",)
2171
2172
2173 def test_apprise_template_url_uses_written_name():
2174 """A setting keeps the name it was written under, not an alias.
2175
2176 mailto's ``from`` and ``name`` both end up in ``from_addr``, yet they
2177 mean different things, so the listing must not rename one to the other.
2178 """
2179 entry = parse(
2180 "template:\n - t\n"
2181 "urls:\n - mailtos://u:[email protected]:\n name: ${T}\n"
2182 )[0]
2183
2184 url = entry.url()
2185 assert "name=${T}" in url
2186 assert "from=" not in url
2187
2188
2189 def test_apprise_template_url_setting_precedence():
2190 """A YAML setting replaces a URL alias for the same field.
2191
2192 Here, ``name:`` and ``from=`` both fill ``from_addr``. Listing only the
2193 YAML setting ensures the displayed URL behaves like the configuration.
2194 """
2195 entry = parse(
2196 "template:\n - t\n"
2197 "urls:\n - mailtos://u:[email protected][email protected]:\n"
2198 " name: ${T}\n"
2199 )[0]
2200
2201 url = entry.url()
2202 assert "name=${T}" in url
2203 assert "someone%40example.com" not in url
2204
2205
2206 def test_apprise_template_url_last_written_setting_wins():
2207 """When two names fill one field, the later one is the one listed."""
2208 entry = parse(
2209 "template:\n - t\n"
2210 "urls:\n - mailtos://u:[email protected]:\n"
2211 " from: [email protected]\n name: ${T}\n"
2212 )[0]
2213
2214 url = entry.url()
2215 assert "name=${T}" in url
2216 assert "real%40example.com" not in url
2217
2218
2219 def test_apprise_template_url_round_trip():
2220 """A listed URL resolves to what the saved configuration resolves to.
2221
2222 Settings that hold no marker are listed too, so nothing the entry needs
2223 is lost when the URL is filled in and loaded on its own.
2224 """
2225 config = (
2226 "template:\n - t\n"
2227 "urls:\n - mailtos://u:[email protected]:\n"
2228 " to: [email protected]\n name: ${T}\n"
2229 )
2230
2231 entry = parse(config)[0]
2232 url = entry.url().replace("${T}", "Bob")
2233
2234 # The recipient is carried over rather than dropped
2235 assert "to=rcpt%40example.com" in url
2236
2237 apobj = load(config)
2238 saved = next(apobj.find(template={"t": "Bob"}))
2239
2240 reloaded = Apprise()
2241 assert reloaded.add(url)
2242 listed = next(reloaded.find())
2243
2244 assert listed.from_addr == saved.from_addr
2245 assert listed.targets == saved.targets
2246
2247
2248 def test_apprise_template_flatten_reads_nested_lists():
2249 """A list wrapped in more lists is read as one list of text."""
2250 from apprise.template import _flatten
2251
2252 assert _flatten(["a", ["b", ("c",)]]) == ["a", "b", "c"]
2253
2254 # A set is ordered only once every member is known to be text
2255 assert _flatten({"b", "a"}) == ["a", "b"]
2256
2257
2258 def test_apprise_template_flatten_rejects_non_text():
2259 """Anything that is not text makes the whole setting unusable."""
2260 from apprise.template import _flatten
2261
2262 # A number cannot hold a marker
2263 assert _flatten(["a", 5]) is None
2264
2265 # ...and neither can one nested inside another list
2266 assert _flatten(["a", ["b", 5]]) is None
2267
2268 # A set mixing text and numbers cannot even be ordered
2269 assert _flatten({"${T}", 5}) is None
2270
2271
2272 def test_apprise_template_flatten_stops_at_the_nesting_limit():
2273 """A list that contains itself is abandoned rather than followed."""
2274 from apprise.template import _flatten
2275
2276 loop = ["a"]
2277 loop.append(loop)
2278 assert _flatten(loop) is None
2279
2280
2281 def test_apprise_template_url_omits_empty_setting():
2282 """An empty list, or a value no URL can carry, is left out."""
2283 entry = parse(
2284 "template:\n - t\n"
2285 "urls:\n - mailtos://u:[email protected]:\n"
2286 " to: []\n cc: null\n name: ${T}\n"
2287 )[0]
2288
2289 url = entry.url()
2290 assert "name=${T}" in url
2291 assert "to=" not in url
2292 assert "cc=" not in url
2293
2294
2295 def test_apprise_template_url_args_without_a_usable_plugin():
2296 """A service we cannot describe simply gets no translation."""
2297 from apprise.template import _url_args
2298
2299 # Nothing to describe at all
2300 assert _url_args(None) == {}
2301
2302 # ...and a plugin whose details cannot be read is treated the same way
2303 class Broken:
2304 """Stands in for a service that cannot be described."""
2305
2306 with mock.patch("apprise.plugins.details", side_effect=ValueError("nope")):
2307 assert _url_args(Broken) == {}
2308
2309
2310 def test_apprise_template_settable_needs_a_known_service():
2311 """A schema with no plugin behind it can carry no settings."""
2312 entry = parse(
2313 "template:\n - t\n"
2314 "urls:\n - mailtos://u:[email protected]:\n name: ${T}\n"
2315 )[0]
2316
2317 # Point the entry at a schema no plugin provides
2318 entry.results["schema"] = "not-a-real-schema"
2319 assert entry._settable("name") is False