Debian Codegraph @

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