Debian Codegraph @

tests/test_plugin_ntfy.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 import json
29
30 # Disable logging for a cleaner testing output
31 import logging
32 import os
33 import re
34 from unittest import mock
35
36 from helpers import AppriseURLTester
37 import requests
38
39 import apprise
40 from apprise import NotifyFormat
41 from apprise.plugins.ntfy import NotifyNtfy, NtfyPriority
42
43 logging.disable(logging.CRITICAL)
44
45 # Attachment Directory
46 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
47
48 # For testing our return response
49 GOOD_RESPONSE_TEXT = {
50 "code": "0",
51 "error": "success",
52 }
53
54 # Our Testing URLs
55 apprise_url_tests = (
56 (
57 "ntfy://",
58 {
59 # Initializes okay (as cloud mode) but has no topics to notify
60 "instance": NotifyNtfy,
61 # invalid topics specified (nothing to notify)
62 # as a result the response type will be false
63 "requests_response_text": GOOD_RESPONSE_TEXT,
64 "response": False,
65 },
66 ),
67 (
68 "ntfys://",
69 {
70 # Initializes okay (as cloud mode) but has no topics to notify
71 "instance": NotifyNtfy,
72 # invalid topics specified (nothing to notify)
73 # as a result the response type will be false
74 "requests_response_text": GOOD_RESPONSE_TEXT,
75 "response": False,
76 },
77 ),
78 (
79 "ntfy://:@/",
80 {
81 # Initializes okay (as cloud mode) but has no topics to notify
82 "instance": NotifyNtfy,
83 # invalid topics specified (nothing to notify)
84 # as a result the response type will be false
85 "requests_response_text": GOOD_RESPONSE_TEXT,
86 "response": False,
87 },
88 ),
89 # No topics
90 (
91 "ntfy://user:pass@localhost?mode=private",
92 {
93 "instance": NotifyNtfy,
94 # invalid topics specified (nothing to notify)
95 # as a result the response type will be false
96 "requests_response_text": GOOD_RESPONSE_TEXT,
97 "response": False,
98 },
99 ),
100 # No valid topics
101 (
102 "ntfy://user:pass@localhost/#/!/@",
103 {
104 "instance": NotifyNtfy,
105 # invalid topics specified (nothing to notify)
106 # as a result the response type will be false
107 "requests_response_text": GOOD_RESPONSE_TEXT,
108 "response": False,
109 },
110 ),
111 # user/pass combos
112 (
113 "ntfy://user@localhost/topic/",
114 {
115 "instance": NotifyNtfy,
116 "requests_response_text": GOOD_RESPONSE_TEXT,
117 # Our expected url(privacy=True) startswith() response:
118 "privacy_url": "ntfy://user@localhost/topic",
119 },
120 ),
121 # Ntfy cloud mode (enforced)
122 (
123 "ntfy://ntfy.sh/topic1/topic2/",
124 {
125 "instance": NotifyNtfy,
126 "requests_response_text": GOOD_RESPONSE_TEXT,
127 },
128 ),
129 # No user/pass combo
130 (
131 "ntfy://localhost/topic1/topic2/",
132 {
133 "instance": NotifyNtfy,
134 "requests_response_text": GOOD_RESPONSE_TEXT,
135 },
136 ),
137 # A Email Testing
138 (
139 "ntfy://localhost/topic1/[email protected]",
140 {
141 "instance": NotifyNtfy,
142 "requests_response_text": GOOD_RESPONSE_TEXT,
143 },
144 ),
145 # X-Tags via canonical xtags= parameter
146 (
147 "ntfy://localhost/topic1/?xtags=tag1,tag2,tag3",
148 {
149 "instance": NotifyNtfy,
150 "requests_response_text": GOOD_RESPONSE_TEXT,
151 },
152 ),
153 # X-Tags via legacy tags= parameter (backward compat)
154 (
155 "ntfy://localhost/topic1/?tags=tag1,tag2,tag3",
156 {
157 "instance": NotifyNtfy,
158 "requests_response_text": GOOD_RESPONSE_TEXT,
159 },
160 ),
161 # Actions
162 (
163 "ntfy://localhost/topic1/?actions=view%2CExample%2Chttp://www.example.com/%3Bview%2CTest%2Chttp://www.test.com/",
164 {
165 "instance": NotifyNtfy,
166 "requests_response_text": GOOD_RESPONSE_TEXT,
167 },
168 ),
169 # Delay
170 (
171 "ntfy://localhost/topic1/?delay=3600",
172 {
173 "instance": NotifyNtfy,
174 "requests_response_text": GOOD_RESPONSE_TEXT,
175 },
176 ),
177 # Title
178 (
179 "ntfy://localhost/topic1/?title=A%20Great%20Title",
180 {
181 "instance": NotifyNtfy,
182 "requests_response_text": GOOD_RESPONSE_TEXT,
183 },
184 ),
185 # Click
186 (
187 "ntfy://localhost/topic1/?click=yes",
188 {
189 "instance": NotifyNtfy,
190 "requests_response_text": GOOD_RESPONSE_TEXT,
191 },
192 ),
193 # Email
194 (
195 "ntfy://localhost/topic1/[email protected]",
196 {
197 "instance": NotifyNtfy,
198 "requests_response_text": GOOD_RESPONSE_TEXT,
199 },
200 ),
201 # No images
202 (
203 "ntfy://localhost/topic1/?image=False",
204 {
205 "instance": NotifyNtfy,
206 "requests_response_text": GOOD_RESPONSE_TEXT,
207 },
208 ),
209 # Over-ride Image Path
210 (
211 "ntfy://localhost/topic1/?avatar_url=ttp://localhost/test.jpg",
212 {
213 "instance": NotifyNtfy,
214 "requests_response_text": GOOD_RESPONSE_TEXT,
215 },
216 ),
217 # Attach
218 (
219 "ntfy://localhost/topic1/?attach=http://example.com/file.jpg",
220 {
221 "instance": NotifyNtfy,
222 "requests_response_text": GOOD_RESPONSE_TEXT,
223 },
224 ),
225 # Attach with filename over-ride
226 (
227 (
228 "ntfy://localhost/topic1/"
229 "?attach=http://example.com/file.jpg&filename=smoke.jpg"
230 ),
231 {"instance": NotifyNtfy, "requests_response_text": GOOD_RESPONSE_TEXT},
232 ),
233 # Attach with bad url
234 (
235 "ntfy://localhost/topic1/?attach=http://-%20",
236 {
237 "instance": NotifyNtfy,
238 "requests_response_text": GOOD_RESPONSE_TEXT,
239 },
240 ),
241 # Auth Token Types (tk_ gets detected as a auth=token)
242 (
243 "ntfy://tk_abcd123456@localhost/topic1",
244 {
245 "instance": NotifyNtfy,
246 "requests_response_text": GOOD_RESPONSE_TEXT,
247 # Our expected url(privacy=True) startswith() response:
248 "privacy_url": "ntfy://t...6@localhost/topic1",
249 },
250 ),
251 # Force an auth token since lack of tk_ prevents auto-detection
252 (
253 "ntfy://abcd123456@localhost/topic1?auth=token",
254 {
255 "instance": NotifyNtfy,
256 "requests_response_text": GOOD_RESPONSE_TEXT,
257 # Our expected url(privacy=True) startswith() response:
258 "privacy_url": "ntfy://a...6@localhost/topic1",
259 },
260 ),
261 # Force an auth token since lack of tk_ prevents auto-detection
262 (
263 "ntfy://:abcd123456@localhost/topic1?auth=token",
264 {
265 "instance": NotifyNtfy,
266 "requests_response_text": GOOD_RESPONSE_TEXT,
267 # Our expected url(privacy=True) startswith() response:
268 "privacy_url": "ntfy://a...6@localhost/topic1",
269 },
270 ),
271 # Token detection already implied when token keyword is set
272 (
273 "ntfy://localhost/topic1?token=abc1234",
274 {
275 "instance": NotifyNtfy,
276 "requests_response_text": GOOD_RESPONSE_TEXT,
277 # Our expected url(privacy=True) startswith() response:
278 "privacy_url": "ntfy://a...4@localhost/topic1",
279 },
280 ),
281 # Token enforced, but since a user/pass provided, only the pass is kept
282 (
283 "ntfy://user:token@localhost/topic1?auth=token",
284 {
285 "instance": NotifyNtfy,
286 "requests_response_text": GOOD_RESPONSE_TEXT,
287 # Our expected url(privacy=True) startswith() response:
288 "privacy_url": "ntfy://t...n@localhost/topic1",
289 },
290 ),
291 # Token mode force, but there was no token provided
292 (
293 "ntfy://localhost/topic1?auth=token",
294 {
295 "instance": NotifyNtfy,
296 # We'll out-right fail to send the notification
297 "response": False,
298 # Our expected url(privacy=True) startswith() response:
299 "privacy_url": "ntfy://localhost/topic1",
300 },
301 ),
302 # Priority
303 (
304 "ntfy://localhost/topic1/?priority=default",
305 {
306 "instance": NotifyNtfy,
307 "requests_response_text": GOOD_RESPONSE_TEXT,
308 # Our expected url(privacy=True) startswith() response:
309 "privacy_url": "ntfy://localhost/topic1",
310 },
311 ),
312 # Priority higher
313 (
314 "ntfy://localhost/topic1/?priority=high",
315 {
316 "instance": NotifyNtfy,
317 "requests_response_text": GOOD_RESPONSE_TEXT,
318 },
319 ),
320 # A topic and port identifier
321 (
322 "ntfy://user:pass@localhost:8080/topic/",
323 {
324 "instance": NotifyNtfy,
325 # The response text is expected to be the following on a success
326 "requests_response_text": GOOD_RESPONSE_TEXT,
327 },
328 ),
329 # A topic (using the to=)
330 (
331 "ntfys://user:pass@localhost?to=topic",
332 {
333 "instance": NotifyNtfy,
334 # The response text is expected to be the following on a success
335 "requests_response_text": GOOD_RESPONSE_TEXT,
336 },
337 ),
338 (
339 "https://just/a/random/host/that/means/nothing",
340 {
341 # Nothing transpires from this
342 "instance": None
343 },
344 ),
345 # reference the ntfy.sh url
346 (
347 "https://ntfy.sh?to=topic",
348 {
349 "instance": NotifyNtfy,
350 # The response text is expected to be the following on a success
351 "requests_response_text": GOOD_RESPONSE_TEXT,
352 },
353 ),
354 # Several topics
355 (
356 "ntfy://user:pass@topic1/topic2/topic3/?mode=cloud",
357 {
358 "instance": NotifyNtfy,
359 # The response text is expected to be the following on a success
360 "requests_response_text": GOOD_RESPONSE_TEXT,
361 },
362 ),
363 # Several topics (but do not add ntfy.sh)
364 (
365 "ntfy://user:[email protected]/topic1/topic2/?mode=cloud",
366 {
367 "instance": NotifyNtfy,
368 # The response text is expected to be the following on a success
369 "requests_response_text": GOOD_RESPONSE_TEXT,
370 },
371 ),
372 (
373 "ntfys://user:web/token@localhost/topic/?mode=invalid",
374 {
375 # Invalid mode
376 "instance": TypeError,
377 },
378 ),
379 (
380 "ntfys://token@localhost/topic/?auth=invalid",
381 {
382 # Invalid Authentication type
383 "instance": TypeError,
384 },
385 ),
386 # Invalid hostname on localhost/private mode
387 (
388 "ntfys://user:web@-_/topic1/topic2/?mode=private",
389 {
390 "instance": None,
391 },
392 ),
393 (
394 "ntfy://user:pass@localhost:8089/topic/topic2",
395 {
396 "instance": NotifyNtfy,
397 # force a failure using basic mode
398 "response": False,
399 "requests_response_code": requests.codes.internal_server_error,
400 },
401 ),
402 (
403 "ntfy://user:pass@localhost:8082/topic",
404 {
405 "instance": NotifyNtfy,
406 # throw a bizarre code forcing us to fail to look it up
407 "response": False,
408 "requests_response_code": 999,
409 "requests_response_text": GOOD_RESPONSE_TEXT,
410 },
411 ),
412 (
413 "ntfy://user:pass@localhost:8083/topic1/topic2/",
414 {
415 "instance": NotifyNtfy,
416 # Throws a series of i/o exceptions with this flag
417 # is set and tests that we gracefully handle them
418 "test_requests_exceptions": True,
419 "requests_response_text": GOOD_RESPONSE_TEXT,
420 },
421 ),
422 )
423
424
425 def test_plugin_ntfy_chat_urls():
426 """NotifyNtfy() Apprise URLs."""
427
428 # Run our general tests
429 AppriseURLTester(tests=apprise_url_tests).run_all()
430
431
432 @mock.patch("requests.post")
433 def test_plugin_ntfy_attachments(mock_post):
434 """NotifyNtfy() Attachment Checks."""
435
436 # Prepare Mock return object
437 response = mock.Mock()
438 response.content = GOOD_RESPONSE_TEXT
439 response.status_code = requests.codes.ok
440 mock_post.return_value = response
441
442 # Test how the notifications work without attachments as they use the
443 # JSON type posting instead
444
445 # Reset our mock object
446 mock_post.reset_mock()
447
448 # Prepare our object
449 obj = apprise.Apprise.instantiate("ntfy://user:pass@localhost:8080/topic")
450
451 # Send a good attachment
452 assert obj.notify(title="hello", body="world")
453 assert mock_post.call_count == 1
454
455 assert mock_post.call_args_list[0][0][0] == "http://localhost:8080"
456
457 response = json.loads(mock_post.call_args_list[0][1]["data"])
458 assert response["topic"] == "topic"
459 assert response["title"] == "hello"
460 assert response["message"] == "world"
461 assert "attach" not in response
462
463 # Reset our mock object
464 mock_post.reset_mock()
465
466 # prepare our attachment
467 attach = apprise.AppriseAttachment(
468 os.path.join(TEST_VAR_DIR, "apprise-test.gif")
469 )
470
471 # Prepare our object
472 obj = apprise.Apprise.instantiate("ntfy://user:pass@localhost:8084/topic")
473
474 # Send a good attachment
475 assert obj.notify(body="test", attach=attach) is True
476
477 # Test our call count; includes both image and message
478 assert mock_post.call_count == 1
479
480 assert mock_post.call_args_list[0][0][0] == "http://localhost:8084/topic"
481
482 assert mock_post.call_args_list[0][1]["params"]["message"] == "test"
483 assert "title" not in mock_post.call_args_list[0][1]["params"]
484 assert (
485 mock_post.call_args_list[0][1]["params"]["filename"]
486 == "apprise-test.gif"
487 )
488
489 # Reset our mock object
490 mock_post.reset_mock()
491
492 # Add another attachment so we drop into the area of the PushBullet code
493 # that sends remaining attachments (if more detected)
494 attach.add(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
495
496 # Send our attachments
497 assert obj.notify(body="test", title="wonderful", attach=attach) is True
498
499 # Test our call count
500 assert mock_post.call_count == 2
501 # Image + Message sent
502 assert mock_post.call_args_list[0][0][0] == "http://localhost:8084/topic"
503 assert mock_post.call_args_list[0][1]["params"]["message"] == "test"
504 assert mock_post.call_args_list[0][1]["params"]["title"] == "wonderful"
505 assert (
506 mock_post.call_args_list[0][1]["params"]["filename"]
507 == "apprise-test.gif"
508 )
509
510 # Image no 2 (no message)
511 assert mock_post.call_args_list[1][0][0] == "http://localhost:8084/topic"
512 assert "message" not in mock_post.call_args_list[1][1]["params"]
513 assert "title" not in mock_post.call_args_list[1][1]["params"]
514 assert (
515 mock_post.call_args_list[1][1]["params"]["filename"]
516 == "apprise-test.png"
517 )
518
519 # Reset our mock object
520 mock_post.reset_mock()
521
522 # An invalid attachment will cause a failure
523 path = os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg")
524 attach = apprise.AppriseAttachment(path)
525 assert obj.notify(body="test", attach=attach) is False
526
527 # Test our call count
528 assert mock_post.call_count == 0
529
530 # prepare our attachment
531 attach = apprise.AppriseAttachment(
532 os.path.join(TEST_VAR_DIR, "apprise-test.gif")
533 )
534
535 # Throw an exception on the first call to requests.post()
536 mock_post.return_value = None
537 for side_effect in (requests.RequestException(), OSError()):
538 mock_post.side_effect = side_effect
539
540 # We'll fail now because of our error handling
541 assert obj.send(body="test", attach=attach) is False
542
543
544 @mock.patch("requests.post")
545 def test_plugin_custom_ntfy_edge_cases(mock_post):
546 """NotifyNtfy() Edge Cases."""
547
548 # Prepare our response
549 response = requests.Request()
550 response.status_code = requests.codes.ok
551 response.content = json.dumps(GOOD_RESPONSE_TEXT)
552
553 # Prepare Mock
554 mock_post.return_value = response
555
556 results = NotifyNtfy.parse_url(
557 "ntfys://abc---,topic2,~~,,?priority=max&tags=smile,de"
558 )
559
560 assert isinstance(results, dict)
561 assert results["user"] is None
562 assert results["password"] is None
563 assert results["port"] is None
564 assert results["host"] == "abc---,topic2,~~,,"
565 assert results["fullpath"] is None
566 assert results["path"] is None
567 assert results["query"] is None
568 assert results["schema"] == "ntfys"
569 assert results["url"] == "ntfys://abc---,topic2,~~,,"
570 assert isinstance(results["qsd:"], dict) is True
571 assert results["qsd"]["priority"] == "max"
572 assert results["qsd"]["tags"] == "smile,de"
573 # Legacy tags= is translated to xtags internally; must not leak as
574 # results["tags"] or the config/base YAML parser would treat it as
575 # an Apprise routing tag and silently drop the notification.
576 assert "tags" not in results
577 assert results["xtags"] == ["de", "smile"]
578
579 instance = NotifyNtfy(**results)
580 assert isinstance(instance, NotifyNtfy)
581 assert len(instance.topics) == 2
582 assert "abc---" in instance.topics
583 assert "topic2" in instance.topics
584 # X-Tags header must be set correctly
585 assert instance._NotifyNtfy__tags == ["de", "smile"]
586
587 results = NotifyNtfy.parse_url(
588 "ntfy://localhost/topic1/"
589 "?attach=http://example.com/file.jpg&filename=smoke.jpg"
590 )
591
592 assert isinstance(results, dict)
593 assert results["user"] is None
594 assert results["password"] is None
595 assert results["port"] is None
596 assert results["host"] == "localhost"
597 assert results["fullpath"] == "/topic1/"
598 assert results["path"] == "/topic1/"
599 assert results["query"] is None
600 assert results["schema"] == "ntfy"
601 assert results["url"] == "ntfy://localhost/topic1/"
602 assert results["attach"] == "http://example.com/file.jpg"
603 assert results["filename"] == "smoke.jpg"
604
605 instance = NotifyNtfy(**results)
606 assert isinstance(instance, NotifyNtfy)
607 assert len(instance.topics) == 1
608 assert "topic1" in instance.topics
609
610 assert (
611 instance.notify(
612 body="body", title="title", notify_type=apprise.NotifyType.INFO
613 )
614 is True
615 )
616
617 # Test our call count
618 assert mock_post.call_count == 1
619 assert mock_post.call_args_list[0][0][0] == "http://localhost"
620
621 response = json.loads(mock_post.call_args_list[0][1]["data"])
622 assert response["topic"] == "topic1"
623 assert response["message"] == "body"
624 assert response["title"] == "title"
625 assert response["attach"] == "http://example.com/file.jpg"
626 assert response["filename"] == "smoke.jpg"
627
628 # Reset our mock object
629 mock_post.reset_mock()
630
631 # Markdown Support
632 results = NotifyNtfy.parse_url("ntfys://topic/?format=markdown")
633 assert isinstance(results, dict)
634 instance = NotifyNtfy(**results)
635
636 assert (
637 instance.notify(
638 body="body", title="title", notify_type=apprise.NotifyType.INFO
639 )
640 is True
641 )
642
643 assert mock_post.call_count == 1
644 assert mock_post.call_args_list[0][0][0] == "https://ntfy.sh"
645 assert "X-Markdown" in mock_post.call_args_list[0][1]["headers"]
646
647
648 @mock.patch("requests.post")
649 @mock.patch("requests.get")
650 def test_plugin_ntfy_config_files(mock_post, mock_get):
651 """NotifyNtfy() Config File Cases."""
652 content = """
653 urls:
654 - ntfy://localhost/topic1:
655 - priority: 1
656 tag: ntfy_int min
657 - priority: "1"
658 tag: ntfy_str_int min
659 - priority: min
660 tag: ntfy_str min
661
662 # This will take on normal (default) priority
663 - priority: invalid
664 tag: ntfy_invalid
665
666 - ntfy://localhost/topic2:
667 - priority: 5
668 tag: ntfy_int max
669 - priority: "5"
670 tag: ntfy_str_int max
671 - priority: emergency
672 tag: ntfy_str max
673 - priority: max
674 tag: ntfy_str max
675 """
676
677 # Prepare Mock
678 mock_post.return_value = requests.Request()
679 mock_post.return_value.status_code = requests.codes.ok
680 mock_get.return_value = requests.Request()
681 mock_get.return_value.status_code = requests.codes.ok
682
683 # Create ourselves a config object
684 ac = apprise.AppriseConfig()
685 assert ac.add_config(content=content) is True
686
687 aobj = apprise.Apprise()
688
689 # Add our configuration
690 aobj.add(ac)
691
692 # We should be able to read our 8 servers from that
693 # 3x min
694 # 4x max
695 # 1x invalid (so takes on normal priority)
696 assert len(ac.servers()) == 8
697 assert len(aobj) == 8
698 assert len(list(aobj.find(tag="min"))) == 3
699 for s in aobj.find(tag="min"):
700 assert s.priority == NtfyPriority.MIN
701
702 assert len(list(aobj.find(tag="max"))) == 4
703 for s in aobj.find(tag="max"):
704 assert s.priority == NtfyPriority.MAX
705
706 assert len(list(aobj.find(tag="ntfy_str"))) == 3
707 assert len(list(aobj.find(tag="ntfy_str_int"))) == 2
708 assert len(list(aobj.find(tag="ntfy_int"))) == 2
709
710 assert len(list(aobj.find(tag="ntfy_invalid"))) == 1
711 assert next(aobj.find(tag="ntfy_invalid")).priority == NtfyPriority.NORMAL
712
713 # A cloud reference without any identifiers; the ntfy:// (insecure mode)
714 # is not considered during the id generation as ntfys:// is always
715 # implied
716 results = NotifyNtfy.parse_url("ntfy://")
717 obj = NotifyNtfy(**results)
718 new_results = NotifyNtfy.parse_url(obj.url())
719 obj2 = NotifyNtfy(**new_results)
720 assert obj.url_id() == obj2.url_id()
721
722
723 @mock.patch("requests.post")
724 def test_plugin_ntfy_internationalized_urls(mock_post):
725 """NotifyNtfy() Internationalized URL Support."""
726
727 # Prepare Mock return object
728 response = mock.Mock()
729 response.content = GOOD_RESPONSE_TEXT
730 response.status_code = requests.codes.ok
731 mock_post.return_value = response
732
733 # Our input
734 title = "My Title"
735 body = "My Body"
736
737 # Google Translate promised me this just says 'Apprise Example' (I hope
738 # this is the case 🙏). Below is a URL requiring encoding so that it
739 # can be correctly passed into an http header:
740 click = "https://通知の例"
741
742 # Prepare our object
743 obj = apprise.Apprise.instantiate(f"ntfy://ntfy.sh/topic1?click={click}")
744
745 # Send our notification
746 assert obj.notify(title=title, body=body)
747 assert mock_post.call_count == 1
748
749 assert mock_post.call_args_list[0][0][0] == "http://ntfy.sh"
750
751 # Verify that our International URL was correctly escaped
752 assert (
753 "https://%25E9%2580%259A%25E7%259F%25A5%25E3%2581%25AE%25E4%25BE%258B"
754 in mock_post.call_args_list[0][1]["headers"]["X-Click"]
755 )
756
757 # Validate that we did not obstruct our URL in anyway
758 assert apprise.Apprise.instantiate(obj.url()).url() == obj.url()
759
760
761 @mock.patch("requests.post")
762 def test_plugin_ntfy_message_to_attach(mock_post):
763 """NotifyNtfy() large messages converted into attachments."""
764
765 # Prepare Mock return object
766 response = mock.Mock()
767 response.content = GOOD_RESPONSE_TEXT
768 response.status_code = requests.codes.ok
769 mock_post.return_value = response
770
771 # Create a very, very big message
772 title = "My Title"
773 body = "b" * NotifyNtfy.ntfy_json_upstream_size_limit
774
775 for fmt in apprise.NOTIFY_FORMATS:
776 # Prepare our object
777 obj = apprise.Apprise.instantiate(
778 f"ntfy://user:pass@localhost:8080/topic?format={fmt}"
779 )
780
781 # Our content will actually transfer as an attachment
782 assert obj.notify(title=title, body=body)
783 assert mock_post.call_count == 1
784
785 assert (
786 mock_post.call_args_list[0][0][0] == "http://localhost:8080/topic"
787 )
788
789 response = mock_post.call_args_list[0][1]
790 assert "data" in response
791 assert response["data"].decode("utf-8").startswith(title)
792 assert response["data"].decode("utf-8").endswith(body)
793 assert "params" in response
794 assert "filename" in response["params"]
795 # Our filename is automatically generated (with .txt)
796 assert re.match(
797 r"^[a-z0-9-]+\.txt$", response["params"]["filename"], re.I
798 )
799
800 # Reset our mock object
801 mock_post.reset_mock()
802
803
804 def test_plugin_ntfy_xtags_no_apprise_tag_collision():
805 """Regression: ntfy xtags= / tags= must never become an Apprise routing
806 tag.
807
808 Prior to the xtags= rename (commit that introduced this test), ntfy stored
809 its X-Tags value in results["tags"]. The config/base YAML parser
810 intercepts results["tags"] and converts it to an Apprise routing tag,
811 which caused the plugin to be silently skipped when a notify request
812 arrived without a matching tag filter.
813 """
814
815 # --- parse_url: canonical xtags= form ---
816 r = NotifyNtfy.parse_url("ntfy://myhost/mytopic?xtags=warning,critical")
817 assert r is not None
818 assert "tags" not in r, "xtags= must not appear as results['tags']"
819 assert r["xtags"] == ["critical", "warning"]
820
821 n = NotifyNtfy(**r)
822 assert n._NotifyNtfy__tags == ["critical", "warning"]
823 # apprise routing tag must remain empty
824 assert not n.tags
825 # canonical URL must use xtags= and must not contain a bare tags= param
826 assert "xtags=" in n.url()
827 assert "&tags=" not in n.url() and "?tags=" not in n.url()
828
829 # --- parse_url: legacy tags= form (backward compat) ---
830 r2 = NotifyNtfy.parse_url("ntfy://myhost/mytopic?tags=info,storage")
831 assert r2 is not None
832 assert "tags" not in r2, "legacy tags= must be re-keyed as xtags, not tags"
833 assert r2["xtags"] == ["info", "storage"]
834
835 n2 = NotifyNtfy(**r2)
836 assert n2._NotifyNtfy__tags == ["info", "storage"]
837 assert not n2.tags
838
839 # --- YAML config: tags= in URL must not become an Apprise routing tag ---
840 cfg = apprise.AppriseConfig()
841 cfg.add_config(
842 "urls:\n - ntfy://myhost/mytopic?tags=warning\n",
843 format="yaml",
844 )
845 a = apprise.Apprise()
846 a.add(cfg)
847 servers = list(cfg.servers())
848 assert len(servers) == 1
849 s = servers[0]
850 # X-Tags must be preserved
851 assert s._NotifyNtfy__tags == ["warning"]
852 # No Apprise routing tag should have been created
853 assert not s.tags, (
854 "tags= in a YAML ntfy URL must not create an Apprise routing tag"
855 )
856
857
858 @mock.patch("requests.post")
859 def test_plugin_ntfy_html_to_markdown_format(mock_post):
860 """NotifyNtfy(): HTML body is converted to Markdown."""
861
862 # Prepare Mock
863 mock_post.return_value = requests.Request()
864 mock_post.return_value.status_code = requests.codes.ok
865 mock_post.return_value.content = b"{}"
866
867 # Instantiate an ntfy plugin in Markdown mode using a private server
868 aobj = apprise.Apprise()
869 assert aobj.add("ntfy://localhost/topic?format=markdown")
870
871 # Notify with an HTML body; the framework should convert it
872 # to Markdown before dispatching to ntfy
873 assert (
874 aobj.notify(
875 body="<b>hello</b> <i>world</i>",
876 body_format=NotifyFormat.HTML,
877 )
878 is True
879 )
880 assert mock_post.call_count == 1
881
882 # The body must arrive as Markdown, not as stripped plain text
883 payload = json.loads(mock_post.call_args_list[0][1]["data"])
884 assert payload["message"] == "**hello** *world*"