Debian Codegraph @

tests/test_plugin_fluxer.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 from __future__ import annotations
28
29 from datetime import datetime, timedelta, timezone
30 from json import loads
31
32 # Disable logging for a cleaner testing output
33 import logging
34 import os
35 from random import choice
36 from string import ascii_uppercase as str_alpha, digits as str_num
37 from unittest import mock
38
39 from helpers import AppriseURLTester
40 import pytest
41 import requests
42
43 from apprise import Apprise, AppriseAttachment, NotifyFormat, NotifyType
44 from apprise.common import OverflowMode
45 from apprise.plugins.fluxer import NotifyFluxer
46
47 logging.disable(logging.CRITICAL)
48
49 # Attachment Directory
50 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
51
52
53 def _tokens() -> tuple[str, str]:
54 """Return tokens that satisfy Fluxer validation."""
55
56 # webhook_id: digits, >= 10
57 # webhook_token: [A-Za-z0-9_-], >= 16
58 return ("0" * 10, "B" * 40)
59
60
61 # Our Testing URLs
62 apprise_url_tests = (
63 (
64 "fluxer://",
65 {
66 "instance": TypeError,
67 },
68 ),
69 # An invalid url
70 (
71 "fluxer://:@/",
72 {
73 "instance": TypeError,
74 },
75 ),
76 # No webhook_token specified
77 (
78 "fluxer://%s" % ("0" * 10),
79 {
80 "instance": TypeError,
81 },
82 ),
83 # Provide both a webhook id and a webhook token
84 (
85 "fluxer://{}/{}".format(*_tokens()),
86 {
87 "instance": NotifyFluxer,
88 "requests_response_code": requests.codes.no_content,
89 },
90 ),
91 # Provide a temporary username
92 (
93 "fluxer://l2g@{}/{}".format(*_tokens()),
94 {
95 "instance": NotifyFluxer,
96 "requests_response_code": requests.codes.no_content,
97 },
98 ),
99 # Mode set to private, but no hostname was fluxers; we toggle to cloud mode
100 (
101 "fluxer://api.fluxer.app/{}/{}?mode=private".format(*_tokens()),
102 {
103 "instance": NotifyFluxer,
104 "requests_response_code": requests.codes.no_content,
105 },
106 ),
107 # test image= field
108 (
109 "fluxer://{}/{}?format=markdown&footer=Yes&image=Yes&ping=Joe".format(
110 *_tokens()
111 ),
112 {
113 "instance": NotifyFluxer,
114 "requests_response_code": requests.codes.no_content,
115 # don't include an image by default
116 "include_image": False,
117 },
118 ),
119 (
120 "fluxer://{}/{}?format=markdown&footer=Yes&image=No&fields=no".format(
121 *_tokens()
122 ),
123 {
124 "instance": NotifyFluxer,
125 "requests_response_code": requests.codes.no_content,
126 },
127 ),
128 (
129 "fluxer://jack@{}/{}?format=markdown&footer=Yes&image=Yes".format(
130 *_tokens()
131 ),
132 {
133 "instance": NotifyFluxer,
134 "requests_response_code": requests.codes.no_content,
135 },
136 ),
137 (
138 "fluxer://jack@{}/{}?mode=private&host=example.ca".format(*_tokens()),
139 {
140 "instance": NotifyFluxer,
141 "requests_response_code": requests.codes.no_content,
142 },
143 ),
144 (
145 "fluxer://{}/{}?mode=private&host=example.ca&name=jack".format(
146 *_tokens()
147 ),
148 {
149 "instance": NotifyFluxer,
150 "requests_response_code": requests.codes.no_content,
151 },
152 ),
153 (
154 "fluxer://example.ca:123/{}/{}".format(*_tokens()),
155 {
156 "instance": NotifyFluxer,
157 "requests_response_code": requests.codes.no_content,
158 },
159 ),
160 (
161 # Invalid Mode
162 "fluxer://jack@{}/{}?mode=invalid".format(*_tokens()),
163 {
164 "instance": TypeError,
165 },
166 ),
167 (
168 "https://api.fluxer.app/webhooks/{}/{}".format(*_tokens()),
169 {
170 # Native URL Support
171 "instance": NotifyFluxer,
172 "requests_response_code": requests.codes.no_content,
173 },
174 ),
175 (
176 "https://api.fluxer.app/v1/webhooks/{}/{}?footer=yes".format(
177 *_tokens()
178 ),
179 {
180 # Native URL Support with arguments
181 "instance": NotifyFluxer,
182 "requests_response_code": requests.codes.no_content,
183 "privacy_url": "fluxer://0...0/B...B/",
184 },
185 ),
186 (
187 "https://api.fluxer.app/v1/webhooks/{}/{}?footer=yes&botname=joe".format(
188 *_tokens()
189 ),
190 {
191 # Native URL Support with arguments
192 "instance": NotifyFluxer,
193 "requests_response_code": requests.codes.no_content,
194 "privacy_url": "fluxer://[email protected]/B...B/",
195 },
196 ),
197 (
198 "fluxer://{}/{}?format=markdown&avatar=No&footer=No".format(
199 *_tokens()
200 ),
201 {
202 "instance": NotifyFluxer,
203 "requests_response_code": requests.codes.no_content,
204 },
205 ),
206 (
207 "fluxer://{}/{}?flags=1".format(*_tokens()),
208 {
209 "instance": NotifyFluxer,
210 "requests_response_code": requests.codes.no_content,
211 },
212 ),
213 (
214 "fluxer://{}/{}?flags=-1".format(*_tokens()),
215 {
216 # invalid flags specified (variation 1)
217 "instance": TypeError,
218 },
219 ),
220 (
221 "fluxer://{}/{}?flags=invalid".format(*_tokens()),
222 {
223 # invalid flags specified (variation 2)
224 "instance": TypeError,
225 },
226 ),
227 # different format support
228 (
229 "fluxer://{}/{}?format=markdown".format(*_tokens()),
230 {
231 "instance": NotifyFluxer,
232 "requests_response_code": requests.codes.no_content,
233 },
234 ),
235 # Thread ID (forces markdown mode)
236 (
237 "fluxer://{}/{}?format=markdown&thread=abc123".format(*_tokens()),
238 {
239 "instance": NotifyFluxer,
240 "requests_response_code": requests.codes.no_content,
241 },
242 ),
243 (
244 "fluxer://{}/{}?format=text".format(*_tokens()),
245 {
246 "instance": NotifyFluxer,
247 "requests_response_code": requests.codes.no_content,
248 },
249 ),
250 # Test with href (title link)
251 (
252 "fluxer://{}/{}?hmarkdown=true&ref=http://localhost".format(
253 *_tokens()
254 ),
255 {
256 "instance": NotifyFluxer,
257 "requests_response_code": requests.codes.no_content,
258 },
259 ),
260 # Test with url (title link) - Alias of href
261 (
262 "fluxer://{}/{}?markdown=true&url=http://localhost".format(*_tokens()),
263 {
264 "instance": NotifyFluxer,
265 "requests_response_code": requests.codes.no_content,
266 },
267 ),
268 # Test with avatar URL
269 (
270 "fluxer://{}/{}?avatar_url=http://localhost/test.jpg".format(
271 *_tokens()
272 ),
273 {
274 "instance": NotifyFluxer,
275 "requests_response_code": requests.codes.no_content,
276 },
277 ),
278 # Test without image set
279 (
280 "fluxer://{}/{}".format(*_tokens()),
281 {
282 "instance": NotifyFluxer,
283 "requests_response_code": requests.codes.no_content,
284 # don't include an image by default
285 "include_image": False,
286 },
287 ),
288 (
289 "fluxer://{}/{}".format(*_tokens()),
290 {
291 "instance": NotifyFluxer,
292 # force a failure
293 "response": False,
294 "requests_response_code": requests.codes.internal_server_error,
295 },
296 ),
297 (
298 "fluxer://{}/{}".format(*_tokens()),
299 {
300 "instance": NotifyFluxer,
301 # throw a bizarre code forcing us to fail to look it up
302 "response": False,
303 "requests_response_code": 999,
304 },
305 ),
306 (
307 "fluxer://{}/{}".format(*_tokens()),
308 {
309 "instance": NotifyFluxer,
310 # Throws a series of i/o exceptions with this flag set and tests
311 # that we gracefully handle them
312 "test_requests_exceptions": True,
313 },
314 ),
315 )
316
317
318 def test_plugin_fluxer_urls() -> None:
319 """NotifyFluxer() Apprise URLs."""
320
321 # Run our general tests
322 AppriseURLTester(tests=apprise_url_tests).run_all()
323
324
325 @mock.patch("requests.post")
326 def test_plugin_fluxer_notifications(mock_post: mock.MagicMock) -> None:
327 """NotifyFluxer() Notifications/Ping Support."""
328
329 webhook_id, webhook_token = _tokens()
330
331 # Prepare Mock
332 mock_post.return_value = requests.Request()
333 mock_post.return_value.status_code = requests.codes.ok
334 mock_post.return_value.content = b""
335 mock_post.return_value.headers = {}
336
337 # Test our header parsing when not lead with a header
338 body = """
339 # Heading
340 @everyone and @admin, wake and meet our new user <@123>; <@&456>"
341 """
342
343 results = NotifyFluxer.parse_url(
344 f"fluxer://{webhook_id}/{webhook_token}/?format=markdown"
345 )
346
347 assert isinstance(results, dict)
348 assert results["user"] is None
349 assert results["webhook_id"] == webhook_id
350 assert results["webhook_token"] == webhook_token
351 assert results["schema"] == "fluxer"
352
353 instance = NotifyFluxer(**results)
354 assert isinstance(instance, NotifyFluxer)
355
356 assert instance.send(body=body) is True
357 assert mock_post.call_count == 1
358
359 details = mock_post.call_args_list[0]
360 assert (
361 details[0][0]
362 == f"https://api.fluxer.app/webhooks/{webhook_id}/{webhook_token}"
363 )
364
365 payload = loads(details[1]["data"])
366 assert isinstance(payload, dict)
367
368 assert "allow_mentions" in payload
369 assert set(payload["allow_mentions"]["users"]) == {"123"}
370 assert set(payload["allow_mentions"]["roles"]) == {"456"}
371 assert set(payload["allow_mentions"]["parse"]) == {"everyone", "admin"}
372 assert payload["content"].startswith("👉 ")
373
374 # Reset our object
375 mock_post.reset_mock()
376
377 results = NotifyFluxer.parse_url(
378 f"fluxer://{webhook_id}/{webhook_token}/?format=text"
379 )
380
381 instance = NotifyFluxer(**results)
382 assert isinstance(instance, NotifyFluxer)
383
384 assert instance.send(body=body) is True
385 payload = loads(mock_post.call_args_list[0][1]["data"])
386
387 # text mode does not parse mentions from body
388 assert "allow_mentions" not in payload
389
390 # Reset our object
391 mock_post.reset_mock()
392
393 body = " "
394 results = NotifyFluxer.parse_url(
395 # & -> %26 for role otherwise & separates our URL from further parsing
396 f"fluxer://{webhook_id}/{webhook_token}/?ping=@joe,<@321>,<@%26654>"
397 )
398 instance = NotifyFluxer(**results)
399 assert isinstance(instance, NotifyFluxer)
400
401 assert instance.send(body=body) is True
402 payload = loads(mock_post.call_args_list[0][1]["data"])
403
404 assert "allow_mentions" in payload
405 assert set(payload["allow_mentions"]["users"]) == {"321"}
406 assert set(payload["allow_mentions"]["roles"]) == {"654"}
407 assert set(payload["allow_mentions"]["parse"]) == {"joe"}
408 assert "<@321>" in payload["content"]
409 assert "<@&654>" in payload["content"]
410 assert "@joe" in payload["content"]
411
412 # Reset our object
413 mock_post.reset_mock()
414
415 # Test our body in text mode, with ping=set
416 body = """
417 # Heading
418 @everyone and @admin, wake and meet our new user <@123>; <@&456>"
419 """
420
421 results = NotifyFluxer.parse_url(
422 # & -> %26 for role otherwise & separates our URL from further parsing
423 f"fluxer://{webhook_id}/{webhook_token}/?ping=@joe,<@321>,<@%26654>"
424 "&format=text"
425 )
426
427 instance = NotifyFluxer(**results)
428 assert isinstance(instance, NotifyFluxer)
429
430 assert instance.send(body=body) is True
431 payload = loads(mock_post.call_args_list[0][1]["data"])
432
433 # Payload only includes elements on ping= line with text mode
434 assert "allow_mentions" in payload
435 assert set(payload["allow_mentions"]["users"]) == {"321"}
436 assert set(payload["allow_mentions"]["roles"]) == {"654"}
437 assert set(payload["allow_mentions"]["parse"]) == {"joe"}
438
439
440 @mock.patch("requests.post")
441 @mock.patch("time.sleep")
442 def test_plugin_fluxer_429(
443 mock_sleep: mock.MagicMock,
444 mock_post: mock.MagicMock,
445 ) -> None:
446 """
447 NotifyFluxer() 429 handling
448
449 Focus: Fluxer-specific HTTP 429 + Retry-After handling (recursive retry),
450 including header parsing edge cases and retry exhaustion.
451 """
452
453 # Prevent throttling side effects
454 mock_sleep.return_value = True
455
456 webhook_id, webhook_token = _tokens()
457
458 # Basic construction checks (keep these, they match plugin validation)
459 with pytest.raises(TypeError):
460 NotifyFluxer(webhook_id=None, webhook_token=webhook_token)
461 with pytest.raises(TypeError):
462 NotifyFluxer(webhook_id=" ", webhook_token=webhook_token)
463
464 with pytest.raises(TypeError):
465 NotifyFluxer(webhook_id=webhook_id, webhook_token=None)
466 with pytest.raises(TypeError):
467 NotifyFluxer(webhook_id=webhook_id, webhook_token=" ")
468
469 obj = NotifyFluxer(
470 webhook_id=webhook_id,
471 webhook_token=webhook_token,
472 footer=True,
473 include_image=True,
474 )
475
476 # url() must always return a string
477 assert isinstance(obj.url(), str)
478
479 # Helper to build responses
480 def _resp(code: int, headers: dict[str, str] | None = None) -> mock.Mock:
481 r = mock.Mock()
482 r.status_code = code
483 r.content = b""
484 r.headers = headers or {}
485 return r
486
487 # Retry-After header missing -> defaults to default_delay_sec (1.0)
488 mock_post.reset_mock()
489 mock_sleep.reset_mock()
490 mock_post.side_effect = [
491 _resp(requests.codes.too_many_requests, {}),
492 _resp(requests.codes.no_content, {}),
493 ]
494
495 assert obj.send(body="test") is True
496 assert mock_post.call_count == 2
497 assert mock_sleep.call_count == 1
498 assert mock_sleep.call_args_list[-1][0][0] == pytest.approx(
499 1.0, rel=0, abs=0.05
500 )
501
502 # Retry-After invalid -> falls back to 1.0
503 mock_post.reset_mock()
504 mock_sleep.reset_mock()
505 mock_post.side_effect = [
506 _resp(requests.codes.too_many_requests, {"Retry-After": "garbage"}),
507 _resp(requests.codes.no_content, {}),
508 ]
509
510 assert obj.send(body="test") is True
511 assert mock_post.call_count == 2
512 assert mock_sleep.call_count >= 1
513 assert mock_sleep.call_args_list[-1][0][0] == pytest.approx(
514 1.0, rel=0, abs=0.05
515 )
516
517 # Retry-After < 1.0 -> max(1.0, value) enforces 1.0
518 mock_post.reset_mock()
519 mock_sleep.reset_mock()
520 mock_post.side_effect = [
521 _resp(requests.codes.too_many_requests, {"Retry-After": "0.25"}),
522 _resp(requests.codes.no_content, {}),
523 ]
524
525 assert obj.send(body="test") is True
526 assert mock_post.call_count == 2
527 assert mock_sleep.call_count >= 1
528 assert mock_sleep.call_args_list[-1][0][0] == pytest.approx(
529 1.0, rel=0, abs=0.05
530 )
531
532 # Retry-After valid integer -> sleeps that many seconds
533 mock_post.reset_mock()
534 mock_sleep.reset_mock()
535 mock_post.side_effect = [
536 _resp(requests.codes.too_many_requests, {"Retry-After": "2"}),
537 _resp(requests.codes.no_content, {}),
538 ]
539
540 assert obj.send(body="test") is True
541 assert mock_post.call_count == 2
542 assert mock_sleep.call_count >= 1
543 assert mock_sleep.call_args_list[-1][0][0] == pytest.approx(
544 2.0, rel=0, abs=0.05
545 )
546
547 # Retry exhaustion: default send() retries once.
548 # If we get 429 twice, second one is not retried and send fails.
549 mock_post.reset_mock()
550 mock_sleep.reset_mock()
551 mock_post.side_effect = [
552 _resp(requests.codes.too_many_requests, {"Retry-After": "1"}),
553 _resp(requests.codes.too_many_requests, {"Retry-After": "1"}),
554 ]
555
556 assert obj.send(body="test") is False
557 assert mock_post.call_count == 2
558 assert mock_sleep.call_count >= 1
559
560 mock_sleep.reset_mock()
561 mock_post.reset_mock()
562
563 response = mock.Mock()
564 response.status_code = requests.codes.no_content
565 response.content = b""
566 response.headers = {}
567 mock_post.return_value = response
568 mock_post.side_effect = None
569
570 # Force the 'now <= ratelimit_reset' path to compute a wait.
571 obj = NotifyFluxer(webhook_id=webhook_id, webhook_token=webhook_token)
572
573 # Force the rate-limit gate to run
574 obj.ratelimit_remaining = 0.0
575
576 now = datetime.now(timezone.utc).replace(tzinfo=None)
577 obj.ratelimit_reset = now - timedelta(seconds=2)
578
579 with mock.patch.object(obj, "throttle") as m_throttle:
580 assert obj.send(body="test") is True
581
582 # We expect throttle(wait=~2.0) to be called.
583 assert m_throttle.call_count >= 1
584 wait = m_throttle.call_args_list[-1][1].get("wait")
585
586 assert wait is None
587
588 # Call count
589 assert mock_post.call_count == 1
590
591 # Reset our object
592 mock_post.reset_mock()
593
594 # Force the 'now < ratelimit_reset' path to compute a wait.
595 obj = NotifyFluxer(webhook_id=webhook_id, webhook_token=webhook_token)
596
597 # Force the rate-limit gate to run
598 obj.ratelimit_remaining = 0.0
599
600 # Bracket the call with timestamps so the assertion is
601 # architecture-independent (slow ppc64le build machines can add
602 # hundreds of ms of overhead between captures of datetime.now()).
603 t_before = datetime.now(timezone.utc).replace(tzinfo=None)
604 obj.ratelimit_reset = t_before + timedelta(seconds=2)
605
606 with mock.patch.object(obj, "throttle") as m_throttle:
607 assert obj.send(body="test") is True
608
609 t_after = datetime.now(timezone.utc).replace(tzinfo=None)
610
611 # We expect throttle(wait=~2.0) to be called.
612 assert m_throttle.call_count >= 1
613 wait = m_throttle.call_args_list[-1][1].get("wait")
614
615 assert wait is not None
616 # wait = ratelimit_reset - now_inside_plugin
617 # The plugin's 'now' is somewhere in [t_before, t_after], so:
618 # lower bound: ratelimit_reset - t_after = 2.0 - elapsed
619 # upper bound: ratelimit_reset - t_before = 2.0
620 elapsed = (t_after - t_before).total_seconds()
621 assert (2.0 - elapsed) <= wait <= 2.0
622
623 # Call count
624 assert mock_post.call_count == 1
625
626
627 @mock.patch("requests.post")
628 def test_plugin_fluxer_general(
629 mock_post: mock.MagicMock,
630 ) -> None:
631 """NotifyFluxer() General Checks."""
632
633 webhook_id, webhook_token = _tokens()
634
635 # Prepare Mock
636 mock_post.return_value = requests.Request()
637 mock_post.return_value.status_code = requests.codes.ok
638 mock_post.return_value.content = ""
639
640 # Invalid webhook id
641 with pytest.raises(TypeError):
642 NotifyFluxer(webhook_id=None, webhook_token=webhook_token)
643 # Invalid webhook id (whitespace)
644 with pytest.raises(TypeError):
645 NotifyFluxer(webhook_id=" ", webhook_token=webhook_token)
646
647 # Invalid webhook token
648 with pytest.raises(TypeError):
649 NotifyFluxer(webhook_id=webhook_id, webhook_token=None)
650
651 # Private mode but no hostname provided
652 with pytest.raises(TypeError):
653 NotifyFluxer(
654 webhook_id=webhook_id,
655 webhook_token=webhook_token,
656 mode="private",
657 )
658
659 obj = NotifyFluxer(
660 webhook_id=webhook_id,
661 webhook_token=webhook_token,
662 footer=True,
663 include_image=True,
664 )
665
666 # Simple Markdown Single line of text
667 test_markdown = "body"
668 desc, results = obj.extract_markdown_sections(test_markdown)
669 assert isinstance(results, list) is True
670 assert len(results) == 0
671 assert desc == "body"
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"fluxer://{webhook_id}/{webhook_token}/"
745 "?format=markdown&footer=Yes"
746 )
747 is True
748 )
749
750 # This call includes an image with its payload:
751 orig_fluxer_max_fields = NotifyFluxer.fluxer_max_fields
752 try:
753 NotifyFluxer.fluxer_max_fields = 1
754 assert (
755 a.notify(
756 body=test_markdown,
757 title="title",
758 notify_type=NotifyType.INFO,
759 body_format=NotifyFormat.TEXT,
760 )
761 is True
762 )
763 finally:
764 # Restore the original value to avoid impacting other tests
765 NotifyFluxer.fluxer_max_fields = orig_fluxer_max_fields
766
767 # Throw an exception on the forth call to requests.post()
768 # This allows to test our batch field processing
769 response = mock.Mock()
770 response.content = b""
771 response.status_code = requests.codes.ok
772 response.headers = {}
773 mock_post.return_value = response
774 mock_post.side_effect = [
775 response,
776 response,
777 response,
778 requests.RequestException(),
779 ]
780
781 # Test our markdown
782 obj = Apprise.instantiate(
783 f"fluxer://{webhook_id}/{webhook_token}/?format=markdown"
784 )
785 assert isinstance(obj, NotifyFluxer)
786
787 # Force batching so we actually hit the 4th post() call
788 orig_fluxer_max_fields = NotifyFluxer.fluxer_max_fields
789 try:
790 NotifyFluxer.fluxer_max_fields = 1
791
792 assert (
793 obj.notify(
794 body=test_markdown, title="title", notify_type=NotifyType.INFO
795 )
796 is False
797 )
798 finally:
799 NotifyFluxer.fluxer_max_fields = orig_fluxer_max_fields
800 mock_post.side_effect = None
801
802 # Empty String
803 desc, results = obj.extract_markdown_sections("")
804 assert isinstance(results, list) is True
805 assert len(results) == 0
806
807 # No desc details filled out
808 assert isinstance(desc, str) is True
809 assert not desc
810
811 # String without Heading
812 test_markdown = (
813 "Just a string without any header entries.\n" + "A second line"
814 )
815 desc, results = obj.extract_markdown_sections(test_markdown)
816 assert isinstance(results, list) is True
817 assert len(results) == 0
818
819 # No desc details filled out
820 assert isinstance(desc, str) is True
821 assert (
822 desc == "Just a string without any header entries.\n" + "A second line"
823 )
824
825 # Use our test markdown string during a notification
826 assert (
827 obj.notify(
828 body=test_markdown, title="title", notify_type=NotifyType.INFO
829 )
830 is True
831 )
832
833 # Create an apprise instance
834 a = Apprise()
835
836 # Our processing is slightly different when we aren't using markdown
837 # as we do not pre-parse content during our notifications
838 assert (
839 a.add(
840 f"fluxer://{webhook_id}/{webhook_token}/"
841 "?format=markdown&footer=Yes"
842 )
843 is True
844 )
845
846 # This call includes an image with it's payload:
847 assert (
848 a.notify(
849 body=test_markdown,
850 title="title",
851 notify_type=NotifyType.INFO,
852 body_format=NotifyFormat.TEXT,
853 )
854 is True
855 )
856
857 assert (
858 a.notify(
859 body=test_markdown,
860 title="title",
861 notify_type=NotifyType.INFO,
862 body_format=NotifyFormat.MARKDOWN,
863 )
864 is True
865 )
866
867 # Toggle our logo availability
868 a.asset.image_url_logo = None
869 assert (
870 a.notify(body="body", title="title", notify_type=NotifyType.INFO)
871 is True
872 )
873
874 # Create an apprise instance
875 a = Apprise()
876
877 # Reset our object
878 mock_post.reset_mock()
879
880 # Test our threading
881 assert (
882 a.add(f"fluxer://{webhook_id}/{webhook_token}/?thread=12345") is True
883 )
884
885 # This call includes an image with it's payload:
886 assert a.notify(body="test", title="title") is True
887
888 assert mock_post.call_count == 1
889 response = mock_post.call_args_list[0][1]
890 assert "params" in response
891 assert response["params"].get("thread_id") == "12345"
892
893
894 @mock.patch("requests.post")
895 def test_plugin_fluxer_overflow(mock_post):
896 """NotifyFluxer() Overflow Checks."""
897
898 webhook_id, webhook_token = _tokens()
899
900 # Prepare Mock
901 mock_post.return_value = requests.Request()
902 mock_post.return_value.status_code = requests.codes.ok
903
904 # Some variables we use to control the data we work with
905 body_len = 8000
906 title_len = 1024
907
908 # Number of characters per line
909 row = 24
910
911 # Create a large body and title with random data
912 body = "".join(choice(str_alpha + str_num + " ") for _ in range(body_len))
913 body = "\r\n".join([body[i : i + row] for i in range(0, len(body), row)])
914
915 # Create our title using random data
916 title = "".join(choice(str_alpha + str_num) for _ in range(title_len))
917
918 results = NotifyFluxer.parse_url(
919 f"fluxer://{webhook_id}/{webhook_token}/?overflow=split"
920 )
921
922 instance = NotifyFluxer(**results)
923 assert isinstance(instance, NotifyFluxer)
924
925 results = instance._apply_overflow(
926 body, title=title, overflow=OverflowMode.SPLIT
927 )
928
929 # Ensure we never exceed 2000 characters
930 for entry in results:
931 assert len(entry["title"]) <= instance.title_maxlen
932 assert len(entry["title"]) + len(entry["body"]) <= instance.body_maxlen
933
934
935 @mock.patch("requests.post")
936 def test_plugin_fluxer_markdown_extra(mock_post):
937 """NotifyFluxer() Markdown Extra Checks."""
938
939 webhook_id, webhook_token = _tokens()
940
941 # Prepare Mock
942 mock_post.return_value = requests.Request()
943 mock_post.return_value.status_code = requests.codes.ok
944 mock_post.return_value.content = b""
945 mock_post.return_value.headers = {}
946
947 # Reset our apprise object
948 a = Apprise()
949
950 assert (
951 a.add(
952 f"fluxer://{webhook_id}/{webhook_token}/"
953 "?format=markdown&footer=Yes"
954 )
955 is True
956 )
957
958 test_markdown = "[green-blue](https://google.com)"
959
960 # This call includes an image with it's payload:
961 assert (
962 a.notify(
963 body=test_markdown,
964 title="title",
965 notify_type=NotifyType.INFO,
966 body_format=NotifyFormat.TEXT,
967 )
968 is True
969 )
970
971 assert (
972 a.notify(body="body", title="title", notify_type=NotifyType.INFO)
973 is True
974 )
975
976
977 @mock.patch("requests.post")
978 def test_plugin_fluxer_markdown_attachments(
979 mock_post: mock.MagicMock,
980 ) -> None:
981 # Prepare our tokens
982 webhook_id, webhook_token = _tokens()
983
984 # Prepare a good response
985 response = mock.Mock()
986 response.status_code = requests.codes.ok
987 response.content = b""
988
989 # Prepare a bad response
990 bad_response = mock.Mock()
991 bad_response.status_code = requests.codes.internal_server_error
992 bad_response.content = b""
993
994 # Prepare Mock return object
995 mock_post.return_value = response
996
997 # Test our markdown
998 obj = Apprise.instantiate(
999 f"fluxer://{webhook_id}/{webhook_token}/?format=markdown"
1000 )
1001
1002 # attach our content
1003 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
1004
1005 assert (
1006 obj.notify(
1007 body="body",
1008 title="title",
1009 notify_type=NotifyType.INFO,
1010 attach=attach,
1011 )
1012 is True
1013 )
1014
1015 # Test our call count
1016 assert mock_post.call_count == 2
1017 assert (
1018 mock_post.call_args_list[0][0][0]
1019 == f"https://api.fluxer.app/webhooks/{webhook_id}/{webhook_token}"
1020 )
1021 assert (
1022 mock_post.call_args_list[1][0][0]
1023 == f"https://api.fluxer.app/webhooks/{webhook_id}/{webhook_token}"
1024 )
1025
1026 # Reset our object
1027 mock_post.reset_mock()
1028
1029 # Test notifications with mentions and attachments in it
1030 assert (
1031 obj.notify(
1032 body="Say hello to <@1234>!",
1033 notify_type=NotifyType.INFO,
1034 attach=attach,
1035 )
1036 is True
1037 )
1038
1039 # Test our call count
1040 assert mock_post.call_count == 2
1041 assert (
1042 mock_post.call_args_list[0][0][0]
1043 == f"https://api.fluxer.app/webhooks/{webhook_id}/{webhook_token}"
1044 )
1045 assert (
1046 mock_post.call_args_list[1][0][0]
1047 == f"https://api.fluxer.app/webhooks/{webhook_id}/{webhook_token}"
1048 )
1049
1050 # Reset our object
1051 mock_post.reset_mock()
1052
1053 # An invalid attachment will cause a failure
1054 path = os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg")
1055 attach = AppriseAttachment(path)
1056 assert (
1057 obj.notify(
1058 body="body",
1059 title="title",
1060 notify_type=NotifyType.INFO,
1061 attach=path,
1062 )
1063 is False
1064 )
1065
1066 # update our attachment to be valid
1067 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
1068
1069 mock_post.return_value = None
1070 # Throw an exception on the first call to requests.post()
1071 for side_effect in (requests.RequestException(), OSError(), bad_response):
1072 mock_post.side_effect = [side_effect]
1073
1074 # We'll fail now because of our error handling
1075 assert obj.send(body="test", attach=attach) is False
1076
1077 # Throw an exception on the second call to requests.post()
1078 for side_effect in (requests.RequestException(), OSError(), bad_response):
1079 mock_post.side_effect = [response, side_effect]
1080
1081 # We'll fail now because of our error handling
1082 assert obj.send(body="test", attach=attach) is False
1083
1084 # handle a bad response
1085 bad_response = mock.Mock()
1086 bad_response.content = b""
1087 bad_response.headers = {}
1088 bad_response.status_code = requests.codes.internal_server_error
1089 mock_post.side_effect = [response, bad_response]
1090
1091 # We'll fail now because of an internal exception
1092 assert obj.send(body="test", attach=attach) is False
1093
1094
1095 @mock.patch("requests.post")
1096 def test_plugin_fluxer_markdown_fields_batches_exactly(mock_post):
1097 webhook_id, webhook_token = _tokens()
1098 response = mock.Mock()
1099 response.status_code = requests.codes.ok
1100 response.content = ""
1101 response.headers = {}
1102 mock_post.return_value = response
1103
1104 # Force tiny batches
1105 NotifyFluxer.fluxer_max_fields = 1
1106
1107 body = "# H1\nv1\n# H2\nv2\n# H3\nv3\n"
1108 obj = Apprise.instantiate(
1109 f"fluxer://{webhook_id}/{webhook_token}/?format=markdown&fields=yes"
1110 )
1111 assert isinstance(obj, NotifyFluxer)
1112
1113 assert obj.send(body=body) is True
1114
1115 # H1, H2, H3 => 3 fields => 3 posts (since max_fields=1)
1116 assert mock_post.call_count == 3
1117
1118 NotifyFluxer.fluxer_max_fields = 10
1119
1120
1121 @mock.patch("requests.post")
1122 def test_plugin_fluxer_markdown_ping_is_additive(
1123 mock_post: mock.MagicMock,
1124 ) -> None:
1125 webhook_id, webhook_token = _tokens()
1126
1127 mock_post.return_value = requests.Request()
1128 mock_post.return_value.status_code = requests.codes.ok
1129 mock_post.return_value.content = b""
1130 mock_post.return_value.headers = {}
1131
1132 body = "Body pings <@111> and <@&222> @everyone"
1133 results = NotifyFluxer.parse_url(
1134 f"fluxer://{webhook_id}/{webhook_token}/"
1135 "?format=markdown"
1136 "&ping=<@333>,<@%26444>,@joe"
1137 )
1138 obj = NotifyFluxer(**results)
1139
1140 assert obj.send(body=body) is True
1141 assert mock_post.call_count == 1
1142
1143 payload = loads(mock_post.call_args_list[0][1]["data"])
1144
1145 assert "allow_mentions" in payload
1146 # union
1147 assert set(payload["allow_mentions"]["users"]) == {"111", "333"}
1148 assert set(payload["allow_mentions"]["roles"]) == {"222", "444"}
1149 assert set(payload["allow_mentions"]["parse"]) == {"everyone", "joe"}
1150 assert payload["content"].startswith("👉 ")
1151
1152
1153 @mock.patch("requests.post")
1154 def test_plugin_fluxer_html_ping_is_exclusive(
1155 mock_post: mock.MagicMock,
1156 ) -> None:
1157 webhook_id, webhook_token = _tokens()
1158
1159 mock_post.return_value = requests.Request()
1160 mock_post.return_value.status_code = requests.codes.ok
1161
1162 body = "Body includes <@111> <@&222> @everyone but must be ignored"
1163 results = NotifyFluxer.parse_url(
1164 f"fluxer://{webhook_id}/{webhook_token}/"
1165 "?format=html"
1166 "&ping=<@333>,<@%26444>,@joe"
1167 )
1168 obj = NotifyFluxer(**results)
1169
1170 assert obj.send(body=body) is True
1171 payload = loads(mock_post.call_args_list[0][1]["data"])
1172
1173 assert set(payload["allow_mentions"]["users"]) == {"333"}
1174 assert set(payload["allow_mentions"]["roles"]) == {"444"}
1175 assert set(payload["allow_mentions"]["parse"]) == {"joe"}
1176
1177
1178 @mock.patch("requests.post")
1179 def test_plugin_fluxer_markdown_no_mentions_has_no_allow_mentions(
1180 mock_post: mock.MagicMock,
1181 ) -> None:
1182 webhook_id, webhook_token = _tokens()
1183
1184 mock_post.return_value = requests.Request()
1185 mock_post.return_value.status_code = requests.codes.ok
1186 mock_post.return_value.content = b""
1187 mock_post.return_value.headers = {}
1188
1189 results = NotifyFluxer.parse_url(
1190 f"fluxer://{webhook_id}/{webhook_token}/?format=markdown"
1191 )
1192 obj = NotifyFluxer(**results)
1193
1194 assert obj.send(body="Hello world") is True
1195 payload = loads(mock_post.call_args_list[0][1]["data"])
1196
1197 assert "allow_mentions" not in payload
1198 assert "content" not in payload
1199
1200
1201 @mock.patch("requests.post")
1202 def test_plugin_fluxer_markdown_single_field_posts_once(
1203 mock_post: mock.MagicMock,
1204 ) -> None:
1205 webhook_id, webhook_token = _tokens()
1206
1207 response = mock.Mock()
1208 response.status_code = requests.codes.ok
1209 response.content = b""
1210 response.headers = {}
1211 mock_post.return_value = response
1212
1213 NotifyFluxer.fluxer_max_fields = 10
1214
1215 body = "# H1\nv1\n"
1216 obj = Apprise.instantiate(
1217 f"fluxer://{webhook_id}/{webhook_token}/?format=markdown&fields=yes"
1218 )
1219 assert isinstance(obj, NotifyFluxer)
1220
1221 assert obj.send(body=body) is True
1222 assert mock_post.call_count == 1
1223
1224
1225 @mock.patch("requests.post")
1226 def test_plugin_fluxer_threading(mock_post: mock.MagicMock) -> None:
1227 """Threading passes thread_id parameter."""
1228
1229 webhook_id, webhook_token = _tokens()
1230
1231 response = mock.Mock()
1232 response.status_code = requests.codes.ok
1233 response.content = b""
1234 response.headers = {}
1235 mock_post.return_value = response
1236
1237 a = Apprise()
1238 assert (
1239 a.add(
1240 f"fluxer://{webhook_id}/{webhook_token}/"
1241 "?thread=12345&thread_name=abc"
1242 )
1243 is True
1244 )
1245
1246 assert a.notify(body="test", title="title") is True
1247
1248 kwargs = mock_post.call_args_list[0][1]
1249 assert "params" in kwargs
1250 assert kwargs["params"].get("thread_id") == "12345"
1251
1252 payload = loads(mock_post.call_args_list[0][1]["data"])
1253 assert payload.get("thread_name") == "abc"
1254
1255 assert "thread_name=abc" in a[0].url()
1256 assert "thread=12345" in a[0].url()
1257
1258
1259 @mock.patch("requests.post")
1260 @mock.patch("time.sleep")
1261 @mock.patch("builtins.open")
1262 def test_plugin_fluxer_429_attachment_closes_edge_cases(
1263 mock_open: mock.MagicMock,
1264 mock_sleep: mock.MagicMock,
1265 mock_post: mock.MagicMock,
1266 ) -> None:
1267 """
1268 Cover 429 error during attachment upload triggers the pre-recursion close
1269 loop, and close() exceptions are suppressed.
1270 """
1271
1272 mock_sleep.return_value = True
1273
1274 webhook_id, webhook_token = _tokens()
1275 obj = NotifyFluxer(webhook_id=webhook_id, webhook_token=webhook_token)
1276
1277 attach_path = os.path.join(TEST_VAR_DIR, "apprise-test.png")
1278 attach = AppriseAttachment(attach_path)
1279
1280 class _BadCloseIO:
1281 def __init__(self) -> None:
1282 self.closed = False
1283
1284 def close(self) -> None:
1285 self.closed = True
1286 raise OSError("boom")
1287
1288 bad = _BadCloseIO()
1289 mock_open.return_value = bad
1290
1291 def _resp(code: int, headers: dict[str, str] | None = None) -> mock.Mock:
1292 r = mock.Mock()
1293 r.status_code = code
1294 r.content = b""
1295 r.headers = headers or {}
1296 return r
1297
1298 # 3 posts:
1299 # (1) initial message post succeeds
1300 # (2) attachment post 429 triggers file close-before-recursion
1301 # (3) recursive retry succeeds (note: retry is non-attachment in baseline)
1302 mock_post.side_effect = [
1303 _resp(requests.codes.no_content, {}),
1304 _resp(requests.codes.too_many_requests, {"Retry-After": "1"}),
1305 _resp(requests.codes.no_content, {}),
1306 ]
1307
1308 assert obj.send(body="test", attach=attach) is True
1309 assert bad.closed is True
1310
1311 mock_post.reset_mock()
1312 mock_open.reset_mock()
1313
1314 mock_sleep.reset_mock()
1315 mock_sleep.return_value = True
1316
1317 webhook_id, webhook_token = _tokens()
1318 obj = NotifyFluxer(webhook_id=webhook_id, webhook_token=webhook_token)
1319
1320 attach_path = os.path.join(TEST_VAR_DIR, "apprise-test.png")
1321 attach = AppriseAttachment(attach_path)
1322
1323 class _GoodCloseIO:
1324 def __init__(self) -> None:
1325 self.closed = False
1326
1327 def close(self) -> None:
1328 self.closed = True
1329
1330 good = _GoodCloseIO()
1331 mock_open.return_value = good
1332
1333 def _resp(code: int, headers: dict[str, str] | None = None) -> mock.Mock:
1334 r = mock.Mock()
1335 r.status_code = code
1336 r.content = b""
1337 r.headers = headers or {}
1338 return r
1339
1340 mock_post.side_effect = [
1341 _resp(requests.codes.no_content, {}),
1342 _resp(requests.codes.too_many_requests, {"Retry-After": "1"}),
1343 _resp(requests.codes.no_content, {}),
1344 ]
1345
1346 assert obj.send(body="test", attach=attach) is True
1347 assert good.closed is True
1348
1349
1350 @mock.patch("requests.post")
1351 def test_plugin_fluxer_attach_memory(mock_post: mock.MagicMock) -> None:
1352 """Regression: AttachMemory must be sendable without OSError."""
1353 from apprise.attachment.memory import AttachMemory
1354
1355 webhook_id, webhook_token = _tokens()
1356
1357 response = mock.Mock()
1358 response.status_code = requests.codes.ok
1359 response.content = b""
1360 mock_post.return_value = response
1361
1362 obj = Apprise.instantiate(f"fluxer://{webhook_id}/{webhook_token}/")
1363
1364 mem = AttachMemory(
1365 content=b"<html><body><h1>Test</h1></body></html>",
1366 name="report.html",
1367 mimetype="text/html",
1368 )
1369
1370 assert obj.notify(body="Test", attach=mem) is True
1371 assert mock_post.call_count >= 1
1372
1373
1374 @mock.patch("requests.post")
1375 def test_plugin_fluxer_html_to_markdown_format(mock_post):
1376 """NotifyFluxer(): HTML body is converted to Markdown."""
1377
1378 webhook_id, webhook_token = _tokens()
1379
1380 mock_post.return_value = requests.Request()
1381 mock_post.return_value.status_code = requests.codes.ok
1382 mock_post.return_value.content = ""
1383 mock_post.return_value.headers = {}
1384
1385 # Instantiate a Fluxer plugin in Markdown mode with fields
1386 # disabled so the body lands in embeds[0]["description"] directly
1387 obj = Apprise.instantiate(
1388 f"fluxer://{webhook_id}/{webhook_token}/?format=markdown&fields=no"
1389 )
1390
1391 aobj = Apprise()
1392 aobj.add(obj)
1393
1394 # Notify with an HTML body; the framework should convert it
1395 # to Markdown before dispatching to Fluxer
1396 assert (
1397 aobj.notify(
1398 body="<b>hello</b> <i>world</i>",
1399 body_format=NotifyFormat.HTML,
1400 )
1401 is True
1402 )
1403 assert mock_post.call_count == 1
1404
1405 # The body must arrive in the embed description as Markdown,
1406 # not as stripped plain text
1407 payload = loads(mock_post.call_args_list[0][1]["data"])
1408 assert payload["embeds"][0]["description"] == "**hello** *world*"