Debian Codegraph @

tests/test_plugin_workflows.py

raw
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28 from inspect import cleandoc
29 import json
30
31 # Disable logging for a cleaner testing output
32 import logging
33 import sys
34 from unittest import mock
35
36 from helpers import AppriseURLTester
37 import pytest
38 import requests
39
40 from apprise import Apprise, AppriseConfig, NotifyFormat, NotifyType
41 from apprise.exception import AppriseImproperlyConfigured
42 from apprise.plugins.workflows import NotifyWorkflows
43
44 logging.disable(logging.CRITICAL)
45
46 # Our Testing URLs
47 apprise_url_tests = (
48 ##################################
49 # NotifyWorkflows
50 ##################################
51 (
52 "workflow://",
53 {
54 # invalid host details (parsing fails very early)
55 "instance": None,
56 },
57 ),
58 (
59 "workflow://:@/",
60 {
61 # invalid host details (parsing fails very early)
62 "instance": None,
63 },
64 ),
65 (
66 "workflow://host/workflow",
67 {
68 # workflow provided only, no signature
69 "instance": AppriseImproperlyConfigured,
70 },
71 ),
72 (
73 "workflow://host:443/^(/signature",
74 {
75 # invalid workflow provided
76 "instance": AppriseImproperlyConfigured,
77 },
78 ),
79 (
80 "workflow://host:443/workflow1a/signature/?image=no",
81 {
82 # All tokens provided - we're good
83 # Tests case without image defined
84 "instance": NotifyWorkflows,
85 },
86 ),
87 (
88 "workflows://host:443/workflow1b/signature/",
89 {
90 # support workflows (s added to end)
91 "instance": NotifyWorkflows,
92 },
93 ),
94 (
95 "workflows://host:443/signature/?id=workflow1c",
96 {
97 # id= to store workflow id
98 "instance": NotifyWorkflows,
99 },
100 ),
101 (
102 "workflows://host:443/signature/?workflow=workflow1d&wrap=yes",
103 {
104 # workflow= to store workflow id
105 "instance": NotifyWorkflows,
106 },
107 ),
108 (
109 "workflows://host:443/signature/?workflow=workflow1d&wrap=no",
110 {
111 # workflow= to store workflow id
112 "instance": NotifyWorkflows,
113 },
114 ),
115 (
116 "workflows://host:443/workflow1e/signature/?api-version=2024-01-01",
117 {
118 # support api-version which is extracted from webhook
119 "instance": NotifyWorkflows,
120 # Our expected url(privacy=True) startswith() response
121 "privacy_url": "workflow://host:443/w...e/s...e/",
122 },
123 ),
124 (
125 "workflows://host:443/workflow1b/signature/?ver=2016-06-01",
126 {
127 # Support ver= (api-version alias)
128 "instance": NotifyWorkflows,
129 },
130 ),
131 (
132 "workflows://host:443/?id=workflow1b&signature=signature",
133 {
134 # Support signature= (sig= alias)
135 "instance": NotifyWorkflows,
136 # Our expected url(privacy=True) startswith() response
137 "privacy_url": "workflow://host:443/w...b/s...e/",
138 },
139 ),
140 (
141 "workflows://host:443/workflow1e/signature/?powerautomate=yes",
142 {
143 # support power_automate flag
144 "instance": NotifyWorkflows,
145 },
146 ),
147 (
148 "workflows://host:443/workflow1e/signature/?pa=yes&ver=1995-01-01",
149 {
150 # support power_automate flag with ver flag
151 "instance": NotifyWorkflows,
152 },
153 ),
154 (
155 "workflows://host:443/workflow1e/signature/?pa=yes",
156 {
157 # support power_automate flag
158 "instance": NotifyWorkflows,
159 },
160 ),
161 # Support native URLs
162 (
163 (
164 "https://server.azure.com:443/workflows/643e69f83c8944/"
165 "triggers/manual/paths/invoke?"
166 "api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&"
167 "sv=1.0&sig=KODuebWbDGYFr0z0eu"
168 ),
169 {
170 # All tokens provided - we're good
171 "instance": NotifyWorkflows,
172 # Our expected url(privacy=True) startswith() response
173 "privacy_url": "workflow://server.azure.com:443/6...4/K...u/",
174 },
175 ),
176 (
177 (
178 "https://server.azure.com:443/"
179 "powerautomate/automations/direct/"
180 "workflows/643e69f83c8944/"
181 "triggers/manual/paths/invoke?"
182 "api-version=2022-03-01-preview&sp=%2Ftriggers%2Fmanual%2Frun&"
183 "sv=1.0&sig=KODuebWbDGYFr0z0eu"
184 ),
185 {
186 # Power-Automate alternative URL - All tokens provided - we're good
187 "instance": NotifyWorkflows,
188 },
189 ),
190 (
191 "workflow://host:443/workflow2/signature/",
192 {
193 "instance": NotifyWorkflows,
194 # force a failure
195 "response": False,
196 "requests_response_code": requests.codes.internal_server_error,
197 },
198 ),
199 (
200 "workflow://host:443/workflow3/signature/",
201 {
202 "instance": NotifyWorkflows,
203 # throw a bizarre code forcing us to fail to look it up
204 "response": False,
205 "requests_response_code": 999,
206 },
207 ),
208 (
209 "workflow://host:443/workflow4/signature/",
210 {
211 "instance": NotifyWorkflows,
212 # Throws a series of i/o exceptions with this flag
213 # is set and tests that we gracefully handle them
214 "test_requests_exceptions": True,
215 },
216 ),
217 )
218
219
220 def test_plugin_workflows_urls():
221 """NotifyWorkflows() Apprise URLs."""
222
223 # Run our general tests
224 AppriseURLTester(tests=apprise_url_tests).run_all()
225
226
227 @pytest.fixture
228 def workflows_url():
229 return "workflow://host:443/workflow/signature"
230
231
232 @pytest.fixture
233 def request_mock(mocker):
234 """Prepare requests mock."""
235 mock_post = mocker.patch("requests.post")
236 mock_post.return_value = requests.Request()
237 mock_post.return_value.status_code = requests.codes.ok
238 return mock_post
239
240
241 @pytest.fixture
242 def simple_template(tmpdir):
243 template = tmpdir.join("simple.json")
244 template.write(
245 cleandoc("""
246 {
247 "type": "message",
248 "attachments": [{
249 "contentType": "application/vnd.microsoft.card.adaptive",
250 "contentUrl": null,
251 "content": {
252 "$schema":
253 "http://adaptivecards.io/schemas/adaptive-card.json",
254 "type": "AdaptiveCard",
255 "version": "1.4",
256 "msteams": { "width": "full" },
257 "body": [
258 {
259 "type": "TextBlock",
260 "text": "**Test**",
261 "style": "heading"
262 }
263 ]
264 }
265 }]
266 }
267 """)
268 )
269 return template
270
271
272 def test_plugin_workflows_simple_test(
273 request_mock,
274 workflows_url,
275 ):
276 """
277 NotifyWorkflows() simple testing
278 """
279 # Instantiate our URL
280 obj = Apprise.instantiate(workflows_url)
281 assert isinstance(obj, NotifyWorkflows)
282 assert (
283 bool(
284 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
285 )
286 is True
287 )
288
289 assert request_mock.called is True
290 assert request_mock.call_args_list[0][0][0].startswith(
291 "https://host:443/workflows/workflow/triggers/manual/paths/invoke"
292 )
293 payload = json.loads(request_mock.call_args_list[0][1]["data"])
294 assert "NotifyType." not in request_mock.call_args_list[0][1]["data"]
295 assert payload == {
296 "type": "message",
297 "attachments": [
298 {
299 "contentType": "application/vnd.microsoft.card.adaptive",
300 "contentUrl": None,
301 "content": {
302 "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
303 "type": "AdaptiveCard",
304 "version": "1.4",
305 "body": [
306 {
307 "type": "Image",
308 "url": "https://github.com/caronc/apprise/raw/"
309 "master/apprise/assets/themes/default/"
310 "apprise-info-32x32.png",
311 "height": "32px",
312 "altText": NotifyType.INFO.value,
313 },
314 {
315 "type": "TextBlock",
316 # Verify our Title is set
317 "text": "title",
318 "style": "heading",
319 "weight": "Bolder",
320 "size": "Large",
321 "id": "title",
322 },
323 {
324 "type": "TextBlock",
325 # Verify our Body is set
326 "text": "body",
327 "style": "default",
328 "wrap": True,
329 "id": "body",
330 },
331 ],
332 "msteams": {"width": "full"},
333 },
334 },
335 ],
336 }
337
338 request_mock.reset_mock()
339
340 # Instantiate our URL
341 obj = Apprise.instantiate(f"{workflows_url}?pa=yes")
342 assert isinstance(obj, NotifyWorkflows)
343 assert (
344 bool(
345 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
346 )
347 is True
348 )
349
350 assert request_mock.called is True
351 assert request_mock.call_args_list[0][0][0].startswith(
352 "https://host:443/powerautomate/automations/direct/"
353 "workflows/workflow/triggers/manual/paths/invoke"
354 )
355 payload = json.loads(request_mock.call_args_list[0][1]["data"])
356 assert "NotifyType." not in request_mock.call_args_list[0][1]["data"]
357
358 assert payload == {
359 "type": "message",
360 "attachments": [
361 {
362 "contentType": "application/vnd.microsoft.card.adaptive",
363 "contentUrl": None,
364 "content": {
365 "$schema": "http://adaptivecards.io/schemas/"
366 "adaptive-card.json",
367 "type": "AdaptiveCard",
368 "version": "1.4",
369 "body": [
370 {
371 "type": "Image",
372 "url": "https://github.com/caronc/apprise/raw/"
373 "master/apprise/assets/themes/default/"
374 "apprise-info-32x32.png",
375 "height": "32px",
376 "altText": "info",
377 },
378 {
379 "type": "TextBlock",
380 # Verify our Title is set
381 "text": "title",
382 "style": "heading",
383 "weight": "Bolder",
384 "size": "Large",
385 "id": "title",
386 },
387 {
388 "type": "TextBlock",
389 # Verify our Body is set
390 "text": "body",
391 "style": "default",
392 "wrap": True,
393 "id": "body",
394 },
395 ],
396 "msteams": {
397 "width": "full",
398 },
399 },
400 },
401 ],
402 }
403
404
405 def test_plugin_workflows_templating_basic_success(
406 request_mock, workflows_url, tmpdir
407 ):
408 """
409 NotifyWorkflows() Templating - success.
410 Test cases where URL and JSON is valid.
411 """
412
413 template = tmpdir.join("simple.json")
414 template.write(
415 cleandoc("""
416 {
417 "type": "message",
418 "attachments": [{
419 "contentType": "application/vnd.microsoft.card.adaptive",
420 "contentUrl": null,
421 "content": {
422 "$schema":
423 "http://adaptivecards.io/schemas/adaptive-card.json",
424 "type": "AdaptiveCard",
425 "version": "1.4",
426 "body": [
427 {"type": "TextBlock", "id": "app_id", "text": "{{app_id}}"},
428 {"type": "TextBlock", "id": "color", "text": "{{app_color}}"},
429 {"type": "TextBlock", "id": "title", "text": "{{app_title}}"},
430 {"type": "TextBlock", "id": "body", "text": "{{app_body}}"}
431 ]
432 }
433 }]
434 }
435 """)
436 )
437
438 # Instantiate our URL
439 obj = Apprise.instantiate(
440 "{url}/?template={template}&{kwargs}".format(
441 url=workflows_url,
442 template=str(template),
443 kwargs=":key1=token&:key2=token",
444 )
445 )
446
447 assert isinstance(obj, NotifyWorkflows)
448 assert (
449 bool(
450 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
451 )
452 is True
453 )
454
455 assert request_mock.called is True
456 assert request_mock.call_args_list[0][0][0].startswith(
457 "https://host:443/workflows/workflow/triggers/manual/paths/invoke"
458 )
459
460 # Our Posted JSON Object
461 posted_json = json.loads(request_mock.call_args_list[0][1]["data"])
462 assert "NotifyType." not in request_mock.call_args_list[0][1]["data"]
463 # Verify the Adaptive Card envelope
464 assert posted_json["type"] == "message"
465 content = posted_json["attachments"][0]["content"]
466 # Index body blocks by their id for easy lookup
467 blocks = {b["id"]: b["text"] for b in content["body"] if "id" in b}
468 assert blocks["app_id"] == "Apprise"
469 assert blocks["color"] == "#3AA3E3"
470 assert blocks["title"] == "title"
471 assert blocks["body"] == "body"
472
473
474 def test_plugin_workflows_templating_invalid_json(
475 request_mock, workflows_url, tmpdir
476 ):
477 """
478 NotifyWorkflows() Templating - invalid JSON.
479 """
480
481 template = tmpdir.join("invalid.json")
482 template.write("}")
483
484 # Instantiate our URL
485 obj = Apprise.instantiate(
486 "{url}/?template={template}&{kwargs}".format(
487 url=workflows_url,
488 template=str(template),
489 kwargs=":key1=token&:key2=token",
490 )
491 )
492
493 assert isinstance(obj, NotifyWorkflows)
494 # We will fail to preform our notifcation because the JSON is bad
495 assert (
496 bool(
497 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
498 )
499 is False
500 )
501
502
503 def test_plugin_workflows_templating_load_json_failure(
504 request_mock, workflows_url, tmpdir
505 ):
506 """
507 NotifyWorkflows() Templating - template loading failure.
508 Test a case where we can not access the file.
509 """
510
511 template = tmpdir.join("empty.json")
512 template.write("")
513
514 obj = Apprise.instantiate(f"{workflows_url}/?template={template!s}")
515
516 with mock.patch("json.loads", side_effect=OSError):
517 # we fail, but this time it's because we couldn't
518 # access the cached file contents for reading
519 assert (
520 bool(
521 obj.notify(
522 body="body", title="title", notify_type=NotifyType.INFO
523 )
524 )
525 is False
526 )
527
528
529 def test_plugin_workflows_templating_target_success(
530 request_mock, workflows_url, tmpdir
531 ):
532 """
533 NotifyWorkflows() Templating - success with target.
534 A more complicated example; uses a custom token.
535 """
536
537 template = tmpdir.join("more_complicated_example.json")
538 template.write(
539 cleandoc("""
540 {
541 "type": "message",
542 "attachments": [{
543 "contentType": "application/vnd.microsoft.card.adaptive",
544 "contentUrl": null,
545 "content": {
546 "$schema":
547 "http://adaptivecards.io/schemas/adaptive-card.json",
548 "type": "AdaptiveCard",
549 "version": "1.4",
550 "body": [
551 {"type": "TextBlock", "id": "desc", "text": "{{app_desc}}"},
552 {"type": "TextBlock", "id": "color", "text": "{{app_color}}"},
553 {"type": "TextBlock", "id": "title", "text": "{{app_title}}"},
554 {"type": "TextBlock", "id": "body", "text": "{{app_body}}"}
555 ],
556 "actions": [
557 {
558 "type": "Action.OpenUrl",
559 "title": "Open",
560 "url": "{{ target }}"
561 }
562 ]
563 }
564 }]
565 }
566 """)
567 )
568
569 # Instantiate our URL
570 obj = Apprise.instantiate(
571 "{url}/?template={template}&{kwargs}".format(
572 url=workflows_url,
573 template=str(template),
574 kwargs=":key1=token&:key2=token&:target=http://localhost",
575 )
576 )
577
578 assert isinstance(obj, NotifyWorkflows)
579 assert (
580 bool(
581 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
582 )
583 is True
584 )
585
586 assert request_mock.called is True
587 assert request_mock.call_args_list[0][0][0].startswith(
588 "https://host:443/workflows/workflow/triggers/manual/paths/invoke"
589 )
590
591 # Our Posted JSON Object
592 posted_json = json.loads(request_mock.call_args_list[0][1]["data"])
593 assert "NotifyType." not in request_mock.call_args_list[0][1]["data"]
594 # Verify the Adaptive Card envelope
595 assert posted_json["type"] == "message"
596 content = posted_json["attachments"][0]["content"]
597 # Index body blocks by their id for easy lookup
598 blocks = {b["id"]: b["text"] for b in content["body"] if "id" in b}
599 assert blocks["desc"] == "Apprise Notifications"
600 assert blocks["color"] == "#3AA3E3"
601 assert blocks["title"] == "title"
602 assert blocks["body"] == "body"
603 # The custom :target token must be substituted into the action URL
604 assert content["actions"][0]["url"] == "http://localhost"
605
606
607 def test_plugin_workflows_templating_invalid_type(
608 request_mock, workflows_url, tmpdir
609 ):
610 """NotifyWorkflows() Templating - root 'type' != 'message' is rejected."""
611
612 template = tmpdir.join("bad_type.json")
613 template.write(
614 cleandoc("""
615 {
616 "type": "wrongtype",
617 "attachments": [{
618 "contentType": "application/vnd.microsoft.card.adaptive",
619 "contentUrl": null,
620 "content": {}
621 }]
622 }
623 """)
624 )
625
626 obj = Apprise.instantiate(f"{workflows_url}/?template={template!s}")
627 assert isinstance(obj, NotifyWorkflows)
628 # Validation rejects incorrect 'type' value
629 assert (
630 bool(
631 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
632 )
633 is False
634 )
635 assert request_mock.called is False
636
637
638 def test_plugin_workflows_templating_missing_attachments(
639 request_mock, workflows_url, tmpdir
640 ):
641 """NotifyWorkflows() Templating - absent or empty attachments fails."""
642
643 template = tmpdir.join("no_attachments.json")
644
645 # Missing 'attachments' key entirely
646 template.write('{"type": "message"}')
647 obj = Apprise.instantiate(f"{workflows_url}/?template={template!s}")
648 assert isinstance(obj, NotifyWorkflows)
649 assert (
650 bool(
651 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
652 )
653 is False
654 )
655 assert request_mock.called is False
656
657 # Empty list is also rejected
658 template.write('{"type": "message", "attachments": []}')
659 obj2 = Apprise.instantiate(f"{workflows_url}/?template={template!s}")
660 assert isinstance(obj2, NotifyWorkflows)
661 assert (
662 bool(
663 obj2.notify(
664 body="body", title="title", notify_type=NotifyType.INFO
665 )
666 )
667 is False
668 )
669 assert request_mock.called is False
670
671
672 def test_plugin_workflows_templating_invalid_contenttype(
673 request_mock, workflows_url, tmpdir
674 ):
675 """NotifyWorkflows() Templating - attachment missing contentType fails."""
676
677 template = tmpdir.join("no_contenttype.json")
678 template.write('{"type": "message", "attachments": [{"content": {}}]}')
679
680 obj = Apprise.instantiate(f"{workflows_url}/?template={template!s}")
681 assert isinstance(obj, NotifyWorkflows)
682 # An attachment without a 'contentType' string is rejected
683 assert (
684 bool(
685 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
686 )
687 is False
688 )
689 assert request_mock.called is False
690
691
692 @pytest.mark.skipif(
693 sys.version_info < (3, 10),
694 reason="Python <3.10: see test_plugin_workflows_template_add_failure_py39",
695 )
696 def test_plugin_workflows_template_add_failure():
697 """NotifyWorkflows() rejects an attachment it cannot add."""
698 # Simulate add() silently failing (len stays 0); no HTTP call needed
699 with mock.patch("apprise.plugins.workflows.AppriseAttachment") as mock_cls:
700 inst = mock.MagicMock()
701 inst.__len__ = mock.Mock(return_value=0)
702 mock_cls.return_value = inst
703
704 with pytest.raises(AppriseImproperlyConfigured):
705 NotifyWorkflows(
706 workflow="T00000000001",
707 signature="AbCdEfGhIjKlMnOpQrStUvWx",
708 template="file:///some/template.json",
709 )
710
711
712 # --- Python v3.9 Support ---
713 # On Python 3.9, mock.patch() resolves a dotted target ("a.b.c.Name") by
714 # walking getattr(pkg, "sub") chains rather than going straight to
715 # sys.modules (that was fixed in Python 3.10+).
716 # Delete this test once Python 3.9 reaches end-of-life.
717 @pytest.mark.skipif(
718 sys.version_info >= (3, 10),
719 reason="Python 3.10+ mock.patch resolves via sys.modules directly",
720 )
721 def test_plugin_workflows_template_add_failure_py39_compat():
722 """The attachment rejection remains compatible with Python 3.9."""
723 import importlib
724
725 # Resolve the live module so patch.object and the class share the same
726 # module dict regardless of any sys.modules manipulation by earlier tests.
727 wf_mod = importlib.import_module("apprise.plugins.workflows")
728 _NotifyWorkflows = wf_mod.NotifyWorkflows
729
730 # Simulate add() silently failing (len stays 0); no HTTP call needed
731 with mock.patch.object(wf_mod, "AppriseAttachment") as mock_cls:
732 inst = mock.MagicMock()
733 inst.__len__ = mock.Mock(return_value=0)
734 mock_cls.return_value = inst
735
736 with pytest.raises(AppriseImproperlyConfigured):
737 _NotifyWorkflows(
738 workflow="T00000000001",
739 signature="AbCdEfGhIjKlMnOpQrStUvWx",
740 template="file:///some/template.json",
741 )
742
743
744 # --- End Python v3.9 Compat ---
745
746
747 def test_plugin_workflows_templating_content_not_dict(
748 request_mock, workflows_url, tmpdir
749 ):
750 """NotifyWorkflows() Templating - template that parses to a JSON
751 array is rejected cleanly."""
752 # Valid JSON but a list rather than an object; no HTTP call is made
753 template = tmpdir.join("array.json")
754 template.write('[{"type": "message"}]')
755
756 obj = Apprise.instantiate(f"{workflows_url}/?template={template!s}")
757 assert isinstance(obj, NotifyWorkflows)
758 assert (
759 bool(
760 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
761 )
762 is False
763 )
764 assert request_mock.called is False
765
766
767 def test_plugin_workflows_templating_attachment_not_dict(
768 request_mock, workflows_url, tmpdir
769 ):
770 """NotifyWorkflows() Templating - non-dict in attachments rejected."""
771 # attachments list contains a string rather than a dict; no HTTP call made
772 template = tmpdir.join("bad_attach.json")
773 template.write('{"type": "message", "attachments": ["not-a-dict"]}')
774
775 obj = Apprise.instantiate(f"{workflows_url}/?template={template!s}")
776 assert isinstance(obj, NotifyWorkflows)
777 assert (
778 bool(
779 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
780 )
781 is False
782 )
783 assert request_mock.called is False
784
785
786 def test_plugin_workflows_templating_none_token_value(
787 request_mock, workflows_url, tmpdir
788 ):
789 """NotifyWorkflows() Templating - None token value (e.g. app_image_url)
790 is coerced to empty string before JSON-escaping."""
791 # Template references app_image_url which will be None when
792 # include_image=False; old code produced corrupted JSON ("ul" from None)
793 template = tmpdir.join("img_ref.json")
794 template.write(
795 '{"type": "message", "attachments": [{'
796 '"contentType": "application/vnd.microsoft.card.adaptive",'
797 '"content": {"body": [{"type": "TextBlock",'
798 '"text": "{{app_body}} img={{app_image_url}}"}]}}]}'
799 )
800
801 # image=no forces app_image_url to None, exercising the None->""
802 # coercion in safe_tokens
803 obj = Apprise.instantiate(
804 f"{workflows_url}/?image=no&template={template!s}"
805 )
806 assert isinstance(obj, NotifyWorkflows)
807 # Must succeed -- None coerced to "" keeps the JSON valid
808 assert (
809 bool(obj.notify(body="hello", title="t", notify_type=NotifyType.INFO))
810 is True
811 )
812 assert request_mock.called is True
813 posted_data = json.loads(request_mock.call_args_list[0][1]["data"])
814 body_text = posted_data["attachments"][0]["content"]["body"][0]["text"]
815 # app_image_url should expand to "" not "ul"
816 assert "img=" in body_text
817 assert "ul" not in body_text
818
819
820 def test_workflows_yaml_config_missing_template_filename(
821 request_mock, workflows_url, simple_template, tmpdir
822 ):
823 """
824 NotifyWorkflows() YAML Configuration Entries - Missing template reference.
825 """
826
827 config = tmpdir.join("workflow01.yml")
828 config.write(
829 cleandoc(f"""
830 urls:
831 - {workflows_url}:
832 - tag: 'workflow'
833 template: {simple_template!s}.missing
834 :name: 'Template.Missing'
835 :body: 'test body'
836 :title: 'test title'
837 """)
838 )
839
840 # Config still loads okay
841 cfg = AppriseConfig()
842 cfg.add(str(config))
843 assert len(cfg) == 1
844 assert len(cfg[0]) == 1
845
846 obj = cfg[0][0]
847 assert isinstance(obj, NotifyWorkflows)
848
849 # However we can't send notification since the template couldn't be loaded
850 assert (
851 bool(
852 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
853 )
854 is False
855 )
856 assert request_mock.called is False
857
858
859 def test_plugin_workflows_edge_cases():
860 """NotifyWorkflows() Edge Cases."""
861 # Initializes the plugin with an invalid token
862 with pytest.raises(AppriseImproperlyConfigured):
863 NotifyWorkflows(workflow="@", signature="@")
864 with pytest.raises(AppriseImproperlyConfigured):
865 NotifyWorkflows(workflow="", signature="abcd")
866
867 with pytest.raises(AppriseImproperlyConfigured):
868 NotifyWorkflows(workflow=None, signature="abcd")
869 # Whitespace also acts as an invalid token value
870 with pytest.raises(AppriseImproperlyConfigured):
871 NotifyWorkflows(workflow=" ", signature="abcd")
872
873 with pytest.raises(AppriseImproperlyConfigured):
874 NotifyWorkflows(workflow="abcd", signature=None)
875 # Whitespace also acts as an invalid token value
876 with pytest.raises(AppriseImproperlyConfigured):
877 NotifyWorkflows(workflow="abcd", signature=" ")
878
879 # test case where invalid tokens are specified
880 with pytest.raises(AppriseImproperlyConfigured):
881 NotifyWorkflows(
882 workflow="workflow", signature="signature", tokens="not-a-dict"
883 )
884
885 # test case where no tokens are specified
886 obj = NotifyWorkflows(workflow="workflow", signature="signature")
887 assert isinstance(obj, NotifyWorkflows)
888
889
890 def test_plugin_workflows_azure_webhooks(request_mock):
891 """NotifyWorkflows() Azure Webhooks."""
892 url = (
893 "https://prod-15.uksouth.logic.azure.com:443"
894 "/workflows/3XXX5/triggers/manual/paths/invoke"
895 "?api-version=2016-06-01&"
896 "sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=iXXXU"
897 )
898
899 #
900 # Initialize
901 #
902 obj = Apprise.instantiate(url)
903 assert isinstance(obj, NotifyWorkflows)
904 assert obj.workflow == "3XXX5"
905 assert obj.signature == "iXXXU"
906 assert obj.api_version == "2016-06-01"
907
908
909 @pytest.mark.parametrize("routing_id", (123456789, 987654321))
910 def test_plugin_workflows_power_automate_cu_webhooks(request_mock, routing_id):
911 """NotifyWorkflows() preserves Power Automate CU routing IDs."""
912 url = (
913 "https://default.environment.api.powerplatform.com:443"
914 f"/powerautomate/automations/direct/cu/{routing_id}"
915 "/workflows/3XXX5/triggers/manual/paths/invoke"
916 "?api-version=2022-03-01-preview&"
917 "sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=iXXXU"
918 )
919
920 obj = Apprise.instantiate(url)
921 assert isinstance(obj, NotifyWorkflows)
922 assert obj.notify(body="body", title="title") is True
923 assert request_mock.call_args.args[0] == (
924 "https://default.environment.api.powerplatform.com:443"
925 f"/powerautomate/automations/direct/cu/{routing_id}"
926 "/workflows/3XXX5/triggers/manual/paths/invoke"
927 )
928
929 # Our routing ID is tracked and advertised in the Apprise URL
930 assert obj.routing_id == str(routing_id)
931 assert f"route={routing_id}" in obj.url()
932
933
934 @pytest.mark.parametrize("key", ("route", "routeid"))
935 def test_plugin_workflows_routing_id_parse_url(key):
936 """NotifyWorkflows() parses the routing ID from an Apprise URL."""
937
938 results = NotifyWorkflows.parse_url(
939 f"workflow://host/3XXX5/iXXXU/?pa=yes&{key}=123456789"
940 )
941 assert isinstance(results, dict)
942 assert results["routing_id"] == "123456789"
943
944 obj = Apprise.instantiate(
945 f"workflow://host/3XXX5/iXXXU/?pa=yes&{key}=123456789"
946 )
947 assert isinstance(obj, NotifyWorkflows)
948 assert obj.routing_id == "123456789"
949
950 # No routing ID provided; nothing is set and nothing is advertised
951 obj = Apprise.instantiate("workflow://host/3XXX5/iXXXU/?pa=yes")
952 assert isinstance(obj, NotifyWorkflows)
953 assert obj.routing_id is None
954 assert "route=" not in obj.url()
955
956
957 def test_plugin_workflows_routing_id_invalid():
958 """NotifyWorkflows() rejects a non-numeric routing ID."""
959
960 with pytest.raises(AppriseImproperlyConfigured):
961 NotifyWorkflows(
962 workflow="3XXX5", signature="iXXXU", routing_id="1/../evil"
963 )
964
965 # Confirmed unusable (and therefore never reflected) via a full URL too
966 assert (
967 Apprise.instantiate(
968 "workflow://host/3XXX5/iXXXU/?pa=yes&route=1/../evil"
969 )
970 is None
971 )
972
973
974 def test_plugin_workflows_routing_id_round_trip(request_mock):
975 """NotifyWorkflows() round-trips the routing ID through url()."""
976
977 obj = Apprise.instantiate(
978 "https://default.environment.api.powerplatform.com:443"
979 "/powerautomate/automations/direct/cu/123456789"
980 "/workflows/3XXX5/triggers/manual/paths/invoke"
981 "?api-version=2022-03-01-preview&"
982 "sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=iXXXU"
983 )
984 assert isinstance(obj, NotifyWorkflows)
985 assert obj.routing_id == "123456789"
986
987 # Re-instantiate ourselves from our own generated URL
988 obj_copy = Apprise.instantiate(obj.url())
989 assert isinstance(obj_copy, NotifyWorkflows)
990 assert obj_copy.routing_id == obj.routing_id
991 assert obj_copy.url() == obj.url()
992
993 # The routed endpoint survives the round trip
994 assert obj_copy.notify(body="body", title="title") is True
995 assert request_mock.call_args.args[0] == (
996 "https://default.environment.api.powerplatform.com:443"
997 "/powerautomate/automations/direct/cu/123456789"
998 "/workflows/3XXX5/triggers/manual/paths/invoke"
999 )
1000
1001
1002 @mock.patch("requests.post")
1003 def test_plugin_workflows_html_to_markdown_format(mock_post):
1004 """NotifyWorkflows(): HTML body is converted to Markdown."""
1005
1006 # Prepare Mock
1007 mock_post.return_value = requests.Request()
1008 mock_post.return_value.status_code = requests.codes.ok
1009
1010 # Workflows' notify_format is MARKDOWN by default
1011 aobj = Apprise()
1012 assert aobj.add("workflow://hostname/workflow1/signature1/?image=no")
1013
1014 # Notify with an HTML body; the framework should convert it
1015 # to Markdown before dispatching to Workflows
1016 assert (
1017 bool(
1018 aobj.notify(
1019 body="<b>hello</b> <i>world</i>",
1020 body_format=NotifyFormat.HTML,
1021 )
1022 )
1023 is True
1024 )
1025 assert mock_post.call_count == 1
1026
1027 # The body must arrive as Markdown inside the adaptive card body block,
1028 # not as stripped plain text
1029 payload = json.loads(mock_post.call_args_list[0][1]["data"])
1030 body_blocks = payload["attachments"][0]["content"]["body"]
1031 body_text = next(b["text"] for b in body_blocks if b.get("id") == "body")
1032 assert body_text == "**hello** *world*"
1033
1034
1035 @mock.patch("requests.post")
1036 def test_plugin_workflows_mention_entities(mock_post):
1037 """Teams mention tags populate unique ``msteams.entities`` entries."""
1038
1039 # Prepare a successful mocked HTTP response.
1040 mock_post.return_value = requests.Request()
1041 mock_post.return_value.status_code = requests.codes.ok
1042
1043 aobj = Apprise()
1044 assert aobj.add("workflow://hostname/workflow1/signature1/?image=no")
1045
1046 # Keep Teams metadata minimal when the body contains no mentions.
1047 assert bool(aobj.notify(body="Hello world", title="T")) is True
1048 payload = json.loads(mock_post.call_args_list[0][1]["data"])
1049 msteams = payload["attachments"][0]["content"]["msteams"]
1050 assert msteams == {"width": "full"}
1051 mock_post.reset_mock()
1052
1053 # Add one entity for a single mention.
1054 assert (
1055 bool(
1056 aobj.notify(
1057 body="Hello <at>[email protected]</at>!",
1058 title="T",
1059 )
1060 )
1061 is True
1062 )
1063 payload = json.loads(mock_post.call_args_list[0][1]["data"])
1064 msteams = payload["attachments"][0]["content"]["msteams"]
1065 assert msteams == {
1066 "width": "full",
1067 "entities": [
1068 {
1069 "type": "mention",
1070 "text": "<at>[email protected]</at>",
1071 "mentioned": {
1072 "id": "[email protected]",
1073 "name": "[email protected]",
1074 },
1075 }
1076 ],
1077 }
1078 mock_post.reset_mock()
1079
1080 # Preserve source order for distinct mentions.
1081 assert (
1082 bool(
1083 aobj.notify(
1084 body=(
1085 "Hi <at>[email protected]</at> and"
1086 " <at>[email protected]</at>!"
1087 ),
1088 title="T",
1089 )
1090 )
1091 is True
1092 )
1093 payload = json.loads(mock_post.call_args_list[0][1]["data"])
1094 entities = payload["attachments"][0]["content"]["msteams"]["entities"]
1095 assert len(entities) == 2
1096 assert entities[0]["mentioned"]["id"] == "[email protected]"
1097 assert entities[1]["mentioned"]["id"] == "[email protected]"
1098 mock_post.reset_mock()
1099
1100 # Deduplicate repeated mention IDs.
1101 assert (
1102 bool(
1103 aobj.notify(
1104 body=(
1105 "<at>[email protected]</at> and"
1106 " <at>[email protected]</at> again"
1107 ),
1108 title="T",
1109 )
1110 )
1111 is True
1112 )
1113 payload = json.loads(mock_post.call_args_list[0][1]["data"])
1114 entities = payload["attachments"][0]["content"]["msteams"]["entities"]
1115 assert len(entities) == 1
1116 assert entities[0]["mentioned"]["id"] == "[email protected]"
1117 mock_post.reset_mock()
1118
1119 # Recover the valid inner tag from a nested opening sequence.
1120 assert (
1121 bool(
1122 aobj.notify(
1123 body="Hi <at><at>[email protected]</at>!",
1124 title="T",
1125 )
1126 )
1127 is True
1128 )
1129 payload = json.loads(mock_post.call_args_list[0][1]["data"])
1130 entities = payload["attachments"][0]["content"]["msteams"]["entities"]
1131 assert len(entities) == 1
1132 assert entities[0]["mentioned"]["id"] == "[email protected]"
1133 mock_post.reset_mock()
1134
1135 # Recover an inner mention when text invalidates the outer tag.
1136 assert (
1137 bool(
1138 aobj.notify(
1139 body="<at>garbage<at>[email protected]</at>",
1140 title="T",
1141 )
1142 )
1143 is True
1144 )
1145 payload = json.loads(mock_post.call_args_list[0][1]["data"])
1146 entities = payload["attachments"][0]["content"]["msteams"]["entities"]
1147 assert len(entities) == 1
1148 assert entities[0]["mentioned"]["id"] == "[email protected]"
1149 mock_post.reset_mock()
1150
1151 # Ignore empty, whitespace-only, and unclosed mention tags.
1152 for bad_body in ("<at></at>", "<at> </at>", "<at>unclosed"):
1153 assert bool(aobj.notify(body=bad_body, title="T")) is True
1154 payload = json.loads(mock_post.call_args_list[-1][1]["data"])
1155 msteams = payload["attachments"][0]["content"]["msteams"]
1156 assert msteams == {"width": "full"}, (
1157 f"expected no entities for {bad_body!r}"
1158 )
1159
1160 mock_post.reset_mock()
1161
1162 # Preserve mixed-case entity text for Teams' verbatim body match.
1163 assert (
1164 bool(
1165 aobj.notify(
1166 body="Hi <AT>[email protected]</AT>!",
1167 title="T",
1168 )
1169 )
1170 is True
1171 )
1172 payload = json.loads(mock_post.call_args_list[0][1]["data"])
1173 entity = payload["attachments"][0]["content"]["msteams"]["entities"][0]
1174 assert entity["text"] == "<AT>[email protected]</AT>"
1175 assert entity["mentioned"]["id"] == "[email protected]"
1176 mock_post.reset_mock()
1177
1178 # Preserve tag padding while trimming the ID used for user resolution.
1179 assert (
1180 bool(
1181 aobj.notify(
1182 body="Hi <at> [email protected] </at>!",
1183 title="T",
1184 )
1185 )
1186 is True
1187 )
1188 payload = json.loads(mock_post.call_args_list[0][1]["data"])
1189 entity = payload["attachments"][0]["content"]["msteams"]["entities"][0]
1190 assert entity["text"] == "<at> [email protected] </at>"
1191 assert entity["mentioned"]["id"] == "[email protected]"