Debian Codegraph @

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