Debian Codegraph @

tests/test_plugin_custom_form.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 import logging
30 import os
31 from unittest import mock
32
33 from helpers import AppriseURLTester
34 import requests
35
36 from apprise import Apprise, AppriseAttachment, NotifyFormat, NotifyType
37 from apprise.exception import AppriseImproperlyConfigured
38 from apprise.plugins.custom_form import NotifyForm
39
40 logging.disable(logging.CRITICAL)
41
42 # Attachment Directory
43 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
44
45 # Our Testing URLs
46 apprise_url_tests = (
47 (
48 "form://:@/",
49 {
50 "instance": None,
51 },
52 ),
53 (
54 "form://",
55 {
56 "instance": None,
57 },
58 ),
59 (
60 "forms://",
61 {
62 "instance": None,
63 },
64 ),
65 (
66 "form://localhost",
67 {
68 "instance": NotifyForm,
69 },
70 ),
71 (
72 "form://user@localhost?method=invalid",
73 {
74 "instance": AppriseImproperlyConfigured,
75 },
76 ),
77 (
78 "form://user:pass@localhost",
79 {
80 "instance": NotifyForm,
81 # Our expected url(privacy=True) startswith() response:
82 "privacy_url": "form://user:****@localhost",
83 },
84 ),
85 (
86 "form://user@localhost",
87 {
88 "instance": NotifyForm,
89 },
90 ),
91 # Test method variations
92 (
93 "form://user@localhost?method=put",
94 {
95 "instance": NotifyForm,
96 },
97 ),
98 (
99 "form://user@localhost?method=get",
100 {
101 "instance": NotifyForm,
102 },
103 ),
104 (
105 "form://user@localhost?method=post",
106 {
107 "instance": NotifyForm,
108 },
109 ),
110 (
111 "form://user@localhost?method=head",
112 {
113 "instance": NotifyForm,
114 },
115 ),
116 (
117 "form://user@localhost?method=delete",
118 {
119 "instance": NotifyForm,
120 },
121 ),
122 (
123 "form://user@localhost?method=patch",
124 {
125 "instance": NotifyForm,
126 },
127 ),
128 (
129 "form://user@localhost?method=update",
130 {
131 "instance": NotifyForm,
132 },
133 ),
134 (
135 "form://user@localhost?method=options",
136 {
137 "instance": NotifyForm,
138 },
139 ),
140 # Custom payload options
141 (
142 "form://localhost:8080?:key=value&:key2=value2",
143 {
144 "instance": NotifyForm,
145 },
146 ),
147 # Continue testing other cases
148 (
149 "form://localhost:8080",
150 {
151 "instance": NotifyForm,
152 },
153 ),
154 (
155 "form://user:pass@localhost:8080",
156 {
157 "instance": NotifyForm,
158 },
159 ),
160 (
161 "forms://localhost",
162 {
163 "instance": NotifyForm,
164 },
165 ),
166 (
167 "forms://user:pass@localhost",
168 {
169 "instance": NotifyForm,
170 },
171 ),
172 (
173 "forms://localhost:8080/path/",
174 {
175 "instance": NotifyForm,
176 # Our expected url(privacy=True) startswith() response:
177 "privacy_url": "forms://localhost:8080/path/",
178 },
179 ),
180 (
181 "forms://user:password@localhost:8080",
182 {
183 "instance": NotifyForm,
184 # Our expected url(privacy=True) startswith() response:
185 "privacy_url": "forms://user:****@localhost:8080",
186 },
187 ),
188 # Test our GET params
189 (
190 "form://localhost:8080/path?-ParamA=Value",
191 {
192 "instance": NotifyForm,
193 },
194 ),
195 # Test our Headers
196 (
197 "form://localhost:8080/path?+HeaderKey=HeaderValue",
198 {
199 "instance": NotifyForm,
200 },
201 ),
202 (
203 "form://user:pass@localhost:8081",
204 {
205 "instance": NotifyForm,
206 # force a failure
207 "response": False,
208 "requests_response_code": requests.codes.internal_server_error,
209 },
210 ),
211 (
212 "form://user:pass@localhost:8082",
213 {
214 "instance": NotifyForm,
215 # throw a bizarre code forcing us to fail to look it up
216 "response": False,
217 "requests_response_code": 999,
218 },
219 ),
220 (
221 "form://user:pass@localhost:8083",
222 {
223 "instance": NotifyForm,
224 # Throws a series of i/o exceptions with this flag
225 # is set and tests that we gracefully handle them
226 "test_requests_exceptions": True,
227 },
228 ),
229 )
230
231
232 def test_plugin_custom_form_urls():
233 """NotifyForm() Apprise URLs."""
234
235 # Run our general tests
236 AppriseURLTester(tests=apprise_url_tests).run_all()
237
238
239 @mock.patch("requests.request")
240 def test_plugin_custom_form_multi_format(mock_request):
241 """NotifyForm() supports all 3 notify formats as a pass-through."""
242
243 response = requests.Request()
244 response.status_code = requests.codes.ok
245 mock_request.return_value = response
246
247 assert NotifyForm.notify_format == (
248 NotifyFormat.TEXT,
249 NotifyFormat.HTML,
250 NotifyFormat.MARKDOWN,
251 )
252
253 a = Apprise()
254 assert a.add("form://localhost") is True
255
256 # Markdown input aligns directly to the pass-through Markdown path,
257 # so no conversion should alter it.
258 assert (
259 bool(a.notify(body="# hello", body_format=NotifyFormat.MARKDOWN))
260 is True
261 )
262 payload = mock_request.call_args_list[-1][1]["data"]
263 assert payload["message"] == "# hello"
264
265 # ?format=html forces the resolved target regardless of input format.
266 a = Apprise()
267 assert a.add("form://localhost/?format=html") is True
268 assert bool(a.notify(body="a < b", body_format=NotifyFormat.TEXT)) is True
269 payload = mock_request.call_args_list[-1][1]["data"]
270 assert payload["message"] == "a&nbsp;&lt;&nbsp;b"
271
272
273 @mock.patch("requests.request")
274 def test_plugin_custom_form_attachments(mock_request):
275 """NotifyForm() Attachments."""
276
277 okay_response = requests.Request()
278 okay_response.status_code = requests.codes.ok
279 okay_response.content = ""
280
281 # Assign our mock object our return value
282 mock_request.return_value = okay_response
283
284 obj = Apprise.instantiate("form://[email protected]/?method=post")
285 assert isinstance(obj, NotifyForm)
286
287 # Test Valid Attachment
288 path = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
289 attach = AppriseAttachment(path)
290 assert (
291 bool(
292 obj.notify(
293 body="body",
294 title="title",
295 notify_type=NotifyType.INFO,
296 attach=attach,
297 )
298 )
299 is True
300 )
301
302 # Test invalid attachment
303 path = os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg")
304 assert (
305 bool(
306 obj.notify(
307 body="body",
308 title="title",
309 notify_type=NotifyType.INFO,
310 attach=path,
311 )
312 )
313 is False
314 )
315
316 mock_request.return_value = None
317 mock_request.side_effect = OSError()
318 # We can't send the message if we can't read the attachment
319 assert (
320 bool(
321 obj.notify(
322 body="body",
323 title="title",
324 notify_type=NotifyType.INFO,
325 attach=attach,
326 )
327 )
328 is False
329 )
330
331 # Test Valid Attachment (load 3)
332 path = (
333 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
334 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
335 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
336 )
337 attach = AppriseAttachment(path)
338
339 # Return our good configuration
340 mock_request.side_effect = None
341 mock_request.return_value = okay_response
342 with mock.patch("builtins.open", side_effect=OSError()):
343 # We can't send the message we can't open the attachment for reading
344 assert (
345 bool(
346 obj.notify(
347 body="body",
348 title="title",
349 notify_type=NotifyType.INFO,
350 attach=attach,
351 )
352 )
353 is False
354 )
355
356 # Fail on the 2nd attempt (but not the first)
357 with mock.patch("builtins.open", side_effect=[None, OSError(), None]):
358 # We can't send the message we can't open the attachment for reading
359 assert (
360 bool(
361 obj.notify(
362 body="body",
363 title="title",
364 notify_type=NotifyType.INFO,
365 attach=attach,
366 )
367 )
368 is False
369 )
370
371 # Test file exception handling when performing post
372 mock_request.return_value = None
373 mock_request.side_effect = OSError()
374 assert (
375 bool(
376 obj.notify(
377 body="body",
378 title="title",
379 notify_type=NotifyType.INFO,
380 attach=attach,
381 )
382 )
383 is False
384 )
385
386 #
387 # Test attach-as
388 #
389
390 # Assign our mock object our return value
391 mock_request.return_value = okay_response
392 mock_request.side_effect = None
393
394 obj = Apprise.instantiate(
395 "form://[email protected]/?attach-as=file"
396 )
397 assert isinstance(obj, NotifyForm)
398
399 # Test Single Valid Attachment
400 path = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
401 attach = AppriseAttachment(path)
402 assert (
403 bool(
404 obj.notify(
405 body="body",
406 title="title",
407 notify_type=NotifyType.INFO,
408 attach=attach,
409 )
410 )
411 is True
412 )
413
414 # Test Valid Attachment (load 3) (produces a warning)
415 path = (
416 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
417 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
418 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
419 )
420 attach = AppriseAttachment(path)
421 assert (
422 bool(
423 obj.notify(
424 body="body",
425 title="title",
426 notify_type=NotifyType.INFO,
427 attach=attach,
428 )
429 )
430 is True
431 )
432
433 # Test our other variations of accepted values
434 # we support *, :, ?, ., +, %, and $
435 for attach_as in (
436 "file*",
437 "*file",
438 "file*file",
439 "file:",
440 ":file",
441 "file:file",
442 "file?",
443 "?file",
444 "file?file",
445 "file.",
446 ".file",
447 "file.file",
448 "file+",
449 "+file",
450 "file+file",
451 "file$",
452 "$file",
453 "file$file",
454 ):
455 obj = Apprise.instantiate(
456 f"form://[email protected]/?attach-as={attach_as}"
457 )
458 assert isinstance(obj, NotifyForm)
459
460 # Test Single Valid Attachment
461 path = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
462 attach = AppriseAttachment(path)
463 assert (
464 bool(
465 obj.notify(
466 body="body",
467 title="title",
468 notify_type=NotifyType.INFO,
469 attach=attach,
470 )
471 )
472 is True
473 )
474
475 # Test Valid Attachment (load 3) (produces a warning)
476 path = (
477 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
478 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
479 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
480 )
481 attach = AppriseAttachment(path)
482 assert (
483 bool(
484 obj.notify(
485 body="body",
486 title="title",
487 notify_type=NotifyType.INFO,
488 attach=attach,
489 )
490 )
491 is True
492 )
493
494 # Test invalid attach-as input
495 obj = Apprise.instantiate("form://[email protected]/?attach-as={")
496 assert obj is None
497
498
499 @mock.patch("requests.request")
500 def test_plugin_custom_form_edge_cases(mock_request):
501 """NotifyForm() Edge Cases."""
502
503 # Prepare our response
504 response = requests.Request()
505 response.status_code = requests.codes.ok
506
507 # Prepare Mock
508 mock_request.return_value = response
509
510 results = NotifyForm.parse_url(
511 "form://localhost:8080/command?:message=msg&:abcd=test&method=POST"
512 )
513
514 assert isinstance(results, dict)
515 assert results["user"] is None
516 assert results["password"] is None
517 assert results["port"] == 8080
518 assert results["host"] == "localhost"
519 assert results["fullpath"] == "/command"
520 assert results["path"] == "/"
521 assert results["query"] == "command"
522 assert results["schema"] == "form"
523 assert results["url"] == "form://localhost:8080/command"
524 assert isinstance(results["qsd:"], dict) is True
525 assert results["qsd:"]["abcd"] == "test"
526 assert results["qsd:"]["message"] == "msg"
527
528 instance = NotifyForm(**results)
529 assert isinstance(instance, NotifyForm)
530
531 response = instance.send(title="title", body="body")
532 assert response is True
533 assert mock_request.call_count == 1
534
535 details = mock_request.call_args_list[0]
536 assert details[0][0] == "POST"
537 assert details[0][1] == "http://localhost:8080/command"
538 assert "abcd" in details[1]["data"]
539 assert details[1]["data"]["abcd"] == "test"
540 assert "title" in details[1]["data"]
541 assert details[1]["data"]["title"] == "title"
542 assert "message" not in details[1]["data"]
543 # message over-ride was provided; the body is now in `msg` and not
544 # `message`
545 assert "msg" in details[1]["data"]
546 assert details[1]["data"]["msg"] == "body"
547 assert details[1]["data"]["type"] == NotifyType.INFO.value
548 assert "NotifyType." not in str(details[1]["data"])
549
550 assert instance.url(privacy=False).startswith(
551 "form://localhost:8080/command?"
552 )
553
554 # Generate a new URL based on our last and verify key values are the same
555 new_results = NotifyForm.parse_url(instance.url(safe=False))
556 for k in (
557 "user",
558 "password",
559 "port",
560 "host",
561 "fullpath",
562 "path",
563 "query",
564 "schema",
565 "url",
566 "payload",
567 "method",
568 ):
569 assert new_results[k] == results[k]
570
571 # Reset our mock configuration
572 mock_request.reset_mock()
573
574 results = NotifyForm.parse_url(
575 "form://localhost:8080/command?:type=&:message=msg&method=POST"
576 )
577
578 assert isinstance(results, dict)
579 assert results["user"] is None
580 assert results["password"] is None
581 assert results["port"] == 8080
582 assert results["host"] == "localhost"
583 assert results["fullpath"] == "/command"
584 assert results["path"] == "/"
585 assert results["query"] == "command"
586 assert results["schema"] == "form"
587 assert results["url"] == "form://localhost:8080/command"
588 assert isinstance(results["qsd:"], dict) is True
589 assert results["qsd:"]["message"] == "msg"
590
591 instance = NotifyForm(**results)
592 assert isinstance(instance, NotifyForm)
593
594 response = instance.send(title="title", body="body")
595 assert response is True
596 assert mock_request.call_count == 1
597
598 details = mock_request.call_args_list[0]
599 assert details[0][0] == "POST"
600 assert details[0][1] == "http://localhost:8080/command"
601 assert "title" in details[1]["data"]
602 assert details[1]["data"]["title"] == "title"
603
604 # type was removed from response object
605 assert "type" not in details[1]["data"]
606
607 # message over-ride was provided; the body is now in `msg` and not
608 # `message`
609 assert details[1]["data"]["msg"] == "body"
610
611 # 'body' is over-ridden by 'test' passed inline with the URL
612 assert "message" not in details[1]["data"]
613 assert "msg" in details[1]["data"]
614 assert details[1]["data"]["msg"] == "body"
615
616 assert instance.url(privacy=False).startswith(
617 "form://localhost:8080/command?"
618 )
619
620 # Generate a new URL based on our last and verify key values are the same
621 new_results = NotifyForm.parse_url(instance.url(safe=False))
622 for k in (
623 "user",
624 "password",
625 "port",
626 "host",
627 "fullpath",
628 "path",
629 "query",
630 "schema",
631 "url",
632 "payload",
633 "method",
634 ):
635 assert new_results[k] == results[k]
636
637 # Reset our mock configuration
638 mock_request.reset_mock()
639
640 results = NotifyForm.parse_url(
641 "form://localhost:8080/command?:message=test&method=GET"
642 )
643
644 assert isinstance(results, dict)
645 assert results["user"] is None
646 assert results["password"] is None
647 assert results["port"] == 8080
648 assert results["host"] == "localhost"
649 assert results["fullpath"] == "/command"
650 assert results["path"] == "/"
651 assert results["query"] == "command"
652 assert results["schema"] == "form"
653 assert results["url"] == "form://localhost:8080/command"
654 assert isinstance(results["qsd:"], dict) is True
655 assert results["qsd:"]["message"] == "test"
656
657 instance = NotifyForm(**results)
658 assert isinstance(instance, NotifyForm)
659
660 response = instance.send(title="title", body="body")
661 assert response is True
662 assert mock_request.call_count == 1
663
664 details = mock_request.call_args_list[0]
665 assert details[0][0] == "GET"
666 assert details[0][1] == "http://localhost:8080/command"
667
668 assert "title" in details[1]["params"]
669 assert details[1]["params"]["title"] == "title"
670 # 'body' is over-ridden by 'test' passed inline with the URL
671 assert "message" not in details[1]["params"]
672 assert "test" in details[1]["params"]
673 assert details[1]["params"]["test"] == "body"
674
675 assert instance.url(privacy=False).startswith(
676 "form://localhost:8080/command?"
677 )
678
679 # Generate a new URL based on our last and verify key values are the same
680 new_results = NotifyForm.parse_url(instance.url(safe=False))
681 for k in (
682 "user",
683 "password",
684 "port",
685 "host",
686 "fullpath",
687 "path",
688 "query",
689 "schema",
690 "url",
691 "payload",
692 "method",
693 ):
694 assert new_results[k] == results[k]
695
696 mock_request.reset_mock()
697
698 # Verify UPDATE method is forwarded correctly
699 results = NotifyForm.parse_url("form://localhost?method=UPDATE")
700 instance = NotifyForm(**results)
701 assert instance.send(title="title", body="body") is True
702 assert mock_request.call_count == 1
703 details = mock_request.call_args_list[0]
704 assert details[0][0] == "UPDATE"
705 assert details[0][1] == "http://localhost"
706
707 mock_request.reset_mock()
708
709 # Verify OPTIONS method is forwarded correctly
710 results = NotifyForm.parse_url("form://localhost?method=OPTIONS")
711 instance = NotifyForm(**results)
712 assert instance.send(title="title", body="body") is True
713 assert mock_request.call_count == 1
714 details = mock_request.call_args_list[0]
715 assert details[0][0] == "OPTIONS"
716 assert details[0][1] == "http://localhost"