Debian Codegraph @

tests/test_plugin_custom_xml.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 import re
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.custom_xml import NotifyXML
40
41 logging.disable(logging.CRITICAL)
42
43 # Attachment Directory
44 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
45
46
47 # Our Testing URLs
48 apprise_url_tests = (
49 (
50 "xml://:@/",
51 {
52 "instance": None,
53 },
54 ),
55 (
56 "xml://",
57 {
58 "instance": None,
59 },
60 ),
61 (
62 "xmls://",
63 {
64 "instance": None,
65 },
66 ),
67 (
68 "xml://localhost",
69 {
70 "instance": NotifyXML,
71 },
72 ),
73 (
74 "xml://user@localhost",
75 {
76 "instance": NotifyXML,
77 },
78 ),
79 (
80 "xml://user@localhost?method=invalid",
81 {
82 "instance": AppriseImproperlyConfigured,
83 },
84 ),
85 (
86 "xml://user:pass@localhost",
87 {
88 "instance": NotifyXML,
89 # Our expected url(privacy=True) startswith() response:
90 "privacy_url": "xml://user:****@localhost",
91 },
92 ),
93 # Test method variations
94 (
95 "xml://user@localhost?method=put",
96 {
97 "instance": NotifyXML,
98 },
99 ),
100 (
101 "xml://user@localhost?method=get",
102 {
103 "instance": NotifyXML,
104 },
105 ),
106 (
107 "xml://user@localhost?method=post",
108 {
109 "instance": NotifyXML,
110 "force_debug": True,
111 },
112 ),
113 (
114 "xml://user@localhost?method=head",
115 {
116 "instance": NotifyXML,
117 },
118 ),
119 (
120 "xml://user@localhost?method=delete",
121 {
122 "instance": NotifyXML,
123 },
124 ),
125 (
126 "xml://user@localhost?method=patch",
127 {
128 "instance": NotifyXML,
129 },
130 ),
131 (
132 "xml://user@localhost?method=update",
133 {
134 "instance": NotifyXML,
135 },
136 ),
137 (
138 "xml://user@localhost?method=options",
139 {
140 "instance": NotifyXML,
141 },
142 ),
143 # Continue testing other cases
144 (
145 "xml://localhost:8080",
146 {
147 "instance": NotifyXML,
148 },
149 ),
150 (
151 "xml://user:pass@localhost:8080",
152 {
153 "instance": NotifyXML,
154 },
155 ),
156 (
157 "xmls://localhost",
158 {
159 "instance": NotifyXML,
160 },
161 ),
162 (
163 "xmls://user:pass@localhost",
164 {
165 "instance": NotifyXML,
166 },
167 ),
168 # Continue testing other cases
169 (
170 "xml://localhost:8080",
171 {
172 "instance": NotifyXML,
173 },
174 ),
175 (
176 "xml://user:pass@localhost:8080",
177 {
178 "instance": NotifyXML,
179 },
180 ),
181 (
182 "xml://localhost",
183 {
184 "instance": NotifyXML,
185 },
186 ),
187 (
188 "xmls://user:pass@localhost",
189 {
190 "instance": NotifyXML,
191 # Our expected url(privacy=True) startswith() response:
192 "privacy_url": "xmls://user:****@localhost",
193 },
194 ),
195 (
196 "xml://user@localhost:8080/path/",
197 {
198 "instance": NotifyXML,
199 "privacy_url": "xml://user@localhost:8080/path",
200 },
201 ),
202 (
203 "xmls://localhost:8080/path/",
204 {
205 "instance": NotifyXML,
206 # Our expected url(privacy=True) startswith() response:
207 "privacy_url": "xmls://localhost:8080/path/",
208 },
209 ),
210 (
211 "xmls://user:pass@localhost:8080",
212 {
213 "instance": NotifyXML,
214 },
215 ),
216 # Test our GET params
217 (
218 "xml://localhost:8080/path?-ParamA=Value",
219 {
220 "instance": NotifyXML,
221 },
222 ),
223 # Test our Headers
224 (
225 "xml://localhost:8080/path?+HeaderKey=HeaderValue",
226 {
227 "instance": NotifyXML,
228 },
229 ),
230 (
231 "xml://user:pass@localhost:8081",
232 {
233 "instance": NotifyXML,
234 # force a failure
235 "response": False,
236 "requests_response_code": requests.codes.internal_server_error,
237 },
238 ),
239 (
240 "xml://user:pass@localhost:8082",
241 {
242 "instance": NotifyXML,
243 # throw a bizarre code forcing us to fail to look it up
244 "response": False,
245 "requests_response_code": 999,
246 },
247 ),
248 (
249 "xml://user:pass@localhost:8083",
250 {
251 "instance": NotifyXML,
252 # Throws a series of i/o exceptions with this flag
253 # is set and tests that we gracefully handle them
254 "test_requests_exceptions": True,
255 },
256 ),
257 )
258
259
260 def test_plugin_custom_xml_urls():
261 """NotifyXML() Apprise URLs."""
262
263 # Run our general tests
264 AppriseURLTester(tests=apprise_url_tests).run_all()
265
266
267 @mock.patch("requests.request")
268 def test_plugin_custom_xml_multi_format(mock_request):
269 """NotifyXML() supports all 3 notify formats as a pass-through."""
270
271 response = requests.Request()
272 response.status_code = requests.codes.ok
273 mock_request.return_value = response
274
275 assert NotifyXML.notify_format == (
276 NotifyFormat.TEXT,
277 NotifyFormat.HTML,
278 NotifyFormat.MARKDOWN,
279 )
280
281 a = Apprise()
282 assert a.add("xml://localhost") is True
283
284 # Markdown input aligns directly to the pass-through Markdown path,
285 # so no conversion should alter it.
286 assert (
287 bool(a.notify(body="# hello", body_format=NotifyFormat.MARKDOWN))
288 is True
289 )
290 payload = mock_request.call_args_list[-1][1]["data"]
291 assert "# hello" in payload
292
293 # ?format=html forces the resolved target regardless of input format.
294 a = Apprise()
295 assert a.add("xml://localhost/?format=html") is True
296 assert bool(a.notify(body="a < b", body_format=NotifyFormat.TEXT)) is True
297 payload = mock_request.call_args_list[-1][1]["data"]
298 # The body was HTML-converted first (< -> &lt;), then XML-escaped a
299 # second time on top (& -> &amp;), proving format=html was honored
300 # rather than the plain-text default.
301 assert "&amp;lt;" in payload
302
303
304 @mock.patch("requests.request")
305 def test_notify_xml_plugin_attachments(mock_request):
306 """NotifyXML() Attachments."""
307
308 okay_response = requests.Request()
309 okay_response.status_code = requests.codes.ok
310 okay_response.content = ""
311
312 # Assign our mock object our return value
313 mock_request.return_value = okay_response
314
315 obj = Apprise.instantiate("xml://localhost.localdomain/")
316 assert isinstance(obj, NotifyXML)
317
318 # Test Valid 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 # Test invalid attachment
334 path = os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg")
335 assert (
336 bool(
337 obj.notify(
338 body="body",
339 title="title",
340 notify_type=NotifyType.INFO,
341 attach=path,
342 )
343 )
344 is False
345 )
346
347 # Test Valid Attachment (load 3)
348 path = (
349 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
350 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
351 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
352 )
353 attach = AppriseAttachment(path)
354
355 # Return our good configuration
356 mock_request.side_effect = None
357 mock_request.return_value = okay_response
358 with mock.patch("builtins.open", side_effect=OSError()):
359 # We can't send the message we can't open the attachment for reading
360 assert (
361 bool(
362 obj.notify(
363 body="body",
364 title="title",
365 notify_type=NotifyType.INFO,
366 attach=attach,
367 )
368 )
369 is False
370 )
371
372 # test the handling of our batch modes
373 obj = Apprise.instantiate("xml://[email protected]/")
374 assert isinstance(obj, NotifyXML)
375
376 # Now send an attachment normally without issues
377 mock_request.reset_mock()
378 assert (
379 bool(
380 obj.notify(
381 body="body",
382 title="title",
383 notify_type=NotifyType.INFO,
384 attach=attach,
385 )
386 )
387 is True
388 )
389 assert mock_request.call_count == 1
390
391
392 @mock.patch("requests.request")
393 def test_plugin_custom_xml_edge_cases(mock_request):
394 """NotifyXML() Edge Cases."""
395
396 # Prepare our response
397 response = requests.Request()
398 response.status_code = requests.codes.ok
399
400 # Prepare Mock
401 mock_request.return_value = response
402
403 results = NotifyXML.parse_url(
404 "xml://localhost:8080/command?:Message=Body&method=GET"
405 "&:Key=value&:,=invalid&:MessageType="
406 )
407
408 assert isinstance(results, dict)
409 assert results["user"] is None
410 assert results["password"] is None
411 assert results["port"] == 8080
412 assert results["host"] == "localhost"
413 assert results["fullpath"] == "/command"
414 assert results["path"] == "/"
415 assert results["query"] == "command"
416 assert results["schema"] == "xml"
417 assert results["url"] == "xml://localhost:8080/command"
418 assert isinstance(results["qsd:"], dict)
419 assert results["qsd:"]["Message"] == "Body"
420 assert results["qsd:"]["Key"] == "value"
421 assert results["qsd:"][","] == "invalid"
422
423 instance = NotifyXML(**results)
424 assert isinstance(instance, NotifyXML)
425
426 # XSD URL is disabled due to custom formatting
427 assert instance.xsd_url is None
428
429 response = instance.send(title="title", body="body")
430 assert response is True
431 assert mock_request.call_count == 1
432
433 details = mock_request.call_args_list[0]
434 assert "NotifyType." not in details[1]["data"]
435 assert details[0][0] == "GET"
436 assert details[0][1] == "http://localhost:8080/command"
437 assert instance.url(privacy=False).startswith(
438 "xml://localhost:8080/command?"
439 )
440
441 # Generate a new URL based on our last and verify key values are the same
442 new_results = NotifyXML.parse_url(instance.url(safe=False))
443 for k in (
444 "user",
445 "password",
446 "port",
447 "host",
448 "fullpath",
449 "path",
450 "query",
451 "schema",
452 "url",
453 "method",
454 ):
455 assert new_results[k] == results[k]
456
457 # Test our data set for our key/value pair
458 assert re.search(r"<Version>[1-9]+\.[0-9]+</Version>", details[1]["data"])
459 assert "<Subject>title</Subject>" in details[1]["data"]
460
461 assert "<Message>test</Message>" not in details[1]["data"]
462 assert "<Message>" not in details[1]["data"]
463 # MessageType was removed from the payload
464 assert "<MessageType>" not in details[1]["data"]
465 # However we can find our mapped Message to the new value Body
466 assert "<Body>body</Body>" in details[1]["data"]
467 # Custom entry
468 assert "<Key>value</Key>" in details[1]["data"]
469
470 mock_request.reset_mock()
471
472 results = NotifyXML.parse_url(
473 "xml://localhost:8081/command?method=POST&:New=Value"
474 )
475
476 assert isinstance(results, dict)
477 assert results["user"] is None
478 assert results["password"] is None
479 assert results["port"] == 8081
480 assert results["host"] == "localhost"
481 assert results["fullpath"] == "/command"
482 assert results["path"] == "/"
483 assert results["query"] == "command"
484 assert results["schema"] == "xml"
485 assert results["url"] == "xml://localhost:8081/command"
486 assert isinstance(results["qsd:"], dict)
487 assert results["qsd:"]["New"] == "Value"
488
489 instance = NotifyXML(**results)
490 assert isinstance(instance, NotifyXML)
491
492 # XSD URL is disabled due to custom formatting
493 assert instance.xsd_url is None
494
495 response = instance.send(title="title", body="body")
496 assert response is True
497 assert mock_request.call_count == 1
498
499 details = mock_request.call_args_list[0]
500 assert "NotifyType." not in details[1]["data"]
501 assert details[0][0] == "POST"
502 assert details[0][1] == "http://localhost:8081/command"
503 assert instance.url(privacy=False).startswith(
504 "xml://localhost:8081/command?"
505 )
506
507 # Generate a new URL based on our last and verify key values are the same
508 new_results = NotifyXML.parse_url(instance.url(safe=False))
509 for k in (
510 "user",
511 "password",
512 "port",
513 "host",
514 "fullpath",
515 "path",
516 "query",
517 "schema",
518 "url",
519 "method",
520 ):
521 assert new_results[k] == results[k]
522
523 # Test our data set for our key/value pair
524 assert re.search(r"<Version>[1-9]+\.[0-9]+</Version>", details[1]["data"])
525 assert re.search(
526 r"<MessageType>{}</MessageType>".format(NotifyType.INFO.value),
527 details[1]["data"],
528 )
529 assert r"<Subject>title</Subject>" in details[1]["data"]
530 # No over-ride
531 assert r"<Message>body</Message>" in details[1]["data"]
532
533 mock_request.reset_mock()
534
535 results = NotifyXML.parse_url(
536 "xmls://localhost?method=POST&:Message=Body&:Subject=Title&:Version"
537 )
538
539 assert isinstance(results, dict)
540 assert results["user"] is None
541 assert results["password"] is None
542 assert results["port"] is None
543 assert results["host"] == "localhost"
544 assert results["fullpath"] is None
545 assert results["path"] is None
546 assert results["query"] is None
547 assert results["schema"] == "xmls"
548 assert results["url"] == "xmls://localhost"
549 assert isinstance(results["qsd:"], dict)
550 assert results["qsd:"]["Version"] == ""
551 assert results["qsd:"]["Message"] == "Body"
552 assert results["qsd:"]["Subject"] == "Title"
553
554 instance = NotifyXML(**results)
555 assert isinstance(instance, NotifyXML)
556
557 # XSD URL is disabled due to custom formatting
558 assert instance.xsd_url is None
559
560 response = instance.send(title="title", body="body")
561 assert response is True
562 assert mock_request.call_count == 1
563
564 details = mock_request.call_args_list[0]
565 assert "NotifyType." not in details[1]["data"]
566 assert details[0][0] == "POST"
567 assert details[0][1] == "https://localhost"
568 assert instance.url(privacy=False).startswith("xmls://localhost")
569
570 # Generate a new URL based on our last and verify key values are the same
571 new_results = NotifyXML.parse_url(instance.url(safe=False))
572
573 # Test that the Version has been dropped
574 assert (
575 re.search(r"<Version>[1-9]+\.[0-9]+</Version>", details[1]["data"])
576 is None
577 )
578
579 # Test our data set for our key/value pair
580 assert re.search(
581 r"<MessageType>{}</MessageType>".format(NotifyType.INFO.value),
582 details[1]["data"],
583 )
584
585 # Subject is swapped for Title
586 assert r"<Subject>title</Subject>" not in details[1]["data"]
587 assert r"<Title>title</Title>" in details[1]["data"]
588
589 # Message is swapped for Body
590 assert r"<Message>body</Message>" not in details[1]["data"]
591 assert r"<Body>body</Body>" in details[1]["data"]
592
593 mock_request.reset_mock()
594
595 # Verify UPDATE method is forwarded correctly
596 results = NotifyXML.parse_url("xml://localhost?method=UPDATE")
597 instance = NotifyXML(**results)
598 assert instance.send(title="title", body="body") is True
599 assert mock_request.call_count == 1
600 details = mock_request.call_args_list[0]
601 assert details[0][0] == "UPDATE"
602 assert details[0][1] == "http://localhost"
603
604 mock_request.reset_mock()
605
606 # Verify OPTIONS method is forwarded correctly
607 results = NotifyXML.parse_url("xml://localhost?method=OPTIONS")
608 instance = NotifyXML(**results)
609 assert instance.send(title="title", body="body") is True
610 assert mock_request.call_count == 1
611 details = mock_request.call_args_list[0]
612 assert details[0][0] == "OPTIONS"
613 assert details[0][1] == "http://localhost"