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