Debian Codegraph @

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