Debian Codegraph @

tests/test_plugin_apprise_api.py

raw
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28 # Disable logging for a cleaner testing output
29 from json import loads
30 import logging
31 import os
32 from unittest import mock
33
34 from helpers import AppriseURLTester
35 import requests
36
37 from apprise import Apprise, AppriseAttachment, NotifyFormat, NotifyType
38 from apprise.exception import AppriseImproperlyConfigured
39 from apprise.plugins.apprise_api import AppriseAPIVersion, NotifyAppriseAPI
40
41 logging.disable(logging.CRITICAL)
42
43 # Attachment Directory
44 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
45
46 # Our Testing URLs
47 apprise_url_tests = (
48 (
49 "apprise://",
50 {
51 # invalid url (not complete)
52 "instance": None,
53 },
54 ),
55 # A a bad url
56 (
57 "apprise://:@/",
58 {
59 "instance": None,
60 },
61 ),
62 # No token specified
63 (
64 "apprise://localhost",
65 {
66 "instance": AppriseImproperlyConfigured,
67 },
68 ),
69 # invalid token
70 (
71 "apprise://localhost/!",
72 {
73 "instance": AppriseImproperlyConfigured,
74 },
75 ),
76 # No token specified (whitespace is trimmed)
77 (
78 "apprise://localhost/%%20",
79 {
80 "instance": AppriseImproperlyConfigured,
81 },
82 ),
83 # A valid URL with Token
84 (
85 "apprise://localhost/%s" % ("a" * 32),
86 {
87 "instance": NotifyAppriseAPI,
88 # Our expected url(privacy=True) startswith() response:
89 "privacy_url": "apprise://localhost/a...a/",
90 "force_debug": True,
91 },
92 ),
93 # A valid URL with long Token
94 (
95 "apprise://localhost/%s" % ("a" * 128),
96 {
97 "instance": NotifyAppriseAPI,
98 # Our expected url(privacy=True) startswith() response:
99 "privacy_url": "apprise://localhost/a...a/",
100 },
101 ),
102 # A valid URL with Token (using port)
103 (
104 "apprise://localhost:8080/%s" % ("b" * 32),
105 {
106 "instance": NotifyAppriseAPI,
107 # Our expected url(privacy=True) startswith() response:
108 "privacy_url": "apprise://localhost:8080/b...b/",
109 },
110 ),
111 # A secure (https://) reference
112 (
113 "apprises://localhost/%s" % ("c" * 32),
114 {
115 "instance": NotifyAppriseAPI,
116 # Our expected url(privacy=True) startswith() response:
117 "privacy_url": "apprises://localhost/c...c/",
118 },
119 ),
120 # Native URL suport (https)
121 (
122 "https://example.com/path/notify/%s" % ("d" * 32),
123 {
124 "instance": NotifyAppriseAPI,
125 # Our expected url(privacy=True) startswith() response:
126 "privacy_url": "apprises://example.com/path/d...d/",
127 },
128 ),
129 # Native URL suport (http)
130 (
131 "http://example.com/notify/%s" % ("d" * 32),
132 {
133 "instance": NotifyAppriseAPI,
134 # Our expected url(privacy=True) startswith() response:
135 "privacy_url": "apprise://example.com/d...d/",
136 },
137 ),
138 # support to= keyword
139 (
140 "apprises://localhost/?to=%s" % ("e" * 32),
141 {
142 "instance": NotifyAppriseAPI,
143 "privacy_url": "apprises://localhost/e...e/",
144 },
145 ),
146 # support token= keyword (even when passed with to=, token over-rides)
147 (
148 "apprise://localhost/?token={}&to={}".format("f" * 32, "abcd"),
149 {
150 "instance": NotifyAppriseAPI,
151 "privacy_url": "apprise://localhost/f...f/",
152 },
153 ),
154 # Test tags
155 (
156 "apprise://localhost/?token={}&tags=admin,team".format("abcd"),
157 {
158 "instance": NotifyAppriseAPI,
159 "privacy_url": "apprise://localhost/a...d/",
160 },
161 ),
162 # Test Format string
163 (
164 "apprise://user@localhost/mytoken0/?format=markdown",
165 {
166 "instance": NotifyAppriseAPI,
167 "privacy_url": "apprise://user@localhost/m...0/",
168 },
169 ),
170 (
171 "apprise://user@localhost/mytoken1/",
172 {
173 "instance": NotifyAppriseAPI,
174 "privacy_url": "apprise://user@localhost/m...1/",
175 },
176 ),
177 # Version 1 keeps the configuration ID in the request path.
178 (
179 "apprise://localhost/mytoken1/?v=1",
180 {
181 "instance": NotifyAppriseAPI,
182 },
183 ),
184 # Invalid versions are rejected.
185 (
186 "apprise://localhost/mytoken1/?version=3",
187 {
188 "instance": AppriseImproperlyConfigured,
189 },
190 ),
191 (
192 "apprise://localhost:8080/mytoken/",
193 {
194 "instance": NotifyAppriseAPI,
195 },
196 ),
197 (
198 "apprise://user:pass@localhost:8080/mytoken2/",
199 {
200 "instance": NotifyAppriseAPI,
201 "privacy_url": "apprise://user:****@localhost:8080/m...2/",
202 },
203 ),
204 (
205 "apprises://localhost/mytoken/",
206 {
207 "instance": NotifyAppriseAPI,
208 },
209 ),
210 (
211 "apprises://user:pass@localhost/mytoken3/",
212 {
213 "instance": NotifyAppriseAPI,
214 # Our expected url(privacy=True) startswith() response:
215 "privacy_url": "apprises://user:****@localhost/m...3/",
216 },
217 ),
218 (
219 "apprises://localhost:8080/mytoken4/",
220 {
221 "instance": NotifyAppriseAPI,
222 # Our expected url(privacy=True) startswith() response:
223 "privacy_url": "apprises://localhost:8080/m...4/",
224 },
225 ),
226 (
227 "apprises://localhost:8080/abc123/?method=json",
228 {
229 "instance": NotifyAppriseAPI,
230 # Our expected url(privacy=True) startswith() response:
231 "privacy_url": "apprises://localhost:8080/a...3/",
232 },
233 ),
234 (
235 "apprises://localhost:8080/abc123/?method=form",
236 {
237 "instance": NotifyAppriseAPI,
238 # Our expected url(privacy=True) startswith() response:
239 "privacy_url": "apprises://localhost:8080/a...3/",
240 },
241 ),
242 # Invalid method specified
243 (
244 "apprises://localhost:8080/abc123/?method=invalid",
245 {
246 "instance": AppriseImproperlyConfigured,
247 },
248 ),
249 (
250 "apprises://user:password@localhost:8080/mytoken5/",
251 {
252 "instance": NotifyAppriseAPI,
253 # Our expected url(privacy=True) startswith() response:
254 "privacy_url": "apprises://user:****@localhost:8080/m...5/",
255 },
256 ),
257 (
258 "apprises://localhost:8080/path?+HeaderKey=HeaderValue",
259 {
260 "instance": NotifyAppriseAPI,
261 },
262 ),
263 (
264 "apprise://localhost/%s" % ("a" * 32),
265 {
266 "instance": NotifyAppriseAPI,
267 # force a failure
268 "response": False,
269 "requests_response_code": requests.codes.internal_server_error,
270 },
271 ),
272 (
273 "apprise://localhost/%s" % ("a" * 32),
274 {
275 "instance": NotifyAppriseAPI,
276 # throw a bizarre code forcing us to fail to look it up
277 "response": False,
278 "requests_response_code": 999,
279 },
280 ),
281 (
282 "apprise://localhost/%s" % ("a" * 32),
283 {
284 "instance": NotifyAppriseAPI,
285 # Throws a series of i/o exceptions with this flag
286 # is set and tests that we gracefully handle them
287 "test_requests_exceptions": True,
288 },
289 ),
290 )
291
292
293 def test_plugin_apprise_api_urls():
294 """NotifyAppriseAPI() General Checks."""
295
296 # Run our general tests
297 AppriseURLTester(tests=apprise_url_tests).run_all()
298
299
300 @mock.patch("requests.post")
301 def test_notify_apprise_api_payload_check(mock_post):
302 """NotifyAppriseAPI() payload checks"""
303
304 okay_response = requests.Request()
305
306 okay_response.status_code = requests.codes.ok
307 okay_response.content = ""
308
309 # Assign our mock object our return value
310 mock_post.return_value = okay_response
311
312 obj = Apprise.instantiate(
313 "apprise://user@localhost/mytoken1/"
314 "?method=form&+X-Apprise-Config-ID=wrong"
315 )
316 assert isinstance(obj, NotifyAppriseAPI)
317
318 # Test URL with Attachment
319 path = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
320 attach = AppriseAttachment(path)
321 assert (
322 bool(
323 obj.notify(
324 body="body",
325 title="title",
326 notify_type=NotifyType.INFO,
327 attach=attach,
328 )
329 )
330 is True
331 )
332
333 details = mock_post.call_args_list[0]
334 assert details[0][0] == "http://localhost/notify"
335 # Undeclared input relays no format; the downstream server chooses.
336 assert details[1]["data"] == {
337 "title": "title",
338 "body": "body",
339 "type": "info",
340 }
341 assert "X-Apprise-ID" in details[1]["headers"]
342 assert details[1]["headers"].get("User-Agent") == "Apprise"
343 assert details[1]["headers"].get("Accept") == "application/json"
344 assert details[1]["headers"].get("X-Apprise-Recursion-Count") == "1"
345 # The plugin token remains authoritative over a custom header.
346 assert details[1]["headers"].get("X-Apprise-Config-ID") == "mytoken1"
347
348 mock_post.reset_mock()
349
350 obj = Apprise.instantiate("apprise://user@localhost/mytoken1/?method=json")
351 assert isinstance(obj, NotifyAppriseAPI)
352
353 assert (
354 bool(
355 obj.notify(
356 body="body",
357 title="title",
358 notify_type=NotifyType.INFO,
359 attach=attach,
360 )
361 )
362 is True
363 )
364
365 details = mock_post.call_args_list[0]
366 assert details[0][0] == "http://localhost/notify"
367 data = loads(details[1]["data"])
368 assert "attachments" in data
369 assert isinstance(data["attachments"], list)
370 assert len(data["attachments"]) == 1
371
372 # Remove our attachment to make the next assert easier
373 del data["attachments"]
374 # Undeclared input relays no format.
375 assert data == {
376 "title": "title",
377 "body": "body",
378 "type": "info",
379 }
380 assert "X-Apprise-ID" in details[1]["headers"]
381 assert details[1]["headers"].get("User-Agent") == "Apprise"
382 assert details[1]["headers"].get("Accept") == "application/json"
383 assert details[1]["headers"].get("X-Apprise-Recursion-Count") == "1"
384 assert details[1]["headers"].get("X-Apprise-Config-ID") == "mytoken1"
385
386 mock_post.reset_mock()
387
388 # Version 1 retains the original keyed endpoint for older servers.
389 obj = Apprise.instantiate(
390 "apprise://user@localhost/mytoken1/?method=form&v=1"
391 )
392 assert isinstance(obj, NotifyAppriseAPI)
393 assert bool(obj.notify(body="body", title="title")) is True
394
395 details = mock_post.call_args_list[0]
396 assert details[0][0] == "http://localhost/notify/mytoken1"
397 assert "X-Apprise-Config-ID" not in details[1]["headers"]
398 assert "version=1" in obj.url(privacy=False)
399
400
401 @mock.patch("requests.post")
402 def test_notify_apprise_api_password_only_auth(mock_post):
403 """Password-only Apprise API URLs send valid Basic Auth."""
404 okay_response = requests.Request()
405 okay_response.status_code = requests.codes.ok
406 okay_response.content = ""
407 mock_post.return_value = okay_response
408
409 obj = Apprise.instantiate("apprise://:secret@localhost/mytoken1/")
410 assert isinstance(obj, NotifyAppriseAPI)
411 assert bool(obj.notify(body="body", title="title")) is True
412
413 details = mock_post.call_args_list[0]
414 assert details[1]["auth"] == ("", "secret")
415 assert details[0][0] == "http://localhost/notify"
416 assert details[1]["headers"]["X-Apprise-Config-ID"] == "mytoken1"
417 assert obj.url(privacy=False).startswith(
418 "apprise://:secret@localhost/mytoken1/"
419 )
420
421
422 @mock.patch("requests.post")
423 def test_notify_apprise_api_native_url_version(mock_post):
424 """Native /notify/{token} URLs default to Version 1 for old servers."""
425 okay_response = requests.Request()
426 okay_response.status_code = requests.codes.ok
427 okay_response.content = ""
428 mock_post.return_value = okay_response
429
430 # A bare native URL reflects the classic path-based endpoint, so it
431 # should keep talking to the server that shape, not switch to the
432 # newer header-based one.
433 obj = Apprise.instantiate("http://example.com/notify/" + "d" * 32)
434 assert isinstance(obj, NotifyAppriseAPI)
435 assert obj.version == AppriseAPIVersion.V1
436 assert bool(obj.notify(body="body", title="title")) is True
437
438 details = mock_post.call_args_list[0]
439 assert details[0][0] == "http://example.com/notify/" + "d" * 32
440 assert "X-Apprise-Config-ID" not in details[1]["headers"]
441
442 mock_post.reset_mock()
443
444 # A version carried on the native URL itself is honored as-is.
445 obj = Apprise.instantiate(
446 "http://example.com/notify/" + "d" * 32 + "?version=2"
447 )
448 assert isinstance(obj, NotifyAppriseAPI)
449 assert obj.version == AppriseAPIVersion.V2
450 assert bool(obj.notify(body="body", title="title")) is True
451
452 details = mock_post.call_args_list[0]
453 assert details[0][0] == "http://example.com/notify"
454 assert details[1]["headers"]["X-Apprise-Config-ID"] == "d" * 32
455
456
457 @mock.patch("requests.post")
458 def test_notify_apprise_api_relays_declared_format(mock_post):
459 """NotifyAppriseAPI() relays only caller-declared formats."""
460
461 okay_response = requests.Request()
462 okay_response.status_code = requests.codes.ok
463 okay_response.content = ""
464 mock_post.return_value = okay_response
465
466 obj = Apprise.instantiate("apprise://user@localhost/mytoken1/")
467 assert isinstance(obj, NotifyAppriseAPI)
468
469 # A declared source is relayed onward as-is
470 assert (
471 bool(
472 obj.notify(
473 body="# hi",
474 title="title",
475 notify_type=NotifyType.INFO,
476 body_format=NotifyFormat.MARKDOWN,
477 )
478 )
479 is True
480 )
481
482 details = mock_post.call_args_list[0]
483 assert details[1]["data"] == {
484 "title": "title",
485 "body": "# hi",
486 "type": "info",
487 "format": "markdown",
488 }
489
490 mock_post.reset_mock()
491
492 # Undeclared input relays no format, despite the internal default.
493 assert (
494 bool(
495 obj.notify(
496 body="body",
497 title="title",
498 notify_type=NotifyType.INFO,
499 )
500 )
501 is True
502 )
503
504 details = mock_post.call_args_list[0]
505 assert details[1]["data"] == {
506 "title": "title",
507 "body": "body",
508 "type": "info",
509 }
510
511
512 @mock.patch("requests.post")
513 def test_notify_apprise_api_direct_send_defaults(mock_post):
514 """Direct send() calls safely accept their default format arguments."""
515 okay_response = requests.Request()
516 okay_response.status_code = requests.codes.ok
517 okay_response.content = ""
518 mock_post.return_value = okay_response
519
520 obj = Apprise.instantiate("apprise://user@localhost/mytoken1/")
521 assert isinstance(obj, NotifyAppriseAPI)
522
523 # Omit both format arguments to exercise their defaults.
524 assert bool(obj.send(body="body", title="title")) is True
525
526 details = mock_post.call_args_list[0]
527 # No format was declared, so none is relayed onward.
528 assert "format" not in details[1]["data"]
529
530
531 @mock.patch("requests.post")
532 def test_notify_apprise_api_attachments(mock_post):
533 """NotifyAppriseAPI() Attachments."""
534
535 okay_response = requests.Request()
536
537 for method in ("json", "form"):
538 okay_response.status_code = requests.codes.ok
539 okay_response.content = ""
540
541 # Assign our mock object our return value
542 mock_post.return_value = okay_response
543
544 obj = Apprise.instantiate(
545 f"apprise://user@localhost/mytoken1/?method={method}"
546 )
547 assert isinstance(obj, NotifyAppriseAPI)
548
549 # Test Valid Attachment
550 path = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
551 attach = AppriseAttachment(path)
552 assert (
553 bool(
554 obj.notify(
555 body="body",
556 title="title",
557 notify_type=NotifyType.INFO,
558 attach=attach,
559 )
560 )
561 is True
562 )
563
564 # Test invalid attachment
565 path = os.path.join(
566 TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg"
567 )
568 assert (
569 bool(
570 obj.notify(
571 body="body",
572 title="title",
573 notify_type=NotifyType.INFO,
574 attach=path,
575 )
576 )
577 is False
578 )
579
580 # Test Valid Attachment (load 3)
581 path = (
582 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
583 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
584 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
585 )
586 attach = AppriseAttachment(path)
587
588 # Return our good configuration
589 mock_post.side_effect = None
590 mock_post.return_value = okay_response
591 with mock.patch("builtins.open", side_effect=OSError()):
592 # We can't send the message we can't open the attachment for
593 # reading
594 assert (
595 bool(
596 obj.notify(
597 body="body",
598 title="title",
599 notify_type=NotifyType.INFO,
600 attach=attach,
601 )
602 )
603 is False
604 )
605
606 with mock.patch("requests.post", side_effect=OSError()):
607 # Attachment issue
608 assert (
609 bool(
610 obj.notify(
611 body="body",
612 title="title",
613 notify_type=NotifyType.INFO,
614 attach=attach,
615 )
616 )
617 is False
618 )
619
620 # test the handling of our batch modes
621 obj = Apprise.instantiate("apprise://user@localhost/mytoken1/")
622 assert isinstance(obj, NotifyAppriseAPI)
623
624 # Now send an attachment normally without issues
625 mock_post.reset_mock()
626
627 assert (
628 bool(
629 obj.notify(
630 body="body",
631 title="title",
632 notify_type=NotifyType.INFO,
633 attach=attach,
634 )
635 )
636 is True
637 )
638 assert mock_post.call_count == 1
639
640 details = mock_post.call_args_list[0]
641 assert details[0][0] == "http://localhost/notify"
642 assert details[1]["headers"]["X-Apprise-Config-ID"] == "mytoken1"
643 assert obj.url(privacy=False).startswith(
644 "apprise://user@localhost/mytoken1/"
645 )
646
647 mock_post.reset_mock()