Debian Codegraph @

tests/test_plugin_slack.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 from json import dumps, loads
30
31 # Disable logging for a cleaner testing output
32 import logging
33 import os
34 from timeit import default_timer
35 from unittest import mock
36
37 from helpers import AppriseURLTester
38 import pytest
39 import requests
40
41 from apprise import Apprise, AppriseAttachment, NotifyFormat, NotifyType
42 from apprise.exception import AppriseImproperlyConfigured
43 from apprise.plugins.base import _delivery_tracker
44 from apprise.plugins.slack import NotifySlack, SlackMode
45
46 logging.disable(logging.CRITICAL)
47
48 # Attachment Directory
49 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
50
51 # A complete successful response keeps generic bot-mode attachment checks
52 # representative of Slack's message and file-upload APIs.
53 SLACK_BOT_GOOD_RESPONSE = {
54 "ok": True,
55 "message": "",
56 "channel": "C123456",
57 "file_id": "F123ABC456",
58 "upload_url": "https://files.slack.test/upload",
59 "files": [{"id": "F123ABC456", "title": "apprise-test"}],
60 }
61
62 # Our Testing URLs
63 apprise_url_tests = (
64 (
65 "slack://",
66 {
67 "instance": AppriseImproperlyConfigured,
68 },
69 ),
70 (
71 "slack://:@/",
72 {
73 "instance": AppriseImproperlyConfigured,
74 },
75 ),
76 (
77 "slack://T1JJ3T3L2",
78 {
79 # Just Token 1 provided
80 "instance": AppriseImproperlyConfigured,
81 },
82 ),
83 (
84 "slack://T1JJ3T3L2/A1BRTD4JD/",
85 {
86 # Just 2 tokens provided
87 "instance": AppriseImproperlyConfigured,
88 },
89 ),
90 (
91 "slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/?mode=invalid",
92 {
93 # invalid Mode provided
94 "instance": AppriseImproperlyConfigured,
95 },
96 ),
97 (
98 "slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/#hmm/#-invalid-",
99 {
100 # No username specified; this is still okay as we sub in
101 # default; The one invalid channel is skipped when sending a
102 # message
103 "instance": NotifySlack,
104 # There is an invalid channel that we will fail to deliver to
105 # as a result the response type will be false
106 "response": False,
107 "requests_response_text": {
108 "ok": False,
109 "message": "Bad Channel",
110 },
111 },
112 ),
113 (
114 "slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/#channel",
115 {
116 # No username specified; this is still okay as we sub in
117 # default; The one invalid channel is skipped when sending a
118 # message
119 "instance": NotifySlack,
120 # don't include an image by default
121 "include_image": False,
122 "requests_response_text": "ok",
123 },
124 ),
125 (
126 (
127 "slack://[email protected]/#nuxref?footer=no"
128 "&timestamp=yes"
129 ),
130 {
131 "instance": NotifySlack,
132 "requests_response_text": SLACK_BOT_GOOD_RESPONSE,
133 },
134 ),
135 (
136 (
137 "slack://[email protected]/#nuxref?footer=yes"
138 "&timestamp=no"
139 ),
140 {
141 "instance": NotifySlack,
142 "requests_response_text": SLACK_BOT_GOOD_RESPONSE,
143 },
144 ),
145 # Test using a rotating bot-token as argument
146 (
147 (
148 "slack://?token=xoxe.xoxb-1234-1234-abc124&to=#nuxref&footer=no"
149 "&user=test"
150 ),
151 {
152 "instance": NotifySlack,
153 "requests_response_text": SLACK_BOT_GOOD_RESPONSE,
154 "privacy_url": "slack://[email protected]/nuxref/",
155 },
156 ),
157 (
158 "slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/+id/@id/",
159 {
160 # + encoded id,
161 # @ userid
162 "instance": NotifySlack,
163 "requests_response_text": "ok",
164 },
165 ),
166 (
167 (
168 "slack://username@T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
169 "?to=#nuxref"
170 ),
171 {
172 "instance": NotifySlack,
173 # Our expected url(privacy=True) startswith() response:
174 "privacy_url": "slack://[email protected]/A...D/T...Q/",
175 "requests_response_text": "ok",
176 },
177 ),
178 (
179 (
180 "slack://username@T1JJ3T3L2/A1BRTD4JD/"
181 "TIiajkdnlazkcOXrIdevi7FQ/#nuxref"
182 ),
183 {
184 "instance": NotifySlack,
185 "requests_response_text": "ok",
186 },
187 ),
188 # You can't send to email using webhook
189 (
190 "slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnl/[email protected]",
191 {
192 "instance": NotifySlack,
193 "requests_response_text": "ok",
194 # we'll have a notify response failure in this case
195 "notify_response": False,
196 },
197 ),
198 # Specify Token on argument string (with username)
199 (
200 "slack://bot@_/#nuxref?token=T1JJ3T3L2/A1BRTD4JD/TIiajkdnadfdajkjkfl/",
201 {
202 "instance": NotifySlack,
203 "requests_response_text": "ok",
204 },
205 ),
206 # Specify Token and channels on argument string (no username)
207 (
208 (
209 "slack://?token=T1JJ3T3L2/A1BRTD4JD"
210 "/TIiajkdnlazkcOXrIdevi7FQ/&to=#chan"
211 ),
212 {
213 "instance": NotifySlack,
214 "requests_response_text": "ok",
215 },
216 ),
217 # Test webhook that doesn't have a proper response
218 (
219 (
220 "slack://username@T1JJ3T3L2/A1BRTD4JD/"
221 "TIiajkdnlazkcOXrIdevi7FQ/#nuxref"
222 ),
223 {
224 "instance": NotifySlack,
225 "requests_response_text": "fail",
226 # we'll have a notify response failure in this case
227 "notify_response": False,
228 },
229 ),
230 # Test using a bot-token (also test footer set to no flag)
231 (
232 (
233 "slack://username@xoxb-1234-1234-abc124/#nuxref?footer=no"
234 "&timestamp=yes"
235 ),
236 {
237 "instance": NotifySlack,
238 "requests_response_text": SLACK_BOT_GOOD_RESPONSE,
239 },
240 ),
241 (
242 (
243 "slack://username@xoxb-1234-1234-abc124/#nuxref?footer=yes"
244 "&timestamp=yes"
245 ),
246 {
247 "instance": NotifySlack,
248 "requests_response_text": SLACK_BOT_GOOD_RESPONSE,
249 },
250 ),
251 (
252 (
253 "slack://username@xoxb-1234-1234-abc124/#nuxref?footer=yes"
254 "&timestamp=no"
255 ),
256 {
257 "instance": NotifySlack,
258 "requests_response_text": SLACK_BOT_GOOD_RESPONSE,
259 },
260 ),
261 (
262 (
263 "slack://username@xoxb-1234-1234-abc124/#nuxref?footer=yes"
264 "&timestamp=no"
265 ),
266 {
267 "instance": NotifySlack,
268 "requests_response_text": SLACK_BOT_GOOD_RESPONSE,
269 },
270 ),
271 # Testing modes
272 (
273 (
274 "slack://?token=T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
275 "&to=#chan&mode=hook"
276 ),
277 {"instance": NotifySlack, "requests_response_text": "ok"},
278 ),
279 # Forced mode on a url that does not have enough details to accommodate
280 (
281 (
282 "slack://?token=T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
283 "&to=#chan&mode=bot"
284 ),
285 {"instance": AppriseImproperlyConfigured},
286 ),
287 # Test blocks mode with timestamp variation
288 (
289 (
290 "slack://?token=T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
291 "&to=#chan&blocks=yes&footer=yes&timestamp=no"
292 ),
293 {"instance": NotifySlack, "requests_response_text": "ok"},
294 ),
295 # Test blocks mode with another timestamp
296 (
297 (
298 "slack://?token=T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
299 "&to=#chan&blocks=yes&footer=yes&timestamp=yes"
300 ),
301 {"instance": NotifySlack, "requests_response_text": "ok"},
302 ),
303 # footer being disabled means timestamp isn't shown
304 (
305 (
306 "slack://?token=T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
307 "&to=#chan&blocks=yes&footer=no&timestamp=yes"
308 ),
309 {"instance": NotifySlack, "requests_response_text": "ok"},
310 ),
311 # footer and timestamp disabled
312 (
313 (
314 "slack://?token=T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
315 "&to=#chan&blocks=yes&footer=no&timestamp=no"
316 ),
317 {"instance": NotifySlack, "requests_response_text": "ok"},
318 ),
319 (
320 (
321 "slack://?token=T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
322 "&to=#chan&blocks=yes&footer=yes&image=no"
323 ),
324 {"instance": NotifySlack, "requests_response_text": "ok"},
325 ),
326 (
327 (
328 "slack://?token=T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
329 "&to=#chan&blocks=yes&format=text"
330 ),
331 {"instance": NotifySlack, "requests_response_text": "ok"},
332 ),
333 (
334 (
335 "slack://?token=T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
336 "&to=#chan&blocks=no&format=text"
337 ),
338 {"instance": NotifySlack, "requests_response_text": "ok"},
339 ),
340 # Test using a bot-token as argument
341 (
342 "slack://?token=xoxb-1234-1234-abc124&to=#nuxref&footer=no&user=test",
343 {
344 "instance": NotifySlack,
345 "requests_response_text": SLACK_BOT_GOOD_RESPONSE,
346 # Our expected url(privacy=True) startswith() response:
347 "privacy_url": "slack://[email protected]/nuxref/",
348 },
349 ),
350 # We contain 1 or more invalid channels, so we'll fail on our notify call
351 (
352 "slack://?token=xoxb-1234-1234-abc124&to=#nuxref,#$,#-&footer=no",
353 {
354 "instance": NotifySlack,
355 "requests_response_text": {
356 "ok": True,
357 "message": "",
358 },
359 # We fail because of the empty channel #$ and #-
360 "notify_response": False,
361 },
362 ),
363 (
364 "slack://username@xoxb-1234-1234-abc124/#nuxref",
365 {
366 "instance": NotifySlack,
367 "requests_response_text": {
368 "ok": True,
369 "message": "",
370 },
371 # we'll fail to send attachments because we had no 'file' response
372 # in our object
373 "response": False,
374 },
375 ),
376 (
377 "slack://username@T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ",
378 {
379 # Missing a channel, falls back to webhook channel bindings
380 "instance": NotifySlack,
381 "requests_response_text": "ok",
382 },
383 ),
384 # Native URL Support, take the slack URL and still build from it
385 (
386 "https://hooks.slack.com/services/{}/{}/{}".format(
387 "A" * 9, "B" * 9, "c" * 24
388 ),
389 {
390 "instance": NotifySlack,
391 "requests_response_text": "ok",
392 "url_matches": "mode=hook",
393 },
394 ),
395 (
396 "https://hooks.slack-gov.com/services/{}/{}/{}".format(
397 "A" * 9, "B" * 9, "c" * 24
398 ),
399 {
400 "instance": NotifySlack,
401 "requests_response_text": "ok",
402 "url_matches": "mode=gov-hook",
403 },
404 ),
405 # Native URL Support with arguments
406 (
407 "https://hooks.slack.com/services/{}/{}/{}?format=text".format(
408 "A" * 9, "B" * 9, "c" * 24
409 ),
410 {
411 "instance": NotifySlack,
412 "requests_response_text": "ok",
413 },
414 ),
415 (
416 "slack://username@-INVALID-/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/#cool",
417 {
418 # invalid 1st Token
419 "instance": AppriseImproperlyConfigured,
420 },
421 ),
422 (
423 "slack://username@T1JJ3T3L2/-INVALID-/TIiajkdnlazkcOXrIdevi7FQ/#great",
424 {
425 # invalid 2rd Token
426 "instance": AppriseImproperlyConfigured,
427 },
428 ),
429 (
430 "slack://username@T1JJ3T3L2/A1BRTD4JD/-INVALID-/#channel",
431 {
432 # invalid 3rd Token
433 "instance": AppriseImproperlyConfigured,
434 },
435 ),
436 (
437 "slack://l2g@T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/#usenet",
438 {
439 "instance": NotifySlack,
440 # force a failure
441 "response": False,
442 "requests_response_code": requests.codes.internal_server_error,
443 "requests_response_text": "ok",
444 },
445 ),
446 (
447 "slack://respect@T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/#a",
448 {
449 "instance": NotifySlack,
450 # throw a bizarre code forcing us to fail to look it up
451 "response": False,
452 "requests_response_code": 999,
453 "requests_response_text": "ok",
454 },
455 ),
456 (
457 "slack://notify@T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/#b",
458 {
459 "instance": NotifySlack,
460 # Throws a series of i/o exceptions with this flag
461 # is set and tests that we gracefully handle them
462 "test_requests_exceptions": True,
463 "requests_response_text": "ok",
464 },
465 ),
466 (
467 "slack://notify@T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/#b:100",
468 {
469 "instance": NotifySlack,
470 "requests_response_text": "ok",
471 },
472 ),
473 (
474 "slack://notify@T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/+124:100",
475 {
476 "instance": NotifySlack,
477 "requests_response_text": "ok",
478 },
479 ),
480 # test a case where we have a channel defined alone (without a thread_ts)
481 # that exists after a definition where a thread_ts does exist. this
482 # tests the branch of code that ensures we do not pass the same thread_ts
483 # twice
484 (
485 (
486 "slack://notify@T1JJ3T3L2/A1BRTD4JD/"
487 "TIiajkdnlazkcOXrIdevi7FQ/+124:100/@chan"
488 ),
489 {
490 "instance": NotifySlack,
491 "requests_response_text": "ok",
492 },
493 ),
494 (
495 "slack://notify@T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/#b:bad",
496 {
497 "instance": NotifySlack,
498 "requests_response_text": "ok",
499 # we'll fail because our thread_ts is bad
500 "response": False,
501 },
502 ),
503 # Workflow Builder webhook (4-segment /workflows/ path)
504 (
505 "slack://T1JJ3T3L2/Ft07XXXX/XXXXXXXX/YYYYYYYY/?mode=workflow",
506 {
507 "instance": NotifySlack,
508 },
509 ),
510 # Workflow trigger webhook (3-segment /triggers/ path)
511 (
512 "slack://T1JJ3T3L2/XXXXXXXX/YYYYYYYY/?mode=trigger",
513 {
514 "instance": NotifySlack,
515 },
516 ),
517 # Workflow native URL (/workflows/)
518 (
519 (
520 "https://hooks.slack.com/workflows/"
521 "T1JJ3T3L2/Ft07XXXX/XXXXXXXX/YYYYYYYY"
522 ),
523 {
524 "instance": NotifySlack,
525 "privacy_url": "slack://T...2/F...X/X...X/Y...Y/",
526 },
527 ),
528 # Workflow trigger native URL (/triggers/)
529 (
530 "https://hooks.slack.com/triggers/T1JJ3T3L2/XXXXXXXX/YYYYYYYY",
531 {
532 "instance": NotifySlack,
533 "privacy_url": "slack://T...2/X...X/Y...Y/",
534 },
535 ),
536 # Workflow mode -- too few segments (2 of required 4)
537 (
538 "slack://T1JJ3T3L2/XXXXXXXX/?mode=workflow",
539 {
540 "instance": AppriseImproperlyConfigured,
541 },
542 ),
543 # Workflow mode -- wrong count: trigger's 3 segments rejected
544 (
545 "slack://T1JJ3T3L2/XXXXXXXX/YYYYYYYY/?mode=workflow",
546 {
547 "instance": AppriseImproperlyConfigured,
548 },
549 ),
550 # Trigger mode -- wrong count: workflow's 4 segments rejected
551 (
552 "slack://T1JJ3T3L2/Ft07XXXX/XXXXXXXX/YYYYYYYY/?mode=trigger",
553 {
554 "instance": AppriseImproperlyConfigured,
555 },
556 ),
557 )
558
559
560 def test_plugin_slack_urls():
561 """NotifySlack() Apprise URLs."""
562
563 # Run our general tests
564 AppriseURLTester(tests=apprise_url_tests).run_all()
565
566
567 @mock.patch("requests.request")
568 def test_plugin_slack_oauth_access_token(mock_request):
569 """NotifySlack() OAuth Access Token Tests."""
570
571 # Generate an invalid bot token
572 token = "xo-invalid"
573
574 request = mock.Mock()
575 request.content = dumps(
576 {
577 "ok": True,
578 "message": "",
579 "channel": "C123456",
580 }
581 )
582 request.status_code = requests.codes.ok
583
584 # We'll fail to validate the access_token
585 with pytest.raises(AppriseImproperlyConfigured):
586 NotifySlack(access_token=token)
587
588 # Generate a (valid) bot token
589 token = "xoxb-1234-1234-abc124"
590
591 # Generate a (valid) rotating bot token
592 rotating_token = "xoxe.xoxb-1234-1234-abc124"
593
594 # Prepare Mock
595 mock_request.return_value = request
596 # Variation Initializations
597 obj = NotifySlack(access_token=token, targets="#apprise")
598 assert isinstance(obj, NotifySlack) is True
599 assert isinstance(obj.url(), str) is True
600
601 # apprise room was found
602 assert obj.send(body="test") is True
603
604 # Validate rotating token is accepted too
605 obj = NotifySlack(access_token=rotating_token, targets="#apprise")
606 assert isinstance(obj, NotifySlack) is True
607 assert isinstance(obj.url(), str) is True
608 assert obj.send(body="test") is True
609
610 # A poorly formatted xoxe prefix should still be rejected
611 with pytest.raises(AppriseImproperlyConfigured):
612 NotifySlack(access_token="xoxe.xo-invalid", targets="#apprise")
613
614 # Test Valid Attachment
615 mock_request.reset_mock()
616 mock_request.side_effect = [
617 request,
618 mock.Mock(
619 **{
620 "content": dumps(
621 {
622 "ok": True,
623 "upload_url": "https://files.slack.com/upload/v1/ABC123",
624 "file_id": "F123ABC456",
625 }
626 ),
627 "status_code": requests.codes.ok,
628 }
629 ),
630 mock.Mock(
631 **{"content": b"OK - 123", "status_code": requests.codes.ok}
632 ),
633 mock.Mock(
634 **{
635 "content": dumps(
636 {
637 "ok": True,
638 "files": [{"id": "F123ABC456", "title": "slack-test"}],
639 }
640 ),
641 "status_code": requests.codes.ok,
642 }
643 ),
644 ]
645
646 path = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
647 attach = AppriseAttachment(path)
648 assert (
649 bool(
650 obj.notify(
651 body="body",
652 title="title",
653 notify_type=NotifyType.INFO,
654 attach=attach,
655 )
656 )
657 is True
658 )
659
660 assert mock_request.call_count == 4
661 assert mock_request.call_args_list[0][0][0] == "post"
662 assert (
663 mock_request.call_args_list[0][0][1]
664 == "https://slack.com/api/chat.postMessage"
665 )
666 assert mock_request.call_args_list[1][0][0] == "get"
667 assert (
668 mock_request.call_args_list[1][0][1]
669 == "https://slack.com/api/files.getUploadURLExternal"
670 )
671 assert mock_request.call_args_list[2][0][0] == "post"
672 assert (
673 mock_request.call_args_list[2][0][1]
674 == "https://files.slack.com/upload/v1/ABC123"
675 )
676 assert mock_request.call_args_list[3][0][0] == "post"
677 assert (
678 mock_request.call_args_list[3][0][1]
679 == "https://slack.com/api/files.completeUploadExternal"
680 )
681
682 # Test a valid attachment that throws an Connection Error
683 mock_request.return_value = None
684 mock_request.side_effect = (
685 request,
686 requests.ConnectionError(0, "requests.ConnectionError() not handled"),
687 )
688 assert (
689 bool(
690 obj.notify(
691 body="body",
692 title="title",
693 notify_type=NotifyType.INFO,
694 attach=attach,
695 )
696 )
697 is False
698 )
699
700 # Test a valid attachment that throws an OSError
701 mock_request.return_value = None
702 mock_request.side_effect = (request, OSError(0, "OSError"))
703 assert (
704 bool(
705 obj.notify(
706 body="body",
707 title="title",
708 notify_type=NotifyType.INFO,
709 attach=attach,
710 )
711 )
712 is False
713 )
714
715 # Reset our mock object back to how it was
716 mock_request.return_value = request
717 mock_request.side_effect = None
718
719 # Test invalid attachment
720 path = os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg")
721 assert (
722 bool(
723 obj.notify(
724 body="body",
725 title="title",
726 notify_type=NotifyType.INFO,
727 attach=path,
728 )
729 )
730 is False
731 )
732
733 # Test case where expected return attachment payload is invalid
734 mock_request.reset_mock()
735 mock_request.side_effect = [
736 request,
737 mock.Mock(
738 **{
739 "content": dumps(
740 {
741 "ok": False,
742 }
743 ),
744 "status_code": requests.codes.internal_server_error,
745 }
746 ),
747 ]
748 path = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
749 attach = AppriseAttachment(path)
750 # We'll fail because of the bad 'file' response
751 assert (
752 bool(
753 obj.notify(
754 body="body",
755 title="title",
756 notify_type=NotifyType.INFO,
757 attach=attach,
758 )
759 )
760 is False
761 )
762
763 # Slack requests pay close attention to the response to determine
764 # if things go well... this is not a good JSON response:
765 request.content = "{"
766 mock_request.reset_mock()
767 mock_request.return_value = request
768 mock_request.side_effect = None
769
770 # As a result, we'll fail to send our notification
771 assert obj.send(body="test", attach=attach) is False
772
773 request.content = dumps(
774 {
775 "ok": False,
776 "message": "We failed",
777 }
778 )
779
780 # A response from Slack (even with a 200 response) still
781 # results in a failure:
782 assert obj.send(body="test", attach=attach) is False
783
784 # Handle exceptions reading our attachment from disk (should it happen)
785 mock_request.side_effect = OSError("Attachment Error")
786 mock_request.return_value = None
787
788 # We'll fail now because of an internal exception
789 assert obj.send(body="test") is False
790
791
792 @mock.patch("requests.request")
793 def test_plugin_slack_webhook_mode(mock_request):
794 """NotifySlack() Webhook Mode Tests."""
795
796 # Prepare Mock
797 mock_request.return_value = requests.Request()
798 mock_request.return_value.status_code = requests.codes.ok
799 mock_request.return_value.content = b"ok"
800 mock_request.return_value.text = "ok"
801
802 # Initialize some generic (but valid) tokens
803 token_a = "A" * 9
804 token_b = "B" * 9
805 token_c = "c" * 24
806 channels = "chan1,#chan2,+BAK4K23G5,@user,,,"
807
808 obj = NotifySlack(
809 token_a=token_a, token_b=token_b, token_c=token_c, targets=channels
810 )
811 assert len(obj.channels) == 4
812
813 # This call includes an image with it's payload:
814 assert (
815 bool(
816 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
817 )
818 is True
819 )
820
821 # Missing first Token
822 with pytest.raises(AppriseImproperlyConfigured):
823 NotifySlack(
824 token_a=None, token_b=token_b, token_c=token_c, targets=channels
825 )
826
827 # Test include_image
828 obj = NotifySlack(
829 token_a=token_a,
830 token_b=token_b,
831 token_c=token_c,
832 targets=channels,
833 include_image=True,
834 )
835
836 # This call includes an image with it's payload:
837 assert (
838 bool(
839 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
840 )
841 is True
842 )
843
844
845 @mock.patch("requests.request")
846 def test_plugin_slack_username_payload_by_mode(mock_request):
847 """NotifySlack() Username payload behavior by mode."""
848
849 # Prepare Mock
850 response = mock.Mock()
851 response.status_code = requests.codes.ok
852 response.content = b"ok"
853 response.text = "ok"
854 mock_request.return_value = response
855
856 token_a = "A" * 9
857 token_b = "B" * 9
858 token_c = "c" * 24
859
860 # Webhook mode without botname should not force username,
861 # allowing Slack's configured webhook identity to be used.
862 obj = NotifySlack(token_a=token_a, token_b=token_b, token_c=token_c)
863 assert bool(obj.notify(body="body", title="title")) is True
864 payload = loads(mock_request.call_args.kwargs["data"])
865 assert "username" not in payload
866
867 # Explicit botname in webhook mode should be honored.
868 mock_request.reset_mock()
869 obj = NotifySlack(
870 token_a=token_a,
871 token_b=token_b,
872 token_c=token_c,
873 user="CustomWebhookName",
874 )
875 assert bool(obj.notify(body="body", title="title")) is True
876 payload = loads(mock_request.call_args.kwargs["data"])
877 assert payload.get("username") == "CustomWebhookName"
878
879 # Bot mode without botname should also omit username, allowing Slack
880 # to use the app's configured display name.
881 mock_request.reset_mock()
882 response.content = dumps({"ok": True, "channel": "C123456"})
883 obj = NotifySlack(access_token="xoxb-1234-1234-abc124", targets="#test")
884 assert bool(obj.notify(body="body", title="title")) is True
885 payload = loads(mock_request.call_args.kwargs["data"])
886 assert "username" not in payload
887
888 # WEBHOOK_GOV mode without botname should also omit username,
889 # deferring to the government webhook's configured identity.
890 mock_request.reset_mock()
891 response.content = b"ok"
892 obj = NotifySlack(
893 token_a=token_a,
894 token_b=token_b,
895 token_c=token_c,
896 mode=SlackMode.WEBHOOK_GOV,
897 )
898 assert bool(obj.notify(body="body", title="title")) is True
899 payload = loads(mock_request.call_args.kwargs["data"])
900 assert "username" not in payload
901
902 # Webhook mode with blocks enabled and no botname should also omit
903 # username, so Slack's webhook identity is used.
904 mock_request.reset_mock()
905 response.content = b"ok"
906 obj = NotifySlack(
907 token_a=token_a,
908 token_b=token_b,
909 token_c=token_c,
910 use_blocks=True,
911 )
912 assert bool(obj.notify(body="body", title="title")) is True
913 payload = loads(mock_request.call_args.kwargs["data"])
914 assert "username" not in payload
915
916
917 @mock.patch("requests.request")
918 @mock.patch("requests.get")
919 def test_plugin_slack_send_by_email(mock_get, mock_request):
920 """NotifySlack() Send by Email Tests."""
921
922 # Generate a (valid) bot token
923 token = "xoxb-1234-1234-abc124"
924
925 request = mock.Mock()
926 request.content = dumps(
927 {"ok": True, "message": "", "user": {"id": "ABCD1234"}}
928 )
929 request.status_code = requests.codes.ok
930
931 # Prepare Mock
932 mock_request.return_value = request
933 mock_get.return_value = request
934
935 # Variation Initializations
936 obj = NotifySlack(access_token=token, targets="[email protected]")
937 assert isinstance(obj, NotifySlack) is True
938 assert isinstance(obj.url(), str) is True
939
940 # No calls made yet
941 assert mock_request.call_count == 0
942 assert mock_get.call_count == 0
943
944 # Send our notification
945 assert (
946 bool(
947 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
948 )
949 is True
950 )
951
952 # 2 calls were made, one to perform an email lookup, the second
953 # was the notification itself
954 assert mock_get.call_count == 1
955 assert mock_request.call_count == 1
956 assert (
957 mock_get.call_args_list[0][0][0]
958 == "https://slack.com/api/users.lookupByEmail"
959 )
960 assert (
961 mock_request.call_args_list[0][0][1]
962 == "https://slack.com/api/chat.postMessage"
963 )
964
965 # Reset our mock object
966 mock_request.reset_mock()
967 mock_get.reset_mock()
968
969 # Prepare Mock
970 mock_request.return_value = request
971 mock_get.return_value = request
972
973 # Send our notification again (cached copy of user id associated with
974 # email is used)
975 assert (
976 bool(
977 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
978 )
979 is True
980 )
981
982 assert mock_get.call_count == 0
983 assert mock_request.call_count == 1
984 assert (
985 mock_request.call_args_list[0][0][1]
986 == "https://slack.com/api/chat.postMessage"
987 )
988
989 #
990 # Now test a case where we can't look up the valid email
991 #
992 request.content = dumps(
993 {
994 "ok": False,
995 "message": "",
996 }
997 )
998
999 # Reset our mock object
1000 mock_request.reset_mock()
1001 mock_get.reset_mock()
1002
1003 # Prepare Mock
1004 mock_request.return_value = request
1005 mock_get.return_value = request
1006
1007 # Variation Initializations
1008 obj = NotifySlack(access_token=token, targets="[email protected]")
1009 assert isinstance(obj, NotifySlack) is True
1010 assert isinstance(obj.url(), str) is True
1011
1012 # No calls made yet
1013 assert mock_request.call_count == 0
1014 assert mock_get.call_count == 0
1015
1016 # Send our notification; it will fail because we failed to look up
1017 # the user id
1018 assert (
1019 bool(
1020 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
1021 )
1022 is False
1023 )
1024
1025 # We would have failed to look up the email, therefore we wouldn't have
1026 # even bothered to attempt to send the notification
1027 assert mock_get.call_count == 1
1028 assert mock_request.call_count == 0
1029 assert (
1030 mock_get.call_args_list[0][0][0]
1031 == "https://slack.com/api/users.lookupByEmail"
1032 )
1033
1034 #
1035 # Now test a case where we have a poorly formatted JSON response
1036 #
1037 request.content = "}"
1038
1039 # Reset our mock object
1040 mock_request.reset_mock()
1041 mock_get.reset_mock()
1042
1043 # Prepare Mock
1044 mock_request.return_value = request
1045 mock_get.return_value = request
1046
1047 # Variation Initializations
1048 obj = NotifySlack(access_token=token, targets="[email protected]")
1049 assert isinstance(obj, NotifySlack) is True
1050 assert isinstance(obj.url(), str) is True
1051
1052 # No calls made yet
1053 assert mock_request.call_count == 0
1054 assert mock_get.call_count == 0
1055
1056 # Send our notification; it will fail because we failed to look up
1057 # the user id
1058 assert (
1059 bool(
1060 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
1061 )
1062 is False
1063 )
1064
1065 # We would have failed to look up the email, therefore we wouldn't have
1066 # even bothered to attempt to send the notification
1067 assert mock_get.call_count == 1
1068 assert mock_request.call_count == 0
1069 assert (
1070 mock_get.call_args_list[0][0][0]
1071 == "https://slack.com/api/users.lookupByEmail"
1072 )
1073
1074 #
1075 # Now test a case where we have a poorly formatted JSON response
1076 #
1077 request.content = "}"
1078
1079 # Reset our mock object
1080 mock_request.reset_mock()
1081 mock_get.reset_mock()
1082
1083 # Prepare Mock
1084 mock_request.return_value = request
1085 mock_get.return_value = request
1086
1087 # Variation Initializations
1088 obj = NotifySlack(access_token=token, targets="[email protected]")
1089 assert isinstance(obj, NotifySlack) is True
1090 assert isinstance(obj.url(), str) is True
1091
1092 # No calls made yet
1093 assert mock_request.call_count == 0
1094 assert mock_get.call_count == 0
1095
1096 # Send our notification; it will fail because we failed to look up
1097 # the user id
1098 assert (
1099 bool(
1100 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
1101 )
1102 is False
1103 )
1104
1105 # We would have failed to look up the email, therefore we wouldn't have
1106 # even bothered to attempt to send the notification
1107 assert mock_get.call_count == 1
1108 assert mock_request.call_count == 0
1109 assert (
1110 mock_get.call_args_list[0][0][0]
1111 == "https://slack.com/api/users.lookupByEmail"
1112 )
1113
1114 #
1115 # Now test a case where we throw an exception trying to perform the lookup
1116 #
1117
1118 request.content = dumps(
1119 {"ok": True, "message": "", "user": {"id": "ABCD1234"}}
1120 )
1121 # Create an unauthorized response
1122 request.status_code = requests.codes.ok
1123
1124 # Reset our mock object
1125 mock_request.reset_mock()
1126 mock_get.reset_mock()
1127
1128 # Prepare Mock
1129 mock_request.return_value = request
1130 mock_get.side_effect = requests.ConnectionError(
1131 0, "requests.ConnectionError() not handled"
1132 )
1133
1134 # Variation Initializations
1135 obj = NotifySlack(access_token=token, targets="[email protected]")
1136 assert isinstance(obj, NotifySlack) is True
1137 assert isinstance(obj.url(), str) is True
1138
1139 # No calls made yet
1140 assert mock_request.call_count == 0
1141 assert mock_get.call_count == 0
1142
1143 # Send our notification; it will fail because we failed to look up
1144 # the user id
1145 assert (
1146 bool(
1147 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
1148 )
1149 is False
1150 )
1151
1152 # We would have failed to look up the email, therefore we wouldn't have
1153 # even bothered to attempt to send the notification
1154 assert mock_get.call_count == 1
1155 assert mock_request.call_count == 0
1156 assert (
1157 mock_get.call_args_list[0][0][0]
1158 == "https://slack.com/api/users.lookupByEmail"
1159 )
1160
1161
1162 @mock.patch("requests.request")
1163 @mock.patch("requests.get")
1164 def test_plugin_slack_markdown(mock_get, mock_request):
1165 """NotifySlack() Markdown tests."""
1166
1167 request = mock.Mock()
1168 request.content = b"ok"
1169 request.status_code = requests.codes.ok
1170
1171 # Prepare Mock
1172 mock_request.return_value = request
1173 mock_get.return_value = request
1174
1175 # Variation Initializations
1176 aobj = Apprise()
1177 assert aobj.add(
1178 "slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/#channel"
1179 )
1180
1181 body = cleandoc("""
1182 Here is a <https://slack.com|Slack Link> we want to support as part of it's
1183 markdown.
1184
1185 This one has arguments we want to preserve:
1186 <https://slack.com?arg=val&arg2=val2|Slack Link>.
1187 We also want to be able to support <https://slack.com> links without the
1188 description.
1189
1190 Channel Testing
1191 <!channelA>
1192 <!channelA|Description>
1193
1194 User ID Testing
1195 <@U1ZQL9N3Y>
1196 <@U1ZQL9N3Y|heheh>
1197 """)
1198
1199 # Send our notification
1200 assert aobj.notify(body=body, title="title", notify_type=NotifyType.INFO)
1201
1202 # We would have failed to look up the email, therefore we wouldn't have
1203 # even bothered to attempt to send the notification
1204 assert mock_get.call_count == 0
1205 assert mock_request.call_count == 1
1206 assert (
1207 mock_request.call_args_list[0][0][1]
1208 == "https://hooks.slack.com/services/T1JJ3T3L2/A1BRTD4JD/"
1209 "TIiajkdnlazkcOXrIdevi7FQ"
1210 )
1211
1212 data = loads(mock_request.call_args_list[0][1]["data"])
1213 assert (
1214 data["attachments"][0]["text"]
1215 == "Here is a <https://slack.com|Slack Link> we want to support as"
1216 " part "
1217 "of it's\nmarkdown.\n\nThis one has arguments we want to preserve:"
1218 "\n <https://slack.com?arg=val&arg2=val2|Slack Link>.\n"
1219 "We also want to be able to support <https://slack.com> "
1220 "links without the\ndescription."
1221 "\n\nChannel Testing\n<!channelA>\n<!channelA|Description>\n\n"
1222 "User ID Testing\n<@U1ZQL9N3Y>\n<@U1ZQL9N3Y|heheh>"
1223 )
1224
1225
1226 @mock.patch("requests.request")
1227 def test_plugin_slack_single_thread_reply(mock_request):
1228 """NotifySlack() Send Notification as a Reply."""
1229
1230 # Generate a (valid) bot token
1231 token = "xoxb-1234-1234-abc124"
1232 thread_id = 100
1233 request = mock.Mock()
1234 request.content = dumps(
1235 {"ok": True, "message": "", "user": {"id": "ABCD1234"}}
1236 )
1237 request.status_code = requests.codes.ok
1238
1239 # Prepare Mock
1240 mock_request.return_value = request
1241
1242 # Variation Initializations
1243 obj = NotifySlack(access_token=token, targets=[f"#general:{thread_id}"])
1244 assert isinstance(obj, NotifySlack) is True
1245 assert isinstance(obj.url(), str) is True
1246
1247 # No calls made yet
1248 assert mock_request.call_count == 0
1249
1250 # Send our notification
1251 assert (
1252 bool(
1253 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
1254 )
1255 is True
1256 )
1257
1258 # Post was made
1259 assert mock_request.call_count == 1
1260 assert (
1261 mock_request.call_args_list[0][0][1]
1262 == "https://slack.com/api/chat.postMessage"
1263 )
1264 assert loads(mock_request.call_args_list[0][1]["data"]).get(
1265 "thread_ts"
1266 ) == str(thread_id)
1267
1268
1269 @mock.patch("requests.request")
1270 def test_plugin_slack_multiple_thread_reply(mock_request):
1271 """NotifySlack() Send Notification to multiple channels as Reply."""
1272
1273 # Generate a (valid) bot token
1274 token = "xoxb-1234-1234-abc124"
1275 thread_id_1, thread_id_2 = 100, 200
1276 request = mock.Mock()
1277 request.content = dumps(
1278 {"ok": True, "message": "", "user": {"id": "ABCD1234"}}
1279 )
1280 request.status_code = requests.codes.ok
1281
1282 # Prepare Mock
1283 mock_request.return_value = request
1284
1285 # Variation Initializations
1286 obj = NotifySlack(
1287 access_token=token,
1288 targets=[f"#general:{thread_id_1}", f"#other:{thread_id_2}"],
1289 )
1290 assert isinstance(obj, NotifySlack) is True
1291 assert isinstance(obj.url(), str) is True
1292
1293 # No calls made yet
1294 assert mock_request.call_count == 0
1295
1296 # Send our notification
1297 assert (
1298 bool(
1299 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
1300 )
1301 is True
1302 )
1303
1304 # Post was made
1305 assert mock_request.call_count == 2
1306 assert (
1307 mock_request.call_args_list[0][0][1]
1308 == "https://slack.com/api/chat.postMessage"
1309 )
1310 assert loads(mock_request.call_args_list[0][1]["data"]).get(
1311 "thread_ts"
1312 ) == str(thread_id_1)
1313 assert loads(mock_request.call_args_list[1][1]["data"]).get(
1314 "thread_ts"
1315 ) == str(thread_id_2)
1316
1317
1318 @mock.patch("requests.request")
1319 def test_plugin_slack_file_upload_success(mock_request):
1320 """Test Slack BOT attachment upload success path."""
1321
1322 token = "xoxb-1234-1234-abc124"
1323 path = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
1324 attach = AppriseAttachment(path)
1325
1326 # Simulate all successful Slack API responses
1327 mock_request.side_effect = [
1328 mock.Mock(
1329 **{
1330 "content": dumps(
1331 {
1332 "ok": True,
1333 "channel": "C123456",
1334 }
1335 ),
1336 "status_code": requests.codes.ok,
1337 }
1338 ),
1339 mock.Mock(
1340 **{
1341 "content": dumps(
1342 {
1343 "ok": True,
1344 "upload_url": "https://files.slack.com/upload/v1/ABC123",
1345 "file_id": "F123ABC456",
1346 }
1347 ),
1348 "status_code": requests.codes.ok,
1349 }
1350 ),
1351 mock.Mock(
1352 **{
1353 "content": b"OK - 123",
1354 "status_code": requests.codes.ok,
1355 }
1356 ),
1357 mock.Mock(
1358 **{
1359 "content": dumps(
1360 {
1361 "ok": True,
1362 "files": [
1363 {"id": "F123ABC456", "title": "apprise-test"}
1364 ],
1365 }
1366 ),
1367 "status_code": requests.codes.ok,
1368 }
1369 ),
1370 ]
1371
1372 obj = NotifySlack(access_token=token, targets=["#general"])
1373 assert (
1374 bool(
1375 obj.notify(
1376 body="Success path test",
1377 title="Slack Upload OK",
1378 notify_type=NotifyType.INFO,
1379 attach=attach,
1380 )
1381 )
1382 is True
1383 )
1384
1385
1386 @mock.patch("requests.request")
1387 def test_plugin_slack_failed_attachment_is_retried(mock_request):
1388 """An attachment failure does not repost the visible message."""
1389
1390 def response(data):
1391 return mock.Mock(
1392 content=dumps(data) if isinstance(data, dict) else data,
1393 status_code=requests.codes.ok,
1394 )
1395
1396 message = {"ok": True, "channel": "C123456"}
1397 upload = {
1398 "ok": True,
1399 "upload_url": "https://files.slack.com/upload/v1/ABC123",
1400 "file_id": "F123ABC456",
1401 }
1402 mock_request.side_effect = [
1403 response(message),
1404 response(upload),
1405 response(b"OK"),
1406 response({"ok": False}),
1407 ]
1408
1409 obj = NotifySlack(
1410 access_token="xoxb-1234-1234-abc124",
1411 targets=["#general"],
1412 )
1413 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
1414
1415 tracker_token = _delivery_tracker.set(set())
1416 try:
1417 assert obj.notify(body="body", attach=attach) is False
1418 assert obj.is_delivered(("message", "#general")) is True
1419
1420 assert obj.notify(body="body", attach=attach) is False
1421 assert not obj.is_delivered(("attachment", 1, ("message", "#general")))
1422 finally:
1423 _delivery_tracker.reset(tracker_token)
1424
1425 message_calls = [
1426 call
1427 for call in mock_request.call_args_list
1428 if call.args[1] == "https://slack.com/api/chat.postMessage"
1429 ]
1430 assert len(message_calls) == 1
1431
1432
1433 @mock.patch("requests.request")
1434 def test_plugin_slack_file_upload_fails_missing_files(mock_request):
1435 """Test that file upload fails when 'files' is missing or empty."""
1436
1437 token = "xoxb-1234-1234-abc124"
1438 path = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
1439 attach = AppriseAttachment(path)
1440
1441 # Mock sequence:
1442 # 1. chat.postMessage returns valid channel
1443 # 2. files.getUploadURLExternal returns file_id and upload_url
1444 # 3. Upload returns 'OK'
1445 # 4. files.completeUploadExternal returns missing/empty 'files'
1446
1447 mock_request.side_effect = [
1448 mock.Mock(
1449 **{
1450 "content": dumps(
1451 {
1452 "ok": True,
1453 "channel": "C555555",
1454 }
1455 ),
1456 "status_code": requests.codes.ok,
1457 }
1458 ),
1459 mock.Mock(
1460 **{
1461 "content": dumps(
1462 {
1463 "ok": True,
1464 "upload_url": "https://files.slack.com/upload/v1/X99999",
1465 "file_id": "F999XYZ888",
1466 }
1467 ),
1468 "status_code": requests.codes.ok,
1469 }
1470 ),
1471 mock.Mock(
1472 **{
1473 "content": b"OK - 2048",
1474 "status_code": requests.codes.ok,
1475 }
1476 ),
1477 # <== This response will trigger the error condition
1478 mock.Mock(
1479 **{
1480 "content": dumps(
1481 {
1482 "ok": True,
1483 "files": [],
1484 }
1485 ),
1486 "status_code": requests.codes.ok,
1487 }
1488 ),
1489 ]
1490
1491 obj = NotifySlack(access_token=token, targets=["#fail-channel"])
1492 result = obj.notify(
1493 body="This should trigger a failed file upload",
1494 title="Trigger failure",
1495 notify_type=NotifyType.INFO,
1496 attach=attach,
1497 )
1498
1499 assert result is False
1500
1501
1502 @mock.patch("requests.request")
1503 def test_plugin_slack_attach_memory(mock_request):
1504 """Regression: AttachMemory must be sendable without OSError."""
1505 from apprise.attachment.memory import AttachMemory
1506
1507 token = "xoxb-1234-1234-abc124"
1508
1509 mock_request.side_effect = [
1510 mock.Mock(
1511 **{
1512 "content": dumps({"ok": True, "channel": "C123456"}),
1513 "status_code": requests.codes.ok,
1514 }
1515 ),
1516 mock.Mock(
1517 **{
1518 "content": dumps(
1519 {
1520 "ok": True,
1521 "upload_url": "https://files.slack.com/upload/v1/ABC123",
1522 "file_id": "F123ABC456",
1523 }
1524 ),
1525 "status_code": requests.codes.ok,
1526 }
1527 ),
1528 mock.Mock(
1529 **{
1530 "content": b"OK - 100",
1531 "status_code": requests.codes.ok,
1532 }
1533 ),
1534 mock.Mock(
1535 **{
1536 "content": dumps(
1537 {
1538 "ok": True,
1539 "files": [{"id": "F123ABC456", "title": "report"}],
1540 }
1541 ),
1542 "status_code": requests.codes.ok,
1543 }
1544 ),
1545 ]
1546
1547 obj = NotifySlack(access_token=token, targets=["#general"])
1548
1549 mem = AttachMemory(
1550 content=b"<html><body><h1>Test</h1></body></html>",
1551 name="report.html",
1552 mimetype="text/html",
1553 )
1554
1555 assert bool(obj.notify(body="Test", attach=mem)) is True
1556 assert mock_request.call_count >= 1
1557
1558
1559 @mock.patch("requests.request")
1560 def test_plugin_slack_template_blocks(mock_request, tmpdir):
1561 """NotifySlack() - blocks mode with JSON template."""
1562 # Valid webhook mock response
1563 mock_request.return_value = mock.Mock(
1564 **{
1565 "content": b"ok",
1566 "status_code": requests.codes.ok,
1567 }
1568 )
1569
1570 # Write a minimal Block Kit JSON template to disk
1571 template = tmpdir.join("blocks.json")
1572 template.write(
1573 cleandoc("""
1574 {
1575 "blocks": [
1576 {
1577 "type": "header",
1578 "text": {
1579 "type": "plain_text",
1580 "text": "{{app_title}}"
1581 }
1582 },
1583 {
1584 "type": "section",
1585 "text": {
1586 "type": "mrkdwn",
1587 "text": "{{app_body}}"
1588 }
1589 }
1590 ],
1591 "color": "{{app_color}}"
1592 }
1593 """)
1594 )
1595
1596 # Instantiate via URL with blocks=yes and template path
1597 obj = Apprise.instantiate(
1598 "slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
1599 "?blocks=yes&template={}&:mykey=myval".format(str(template))
1600 )
1601 assert isinstance(obj, NotifySlack)
1602
1603 # Verify tokens and template were parsed correctly
1604 assert "mykey" in obj.tokens
1605 assert obj.tokens["mykey"] == "myval"
1606 assert obj.template
1607
1608 # Notification should succeed
1609 assert (
1610 bool(
1611 obj.notify(
1612 body="hello", title="world", notify_type=NotifyType.INFO
1613 )
1614 )
1615 is True
1616 )
1617 assert mock_request.called is True
1618
1619 # Inspect the posted payload
1620 posted = loads(mock_request.call_args_list[0][1]["data"])
1621 assert "attachments" in posted
1622 assert "blocks" in posted["attachments"][0]
1623 # Header and section blocks should be present
1624 blocks = posted["attachments"][0]["blocks"]
1625 assert any(b.get("type") == "header" for b in blocks)
1626 assert any(b.get("type") == "section" for b in blocks)
1627 # Title and body substituted correctly
1628 header = next(b for b in blocks if b.get("type") == "header")
1629 assert header["text"]["text"] == "world"
1630 section = next(b for b in blocks if b.get("type") == "section")
1631 assert section["text"]["text"] == "hello"
1632
1633
1634 @mock.patch("requests.request")
1635 def test_plugin_slack_template_blocks_implied(mock_request, tmpdir):
1636 """NotifySlack() - template= alone implies blocks=yes."""
1637 # Valid webhook mock response
1638 mock_request.return_value = mock.Mock(
1639 **{
1640 "content": b"ok",
1641 "status_code": requests.codes.ok,
1642 }
1643 )
1644
1645 template = tmpdir.join("implied.json")
1646 template.write(
1647 cleandoc("""
1648 {
1649 "blocks": [
1650 {
1651 "type": "section",
1652 "text": {"type": "mrkdwn", "text": "{{app_body}}"}
1653 }
1654 ]
1655 }
1656 """)
1657 )
1658
1659 # No blocks=yes in the URL -- should still use the template
1660 obj = Apprise.instantiate(
1661 "slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
1662 "?template={}".format(str(template))
1663 )
1664 assert isinstance(obj, NotifySlack)
1665 # use_blocks must have been forced on by the template
1666 assert obj.use_blocks is True
1667 assert (
1668 bool(
1669 obj.notify(body="implied", title="t", notify_type=NotifyType.INFO)
1670 )
1671 is True
1672 )
1673 assert mock_request.called is True
1674 posted = loads(mock_request.call_args_list[0][1]["data"])
1675 blocks = posted["attachments"][0]["blocks"]
1676 section = next(b for b in blocks if b.get("type") == "section")
1677 assert section["text"]["text"] == "implied"
1678
1679
1680 @mock.patch("requests.request")
1681 def test_plugin_slack_blocks_payload_uses_username(mock_request):
1682 """NotifySlack() - blocks payload includes explicit username."""
1683 mock_request.return_value = mock.Mock(
1684 **{"content": b"ok", "status_code": requests.codes.ok}
1685 )
1686
1687 obj = NotifySlack(
1688 token_a="T1JJ3T3L2",
1689 token_b="A1BRTD4JD",
1690 token_c="TIiajkdnlazkcOXrIdevi7FQ",
1691 use_blocks=True,
1692 user="BlockBot",
1693 )
1694
1695 assert obj.notify(body="hello", title="world", notify_type=NotifyType.INFO)
1696 payload = loads(mock_request.call_args.kwargs["data"])
1697 assert payload["username"] == "BlockBot"
1698
1699
1700 @mock.patch("requests.request")
1701 def test_plugin_slack_template_blocks_payload_uses_username(
1702 mock_request, tmpdir
1703 ):
1704 """NotifySlack() - template blocks payload includes explicit username."""
1705 mock_request.return_value = mock.Mock(
1706 **{"content": b"ok", "status_code": requests.codes.ok}
1707 )
1708
1709 template = tmpdir.join("username_blocks.json")
1710 template.write(
1711 cleandoc("""
1712 {
1713 "blocks": [
1714 {
1715 "type": "section",
1716 "text": {"type": "mrkdwn", "text": "{{app_body}}"}
1717 }
1718 ]
1719 }
1720 """)
1721 )
1722
1723 obj = NotifySlack(
1724 token_a="T1JJ3T3L2",
1725 token_b="A1BRTD4JD",
1726 token_c="TIiajkdnlazkcOXrIdevi7FQ",
1727 template=str(template),
1728 user="TemplateBot",
1729 )
1730
1731 assert obj.notify(body="hello", title="world", notify_type=NotifyType.INFO)
1732 payload = loads(mock_request.call_args.kwargs["data"])
1733 assert payload["username"] == "TemplateBot"
1734
1735
1736 @mock.patch("requests.request")
1737 def test_plugin_slack_template_blocks_no_username(mock_request, tmpdir):
1738 """NotifySlack() - template blocks omit username when no botname set."""
1739 mock_request.return_value = mock.Mock(
1740 **{"content": b"ok", "status_code": requests.codes.ok}
1741 )
1742
1743 template = tmpdir.join("no_username_blocks.json")
1744 template.write(
1745 cleandoc("""
1746 {
1747 "blocks": [
1748 {
1749 "type": "section",
1750 "text": {"type": "mrkdwn", "text": "{{app_body}}"}
1751 }
1752 ]
1753 }
1754 """)
1755 )
1756
1757 # Webhook mode with template and no botname should not force username,
1758 # allowing Slack's configured webhook identity to be used.
1759 obj = NotifySlack(
1760 token_a="T1JJ3T3L2",
1761 token_b="A1BRTD4JD",
1762 token_c="TIiajkdnlazkcOXrIdevi7FQ",
1763 template=str(template),
1764 )
1765
1766 assert obj.notify(body="hello", title="world", notify_type=NotifyType.INFO)
1767 payload = loads(mock_request.call_args.kwargs["data"])
1768 assert "username" not in payload
1769
1770
1771 @mock.patch("requests.request")
1772 def test_plugin_slack_template_invalid_json(mock_request, tmpdir):
1773 """NotifySlack() - blocks template with invalid JSON fails gracefully."""
1774 mock_request.return_value = mock.Mock(
1775 **{"content": b"ok", "status_code": requests.codes.ok}
1776 )
1777
1778 template = tmpdir.join("bad.json")
1779 template.write("{ not valid json }")
1780
1781 obj = Apprise.instantiate(
1782 "slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
1783 "?blocks=yes&template={}".format(str(template))
1784 )
1785 assert isinstance(obj, NotifySlack)
1786
1787 # Notification must fail due to bad JSON
1788 assert (
1789 bool(obj.notify(body="x", title="y", notify_type=NotifyType.INFO))
1790 is False
1791 )
1792 # No HTTP call should have been made
1793 assert mock_request.called is False
1794
1795
1796 @mock.patch("requests.request")
1797 def test_plugin_slack_template_blocks_not_list(mock_request, tmpdir):
1798 """NotifySlack() - blocks template where 'blocks' is not a list fails."""
1799 mock_request.return_value = mock.Mock(
1800 **{"content": b"ok", "status_code": requests.codes.ok}
1801 )
1802
1803 # 'blocks' present but not a list
1804 template = tmpdir.join("bad_blocks.json")
1805 template.write('{"blocks": "not-a-list"}')
1806
1807 obj = Apprise.instantiate(
1808 "slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
1809 "?blocks=yes&template={}".format(str(template))
1810 )
1811 assert isinstance(obj, NotifySlack)
1812 assert (
1813 bool(obj.notify(body="x", title="y", notify_type=NotifyType.INFO))
1814 is False
1815 )
1816 assert mock_request.called is False
1817
1818 # Empty list is also rejected
1819 template.write('{"blocks": []}')
1820 obj2 = Apprise.instantiate(
1821 "slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
1822 "?blocks=yes&template={}".format(str(template))
1823 )
1824 assert isinstance(obj2, NotifySlack)
1825 assert (
1826 bool(obj2.notify(body="x", title="y", notify_type=NotifyType.INFO))
1827 is False
1828 )
1829 assert mock_request.called is False
1830
1831
1832 @mock.patch("requests.request")
1833 def test_plugin_slack_template_block_missing_type(mock_request, tmpdir):
1834 """NotifySlack() - block missing 'type' string is rejected."""
1835 mock_request.return_value = mock.Mock(
1836 **{"content": b"ok", "status_code": requests.codes.ok}
1837 )
1838
1839 # Block present but has no 'type' key
1840 template = tmpdir.join("no_type.json")
1841 template.write('{"blocks": [{"text": {"type": "mrkdwn", "text": "hi"}}]}')
1842
1843 obj = Apprise.instantiate(
1844 "slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
1845 "?blocks=yes&template={}".format(str(template))
1846 )
1847 assert isinstance(obj, NotifySlack)
1848 assert (
1849 bool(obj.notify(body="x", title="y", notify_type=NotifyType.INFO))
1850 is False
1851 )
1852 assert mock_request.called is False
1853
1854
1855 @mock.patch("requests.request")
1856 def test_plugin_slack_template_load_error(mock_request, tmpdir):
1857 """NotifySlack() - template OSError during read fails gracefully."""
1858 mock_request.return_value = mock.Mock(
1859 **{"content": b"ok", "status_code": requests.codes.ok}
1860 )
1861
1862 # Write an empty file so the attachment resolves but open() can be mocked
1863 template = tmpdir.join("empty.json")
1864 template.write("")
1865
1866 obj = Apprise.instantiate(
1867 "slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
1868 "?blocks=yes&template={}".format(str(template))
1869 )
1870 assert isinstance(obj, NotifySlack)
1871
1872 with mock.patch("builtins.open", side_effect=OSError):
1873 # Notification must fail because the file cannot be read
1874 assert (
1875 bool(obj.notify(body="x", title="y", notify_type=NotifyType.INFO))
1876 is False
1877 )
1878 assert mock_request.called is False
1879
1880
1881 def test_plugin_slack_template_bad_tokens():
1882 """NotifySlack() rejects an invalid template token type."""
1883 with pytest.raises(AppriseImproperlyConfigured):
1884 NotifySlack(
1885 token_a="T1JJ3T3L2",
1886 token_b="A1BRTD4JD",
1887 token_c="TIiajkdnlazkcOXrIdevi7FQ",
1888 tokens="not-a-dict",
1889 )
1890
1891
1892 @mock.patch("requests.request")
1893 def test_plugin_slack_template_url_roundtrip(mock_request, tmpdir):
1894 """NotifySlack() - template + tokens survive url()/parse_url()
1895 round-trip."""
1896 mock_request.return_value = mock.Mock(
1897 **{"content": b"ok", "status_code": requests.codes.ok}
1898 )
1899
1900 template = tmpdir.join("rt.json")
1901 template.write(
1902 cleandoc("""
1903 {
1904 "blocks": [
1905 {
1906 "type": "section",
1907 "text": {"type": "mrkdwn", "text": "{{app_body}}"}
1908 }
1909 ]
1910 }
1911 """)
1912 )
1913
1914 # Build an instance with template and tokens
1915 obj1 = NotifySlack(
1916 token_a="T1JJ3T3L2",
1917 token_b="A1BRTD4JD",
1918 token_c="TIiajkdnlazkcOXrIdevi7FQ",
1919 use_blocks=True,
1920 template=str(template),
1921 tokens={"key1": "val1", "key2": "val2"},
1922 )
1923
1924 # Round-trip through url() -> parse_url()
1925 url = obj1.url()
1926 result = NotifySlack.parse_url(url)
1927 assert result is not None
1928
1929 obj2 = NotifySlack(**result)
1930 assert isinstance(obj2, NotifySlack)
1931
1932 # Connection identity must be preserved
1933 assert obj1.url_identifier == obj2.url_identifier
1934
1935 # Tokens must survive the round-trip
1936 assert obj2.tokens.get("key1") == "val1"
1937 assert obj2.tokens.get("key2") == "val2"
1938
1939 # Template must be present after round-trip
1940 assert obj2.template
1941
1942
1943 @mock.patch("requests.request")
1944 def test_plugin_slack_template_inaccessible(mock_request, tmpdir):
1945 """NotifySlack() - template attachment that cannot be accessed fails."""
1946 mock_request.return_value = mock.Mock(
1947 **{"content": b"ok", "status_code": requests.codes.ok}
1948 )
1949
1950 # Point to a template file that does not exist
1951 missing = str(tmpdir.join("missing.json"))
1952
1953 obj = Apprise.instantiate(
1954 "slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
1955 "?blocks=yes&template={}".format(missing)
1956 )
1957 assert isinstance(obj, NotifySlack)
1958
1959 # Template attachment resolves to falsy because the file is missing
1960 assert (
1961 bool(obj.notify(body="x", title="y", notify_type=NotifyType.INFO))
1962 is False
1963 )
1964 assert mock_request.called is False
1965
1966
1967 def test_plugin_slack_template_add_failure():
1968 """NotifySlack() rejects a template attachment it cannot add."""
1969 # Simulate add() silently failing (returns 0 / len stays 0)
1970 with mock.patch("apprise.plugins.slack.AppriseAttachment") as mock_cls:
1971 inst = mock.MagicMock()
1972 inst.__len__ = mock.Mock(return_value=0)
1973 mock_cls.return_value = inst
1974
1975 with pytest.raises(AppriseImproperlyConfigured):
1976 NotifySlack(
1977 token_a="T1JJ3T3L2",
1978 token_b="A1BRTD4JD",
1979 token_c="TIiajkdnlazkcOXrIdevi7FQ",
1980 template="file:///some/template.json",
1981 )
1982
1983
1984 @mock.patch("requests.request")
1985 def test_plugin_slack_template_content_not_dict(mock_request, tmpdir):
1986 """NotifySlack() - template that parses to a JSON array is rejected."""
1987 mock_request.return_value = mock.Mock(
1988 **{"content": b"ok", "status_code": requests.codes.ok}
1989 )
1990
1991 # Valid JSON but a list rather than an object
1992 template = tmpdir.join("array.json")
1993 template.write('[{"type": "section"}]')
1994
1995 obj = Apprise.instantiate(
1996 "slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
1997 "?template={}".format(str(template))
1998 )
1999 assert isinstance(obj, NotifySlack)
2000 assert (
2001 bool(obj.notify(body="x", title="y", notify_type=NotifyType.INFO))
2002 is False
2003 )
2004 assert mock_request.called is False
2005
2006
2007 @mock.patch("requests.request")
2008 def test_plugin_slack_template_block_not_dict(mock_request, tmpdir):
2009 """NotifySlack() - non-dict entry in blocks list is rejected."""
2010 mock_request.return_value = mock.Mock(
2011 **{"content": b"ok", "status_code": requests.codes.ok}
2012 )
2013
2014 # blocks list contains a string rather than a dict
2015 template = tmpdir.join("bad_block.json")
2016 template.write('{"blocks": ["not-a-dict"]}')
2017
2018 obj = Apprise.instantiate(
2019 "slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
2020 "?template={}".format(str(template))
2021 )
2022 assert isinstance(obj, NotifySlack)
2023 assert (
2024 bool(obj.notify(body="x", title="y", notify_type=NotifyType.INFO))
2025 is False
2026 )
2027 assert mock_request.called is False
2028
2029
2030 @mock.patch("requests.request")
2031 def test_plugin_slack_template_none_token_value(mock_request, tmpdir):
2032 """NotifySlack() - None token value (e.g. app_image_url) is coerced
2033 to empty string before JSON-escaping."""
2034 mock_request.return_value = mock.Mock(
2035 **{"content": b"ok", "status_code": requests.codes.ok}
2036 )
2037
2038 # Template references app_image_url which will be None when
2039 # include_image=False; old code produced corrupted JSON ("ul")
2040 template = tmpdir.join("img.json")
2041 template.write(
2042 '{"blocks": [{"type": "section",'
2043 ' "text": {"type": "mrkdwn",'
2044 ' "text": "{{app_body}} img={{app_image_url}}"}}]}'
2045 )
2046
2047 obj = Apprise.instantiate(
2048 "slack://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/"
2049 "?image=no&template={}".format(str(template))
2050 )
2051 assert isinstance(obj, NotifySlack)
2052 # Must succeed -- None coerced to "" keeps the JSON valid
2053 assert (
2054 bool(obj.notify(body="hello", title="t", notify_type=NotifyType.INFO))
2055 is True
2056 )
2057 assert mock_request.called is True
2058 payload = loads(mock_request.call_args_list[0][1]["data"])
2059 block_text = payload["attachments"][0]["blocks"][0]["text"]["text"]
2060 # app_image_url should expand to empty string, not "ul"
2061 assert "img=" in block_text
2062 assert "ul" not in block_text
2063
2064
2065 @mock.patch("requests.request")
2066 def test_plugin_slack_workflow_default_payload(mock_request):
2067 """NotifySlack() - Workflow Builder mode, default text payload."""
2068 mock_request.return_value = mock.Mock(
2069 **{"content": b"", "status_code": requests.codes.ok}
2070 )
2071
2072 # 4-segment /workflows/ path via mode=workflow
2073 obj = Apprise.instantiate(
2074 "slack://T1JJ3T3L2/Ft07XXXX/XXXXXXXX/YYYYYYYY/?mode=workflow"
2075 )
2076 assert isinstance(obj, NotifySlack)
2077 assert obj.mode == "workflow"
2078 assert obj.workflow_path == [
2079 "T1JJ3T3L2",
2080 "Ft07XXXX",
2081 "XXXXXXXX",
2082 "YYYYYYYY",
2083 ]
2084
2085 # Notification with title
2086 assert (
2087 bool(
2088 obj.notify(
2089 body="hello", title="Alert", notify_type=NotifyType.INFO
2090 )
2091 )
2092 is True
2093 )
2094 assert mock_request.called is True
2095 # Verify the POST URL uses the workflow base
2096 call_url = mock_request.call_args_list[0][0][1]
2097 assert "hooks.slack.com/workflows/" in call_url
2098 assert "T1JJ3T3L2/Ft07XXXX/XXXXXXXX/YYYYYYYY" in call_url
2099 # Verify default payload combines title and body
2100 posted = loads(mock_request.call_args_list[0][1]["data"])
2101 assert posted["text"] == "Alert: hello"
2102
2103 mock_request.reset_mock()
2104
2105 # Notification without title -- body only
2106 assert (
2107 bool(
2108 obj.notify(body="body only", title="", notify_type=NotifyType.INFO)
2109 )
2110 is True
2111 )
2112 posted = loads(mock_request.call_args_list[0][1]["data"])
2113 assert posted["text"] == "body only"
2114
2115
2116 @mock.patch("requests.request")
2117 def test_plugin_slack_workflow_trigger_mode(mock_request):
2118 """NotifySlack() - Workflow trigger mode (/triggers/ URL)."""
2119 mock_request.return_value = mock.Mock(
2120 **{"content": b"", "status_code": requests.codes.ok}
2121 )
2122
2123 # 3-segment /triggers/ path via mode=trigger
2124 obj = Apprise.instantiate(
2125 "slack://T1JJ3T3L2/XXXXXXXX/YYYYYYYY/?mode=trigger"
2126 )
2127 assert isinstance(obj, NotifySlack)
2128 assert obj.mode == "trigger"
2129 assert obj.workflow_path == ["T1JJ3T3L2", "XXXXXXXX", "YYYYYYYY"]
2130
2131 assert (
2132 bool(obj.notify(body="hi", title="", notify_type=NotifyType.INFO))
2133 is True
2134 )
2135 call_url = mock_request.call_args_list[0][0][1]
2136 assert "hooks.slack.com/triggers/" in call_url
2137 assert "T1JJ3T3L2/XXXXXXXX/YYYYYYYY" in call_url
2138
2139
2140 @mock.patch("requests.request")
2141 def test_plugin_slack_workflow_native_url(mock_request):
2142 """NotifySlack() - parse_native_url() handles workflow/trigger URLs."""
2143 mock_request.return_value = mock.Mock(
2144 **{"content": b"", "status_code": requests.codes.ok}
2145 )
2146
2147 # /workflows/ native URL
2148 obj = Apprise.instantiate(
2149 "https://hooks.slack.com/workflows"
2150 "/T1JJ3T3L2/Ft07XXXX/XXXXXXXX/YYYYYYYY"
2151 )
2152 assert isinstance(obj, NotifySlack)
2153 assert obj.mode == "workflow"
2154 assert obj.workflow_path == [
2155 "T1JJ3T3L2",
2156 "Ft07XXXX",
2157 "XXXXXXXX",
2158 "YYYYYYYY",
2159 ]
2160 assert (
2161 bool(obj.notify(body="native", title="", notify_type=NotifyType.INFO))
2162 is True
2163 )
2164 call_url = mock_request.call_args_list[0][0][1]
2165 assert "hooks.slack.com/workflows/T1JJ3T3L2" in call_url
2166
2167 mock_request.reset_mock()
2168
2169 # /triggers/ native URL
2170 obj2 = Apprise.instantiate(
2171 "https://hooks.slack.com/triggers/T1JJ3T3L2/XXXXXXXX/YYYYYYYY"
2172 )
2173 assert isinstance(obj2, NotifySlack)
2174 assert obj2.mode == "trigger"
2175 assert (
2176 bool(
2177 obj2.notify(body="trigger", title="", notify_type=NotifyType.INFO)
2178 )
2179 is True
2180 )
2181 call_url2 = mock_request.call_args_list[0][0][1]
2182 assert "hooks.slack.com/triggers/T1JJ3T3L2" in call_url2
2183
2184
2185 def test_plugin_slack_parse_native_url_invalid():
2186 """NotifySlack() - parse_native_url() returns None for non-Slack URLs."""
2187 assert (
2188 NotifySlack.parse_native_url(
2189 "https://hooks.slack.com/not-a-supported-path/T1JJ3T3L2"
2190 )
2191 is None
2192 )
2193
2194
2195 @mock.patch("requests.request")
2196 def test_plugin_slack_workflow_url_roundtrip(mock_request):
2197 """NotifySlack() - workflow url()/parse_url() round-trip."""
2198 mock_request.return_value = mock.Mock(
2199 **{"content": b"", "status_code": requests.codes.ok}
2200 )
2201
2202 original = "slack://T1JJ3T3L2/Ft07XXXX/XXXXXXXX/YYYYYYYY/?mode=workflow"
2203 obj = Apprise.instantiate(original)
2204 assert isinstance(obj, NotifySlack)
2205
2206 # Reconstruct from url() output and re-instantiate
2207 rebuilt = Apprise.instantiate(obj.url())
2208 assert isinstance(rebuilt, NotifySlack)
2209 assert rebuilt.mode == obj.mode
2210 assert rebuilt.workflow_path == obj.workflow_path
2211
2212
2213 def test_plugin_slack_workflow_invalid_path():
2214 """NotifySlack() rejects workflow paths with the wrong segment count."""
2215 from apprise.plugins.slack import NotifySlack as _NS
2216
2217 # Too few segments for explicit workflow mode (needs 4)
2218 with pytest.raises(AppriseImproperlyConfigured):
2219 _NS(workflow_path=["T1JJ3T3L2", "XXXXXXXX"], mode="workflow")
2220
2221 # Trigger's 3 segments rejected when mode=workflow is explicit
2222 with pytest.raises(AppriseImproperlyConfigured):
2223 _NS(
2224 workflow_path=["T1JJ3T3L2", "XXXXXXXX", "YYYYYYYY"],
2225 mode="workflow",
2226 )
2227
2228 # Workflow's 4 segments rejected when mode=trigger is explicit
2229 with pytest.raises(AppriseImproperlyConfigured):
2230 _NS(
2231 workflow_path=["T1JJ3T3L2", "Ft07XXXX", "XXXXXXXX", "YYYY"],
2232 mode="trigger",
2233 )
2234
2235 # Empty path -- must raise (auto-detect path, 0 segments)
2236 with pytest.raises(AppriseImproperlyConfigured):
2237 _NS(workflow_path=[], mode="workflow")
2238
2239 # Non-string / non-list type (else branch) -- 0 segments, must raise
2240 with pytest.raises(AppriseImproperlyConfigured):
2241 _NS(workflow_path=42, mode="workflow")
2242
2243 # Auto-detect: 4 segments -> WORKFLOW
2244 obj = _NS(workflow_path=["T1JJ3T3L2", "Ft07XXXX", "XXXXXXXX", "YYY"])
2245 assert obj.mode == "workflow"
2246 assert obj.workflow_path == ["T1JJ3T3L2", "Ft07XXXX", "XXXXXXXX", "YYY"]
2247
2248 # Auto-detect: 3 segments -> WORKFLOW_TRIGGER
2249 obj = _NS(workflow_path=["T1JJ3T3L2", "XXXXXXXX", "YYYYYYYY"])
2250 assert obj.mode == "trigger"
2251 assert obj.workflow_path == ["T1JJ3T3L2", "XXXXXXXX", "YYYYYYYY"]
2252
2253 # Auto-detection requires either three or four segments.
2254 with pytest.raises(AppriseImproperlyConfigured):
2255 _NS(workflow_path=["T1JJ3T3L2", "XXXXXXXX"])
2256
2257
2258 @mock.patch("requests.request")
2259 def test_plugin_slack_workflow_template(mock_request, tmpdir):
2260 """NotifySlack() - Workflow mode with Block Kit JSON template."""
2261 mock_request.return_value = mock.Mock(
2262 **{"content": b"", "status_code": requests.codes.ok}
2263 )
2264
2265 template = tmpdir.join("wf_blocks.json")
2266 template.write(
2267 cleandoc("""
2268 {
2269 "blocks": [
2270 {
2271 "type": "section",
2272 "text": {"type": "mrkdwn", "text": "{{app_body}}"}
2273 }
2274 ]
2275 }
2276 """)
2277 )
2278
2279 obj = Apprise.instantiate(
2280 "slack://T1JJ3T3L2/Ft07XXXX/XXXXXXXX/YYYYYYYY/"
2281 "?mode=workflow&template={}".format(str(template))
2282 )
2283 assert isinstance(obj, NotifySlack)
2284 assert obj.mode == "workflow"
2285 assert (
2286 bool(obj.notify(body="wf-tmpl", title="", notify_type=NotifyType.INFO))
2287 is True
2288 )
2289 assert mock_request.called is True
2290 call_url = mock_request.call_args_list[0][0][1]
2291 assert "hooks.slack.com/workflows/" in call_url
2292 posted = loads(mock_request.call_args_list[0][1]["data"])
2293 blocks = posted["blocks"]
2294 section = next(b for b in blocks if b.get("type") == "section")
2295 assert section["text"]["text"] == "wf-tmpl"
2296
2297 # Invalid JSON template -- gen_payload() fails, send() returns False
2298 bad_template = tmpdir.join("bad.json")
2299 bad_template.write("not-json!")
2300 obj2 = Apprise.instantiate(
2301 "slack://T1JJ3T3L2/Ft07XXXX/XXXXXXXX/YYYYYYYY/"
2302 "?mode=workflow&template={}".format(str(bad_template))
2303 )
2304 assert isinstance(obj2, NotifySlack)
2305 assert (
2306 bool(obj2.notify(body="x", title="", notify_type=NotifyType.INFO))
2307 is False
2308 )
2309 assert mock_request.call_count == 1 # no new request made
2310
2311
2312 @mock.patch("requests.request")
2313 def test_plugin_slack_html_to_markdown_format(mock_request):
2314 """NotifySlack(): HTML body is converted to Markdown."""
2315
2316 # Use the classic incoming webhook token format
2317 slack_token = "T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ"
2318
2319 # Slack's _send() uses requests.request(), not requests.post();
2320 # webhook mode confirms success via content == b"ok"
2321 mock_request.return_value = requests.Request()
2322 mock_request.return_value.status_code = requests.codes.ok
2323 mock_request.return_value.content = b"ok"
2324 mock_request.return_value.text = "ok"
2325
2326 # Instantiate a Slack plugin (notify_format is MARKDOWN by default)
2327 aobj = Apprise()
2328 assert aobj.add("slack://{}/#general".format(slack_token))
2329
2330 # Notify with an HTML body; the framework should convert it
2331 # to Markdown before dispatching to Slack
2332 assert (
2333 bool(
2334 aobj.notify(
2335 body="<b>hello</b> <i>world</i>",
2336 body_format=NotifyFormat.HTML,
2337 )
2338 )
2339 is True
2340 )
2341 assert mock_request.call_count == 1
2342
2343 # The body must arrive as Markdown in the legacy attachment text, not as
2344 # stripped plain text.
2345 payload = loads(mock_request.call_args_list[0][1]["data"])
2346 assert payload["attachments"][0]["text"] == "*hello* _world_"
2347
2348 mock_request.reset_mock()
2349
2350 # Convert CommonMark links to Slack's ``<url|text>`` syntax.
2351 assert (
2352 bool(
2353 aobj.notify(
2354 body='<a href="https://example.com/x">click here</a>',
2355 body_format=NotifyFormat.HTML,
2356 )
2357 )
2358 is True
2359 )
2360 payload = loads(mock_request.call_args_list[0][1]["data"])
2361 assert (
2362 payload["attachments"][0]["text"]
2363 == "<https://example.com/x|click here>"
2364 )
2365
2366 mock_request.reset_mock()
2367
2368 # '&'/'<'/'>' need Slack's HTML-entity escaping, not CommonMark's backslash
2369 # escaping (which Slack doesn't support for these and would otherwise.
2370 assert (
2371 bool(
2372 aobj.notify(
2373 body="<p>2 &lt; 3 &amp; 4</p>",
2374 body_format=NotifyFormat.HTML,
2375 )
2376 )
2377 is True
2378 )
2379 payload = loads(mock_request.call_args_list[0][1]["data"])
2380 assert payload["attachments"][0]["text"] == "2 &lt; 3 &amp; 4"
2381
2382 mock_request.reset_mock()
2383
2384 # Direct Slack mrkdwn input remains unchanged.
2385 assert (
2386 bool(aobj.notify(body="**already** slack-bound markdown #tag")) is True
2387 )
2388 payload = loads(mock_request.call_args_list[0][1]["data"])
2389 assert (
2390 payload["attachments"][0]["text"]
2391 == "**already** slack-bound markdown #tag"
2392 )
2393
2394
2395 @mock.patch("requests.request")
2396 def test_plugin_slack_markdown_dialect_requires_declared_source(
2397 mock_request,
2398 ):
2399 """Slack dialect conversion requires a declared source format."""
2400
2401 slack_token = "T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ"
2402
2403 mock_request.return_value = requests.Request()
2404 mock_request.return_value.status_code = requests.codes.ok
2405 mock_request.return_value.content = b"ok"
2406 mock_request.return_value.text = "ok"
2407
2408 aobj = Apprise()
2409 assert aobj.add("slack://{}/#general?blocks=yes".format(slack_token))
2410
2411 body = "**hello** &amp; <world>"
2412
2413 def block_text(payload):
2414 return payload["attachments"][0]["blocks"][0]["text"]["text"]
2415
2416 # Declared Markdown is translated to Slack mrkdwn.
2417 assert bool(aobj.notify(body=body, body_format=NotifyFormat.MARKDOWN))
2418 payload = loads(mock_request.call_args_list[0][1]["data"])
2419 assert block_text(payload) == "*hello* &amp;amp; <world>"
2420 mock_request.reset_mock()
2421
2422 # This undeclared body reaches Slack without dialect conversion.
2423 assert bool(aobj.notify(body=body))
2424 payload = loads(mock_request.call_args_list[0][1]["data"])
2425 assert block_text(payload) == body
2426 mock_request.reset_mock()
2427
2428 # Slack's declared plain-text format needs no dialect conversion.
2429 assert bool(aobj.notify(body=body, body_format=NotifyFormat.TEXT))
2430 payload = loads(mock_request.call_args_list[0][1]["data"])
2431 assert block_text(payload) == body
2432
2433
2434 def test_plugin_slack_bare_link_and_autolink_dialect():
2435 """Bare-paren links and standalone autolinks convert safely."""
2436
2437 # Bare destinations convert without treating URL punctuation as emphasis.
2438 assert (
2439 NotifySlack._commonmark_to_slack("[click here](https://a*b)")
2440 == "<https://a*b|click here>"
2441 )
2442
2443 # Complete autolinks become Slack's unlabeled anchors.
2444 assert (
2445 NotifySlack._commonmark_to_slack("see <https://a*b> now")
2446 == "see <https://a*b> now"
2447 )
2448
2449 # A "<" that never forms a valid scheme is passed through literally.
2450 assert NotifySlack._commonmark_to_slack("a < b") == "a < b"
2451
2452
2453 def test_plugin_slack_nested_angle_link():
2454 """Keep the outer link when a nested angle link is invalid."""
2455
2456 # Retire only the invalid inner label so the outer link still converts.
2457 body = "[OUTER [INNER](<badstuff)](https://example.com)"
2458 assert NotifySlack._commonmark_to_slack(body) == (
2459 "<https://example.com|OUTER [INNER](<badstuff)>"
2460 )
2461
2462
2463 def test_plugin_slack_stray_bracket_retires_opener():
2464 """A "]" with no "(" must retire its "[" instead of leaving it
2465 pending for a later, unrelated link to reuse."""
2466
2467 # No "(" ever follows the first "]", so "[label]" is not a link and
2468 # must not be spliced into the later, unrelated "](https://...)".
2469 body = "[label] and ](https://example.com) end"
2470 assert (
2471 NotifySlack._commonmark_to_slack(body)
2472 == "[label] and ](https://example.com) end"
2473 )
2474
2475
2476 @mock.patch("requests.request")
2477 def test_plugin_slack_html_blockquote_heading(mock_request):
2478 """Render an HTML blockquote heading as quoted, bold Slack text.
2479
2480 Use ``Apprise`` to exercise the complete HTML-to-Slack conversion path.
2481 """
2482 mock_request.return_value = requests.Request()
2483 mock_request.return_value.status_code = requests.codes.ok
2484 mock_request.return_value.content = b"ok"
2485 mock_request.return_value.text = "ok"
2486
2487 token_a = "A" * 9
2488 token_b = "B" * 9
2489 token_c = "c" * 24
2490
2491 obj = NotifySlack(token_a=token_a, token_b=token_b, token_c=token_c)
2492 aobj = Apprise()
2493 assert aobj.add(obj) is True
2494 assert bool(
2495 aobj.notify(
2496 body="<blockquote><h2>Alert</h2><p>body</p></blockquote>",
2497 body_format=NotifyFormat.HTML,
2498 )
2499 )
2500
2501 payload = loads(mock_request.call_args_list[0][1]["data"])
2502 assert payload["attachments"][0]["text"] == "> *Alert*\n> body"
2503
2504
2505 def test_plugin_slack_dialect_long_link_destination():
2506 """Convert long links while bounding aggregate destination scanning."""
2507 for size in (4092, 4096, 4100, 50000):
2508 url = "a" * size
2509 body = f"[label](<{url}>)"
2510 result = NotifySlack._commonmark_to_slack(body)
2511 assert result == f"<{url}|label>", f"failed at size={size}"
2512
2513
2514 def test_plugin_slack_scan_budget_preserves_later_links():
2515 """Preserve nearby links after malformed scans exhaust the shared
2516 budget."""
2517 # A handful of malformed prefixes must not prevent a later link from
2518 # converting.
2519 body = (
2520 "".join(f"[bad{i}](" + ("x" * 1000) for i in range(8)) + "[good](ok)"
2521 )
2522 assert NotifySlack._commonmark_to_slack(body).endswith("<ok|good>")
2523
2524 # Scale beyond the shared budget while preserving the trailing link.
2525 times = []
2526 for count in (500, 2000, 8000):
2527 body = (
2528 "".join(f"[bad{i}](" + ("x" * 100) for i in range(count))
2529 + "[good](ok)"
2530 )
2531 start = default_timer()
2532 result = NotifySlack._commonmark_to_slack(body)
2533 times.append(default_timer() - start)
2534 assert result.endswith("<ok|good>")
2535
2536 # A fourfold input increase should remain well below quadratic growth.
2537 assert times[1] < times[0] * 4 * 3
2538 assert times[2] < times[1] * 4 * 3
2539
2540
2541 def test_plugin_slack_dialect_scan_allowance_boundary():
2542 """The fallback scan must leave room for a URL's closing characters.
2543
2544 Malformed prefixes spend the shared budget, forcing the final URL to use
2545 only the fixed fallback allowance.
2546 """
2547 prefix = "".join(f"[bad{i}](" + ("x" * 1000) for i in range(8))
2548
2549 # Angle URLs need enough fallback space for both the content and ``>)``.
2550 for size, should_convert in ((255, True), (256, True), (257, False)):
2551 url = "a" * size
2552 body = prefix + f"[label](<{url}>)"
2553 result = NotifySlack._commonmark_to_slack(body)
2554 assert result.endswith(f"<{url}|label>") == should_convert, (
2555 f"angle destination size={size}"
2556 )
2557
2558 # Bare destinations: the ")" terminator must fit the same way.
2559 for size, should_convert in ((255, True), (256, True), (257, False)):
2560 url = "a" * size
2561 body = prefix + f"[label]({url})"
2562 result = NotifySlack._commonmark_to_slack(body)
2563 assert result.endswith(f"<{url}|label>") == should_convert, (
2564 f"bare destination size={size}"
2565 )
2566
2567
2568 @mock.patch("requests.request")
2569 def test_plugin_slack_html_to_markdown_hardening(mock_request):
2570 """Test edge cases in the CommonMark-to-Slack dialect adaptation."""
2571
2572 slack_token = "T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ"
2573
2574 mock_request.return_value = requests.Request()
2575 mock_request.return_value.status_code = requests.codes.ok
2576 mock_request.return_value.content = b"ok"
2577 mock_request.return_value.text = "ok"
2578
2579 def notify(body):
2580 """Send one HTML body through the configured Slack plugin."""
2581 aobj = Apprise()
2582 assert aobj.add("slack://{}/#general".format(slack_token))
2583 assert (
2584 bool(aobj.notify(body=body, body_format=NotifyFormat.HTML)) is True
2585 )
2586 payload = loads(mock_request.call_args_list[-1][1]["data"])
2587 mock_request.reset_mock()
2588 return payload["attachments"][0]["text"]
2589
2590 # <code>/<pre> content is buffered raw by html_to_markdown.
2591 assert notify("<code>a &lt; b &amp; c</code>") == "`a &lt; b &amp; c`"
2592
2593 # CommonMark reads the combined "***...***" runs as italic around bold.
2594 assert notify("<b><i>x</i></b>") == "_*x*_"
2595
2596 # Bold/italic text nested inside a link is preserved in Slack's own
2597 # "<url|text>" form.
2598 assert (
2599 notify('<a href="https://example.com/x"><b>click</b></a>')
2600 == "<https://example.com/x|*click*>"
2601 )
2602
2603 # CommonMark keeps the ambiguous middle run literal inside one bold span.
2604 assert notify("<b>A</b><b>B</b>") == "*A****B*"
2605
2606 # Entity-escape Slack control characters in link destinations.
2607 assert (
2608 notify('<a href="https://e/x>TAIL">click</a>')
2609 == "<https://e/x&gt;TAIL|click>"
2610 )
2611 assert (
2612 notify('<a href="https://e/x?a=1&b=2">click</a>')
2613 == "<https://e/x?a=1&amp;b=2|click>"
2614 )
2615
2616 # '|' has no entity form and is what separates the URL from its label in
2617 # Slack's own syntax.
2618 assert (
2619 notify('<a href="https://e/x|evil">click</a>')
2620 == "<https://e/x%7Cevil|click>"
2621 )
2622
2623 # A literal "\x02<digits>\x02"-shaped sequence in ordinary text must pass
2624 # through completely unaltered.
2625 assert notify("literal \x020\x02 text, no code or links at all") == (
2626 "literal \x020\x02 text, no code or links at all"
2627 )
2628
2629 # An unmatched (unbalanced) bare backtick run.
2630 assert NotifySlack._commonmark_to_slack("text ``unterminated") == (
2631 "text ``unterminated"
2632 )
2633
2634 # Preserve an opener with no closer.
2635 assert NotifySlack._commonmark_to_slack("****x") == "****x"
2636
2637 # User-supplied Private Use characters must not collide with internal
2638 # emphasis placeholders. ``chr()`` keeps the invisible value explicit.
2639 f = NotifySlack._commonmark_to_slack
2640 marker = chr(0xE000)
2641 attack = f"before {marker}0{marker} after"
2642 assert f(attack) == attack
2643 assert f(f"*bold* {attack}") == f"_bold_ {attack}"
2644
2645 # overflow=split can hand this method just one chunk of a longer body, with
2646 # a span that doesn't open or close until a different chunk entirely.
2647 aobj = Apprise()
2648 assert aobj.add("slack://{}/#general?overflow=split".format(slack_token))
2649 assert (
2650 bool(
2651 aobj.notify(
2652 body="<b>" + ("x" * 39990) + "</b>",
2653 body_format=NotifyFormat.HTML,
2654 )
2655 )
2656 is True
2657 )
2658 assert mock_request.call_count == 2
2659 texts = [
2660 loads(c[1]["data"])["attachments"][0]["text"]
2661 for c in mock_request.call_args_list
2662 ]
2663 for text in texts:
2664 assert text.count("*") % 2 == 0
2665 assert text.count("_") % 2 == 0
2666
2667 # Every backslash-escape branch of the main scan: '>' becomes an HTML
2668 # entity, '(', ')', '[', ']', '!', '#' have their backslash dropped (none
2669 assert (
2670 NotifySlack._commonmark_to_slack(
2671 "a\\>b\\(c\\)d\\[e\\]f\\!g\\#h\\*i\\_j\\~k\\\\l"
2672 )
2673 == "a&gt;b(c)d[e]f!g#h\\*i\\_j\\~k\\\\l"
2674 )
2675
2676 # A '[' with no matching "](<url>)" close at all by the time the scan ends
2677 # (e.g.
2678 assert (
2679 NotifySlack._commonmark_to_slack("[text](<https://incomplete")
2680 == "[text](<https://incomplete"
2681 )
2682
2683
2684 @mock.patch("requests.request")
2685 def test_plugin_slack_dialect_overflow(mock_request):
2686 """Reapply Slack overflow limits after ``mrkdwn`` expansion.
2687
2688 The framework resizes converted output before calling ``send()``.
2689 """
2690
2691 slack_token = "T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ"
2692
2693 mock_request.return_value = requests.Request()
2694 mock_request.return_value.status_code = requests.codes.ok
2695 mock_request.return_value.content = b"ok"
2696 mock_request.return_value.text = "ok"
2697
2698 def notify(overflow):
2699 aobj = Apprise()
2700 assert aobj.add(f"slack://{slack_token}/#general?overflow={overflow}")
2701 # Each "&" expands to "&amp;" once entity-escaped, so this body
2702 # fits comfortably before dialect conversion but not after it.
2703 assert aobj.notify(
2704 body="& " * 10000, body_format=NotifyFormat.MARKDOWN
2705 )
2706 texts = [
2707 loads(c[1]["data"])["attachments"][0]["text"]
2708 for c in mock_request.call_args_list
2709 ]
2710 mock_request.reset_mock()
2711 return texts
2712
2713 # UPSTREAM: sent oversized rather than adjusted.
2714 texts = notify("upstream")
2715 assert len(texts) == 1
2716 assert len(texts[0]) > NotifySlack.body_maxlen
2717
2718 # TRUNCATE: clipped to fit in one message.
2719 texts = notify("truncate")
2720 assert len(texts) == 1
2721 assert len(texts[0]) <= NotifySlack.body_maxlen
2722
2723 # SPLIT preserves every escaped entity; framework chunking may trim
2724 # whitespace exactly at a boundary.
2725 texts = notify("split")
2726 assert len(texts) > 1
2727 assert all(len(text) <= NotifySlack.body_maxlen for text in texts)
2728 assert "".join(texts).count("&amp;") == 10000
2729
2730
2731 def test_plugin_slack_parse_native_url_fallthrough():
2732 """parse_native_url() returns None for unrecognized URLs."""
2733
2734 # A URL that doesn't match any known Slack pattern should yield None.
2735 assert (
2736 NotifySlack.parse_native_url(
2737 "https://not-slack.com/services/ABC/DEF/GHI"
2738 )
2739 is None
2740 )