Debian Codegraph @

tests/test_plugin_workflows.py

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