Debian Codegraph @

tests/test_plugin_discord.py

raw symbols SCIP
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28 from datetime import datetime, timedelta, timezone
29 from json import loads
30
31 # Disable logging for a cleaner testing output
32 import logging
33 import os
34 from random import choice
35 from string import ascii_uppercase as str_alpha, digits as str_num
36 from unittest import mock
37
38 from helpers import AppriseURLTester
39 import pytest
40 import requests
41
42 from apprise import Apprise, AppriseAttachment, NotifyFormat, NotifyType
43 from apprise.common import OverflowMode
44 from apprise.plugins.discord import NotifyDiscord
45
46 logging.disable(logging.CRITICAL)
47
48 # Attachment Directory
49 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
50
51 # Our Testing URLs
52 apprise_url_tests = (
53 (
54 "discord://",
55 {
56 "instance": TypeError,
57 },
58 ),
59 # An invalid url
60 (
61 "discord://:@/",
62 {
63 "instance": TypeError,
64 },
65 ),
66 # No webhook_token specified
67 (
68 "discord://%s" % ("i" * 24),
69 {
70 "instance": TypeError,
71 },
72 ),
73 # Provide both an webhook id and a webhook token
74 (
75 "discord://{}/{}".format("i" * 24, "t" * 64),
76 {
77 "instance": NotifyDiscord,
78 "requests_response_code": requests.codes.no_content,
79 },
80 ),
81 # Provide a temporary username
82 (
83 "discord://l2g@{}/{}".format("i" * 24, "t" * 64),
84 {
85 "instance": NotifyDiscord,
86 "requests_response_code": requests.codes.no_content,
87 },
88 ),
89 # test image= field
90 (
91 "discord://{}/{}?format=markdown&footer=Yes&image=Yes&ping=Joe".format(
92 "i" * 24, "t" * 64
93 ),
94 {
95 "instance": NotifyDiscord,
96 "requests_response_code": requests.codes.no_content,
97 # don't include an image by default
98 "include_image": False,
99 },
100 ),
101 (
102 "discord://{}/{}?format=markdown&footer=Yes&image=No&fields=no".format(
103 "i" * 24, "t" * 64
104 ),
105 {
106 "instance": NotifyDiscord,
107 "requests_response_code": requests.codes.no_content,
108 },
109 ),
110 (
111 "discord://jack@{}/{}?format=markdown&footer=Yes&image=Yes".format(
112 "i" * 24, "t" * 64
113 ),
114 {
115 "instance": NotifyDiscord,
116 "requests_response_code": requests.codes.no_content,
117 "privacy_url": "discord://[email protected]/t...t/",
118 },
119 ),
120 (
121 "https://discord.com/api/webhooks/{}/{}".format("0" * 10, "B" * 40),
122 {
123 # Native URL Support, support the provided discord URL from their
124 # webpage.
125 "instance": NotifyDiscord,
126 "requests_response_code": requests.codes.no_content,
127 },
128 ),
129 (
130 "https://discordapp.com/api/webhooks/{}/{}".format("0" * 10, "B" * 40),
131 {
132 # Legacy Native URL Support, support the older URL (to be
133 # decomissioned on Nov 7th 2020)
134 "instance": NotifyDiscord,
135 "requests_response_code": requests.codes.no_content,
136 },
137 ),
138 (
139 "https://discordapp.com/api/webhooks/{}/{}?footer=yes".format(
140 "0" * 10, "B" * 40
141 ),
142 {
143 # Native URL Support with arguments
144 "instance": NotifyDiscord,
145 "requests_response_code": requests.codes.no_content,
146 "privacy_url": "discord://0...0/B...B/",
147 },
148 ),
149 (
150 "https://discordapp.com/api/webhooks/{}/{}?footer=yes&botname=joe".format(
151 "0" * 10, "B" * 40
152 ),
153 {
154 # Native URL Support with arguments
155 "instance": NotifyDiscord,
156 "requests_response_code": requests.codes.no_content,
157 "privacy_url": "discord://[email protected]/B...B/",
158 },
159 ),
160 (
161 "discord://{}/{}?format=markdown&avatar=No&footer=No".format(
162 "i" * 24, "t" * 64
163 ),
164 {
165 "instance": NotifyDiscord,
166 "requests_response_code": requests.codes.no_content,
167 },
168 ),
169 (
170 "discord://{}/{}?flags=1".format("i" * 24, "t" * 64),
171 {
172 "instance": NotifyDiscord,
173 "requests_response_code": requests.codes.no_content,
174 },
175 ),
176 (
177 "discord://{}/{}?flags=-1".format("i" * 24, "t" * 64),
178 {
179 # invalid flags specified (variation 1)
180 "instance": TypeError,
181 },
182 ),
183 (
184 "discord://{}/{}?flags=invalid".format("i" * 24, "t" * 64),
185 {
186 # invalid flags specified (variation 2)
187 "instance": TypeError,
188 },
189 ),
190 # different format support
191 (
192 "discord://{}/{}?format=markdown".format("i" * 24, "t" * 64),
193 {
194 "instance": NotifyDiscord,
195 "requests_response_code": requests.codes.no_content,
196 },
197 ),
198 # Thread ID
199 (
200 "discord://{}/{}?format=markdown&thread=abc123".format(
201 "i" * 24, "t" * 64
202 ),
203 {
204 "instance": NotifyDiscord,
205 "requests_response_code": requests.codes.no_content,
206 },
207 ),
208 (
209 "discord://{}/{}?format=text".format("i" * 24, "t" * 64),
210 {
211 "instance": NotifyDiscord,
212 "requests_response_code": requests.codes.no_content,
213 },
214 ),
215 # Test with href (title link)
216 (
217 "discord://{}/{}?hmarkdown=true&ref=http://localhost".format(
218 "i" * 24, "t" * 64
219 ),
220 {
221 "instance": NotifyDiscord,
222 "requests_response_code": requests.codes.no_content,
223 },
224 ),
225 # Test with url (title link) - Alias of href
226 (
227 "discord://{}/{}?markdown=true&url=http://localhost".format(
228 "i" * 24, "t" * 64
229 ),
230 {
231 "instance": NotifyDiscord,
232 "requests_response_code": requests.codes.no_content,
233 },
234 ),
235 # Test with avatar URL
236 (
237 "discord://{}/{}?avatar_url=http://localhost/test.jpg".format(
238 "i" * 24, "t" * 64
239 ),
240 {
241 "instance": NotifyDiscord,
242 "requests_response_code": requests.codes.no_content,
243 },
244 ),
245 # Test without image set
246 (
247 "discord://{}/{}".format("i" * 24, "t" * 64),
248 {
249 "instance": NotifyDiscord,
250 "requests_response_code": requests.codes.no_content,
251 # don't include an image by default
252 "include_image": False,
253 },
254 ),
255 # Test batch attachment mode enabled (default)
256 (
257 "discord://{}/{}?batch=yes".format("i" * 24, "t" * 64),
258 {
259 "instance": NotifyDiscord,
260 "requests_response_code": requests.codes.no_content,
261 },
262 ),
263 # Test batch attachment mode disabled (legacy one-per-message)
264 (
265 "discord://{}/{}?batch=no".format("i" * 24, "t" * 64),
266 {
267 "instance": NotifyDiscord,
268 "requests_response_code": requests.codes.no_content,
269 },
270 ),
271 (
272 "discord://{}/{}/".format("a" * 24, "b" * 64),
273 {
274 "instance": NotifyDiscord,
275 # force a failure
276 "response": False,
277 "requests_response_code": requests.codes.internal_server_error,
278 },
279 ),
280 (
281 "discord://{}/{}/".format("a" * 24, "b" * 64),
282 {
283 "instance": NotifyDiscord,
284 # throw a bizarre code forcing us to fail to look it up
285 "response": False,
286 "requests_response_code": 999,
287 },
288 ),
289 (
290 "discord://{}/{}/".format("a" * 24, "b" * 64),
291 {
292 "instance": NotifyDiscord,
293 # Throws a series of i/o exceptions with this flag
294 # is set and tests that we gracefully handle them
295 "test_requests_exceptions": True,
296 },
297 ),
298 )
299
300
301 def test_plugin_discord_urls():
302 """NotifyDiscord() Apprise URLs."""
303
304 # Run our general tests
305 AppriseURLTester(tests=apprise_url_tests).run_all()
306
307
308 @mock.patch("requests.post")
309 def test_plugin_discord_notifications(mock_post):
310 """NotifyDiscord() Notifications/Ping Support."""
311
312 # Initialize some generic (but valid) tokens
313 webhook_id = "A" * 24
314 webhook_token = "B" * 64
315
316 # Prepare Mock
317 mock_post.return_value = requests.Request()
318 mock_post.return_value.status_code = requests.codes.ok
319
320 # Test our header parsing when not lead with a header
321 body = """
322 # Heading
323 @everyone and @admin, wake and meet our new user <@123>; <@&456>"
324 """
325
326 results = NotifyDiscord.parse_url(
327 f"discord://{webhook_id}/{webhook_token}/?format=markdown"
328 )
329
330 assert isinstance(results, dict)
331 assert results["user"] is None
332 assert results["webhook_id"] == webhook_id
333 assert results["webhook_token"] == webhook_token
334 assert results["password"] is None
335 assert results["port"] is None
336 assert results["host"] == webhook_id
337 assert results["fullpath"] == f"/{webhook_token}/"
338 assert results["path"] == f"/{webhook_token}/"
339 assert results["query"] is None
340 assert results["schema"] == "discord"
341 assert results["url"] == f"discord://{webhook_id}/{webhook_token}/"
342
343 instance = NotifyDiscord(**results)
344 assert isinstance(instance, NotifyDiscord)
345
346 response = instance.send(body=body)
347 assert response is True
348 assert mock_post.call_count == 1
349
350 details = mock_post.call_args_list[0]
351 assert (
352 details[0][0]
353 == f"https://discord.com/api/webhooks/{webhook_id}/{webhook_token}"
354 )
355
356 payload = loads(details[1]["data"])
357
358 assert "allow_mentions" in payload
359 assert "users" in payload["allow_mentions"]
360 assert len(payload["allow_mentions"]["users"]) == 1
361 assert "123" in payload["allow_mentions"]["users"]
362 assert "roles" in payload["allow_mentions"]
363 assert len(payload["allow_mentions"]["roles"]) == 1
364 assert "456" in payload["allow_mentions"]["roles"]
365 assert "parse" in payload["allow_mentions"]
366 assert len(payload["allow_mentions"]["parse"]) == 2
367 assert "everyone" in payload["allow_mentions"]["parse"]
368 assert "admin" in payload["allow_mentions"]["parse"]
369
370 # Reset our object
371 mock_post.reset_mock()
372
373 results = NotifyDiscord.parse_url(
374 f"discord://{webhook_id}/{webhook_token}/?format=text"
375 )
376
377 assert isinstance(results, dict)
378 assert results["user"] is None
379 assert results["webhook_id"] == webhook_id
380 assert results["webhook_token"] == webhook_token
381 assert results["password"] is None
382 assert results["port"] is None
383 assert results["host"] == webhook_id
384 assert results["fullpath"] == f"/{webhook_token}/"
385 assert results["path"] == f"/{webhook_token}/"
386 assert results["query"] is None
387 assert results["schema"] == "discord"
388 assert results["url"] == f"discord://{webhook_id}/{webhook_token}/"
389
390 instance = NotifyDiscord(**results)
391 assert isinstance(instance, NotifyDiscord)
392
393 response = instance.send(body=body)
394 assert response is True
395 assert mock_post.call_count == 1
396
397 details = mock_post.call_args_list[0]
398 assert (
399 details[0][0]
400 == f"https://discord.com/api/webhooks/{webhook_id}/{webhook_token}"
401 )
402
403 payload = loads(details[1]["data"])
404
405 # text mode does not ping unless ping is explicitly set to someone
406 assert "allow_mentions" not in payload
407
408 # Reset our object
409 mock_post.reset_mock()
410
411 # Test our header parsing when not lead with a header
412 body = """ """
413
414 results = NotifyDiscord.parse_url(
415 # & -> %26 for role otherwise & separates our URL from further parsing
416 f"discord://{webhook_id}/{webhook_token}/?ping=@joe,<@321>,<@%26654>"
417 )
418
419 assert isinstance(results, dict)
420 assert results["user"] is None
421 assert results["webhook_id"] == webhook_id
422 assert results["webhook_token"] == webhook_token
423 assert results["password"] is None
424 assert results["port"] is None
425 assert results["host"] == webhook_id
426 assert results["fullpath"] == f"/{webhook_token}/"
427 assert results["path"] == f"/{webhook_token}/"
428 assert results["query"] is None
429 assert results["schema"] == "discord"
430 assert results["url"] == f"discord://{webhook_id}/{webhook_token}/"
431 instance = NotifyDiscord(**results)
432 assert isinstance(instance, NotifyDiscord)
433
434 response = instance.send(body=body)
435 assert response is True
436 assert mock_post.call_count == 1
437
438 details = mock_post.call_args_list[0]
439 assert (
440 details[0][0]
441 == f"https://discord.com/api/webhooks/{webhook_id}/{webhook_token}"
442 )
443
444 payload = loads(details[1]["data"])
445
446 assert "allow_mentions" in payload
447 assert len(payload["allow_mentions"]["users"]) == 1
448 assert "321" in payload["allow_mentions"]["users"]
449 assert "<@321>" in payload["content"]
450 assert len(payload["allow_mentions"]["roles"]) == 1
451 assert "654" in payload["allow_mentions"]["roles"]
452 assert "<@&654>" in payload["content"]
453 assert len(payload["allow_mentions"]["parse"]) == 1
454 assert "joe" in payload["allow_mentions"]["parse"]
455 assert "@joe" in payload["content"]
456
457 # Reset our object
458 mock_post.reset_mock()
459
460 # Test our body in text mode, with ping=set
461 body = """
462 # Heading
463 @everyone and @admin, wake and meet our new user <@123>; <@&456>"
464 """
465
466 results = NotifyDiscord.parse_url(
467 # & -> %26 for role otherwise & separates our URL from further parsing
468 f"discord://{webhook_id}/{webhook_token}/?ping=@joe,<@321>,<@%26654>"
469 "&format=text"
470 )
471
472 assert isinstance(results, dict)
473 assert results["user"] is None
474 assert results["webhook_id"] == webhook_id
475 assert results["webhook_token"] == webhook_token
476 assert results["password"] is None
477 assert results["port"] is None
478 assert results["host"] == webhook_id
479 assert results["fullpath"] == f"/{webhook_token}/"
480 assert results["path"] == f"/{webhook_token}/"
481 assert results["query"] is None
482 assert results["schema"] == "discord"
483 assert results["url"] == f"discord://{webhook_id}/{webhook_token}/"
484
485 instance = NotifyDiscord(**results)
486 assert isinstance(instance, NotifyDiscord)
487
488 response = instance.send(body=body)
489 assert response is True
490 assert mock_post.call_count == 1
491
492 details = mock_post.call_args_list[0]
493 assert (
494 details[0][0]
495 == f"https://discord.com/api/webhooks/{webhook_id}/{webhook_token}"
496 )
497
498 payload = loads(details[1]["data"])
499
500 # Payload only includes elements on ping= line with text mode
501 assert "allow_mentions" in payload
502 assert "users" in payload["allow_mentions"]
503 assert len(payload["allow_mentions"]["users"]) == 1
504 assert "321" in payload["allow_mentions"]["users"]
505 assert "roles" in payload["allow_mentions"]
506 assert len(payload["allow_mentions"]["roles"]) == 1
507 assert "654" in payload["allow_mentions"]["roles"]
508 assert "parse" in payload["allow_mentions"]
509 assert len(payload["allow_mentions"]["parse"]) == 1
510 assert "joe" in payload["allow_mentions"]["parse"]
511
512
513 @mock.patch("requests.post")
514 @mock.patch("time.sleep")
515 def test_plugin_discord_general(mock_sleep, mock_post):
516 """NotifyDiscord() General Checks."""
517
518 # Prevent throttling
519 mock_sleep.return_value = True
520
521 # Turn off clock skew for local testing
522 NotifyDiscord.clock_skew = timedelta(seconds=0)
523
524 # Epoch time:
525 epoch = datetime.fromtimestamp(0, timezone.utc)
526
527 # Initialize some generic (but valid) tokens
528 webhook_id = "A" * 24
529 webhook_token = "B" * 64
530
531 # Prepare Mock
532 mock_post.return_value = requests.Request()
533 mock_post.return_value.status_code = requests.codes.ok
534 mock_post.return_value.content = ""
535 mock_post.return_value.headers = {
536 "X-RateLimit-Reset": (
537 (datetime.now(timezone.utc) - epoch).total_seconds()
538 ),
539 "X-RateLimit-Remaining": 1,
540 }
541
542 # Invalid webhook id
543 with pytest.raises(TypeError):
544 NotifyDiscord(webhook_id=None, webhook_token=webhook_token)
545 # Invalid webhook id (whitespace)
546 with pytest.raises(TypeError):
547 NotifyDiscord(webhook_id=" ", webhook_token=webhook_token)
548
549 # Invalid webhook token
550 with pytest.raises(TypeError):
551 NotifyDiscord(webhook_id=webhook_id, webhook_token=None)
552 # Invalid webhook token (whitespace)
553 with pytest.raises(TypeError):
554 NotifyDiscord(webhook_id=webhook_id, webhook_token=" ")
555
556 obj = NotifyDiscord(
557 webhook_id=webhook_id,
558 webhook_token=webhook_token,
559 footer=True,
560 thumbnail=False,
561 )
562 assert obj.ratelimit_remaining == 1
563
564 # Test that we get a string response
565 assert isinstance(obj.url(), str) is True
566
567 # This call includes an image with it's payload:
568 assert (
569 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
570 is True
571 )
572
573 # Force a case where there are no more remaining posts allowed
574 mock_post.return_value.headers = {
575 "X-RateLimit-Reset": (
576 (datetime.now(timezone.utc) - epoch).total_seconds()
577 ),
578 "X-RateLimit-Remaining": 0,
579 }
580
581 # This call includes an image with it's payload:
582 assert (
583 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
584 is True
585 )
586
587 # behind the scenes, it should cause us to update our rate limit
588 assert obj.send(body="test") is True
589 assert obj.ratelimit_remaining == 0
590
591 # This should cause us to block
592 mock_post.return_value.headers = {
593 "X-RateLimit-Reset": (
594 (datetime.now(timezone.utc) - epoch).total_seconds()
595 ),
596 "X-RateLimit-Remaining": 10,
597 }
598 assert obj.send(body="test") is True
599 assert obj.ratelimit_remaining == 10
600
601 # Reset our variable back to 1
602 mock_post.return_value.headers = {
603 "X-RateLimit-Reset": (
604 (datetime.now(timezone.utc) - epoch).total_seconds()
605 ),
606 "X-RateLimit-Remaining": 1,
607 }
608 # Handle cases where our epoch time is wrong
609 del mock_post.return_value.headers["X-RateLimit-Reset"]
610 assert obj.send(body="test") is True
611
612 # Return our object, but place it in the future forcing us to block
613 mock_post.return_value.headers = {
614 "X-RateLimit-Reset": (
615 (datetime.now(timezone.utc) - epoch).total_seconds() + 1
616 ),
617 "X-RateLimit-Remaining": 0,
618 }
619
620 obj.ratelimit_remaining = 0
621 assert obj.send(body="test") is True
622
623 # Test 429 error response
624 mock_post.return_value.status_code = requests.codes.too_many_requests
625
626 # The below will attempt a second transmission and fail (because we didn't
627 # set up a second post request to pass) :)
628 assert obj.send(body="test") is False
629
630 # Return our object, but place it in the future forcing us to block
631 mock_post.return_value.status_code = requests.codes.ok
632 mock_post.return_value.headers = {
633 "X-RateLimit-Reset": (
634 (datetime.now(timezone.utc) - epoch).total_seconds() - 1
635 ),
636 "X-RateLimit-Remaining": 0,
637 }
638 assert obj.send(body="test") is True
639
640 # Return our limits to always work
641 obj.ratelimit_remaining = 1
642
643 # Return our headers to normal
644 mock_post.return_value.headers = {
645 "X-RateLimit-Reset": (
646 (datetime.now(timezone.utc) - epoch).total_seconds()
647 ),
648 "X-RateLimit-Remaining": 1,
649 }
650
651 # This call includes an image with it's payload:
652 assert (
653 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
654 is True
655 )
656
657 # Simple Markdown Single line of text
658 test_markdown = "body"
659 desc, results = obj.extract_markdown_sections(test_markdown)
660 assert isinstance(results, list) is True
661 assert len(results) == 0
662
663 # Test our header parsing when not lead with a header
664 test_markdown = """
665 A section of text that has no header at the top.
666 It also has a hash tag # <- in the middle of a
667 string.
668
669 ## Heading 1
670 body
671
672 # Heading 2
673
674 more content
675 on multi-lines
676 """
677
678 desc, results = obj.extract_markdown_sections(test_markdown)
679 # we have a description
680 assert isinstance(desc, str) is True
681 assert desc.startswith("A section of text that has no header at the top.")
682 assert desc.endswith("string.")
683
684 assert isinstance(results, list) is True
685 assert len(results) == 2
686 assert results[0]["name"] == "Heading 1"
687 assert results[0]["value"] == "```md\nbody\n```"
688 assert results[1]["name"] == "Heading 2"
689 assert (
690 results[1]["value"] == "```md\nmore content\n on multi-lines\n```"
691 )
692
693 # Test our header parsing
694 test_markdown = (
695 "## Heading one\nbody body\n\n"
696 + "# Heading 2 ##\n\nTest\n\n"
697 + "more content\n"
698 + "even more content \t\r\n\n\n"
699 + "# Heading 3 ##\n\n\n"
700 + "normal content\n"
701 + "# heading 4\n"
702 + "#### Heading 5"
703 )
704
705 desc, results = obj.extract_markdown_sections(test_markdown)
706 assert isinstance(results, list) is True
707 # No desc details filled out
708 assert isinstance(desc, str) is True
709 assert not desc
710
711 # We should have 5 sections (since there are 5 headers identified above)
712 assert len(results) == 5
713 assert results[0]["name"] == "Heading one"
714 assert results[0]["value"] == "```md\nbody body\n```"
715 assert results[1]["name"] == "Heading 2"
716 assert (
717 results[1]["value"]
718 == "```md\nTest\n\nmore content\neven more content\n```"
719 )
720 assert results[2]["name"] == "Heading 3"
721 assert results[2]["value"] == "```md\nnormal content\n```"
722 assert results[3]["name"] == "heading 4"
723 assert results[3]["value"] == "```\n```"
724 assert results[4]["name"] == "Heading 5"
725 assert results[4]["value"] == "```\n```"
726
727 # Create an apprise instance
728 a = Apprise()
729
730 # Our processing is slightly different when we aren't using markdown
731 # as we do not pre-parse content during our notifications
732 assert (
733 a.add(
734 f"discord://{webhook_id}/{webhook_token}/"
735 "?format=markdown&footer=Yes"
736 )
737 is True
738 )
739
740 # This call includes an image with it's payload:
741 NotifyDiscord.discord_max_fields = 1
742
743 assert (
744 a.notify(
745 body=test_markdown,
746 title="title",
747 notify_type=NotifyType.INFO,
748 body_format=NotifyFormat.TEXT,
749 )
750 is True
751 )
752
753 # Throw an exception on the forth call to requests.post()
754 # This allows to test our batch field processing
755 response = mock.Mock()
756 response.content = ""
757 response.status_code = requests.codes.ok
758 mock_post.return_value = response
759 mock_post.side_effect = [
760 response,
761 response,
762 response,
763 requests.RequestException(),
764 ]
765
766 # Test our markdown
767 obj = Apprise.instantiate(
768 f"discord://{webhook_id}/{webhook_token}/?format=markdown"
769 )
770 assert isinstance(obj, NotifyDiscord)
771 assert (
772 obj.notify(
773 body=test_markdown, title="title", notify_type=NotifyType.INFO
774 )
775 is False
776 )
777 mock_post.side_effect = None
778
779 # Empty String
780 desc, results = obj.extract_markdown_sections("")
781 assert isinstance(results, list) is True
782 assert len(results) == 0
783
784 # No desc details filled out
785 assert isinstance(desc, str) is True
786 assert not desc
787
788 # String without Heading
789 test_markdown = (
790 "Just a string without any header entries.\n" + "A second line"
791 )
792 desc, results = obj.extract_markdown_sections(test_markdown)
793 assert isinstance(results, list) is True
794 assert len(results) == 0
795
796 # No desc details filled out
797 assert isinstance(desc, str) is True
798 assert (
799 desc == "Just a string without any header entries.\n" + "A second line"
800 )
801
802 # Use our test markdown string during a notification
803 assert (
804 obj.notify(
805 body=test_markdown, title="title", notify_type=NotifyType.INFO
806 )
807 is True
808 )
809
810 # Create an apprise instance
811 a = Apprise()
812
813 # Our processing is slightly different when we aren't using markdown
814 # as we do not pre-parse content during our notifications
815 assert (
816 a.add(
817 f"discord://{webhook_id}/{webhook_token}/"
818 "?format=markdown&footer=Yes"
819 )
820 is True
821 )
822
823 # This call includes an image with it's payload:
824 assert (
825 a.notify(
826 body=test_markdown,
827 title="title",
828 notify_type=NotifyType.INFO,
829 body_format=NotifyFormat.TEXT,
830 )
831 is True
832 )
833
834 assert (
835 a.notify(
836 body=test_markdown,
837 title="title",
838 notify_type=NotifyType.INFO,
839 body_format=NotifyFormat.MARKDOWN,
840 )
841 is True
842 )
843
844 # Toggle our logo availability
845 a.asset.image_url_logo = None
846 assert (
847 a.notify(body="body", title="title", notify_type=NotifyType.INFO)
848 is True
849 )
850
851 # Create an apprise instance
852 a = Apprise()
853
854 # Reset our object
855 mock_post.reset_mock()
856
857 # Test our threading
858 assert (
859 a.add(f"discord://{webhook_id}/{webhook_token}/?thread=12345") is True
860 )
861
862 # This call includes an image with it's payload:
863 assert a.notify(body="test", title="title") is True
864
865 assert mock_post.call_count == 1
866 response = mock_post.call_args_list[0][1]
867 assert "params" in response
868 assert response["params"].get("thread_id") == "12345"
869
870
871 @mock.patch("requests.post")
872 def test_plugin_discord_overflow(mock_post):
873 """NotifyDiscord() Overflow Checks."""
874
875 # Initialize some generic (but valid) tokens
876 webhook_id = "A" * 24
877 webhook_token = "B" * 64
878
879 # Prepare Mock
880 mock_post.return_value = requests.Request()
881 mock_post.return_value.status_code = requests.codes.ok
882
883 # Some variables we use to control the data we work with
884 body_len = 8000
885 title_len = 1024
886
887 # Number of characters per line
888 row = 24
889
890 # Create a large body and title with random data
891 body = "".join(choice(str_alpha + str_num + " ") for _ in range(body_len))
892 body = "\r\n".join([body[i : i + row] for i in range(0, len(body), row)])
893
894 # Create our title using random data
895 title = "".join(choice(str_alpha + str_num) for _ in range(title_len))
896
897 results = NotifyDiscord.parse_url(
898 f"discord://{webhook_id}/{webhook_token}/?overflow=split"
899 )
900
901 assert isinstance(results, dict)
902 assert results["user"] is None
903 assert results["webhook_id"] == webhook_id
904 assert results["webhook_token"] == webhook_token
905 assert results["password"] is None
906 assert results["port"] is None
907 assert results["host"] == webhook_id
908 assert results["fullpath"] == f"/{webhook_token}/"
909 assert results["path"] == f"/{webhook_token}/"
910 assert results["query"] is None
911 assert results["schema"] == "discord"
912 assert results["url"] == f"discord://{webhook_id}/{webhook_token}/"
913
914 instance = NotifyDiscord(**results)
915 assert isinstance(instance, NotifyDiscord)
916
917 results = instance._apply_overflow(
918 body, title=title, overflow=OverflowMode.SPLIT
919 )
920
921 # Ensure we never exceed 2000 characters
922 for entry in results:
923 assert len(entry["title"]) <= instance.title_maxlen
924 assert len(entry["title"]) + len(entry["body"]) <= instance.body_maxlen
925
926
927 @mock.patch("requests.post")
928 def test_plugin_discord_markdown_extra(mock_post):
929 """NotifyDiscord() Markdown Extra Checks."""
930
931 # Initialize some generic (but valid) tokens
932 webhook_id = "A" * 24
933 webhook_token = "B" * 64
934
935 # Prepare Mock
936 mock_post.return_value = requests.Request()
937 mock_post.return_value.status_code = requests.codes.ok
938
939 # Reset our apprise object
940 a = Apprise()
941
942 # We want to further test our markdown support to accommodate bug rased on
943 # 2022.10.25; see https://github.com/caronc/apprise/issues/717
944 assert (
945 a.add(
946 f"discord://{webhook_id}/{webhook_token}/"
947 "?format=markdown&footer=Yes"
948 )
949 is True
950 )
951
952 test_markdown = "[green-blue](https://google.com)"
953
954 # This call includes an image with it's payload:
955 assert (
956 a.notify(
957 body=test_markdown,
958 title="title",
959 notify_type=NotifyType.INFO,
960 body_format=NotifyFormat.TEXT,
961 )
962 is True
963 )
964
965 assert (
966 a.notify(body="body", title="title", notify_type=NotifyType.INFO)
967 is True
968 )
969
970
971 @mock.patch("requests.post")
972 def test_plugin_discord_attachments(mock_post):
973 """NotifyDiscord() Attachment Checks."""
974
975 # Initialize some generic (but valid) tokens
976 webhook_id = "C" * 24
977 webhook_token = "D" * 64
978
979 # Prepare a good response
980 response = mock.Mock()
981 response.status_code = requests.codes.ok
982 response.content = b""
983
984 # Prepare a bad response
985 bad_response = mock.Mock()
986 bad_response.status_code = requests.codes.internal_server_error
987 bad_response.content = b""
988
989 # Prepare Mock return object
990 mock_post.return_value = response
991
992 # Test our markdown
993 obj = Apprise.instantiate(
994 f"discord://{webhook_id}/{webhook_token}/?format=markdown"
995 )
996
997 # attach our content
998 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
999
1000 assert (
1001 obj.notify(
1002 body="body",
1003 title="title",
1004 notify_type=NotifyType.INFO,
1005 attach=attach,
1006 )
1007 is True
1008 )
1009
1010 # Test our call count
1011 assert mock_post.call_count == 2
1012 assert (
1013 mock_post.call_args_list[0][0][0]
1014 == f"https://discord.com/api/webhooks/{webhook_id}/{webhook_token}"
1015 )
1016 assert (
1017 mock_post.call_args_list[1][0][0]
1018 == f"https://discord.com/api/webhooks/{webhook_id}/{webhook_token}"
1019 )
1020
1021 # Reset our object
1022 mock_post.reset_mock()
1023
1024 # Test notifications with mentions and attachments in it
1025 assert (
1026 obj.notify(
1027 body="Say hello to <@1234>!",
1028 notify_type=NotifyType.INFO,
1029 attach=attach,
1030 )
1031 is True
1032 )
1033
1034 # Test our call count
1035 assert mock_post.call_count == 2
1036 assert (
1037 mock_post.call_args_list[0][0][0]
1038 == f"https://discord.com/api/webhooks/{webhook_id}/{webhook_token}"
1039 )
1040 assert (
1041 mock_post.call_args_list[1][0][0]
1042 == f"https://discord.com/api/webhooks/{webhook_id}/{webhook_token}"
1043 )
1044
1045 # Reset our object
1046 mock_post.reset_mock()
1047
1048 # An invalid attachment will cause a failure
1049 path = os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg")
1050 attach = AppriseAttachment(path)
1051 assert (
1052 obj.notify(
1053 body="body",
1054 title="title",
1055 notify_type=NotifyType.INFO,
1056 attach=path,
1057 )
1058 is False
1059 )
1060
1061 # update our attachment to be valid
1062 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
1063
1064 mock_post.return_value = None
1065 # Throw an exception on the first call to requests.post()
1066 for side_effect in (requests.RequestException(), OSError(), bad_response):
1067 mock_post.side_effect = [side_effect]
1068
1069 # We'll fail now because of our error handling
1070 assert obj.send(body="test", attach=attach) is False
1071
1072 # Throw an exception on the second call to requests.post()
1073 for side_effect in (requests.RequestException(), OSError(), bad_response):
1074 mock_post.side_effect = [response, side_effect]
1075
1076 # We'll fail now because of our error handling
1077 assert obj.send(body="test", attach=attach) is False
1078
1079 # handle a bad response
1080 bad_response = mock.Mock()
1081 bad_response.content = b""
1082 bad_response.headers = {}
1083 bad_response.status_code = requests.codes.internal_server_error
1084 mock_post.side_effect = [response, bad_response]
1085
1086 # We'll fail now because of an internal exception
1087 assert obj.send(body="test", attach=attach) is False
1088
1089
1090 @mock.patch("requests.post")
1091 def test_plugin_discord_markdown_fields_batches_exactly(mock_post):
1092 webhook_id = "A" * 24
1093 webhook_token = "B" * 64
1094
1095 response = mock.Mock()
1096 response.status_code = requests.codes.ok
1097 response.content = ""
1098 response.headers = {}
1099 mock_post.return_value = response
1100
1101 # Force tiny batches
1102 NotifyDiscord.discord_max_fields = 1
1103
1104 body = "# H1\nv1\n# H2\nv2\n# H3\nv3\n"
1105 obj = Apprise.instantiate(
1106 f"discord://{webhook_id}/{webhook_token}/?format=markdown&fields=yes"
1107 )
1108 assert isinstance(obj, NotifyDiscord)
1109
1110 assert obj.send(body=body) is True
1111
1112 # H1, H2, H3 => 3 fields => 3 posts (since max_fields=1)
1113 assert mock_post.call_count == 3
1114
1115
1116 @mock.patch("requests.post")
1117 def test_plugin_discord_markdown_ping_is_additive(mock_post):
1118 webhook_id = "A" * 24
1119 webhook_token = "B" * 64
1120
1121 mock_post.return_value = requests.Request()
1122 mock_post.return_value.status_code = requests.codes.ok
1123
1124 body = "Body pings <@111> and <@&222> @everyone"
1125 results = NotifyDiscord.parse_url(
1126 f"discord://{webhook_id}/{webhook_token}/"
1127 "?format=markdown"
1128 "&ping=<@333>,<@%26444>,@joe"
1129 )
1130 obj = NotifyDiscord(**results)
1131
1132 assert obj.send(body=body) is True
1133 assert mock_post.call_count == 1
1134
1135 payload = loads(mock_post.call_args_list[0][1]["data"])
1136
1137 assert "allow_mentions" in payload
1138 # union
1139 assert set(payload["allow_mentions"]["users"]) == {"111", "333"}
1140 assert set(payload["allow_mentions"]["roles"]) == {"222", "444"}
1141 assert set(payload["allow_mentions"]["parse"]) == {"everyone", "joe"}
1142 assert payload["content"].startswith("👉 ")
1143
1144
1145 @mock.patch("requests.post")
1146 def test_plugin_discord_html_ping_is_exclusive(mock_post):
1147 webhook_id = "A" * 24
1148 webhook_token = "B" * 64
1149
1150 mock_post.return_value = requests.Request()
1151 mock_post.return_value.status_code = requests.codes.ok
1152
1153 body = "Body includes <@111> <@&222> @everyone but must be ignored"
1154 results = NotifyDiscord.parse_url(
1155 f"discord://{webhook_id}/{webhook_token}/"
1156 "?format=html"
1157 "&ping=<@333>,<@%26444>,@joe"
1158 )
1159 obj = NotifyDiscord(**results)
1160
1161 assert obj.send(body=body) is True
1162 payload = loads(mock_post.call_args_list[0][1]["data"])
1163
1164 assert set(payload["allow_mentions"]["users"]) == {"333"}
1165 assert set(payload["allow_mentions"]["roles"]) == {"444"}
1166 assert set(payload["allow_mentions"]["parse"]) == {"joe"}
1167
1168
1169 @mock.patch("requests.post")
1170 def test_plugin_discord_markdown_no_mentions_has_no_allow_mentions(mock_post):
1171 webhook_id = "A" * 24
1172 webhook_token = "B" * 64
1173
1174 mock_post.return_value = requests.Request()
1175 mock_post.return_value.status_code = requests.codes.ok
1176
1177 results = NotifyDiscord.parse_url(
1178 f"discord://{webhook_id}/{webhook_token}/?format=markdown"
1179 )
1180 obj = NotifyDiscord(**results)
1181
1182 assert obj.send(body="Hello world") is True
1183 payload = loads(mock_post.call_args_list[0][1]["data"])
1184
1185 assert "allow_mentions" not in payload
1186 assert "content" not in payload
1187
1188
1189 @mock.patch("requests.post")
1190 def test_plugin_discord_markdown_single_field_posts_once(mock_post):
1191 webhook_id = "A" * 24
1192 webhook_token = "B" * 64
1193
1194 response = mock.Mock()
1195 response.status_code = requests.codes.ok
1196 response.content = ""
1197 response.headers = {}
1198 mock_post.return_value = response
1199
1200 NotifyDiscord.discord_max_fields = 10
1201
1202 body = "# H1\nv1\n"
1203 obj = Apprise.instantiate(
1204 f"discord://{webhook_id}/{webhook_token}/?format=markdown&fields=yes"
1205 )
1206 assert obj.send(body=body) is True
1207 assert mock_post.call_count == 1
1208
1209
1210 @mock.patch("requests.post")
1211 def test_plugin_discord_attach_memory(mock_post):
1212 """Regression: AttachMemory must be sendable without OSError."""
1213 from apprise.attachment.memory import AttachMemory
1214
1215 webhook_id = "C" * 24
1216 webhook_token = "D" * 64
1217
1218 response = mock.Mock()
1219 response.status_code = requests.codes.ok
1220 response.content = b""
1221 mock_post.return_value = response
1222
1223 obj = Apprise.instantiate(f"discord://{webhook_id}/{webhook_token}/")
1224
1225 mem = AttachMemory(
1226 content=b"<html><body><h1>Test</h1></body></html>",
1227 name="report.html",
1228 mimetype="text/html",
1229 )
1230
1231 assert obj.notify(body="Test", attach=mem) is True
1232 assert mock_post.call_count >= 1
1233
1234
1235 @mock.patch("requests.post")
1236 def test_plugin_discord_html_to_markdown_format(mock_post):
1237 """NotifyDiscord(): HTML body is converted to Markdown."""
1238
1239 webhook_id = "A" * 24
1240 webhook_token = "B" * 64
1241
1242 mock_post.return_value = requests.Request()
1243 mock_post.return_value.status_code = requests.codes.ok
1244 mock_post.return_value.content = ""
1245 mock_post.return_value.headers = {}
1246
1247 # Instantiate a Discord plugin in Markdown mode with fields
1248 # disabled so the body lands in embeds[0]["description"] directly
1249 obj = Apprise.instantiate(
1250 f"discord://{webhook_id}/{webhook_token}/?format=markdown&fields=no"
1251 )
1252
1253 aobj = Apprise()
1254 aobj.add(obj)
1255
1256 # Notify with an HTML body; the framework should convert it
1257 # to Markdown before dispatching to Discord
1258 assert (
1259 aobj.notify(
1260 body="<b>hello</b> <i>world</i>",
1261 body_format=NotifyFormat.HTML,
1262 )
1263 is True
1264 )
1265 assert mock_post.call_count == 1
1266
1267 # The body must arrive in the embed description as Markdown,
1268 # not as stripped plain text
1269 payload = loads(mock_post.call_args_list[0][1]["data"])
1270 assert payload["embeds"][0]["description"] == "**hello** *world*"
1271
1272
1273 @mock.patch("requests.post")
1274 def test_plugin_discord_template_content(mock_post, tmpdir):
1275 """NotifyDiscord() template with 'content' field."""
1276
1277 webhook_id = "A" * 24
1278 webhook_token = "B" * 64
1279
1280 # Prepare a good mock response
1281 mock_post.return_value = mock.Mock(
1282 status_code=requests.codes.ok,
1283 content=b"",
1284 headers={},
1285 )
1286
1287 # Write a minimal Discord webhook template to disk
1288 template = tmpdir.join("discord.json")
1289 template.write('{"content": "{{app_body}}"}')
1290
1291 # Instantiate via URL with template path
1292 obj = Apprise.instantiate(
1293 "discord://{}/{}/".format(webhook_id, webhook_token)
1294 + "?template={}".format(str(template))
1295 )
1296 assert isinstance(obj, NotifyDiscord)
1297
1298 # Verify the template was loaded
1299 assert obj.template
1300
1301 # Notification must succeed
1302 assert (
1303 obj.notify(body="hello", title="world", notify_type=NotifyType.INFO)
1304 is True
1305 )
1306 assert mock_post.called is True
1307
1308 # Verify the payload sent - content field contains the body
1309 posted = loads(mock_post.call_args_list[0][1]["data"])
1310 assert posted["content"] == "hello"
1311
1312
1313 @mock.patch("requests.post")
1314 def test_plugin_discord_template_embeds(mock_post, tmpdir):
1315 """NotifyDiscord() template with 'embeds' field."""
1316
1317 webhook_id = "A" * 24
1318 webhook_token = "B" * 64
1319
1320 # Prepare a good mock response
1321 mock_post.return_value = mock.Mock(
1322 status_code=requests.codes.ok,
1323 content=b"",
1324 headers={},
1325 )
1326
1327 # Write a template that uses the embeds structure
1328 template = tmpdir.join("embeds.json")
1329 template.write(
1330 '{"embeds": [{"title": "{{app_title}}", '
1331 '"description": "{{app_body}}"}]}'
1332 )
1333
1334 # Instantiate via URL with template path
1335 obj = Apprise.instantiate(
1336 "discord://{}/{}/".format(webhook_id, webhook_token)
1337 + "?template={}".format(str(template))
1338 )
1339 assert isinstance(obj, NotifyDiscord)
1340 assert obj.template
1341
1342 # Notification must succeed
1343 assert (
1344 obj.notify(
1345 body="my body", title="my title", notify_type=NotifyType.INFO
1346 )
1347 is True
1348 )
1349 assert mock_post.called is True
1350
1351 # Verify the embed payload
1352 posted = loads(mock_post.call_args_list[0][1]["data"])
1353 assert "embeds" in posted
1354 assert posted["embeds"][0]["title"] == "my title"
1355 assert posted["embeds"][0]["description"] == "my body"
1356
1357
1358 def test_plugin_discord_template_tokens(tmpdir):
1359 """NotifyDiscord() template tokens and URL round-trip."""
1360
1361 webhook_id = "A" * 24
1362 webhook_token = "B" * 64
1363
1364 # Write a minimal content template to disk
1365 template = tmpdir.join("discord.json")
1366 template.write('{"content": "{{app_body}}"}')
1367
1368 # Instantiate with explicit tokens dict
1369 obj = NotifyDiscord(
1370 webhook_id=webhook_id,
1371 webhook_token=webhook_token,
1372 template=str(template),
1373 tokens={"mykey": "myval", "count": "42"},
1374 )
1375 assert obj.template
1376 assert obj.tokens["mykey"] == "myval"
1377 assert obj.tokens["count"] == "42"
1378
1379 # Round-trip through url() and parse_url()
1380 url = obj.url()
1381 result = NotifyDiscord.parse_url(url)
1382 assert result is not None
1383 assert "mykey" in result["tokens"]
1384 assert result["tokens"]["mykey"] == "myval"
1385
1386 obj2 = NotifyDiscord(**result)
1387 assert obj2.template
1388 assert obj2.tokens.get("mykey") == "myval"
1389 assert obj2.url_identifier == obj.url_identifier
1390
1391
1392 def test_plugin_discord_template_token_invalid():
1393 """NotifyDiscord() non-dict tokens raises TypeError."""
1394
1395 webhook_id = "A" * 24
1396 webhook_token = "B" * 64
1397
1398 with pytest.raises(TypeError):
1399 NotifyDiscord(
1400 webhook_id=webhook_id,
1401 webhook_token=webhook_token,
1402 tokens="not-a-dict",
1403 )
1404
1405
1406 def test_plugin_discord_template_add_failure():
1407 """NotifyDiscord() template add() failure raises TypeError."""
1408
1409 webhook_id = "A" * 24
1410 webhook_token = "B" * 64
1411
1412 # Force add() to report failure so len(self.template) == 0
1413 with (
1414 mock.patch(
1415 "apprise.plugins.discord.AppriseAttachment.add",
1416 return_value=False,
1417 ),
1418 pytest.raises(TypeError),
1419 ):
1420 NotifyDiscord(
1421 webhook_id=webhook_id,
1422 webhook_token=webhook_token,
1423 template="file:///some/template.json",
1424 )
1425
1426
1427 @mock.patch("requests.post")
1428 def test_plugin_discord_template_inaccessible(mock_post, tmpdir):
1429 """NotifyDiscord() inaccessible template fails gracefully."""
1430
1431 webhook_id = "A" * 24
1432 webhook_token = "B" * 64
1433
1434 # Prepare a mock response (should never be called)
1435 mock_post.return_value = mock.Mock(
1436 status_code=requests.codes.ok,
1437 content=b"",
1438 headers={},
1439 )
1440
1441 # Create the template so that add() succeeds during init
1442 template = tmpdir.join("discord.json")
1443 template.write('{"content": "{{app_body}}"}')
1444
1445 obj = Apprise.instantiate(
1446 "discord://{}/{}/".format(webhook_id, webhook_token)
1447 + "?template={}".format(str(template))
1448 )
1449 assert isinstance(obj, NotifyDiscord)
1450
1451 # Remove the file so the template becomes inaccessible
1452 os.remove(str(template))
1453
1454 # Notification must fail; no HTTP call should be made
1455 assert (
1456 obj.notify(body="test", title="t", notify_type=NotifyType.INFO)
1457 is False
1458 )
1459 assert mock_post.called is False
1460
1461
1462 @mock.patch("requests.post")
1463 def test_plugin_discord_template_oserror(mock_post, tmpdir):
1464 """NotifyDiscord() OSError during template read fails gracefully."""
1465
1466 webhook_id = "A" * 24
1467 webhook_token = "B" * 64
1468
1469 # Prepare a mock response (should never be called)
1470 mock_post.return_value = mock.Mock(
1471 status_code=requests.codes.ok,
1472 content=b"",
1473 headers={},
1474 )
1475
1476 # Write a file so the attachment resolves but open() will be mocked
1477 template = tmpdir.join("discord.json")
1478 template.write('{"content": "hello"}')
1479
1480 obj = Apprise.instantiate(
1481 "discord://{}/{}/".format(webhook_id, webhook_token)
1482 + "?template={}".format(str(template))
1483 )
1484 assert isinstance(obj, NotifyDiscord)
1485
1486 # Patch open() to raise OSError when the template is read
1487 with mock.patch("builtins.open", side_effect=OSError):
1488 assert (
1489 obj.notify(body="test", title="t", notify_type=NotifyType.INFO)
1490 is False
1491 )
1492 assert mock_post.called is False
1493
1494
1495 @mock.patch("requests.post")
1496 def test_plugin_discord_template_invalid_json(mock_post, tmpdir):
1497 """NotifyDiscord() invalid JSON template fails gracefully."""
1498
1499 webhook_id = "A" * 24
1500 webhook_token = "B" * 64
1501
1502 # Prepare a mock response (should never be called)
1503 mock_post.return_value = mock.Mock(
1504 status_code=requests.codes.ok,
1505 content=b"",
1506 headers={},
1507 )
1508
1509 # Write a syntactically invalid JSON file
1510 template = tmpdir.join("bad.json")
1511 template.write("{ not valid json }")
1512
1513 obj = Apprise.instantiate(
1514 "discord://{}/{}/".format(webhook_id, webhook_token)
1515 + "?template={}".format(str(template))
1516 )
1517 assert isinstance(obj, NotifyDiscord)
1518
1519 # Notification must fail due to parse error
1520 assert (
1521 obj.notify(body="test", title="t", notify_type=NotifyType.INFO)
1522 is False
1523 )
1524 assert mock_post.called is False
1525
1526
1527 @mock.patch("requests.post")
1528 def test_plugin_discord_template_not_dict(mock_post, tmpdir):
1529 """NotifyDiscord() template root must be a JSON object, not array."""
1530
1531 webhook_id = "A" * 24
1532 webhook_token = "B" * 64
1533
1534 # Prepare a mock response (should never be called)
1535 mock_post.return_value = mock.Mock(
1536 status_code=requests.codes.ok,
1537 content=b"",
1538 headers={},
1539 )
1540
1541 # Write a JSON array instead of an object
1542 template = tmpdir.join("array.json")
1543 template.write('[{"content": "hello"}]')
1544
1545 obj = Apprise.instantiate(
1546 "discord://{}/{}/".format(webhook_id, webhook_token)
1547 + "?template={}".format(str(template))
1548 )
1549 assert isinstance(obj, NotifyDiscord)
1550
1551 # Notification must fail because the root is not a dict
1552 assert (
1553 obj.notify(body="test", title="t", notify_type=NotifyType.INFO)
1554 is False
1555 )
1556 assert mock_post.called is False
1557
1558
1559 @mock.patch("requests.post")
1560 def test_plugin_discord_template_payload_validation(mock_post, tmpdir):
1561 """NotifyDiscord() template payload field validation cases."""
1562
1563 webhook_id = "A" * 24
1564 webhook_token = "B" * 64
1565
1566 # Prepare a mock response (should never be called during failures)
1567 mock_post.return_value = mock.Mock(
1568 status_code=requests.codes.ok,
1569 content=b"",
1570 headers={},
1571 )
1572
1573 template = tmpdir.join("t.json")
1574
1575 # Case 1: no content and no embeds
1576 template.write('{"username": "bot"}')
1577 obj = Apprise.instantiate(
1578 "discord://{}/{}/".format(webhook_id, webhook_token)
1579 + "?template={}".format(str(template))
1580 )
1581 assert isinstance(obj, NotifyDiscord)
1582 assert (
1583 obj.notify(body="test", title="t", notify_type=NotifyType.INFO)
1584 is False
1585 )
1586 assert mock_post.called is False
1587
1588 # Case 2: content is an empty string
1589 template.write('{"content": ""}')
1590 obj = Apprise.instantiate(
1591 "discord://{}/{}/".format(webhook_id, webhook_token)
1592 + "?template={}".format(str(template))
1593 )
1594 assert isinstance(obj, NotifyDiscord)
1595 assert (
1596 obj.notify(body="test", title="t", notify_type=NotifyType.INFO)
1597 is False
1598 )
1599
1600 # Case 3: embeds is an empty list
1601 template.write('{"embeds": []}')
1602 obj = Apprise.instantiate(
1603 "discord://{}/{}/".format(webhook_id, webhook_token)
1604 + "?template={}".format(str(template))
1605 )
1606 assert isinstance(obj, NotifyDiscord)
1607 assert (
1608 obj.notify(body="test", title="t", notify_type=NotifyType.INFO)
1609 is False
1610 )
1611 assert mock_post.called is False
1612
1613
1614 @mock.patch("requests.post")
1615 def test_plugin_discord_template_bad_embeds(mock_post, tmpdir):
1616 """NotifyDiscord() template embeds containing non-dict entries fails."""
1617
1618 webhook_id = "A" * 24
1619 webhook_token = "B" * 64
1620
1621 # Prepare a mock response (should never be called)
1622 mock_post.return_value = mock.Mock(
1623 status_code=requests.codes.ok,
1624 content=b"",
1625 headers={},
1626 )
1627
1628 # Write a template where embeds contains a non-dict entry
1629 template = tmpdir.join("bad_embeds.json")
1630 template.write('{"embeds": ["not-a-dict"]}')
1631
1632 obj = Apprise.instantiate(
1633 "discord://{}/{}/".format(webhook_id, webhook_token)
1634 + "?template={}".format(str(template))
1635 )
1636 assert isinstance(obj, NotifyDiscord)
1637
1638 # Notification must fail because the embed entry is not a dict
1639 assert (
1640 obj.notify(body="test", title="t", notify_type=NotifyType.INFO)
1641 is False
1642 )
1643 assert mock_post.called is False
1644
1645
1646 @mock.patch("requests.post")
1647 def test_plugin_discord_template_send_failure(mock_post, tmpdir):
1648 """NotifyDiscord() HTTP failure in template mode."""
1649
1650 webhook_id = "A" * 24
1651 webhook_token = "B" * 64
1652
1653 # Write a valid template
1654 template = tmpdir.join("discord.json")
1655 template.write('{"content": "hello"}')
1656
1657 obj = Apprise.instantiate(
1658 "discord://{}/{}/".format(webhook_id, webhook_token)
1659 + "?template={}".format(str(template))
1660 )
1661 assert isinstance(obj, NotifyDiscord)
1662
1663 # Simulate an HTTP error response
1664 mock_post.return_value = mock.Mock(
1665 status_code=requests.codes.internal_server_error,
1666 content=b"",
1667 headers={},
1668 )
1669 assert (
1670 obj.notify(body="test", title="t", notify_type=NotifyType.INFO)
1671 is False
1672 )
1673 assert mock_post.called is True
1674
1675
1676 @mock.patch("requests.post")
1677 def test_plugin_discord_template_with_attachments(mock_post, tmpdir):
1678 """NotifyDiscord() template mode still sends attachments."""
1679
1680 webhook_id = "C" * 24
1681 webhook_token = "D" * 64
1682
1683 # Write a valid template
1684 template = tmpdir.join("discord.json")
1685 template.write('{"content": "{{app_body}}"}')
1686
1687 obj = Apprise.instantiate(
1688 "discord://{}/{}/".format(webhook_id, webhook_token)
1689 + "?template={}".format(str(template))
1690 )
1691 assert isinstance(obj, NotifyDiscord)
1692
1693 # Prepare a good mock response for both the template call and attachment
1694 mock_post.return_value = mock.Mock(
1695 status_code=requests.codes.ok,
1696 content=b"",
1697 headers={},
1698 )
1699
1700 # Attach a test file
1701 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
1702 assert (
1703 obj.notify(
1704 body="test",
1705 title="t",
1706 notify_type=NotifyType.INFO,
1707 attach=attach,
1708 )
1709 is True
1710 )
1711
1712 # Both the template message and the attachment should have been posted
1713 assert mock_post.call_count == 2
1714
1715
1716 @mock.patch("requests.post")
1717 def test_plugin_discord_attach_multi_batch(mock_post):
1718 """NotifyDiscord() multi-attachment batching."""
1719
1720 webhook_id = "C" * 24
1721 webhook_token = "D" * 64
1722
1723 response = mock.Mock()
1724 response.status_code = requests.codes.ok
1725 response.content = b""
1726 response.headers = {}
1727 mock_post.return_value = response
1728
1729 obj = Apprise.instantiate(
1730 f"discord://{webhook_id}/{webhook_token}/?format=markdown"
1731 )
1732 assert isinstance(obj, NotifyDiscord)
1733 assert obj.batch is True
1734
1735 # Three test attachments
1736 gif = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
1737 png = os.path.join(TEST_VAR_DIR, "apprise-test.png")
1738 jpg = os.path.join(TEST_VAR_DIR, "apprise-test.jpeg")
1739 attach = AppriseAttachment([gif, png, jpg])
1740
1741 # Default batch mode: all 3 files go in one POST (plus 1 for the message)
1742 assert obj.send(body="test", attach=attach) is True
1743 assert mock_post.call_count == 2
1744 mock_post.reset_mock()
1745
1746 # Reduce max per batch to 1: each file gets its own POST (4 calls total)
1747 obj.discord_max_attachments = 1
1748 assert obj.send(body="test", attach=attach) is True
1749 assert mock_post.call_count == 4
1750 mock_post.reset_mock()
1751 obj.discord_max_attachments = 10
1752
1753 # Size-based split: force a tiny per-batch byte budget
1754 obj.discord_max_attach_bytes = 1
1755 assert obj.send(body="test", attach=attach) is True
1756 assert mock_post.call_count == 4
1757 mock_post.reset_mock()
1758 obj.discord_max_attach_bytes = 25 * 1024 * 1024
1759
1760 # batch=False: reverts to legacy one-per-message regardless of max
1761 obj_no_batch = Apprise.instantiate(
1762 f"discord://{webhook_id}/{webhook_token}/?batch=no"
1763 )
1764 assert isinstance(obj_no_batch, NotifyDiscord)
1765 assert obj_no_batch.batch is False
1766 assert obj_no_batch.send(body="test", attach=attach) is True
1767 assert mock_post.call_count == 4
1768 mock_post.reset_mock()
1769
1770 # URL round-trip preserves batch flag
1771 url_on = NotifyDiscord(
1772 webhook_id=webhook_id,
1773 webhook_token=webhook_token,
1774 batch=True,
1775 ).url()
1776 assert "batch=yes" in url_on
1777 url_off = NotifyDiscord(
1778 webhook_id=webhook_id,
1779 webhook_token=webhook_token,
1780 batch=False,
1781 ).url()
1782 assert "batch=no" in url_off
1783 parsed = NotifyDiscord.parse_url(url_off)
1784 assert parsed["batch"] is False
1785
1786 # Guard 1: inaccessible file causes failure; body POST still goes out
1787 with mock.patch("os.path.isfile", return_value=False):
1788 assert obj.send(body="test", attach=attach) is False
1789 assert mock_post.call_count == 1
1790 mock_post.reset_mock()
1791
1792 # Guard 2: OSError on open causes failure; body POST still goes out
1793 with mock.patch("builtins.open", side_effect=OSError()):
1794 assert obj.send(body="test", attach=attach) is False
1795 assert mock_post.call_count == 1
1796 mock_post.reset_mock()
1797
1798 # HTTP error on the attachment batch POST; body POST succeeds
1799 bad_response = mock.Mock()
1800 bad_response.status_code = requests.codes.internal_server_error
1801 bad_response.content = b""
1802 bad_response.headers = {}
1803 mock_post.side_effect = [response, bad_response]
1804 assert obj.send(body="test", attach=attach) is False
1805 mock_post.side_effect = None
1806 mock_post.reset_mock()
1807
1808 # RequestException on the attachment batch POST
1809 mock_post.side_effect = [response, requests.RequestException()]
1810 assert obj.send(body="test", attach=attach) is False
1811 mock_post.side_effect = None
1812 mock_post.reset_mock()
1813
1814 # OSError raised by requests.post() during attachment send
1815 mock_post.side_effect = [response, OSError()]
1816 assert obj.send(body="test", attach=attach) is False
1817 mock_post.side_effect = None
1818 mock_post.reset_mock()
1819
1820 # Partial batch failure: first batch (files 0+1) succeeds, second fails.
1821 # Set max=2 so 3 files split into [gif, png] and [jpg].
1822 obj.discord_max_attachments = 2
1823 mock_post.side_effect = [response, response, bad_response]
1824 assert obj.send(body="test", attach=attach) is False
1825 assert mock_post.call_count == 3
1826 mock_post.side_effect = None
1827 obj.discord_max_attachments = 10