Debian Codegraph @

tests/test_plugin_revolt.py

raw
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28 from datetime import datetime, timedelta
29 from json import dumps, 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, NotifyFormat, NotifyType
43 from apprise.common import OverflowMode
44 from apprise.exception import AppriseImproperlyConfigured
45 from apprise.plugins.revolt import NotifyRevolt
46
47 logging.disable(logging.CRITICAL)
48
49 # Attachment Directory
50 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
51
52 # Prepare a Valid Response
53 REVOLT_GOOD_RESPONSE = dumps(
54 {
55 "_id": "AAAPWPMMQA2JJB59BR2EASWWWW",
56 "nonce": "01HPWPPMDJABC2FTDG54CBKKKS",
57 "channel": "00000000000000000000000000",
58 "author": "011244Q9S8NCS67KMM9543W7JJ",
59 "content": "test",
60 }
61 )
62
63 # Our Testing URLs
64 apprise_url_tests = (
65 (
66 "revolt://",
67 {
68 "instance": AppriseImproperlyConfigured,
69 },
70 ),
71 # An invalid url
72 (
73 "revolt://:@/",
74 {
75 "instance": AppriseImproperlyConfigured,
76 },
77 ),
78 # No channel_id specified
79 (
80 "revolt://%s" % ("i" * 24),
81 {
82 "instance": NotifyRevolt,
83 # Notify will fail
84 "response": False,
85 # Our response expected server response
86 "requests_response_text": REVOLT_GOOD_RESPONSE,
87 },
88 ),
89 # channel_id specified on url, but no Bot Token
90 (
91 "revolt://?channel=%s" % ("i" * 24),
92 {
93 "instance": AppriseImproperlyConfigured,
94 },
95 ),
96 # channel_id specified on url
97 (
98 "revolt://{}/?channel={}".format("i" * 24, "i" * 24),
99 {
100 "instance": NotifyRevolt,
101 # Our response expected server response
102 "requests_response_text": REVOLT_GOOD_RESPONSE,
103 },
104 ),
105 (
106 "revolt://{}/?to={}".format("i" * 24, "i" * 24),
107 {
108 "instance": NotifyRevolt,
109 # Our response expected server response
110 "requests_response_text": REVOLT_GOOD_RESPONSE,
111 },
112 ),
113 (
114 "revolt://{}/?to={}".format("i" * 24, "i" * 24),
115 {
116 "instance": NotifyRevolt,
117 # an invalid JSON Response
118 "requests_response_text": "{",
119 },
120 ),
121 # channel_id specified on url
122 (
123 "revolt://{}/?channel={},%20".format("i" * 24, "i" * 24),
124 {
125 "instance": NotifyRevolt,
126 # Our response expected server response
127 "requests_response_text": REVOLT_GOOD_RESPONSE,
128 },
129 ),
130 # Provide both a bot token and a channel id
131 (
132 "revolt://{}/{}".format("i" * 24, "t" * 64),
133 {
134 "instance": NotifyRevolt,
135 "requests_response_code": requests.codes.ok,
136 # Our response expected server response
137 "requests_response_text": REVOLT_GOOD_RESPONSE,
138 },
139 ),
140 (
141 "revolt://_?bot_token={}&channel={}".format("i" * 24, "t" * 64),
142 {
143 "instance": NotifyRevolt,
144 "requests_response_code": requests.codes.ok,
145 # Our response expected server response
146 "requests_response_text": REVOLT_GOOD_RESPONSE,
147 },
148 ),
149 # different format support
150 (
151 "revolt://{}/{}?format=markdown".format("i" * 24, "t" * 64),
152 {
153 "instance": NotifyRevolt,
154 "requests_response_code": requests.codes.ok,
155 # Our response expected server response
156 "requests_response_text": REVOLT_GOOD_RESPONSE,
157 },
158 ),
159 (
160 "revolt://{}/{}?format=text".format("i" * 24, "t" * 64),
161 {
162 "instance": NotifyRevolt,
163 "requests_response_code": requests.codes.ok,
164 # Our response expected server response
165 "requests_response_text": REVOLT_GOOD_RESPONSE,
166 },
167 ),
168 # Test with url
169 (
170 "revolt://{}/{}?url=http://localhost".format("i" * 24, "t" * 64),
171 {
172 "instance": NotifyRevolt,
173 "requests_response_code": requests.codes.ok,
174 # Our response expected server response
175 "requests_response_text": REVOLT_GOOD_RESPONSE,
176 },
177 ),
178 # URL implies markdown unless explicitly set otherwise
179 (
180 "revolt://{}/{}?format=text&url=http://localhost".format(
181 "i" * 24, "t" * 64
182 ),
183 {
184 "instance": NotifyRevolt,
185 "requests_response_code": requests.codes.ok,
186 # Our response expected server response
187 "requests_response_text": REVOLT_GOOD_RESPONSE,
188 },
189 ),
190 # Test with Icon URL
191 (
192 "revolt://{}/{}?icon_url=http://localhost/test.jpg".format(
193 "i" * 24, "t" * 64
194 ),
195 {
196 "instance": NotifyRevolt,
197 "requests_response_code": requests.codes.ok,
198 # Our response expected server response
199 "requests_response_text": REVOLT_GOOD_RESPONSE,
200 },
201 ),
202 # Icon URL implies markdown unless explicitly set otherwise
203 (
204 "revolt://{}/{}?format=text&icon_url=http://localhost/test.jpg".format(
205 "i" * 24, "t" * 64
206 ),
207 {
208 "instance": NotifyRevolt,
209 "requests_response_code": requests.codes.ok,
210 # Our response expected server response
211 "requests_response_text": REVOLT_GOOD_RESPONSE,
212 },
213 ),
214 # Test without any image set
215 (
216 "revolt://{}/{}".format("i" * 24, "t" * 64),
217 {
218 "instance": NotifyRevolt,
219 "requests_response_code": requests.codes.ok,
220 # don't include an image by default
221 "include_image": False,
222 # Our response expected server response
223 "requests_response_text": REVOLT_GOOD_RESPONSE,
224 },
225 ),
226 (
227 "revolt://{}/{}/".format("a" * 24, "b" * 64),
228 {
229 "instance": NotifyRevolt,
230 # force a failure
231 "response": False,
232 "requests_response_code": requests.codes.internal_server_error,
233 # Our response expected server response
234 "requests_response_text": REVOLT_GOOD_RESPONSE,
235 },
236 ),
237 (
238 "revolt://{}/{}/".format("a" * 24, "b" * 64),
239 {
240 "instance": NotifyRevolt,
241 # throw a bizarre code forcing us to fail to look it up
242 "response": False,
243 "requests_response_code": 999,
244 # Our response expected server response
245 "requests_response_text": REVOLT_GOOD_RESPONSE,
246 },
247 ),
248 (
249 "revolt://{}/{}/".format("a" * 24, "b" * 64),
250 {
251 "instance": NotifyRevolt,
252 # Throws a series of i/o exceptions with this flag
253 # is set and tests that we gracefully handle them
254 "test_requests_exceptions": True,
255 # Our response expected server response
256 "requests_response_text": REVOLT_GOOD_RESPONSE,
257 },
258 ),
259 )
260
261
262 def test_plugin_revolt_urls():
263 """NotifyRevolt() Apprise URLs."""
264
265 # Run our general tests
266 AppriseURLTester(tests=apprise_url_tests).run_all()
267
268
269 @mock.patch("requests.post")
270 def test_plugin_revolt_notifications(mock_post):
271 """NotifyRevolt() Notifications."""
272
273 # Initialize some generic (but valid) tokens
274 bot_token = "A" * 24
275 channel_id = "B" * 64
276
277 # Prepare Mock
278 mock_post.return_value = requests.Request()
279 mock_post.return_value.status_code = requests.codes.ok
280 mock_post.return_value.content = REVOLT_GOOD_RESPONSE
281
282 # Test our header parsing when not lead with a header
283 body = """
284 # Heading
285 @everyone and @admin, wake and meet our new user <@123>; <@&456>"
286 """
287
288 results = NotifyRevolt.parse_url(
289 f"revolt://{bot_token}/{channel_id}/?format=markdown"
290 )
291
292 assert isinstance(results, dict)
293 assert results["user"] is None
294 assert results["bot_token"] == bot_token
295 assert results["targets"] == [
296 channel_id,
297 ]
298 assert results["password"] is None
299 assert results["port"] is None
300 assert results["host"] == bot_token
301 assert results["fullpath"] == f"/{channel_id}/"
302 assert results["path"] == f"/{channel_id}/"
303 assert results["query"] is None
304 assert results["schema"] == "revolt"
305 assert results["url"] == f"revolt://{bot_token}/{channel_id}/"
306
307 instance = NotifyRevolt(**results)
308 assert isinstance(instance, NotifyRevolt)
309
310 response = instance.send(body=body)
311 assert response is True
312 assert mock_post.call_count == 1
313
314 # Reset our object
315 mock_post.reset_mock()
316
317 results = NotifyRevolt.parse_url(
318 f"revolt://{bot_token}/{channel_id}/?format=text"
319 )
320
321 assert isinstance(results, dict)
322 assert results["user"] is None
323 assert results["bot_token"] == bot_token
324 assert results["targets"] == [
325 channel_id,
326 ]
327 assert results["password"] is None
328 assert results["port"] is None
329 assert results["host"] == bot_token
330 assert results["fullpath"] == f"/{channel_id}/"
331 assert results["path"] == f"/{channel_id}/"
332 assert results["query"] is None
333 assert results["schema"] == "revolt"
334 assert results["url"] == f"revolt://{bot_token}/{channel_id}/"
335
336 instance = NotifyRevolt(**results)
337 assert isinstance(instance, NotifyRevolt)
338
339 response = instance.send(body=body)
340 assert response is True
341 assert mock_post.call_count == 1
342
343
344 @mock.patch("requests.post")
345 @mock.patch("time.sleep")
346 def test_plugin_revolt_general(mock_sleep, mock_post):
347 """NotifyRevolt() General Checks."""
348
349 # Prevent throttling
350 mock_sleep.return_value = True
351
352 # Turn off clock skew for local testing
353 NotifyRevolt.clock_skew = timedelta(seconds=0)
354
355 # Initialize some generic (but valid) tokens
356 bot_token = "A" * 24
357 channel_id = ",".join(["B" * 32, "C" * 32]) + ", ,%%"
358
359 # Prepare Mock
360 mock_post.return_value = requests.Request()
361 mock_post.return_value.status_code = requests.codes.ok
362 mock_post.return_value.content = REVOLT_GOOD_RESPONSE
363 mock_post.return_value.headers = {
364 "X-RateLimit-Remaining": 0,
365 "X-RateLimit-Reset-After": 1,
366 }
367
368 # Invalid bot_token
369 with pytest.raises(AppriseImproperlyConfigured):
370 NotifyRevolt(bot_token=None, targets=channel_id)
371 # Invalid bot_token (whitespace)
372 with pytest.raises(AppriseImproperlyConfigured):
373 NotifyRevolt(bot_token=" ", targets=channel_id)
374
375 obj = NotifyRevolt(bot_token=bot_token, targets=channel_id)
376 assert obj.ratelimit_remaining == 1
377
378 # Test that we get a string response
379 assert isinstance(obj.url(), str)
380
381 # This call includes an image with it's payload:
382 assert (
383 bool(
384 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
385 )
386 is True
387 )
388
389 # Force a case where there are no more remaining posts allowed
390 mock_post.return_value.headers = {
391 "X-RateLimit-Remaining": 0,
392 "X-RateLimit-Reset-After": 0,
393 }
394
395 # This call includes an image with it's payload:
396 assert (
397 bool(
398 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
399 )
400 is True
401 )
402
403 # behind the scenes, it should cause us to update our rate limit
404 assert obj.send(body="test") is True
405 assert obj.ratelimit_remaining == 0
406 assert isinstance(obj.ratelimit_reset, datetime)
407
408 # This should cause us to block
409 mock_post.return_value.headers = {
410 "X-RateLimit-Remaining": 0,
411 "X-RateLimit-Reset-After": 3000,
412 }
413 assert obj.send(body="test") is True
414 assert obj.ratelimit_remaining == 0
415 assert isinstance(obj.ratelimit_reset, datetime)
416
417 # Reset our variable back to 1
418 mock_post.return_value.headers = {
419 "X-RateLimit-Remaining": 0,
420 "X-RateLimit-Reset-After": 10000,
421 }
422 del mock_post.return_value.headers["X-RateLimit-Remaining"]
423 assert obj.send(body="test") is True
424 assert obj.ratelimit_remaining == 0
425 assert isinstance(obj.ratelimit_reset, datetime)
426
427 # Return our object, but place it in the future forcing us to block
428 mock_post.return_value.headers = {
429 "X-RateLimit-Remaining": 0,
430 "X-RateLimit-Reset-After": 0,
431 }
432
433 obj.ratelimit_remaining = 0
434 assert obj.send(body="test") is True
435
436 # Test 429 error response
437 mock_post.return_value.status_code = requests.codes.too_many_requests
438
439 # The below will attempt a second transmission and fail (because we didn't
440 # set up a second post request to pass) :)
441 assert obj.send(body="test") is False
442
443 # Return our object, but place it in the future forcing us to block
444 mock_post.return_value.status_code = requests.codes.ok
445 mock_post.return_value.headers = {
446 "X-RateLimit-Remaining": 0,
447 "X-RateLimit-Reset-After": 0,
448 }
449 assert obj.send(body="test") is True
450
451 # Return our limits to always work
452 obj.ratelimit_remaining = 1
453
454 # Return our headers to normal
455 mock_post.return_value.headers = {
456 "X-RateLimit-Remaining": 0,
457 "X-RateLimit-Reset-After": 1,
458 }
459
460 # This call includes an image with it's payload:
461 assert (
462 bool(
463 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
464 )
465 is True
466 )
467
468 # Create an apprise instance
469 a = Apprise()
470
471 # Our processing is slightly different when we aren't using markdown
472 # as we do not pre-parse content during our notifications
473 assert a.add(f"revolt://{bot_token}/{channel_id}/?format=markdown") is True
474
475 # Toggle our logo availability
476 a.asset.image_url_logo = None
477 assert (
478 bool(a.notify(body="body", title="title", notify_type=NotifyType.INFO))
479 is True
480 )
481
482
483 @mock.patch("requests.post")
484 def test_plugin_revolt_overflow(mock_post):
485 """NotifyRevolt() Overflow Checks."""
486
487 # Initialize some generic (but valid) tokens
488 bot_token = "A" * 24
489 channel_id = "B" * 64
490
491 # Prepare Mock
492 mock_post.return_value = requests.Request()
493 mock_post.return_value.status_code = requests.codes.ok
494 mock_post.return_value.content = REVOLT_GOOD_RESPONSE
495
496 # Some variables we use to control the data we work with
497 body_len = 2005
498 title_len = 110
499
500 # Number of characters per line
501 row = 24
502
503 # Create a large body and title with random data
504 body = "".join(choice(str_alpha + str_num + " ") for _ in range(body_len))
505 body = "\r\n".join([body[i : i + row] for i in range(0, len(body), row)])
506
507 # Create our title using random data
508 title = "".join(choice(str_alpha + str_num) for _ in range(title_len))
509
510 results = NotifyRevolt.parse_url(
511 f"revolt://{bot_token}/{channel_id}/?overflow=split"
512 )
513
514 assert isinstance(results, dict)
515 assert results["user"] is None
516 assert results["bot_token"] == bot_token
517 assert results["targets"] == [
518 channel_id,
519 ]
520 assert results["password"] is None
521 assert results["port"] is None
522 assert results["host"] == bot_token
523 assert results["fullpath"] == f"/{channel_id}/"
524 assert results["path"] == f"/{channel_id}/"
525 assert results["query"] is None
526 assert results["schema"] == "revolt"
527 assert results["url"] == f"revolt://{bot_token}/{channel_id}/"
528
529 instance = NotifyRevolt(**results)
530 assert isinstance(instance, NotifyRevolt)
531
532 results = instance._apply_overflow(
533 body, title=title, overflow=OverflowMode.SPLIT
534 )
535 # Split into 2
536 assert len(results) == 2
537 assert len(results[0]["title"]) <= instance.title_maxlen
538 assert len(results[0]["body"]) <= instance.body_maxlen
539
540
541 @mock.patch("requests.post")
542 def test_plugin_revolt_markdown_extra(mock_post):
543 """NotifyRevolt() Markdown Extra Checks."""
544
545 # Initialize some generic (but valid) tokens
546 bot_token = "A" * 24
547 channel_id = "B" * 64
548
549 # Prepare Mock
550 mock_post.return_value = requests.Request()
551 mock_post.return_value.status_code = requests.codes.ok
552 mock_post.return_value.content = REVOLT_GOOD_RESPONSE
553
554 # Reset our apprise object
555 a = Apprise()
556
557 # We want to further test our markdown support to accommodate bug rased on
558 # 2022.10.25; see https://github.com/caronc/apprise/issues/717
559 assert a.add(f"revolt://{bot_token}/{channel_id}/?format=markdown") is True
560
561 test_markdown = "[green-blue](https://google.com)"
562
563 # This call includes an image with it's payload:
564 assert (
565 bool(
566 a.notify(
567 body=test_markdown,
568 title="title",
569 notify_type=NotifyType.INFO,
570 body_format=NotifyFormat.TEXT,
571 )
572 )
573 is True
574 )
575
576 assert (
577 bool(a.notify(body="body", title="title", notify_type=NotifyType.INFO))
578 is True
579 )
580
581
582 @mock.patch("requests.post")
583 def test_plugin_revolt_html_to_markdown_format(mock_post):
584 """NotifyRevolt(): HTML body is converted to Markdown."""
585
586 # Initialize some generic (but valid) tokens
587 bot_token = "A" * 24
588 channel_id = "B" * 64
589
590 # Prepare Mock
591 mock_post.return_value = requests.Request()
592 mock_post.return_value.status_code = requests.codes.ok
593 mock_post.return_value.content = REVOLT_GOOD_RESPONSE
594
595 # Instantiate a Revolt plugin in Markdown mode
596 aobj = Apprise()
597 assert aobj.add(f"revolt://{bot_token}/{channel_id}/?format=markdown")
598
599 # Notify with an HTML body; the framework should convert it
600 # to Markdown before dispatching to Revolt
601 result = aobj.notify(
602 body="<b>hello</b> <i>world</i>",
603 body_format=NotifyFormat.HTML,
604 )
605 assert bool(result) is True
606 assert mock_post.call_count == 1
607
608 # The body must arrive inside the Markdown embed, not as
609 # stripped plain text in "content"
610 payload = loads(mock_post.call_args_list[0][1]["data"])
611 assert payload["embeds"][0]["description"] == "**hello** *world*"