Debian Codegraph @

tests/test_attach_http.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 mimetypes
31 from os.path import dirname, getsize, join
32 import re
33 from typing import ClassVar
34 from unittest import mock
35
36 import pytest
37 import requests
38
39 from apprise import Apprise, AppriseAttachment, NotificationManager, exception
40 from apprise.attachment.http import AttachHTTP
41 from apprise.common import ContentLocation
42 from apprise.plugins import NotifyBase
43
44 logging.disable(logging.CRITICAL)
45
46 TEST_VAR_DIR = join(dirname(__file__), "var")
47
48 # Grant access to our Notification Manager Singleton
49 N_MGR = NotificationManager()
50
51 # Some exception handling we'll use
52 REQUEST_EXCEPTIONS = (
53 requests.ConnectionError(0, "requests.ConnectionError() not handled"),
54 requests.RequestException(0, "requests.RequestException() not handled"),
55 requests.HTTPError(0, "requests.HTTPError() not handled"),
56 requests.ReadTimeout(0, "requests.ReadTimeout() not handled"),
57 requests.TooManyRedirects(0, "requests.TooManyRedirects() not handled"),
58 # Throw OSError exceptions too
59 OSError("SystemError"),
60 )
61
62
63 def test_attach_http_parse_url():
64 """
65 API: AttachHTTP().parse_url()
66
67 """
68
69 # bad entry
70 assert AttachHTTP.parse_url("garbage://") is None
71
72 # no url specified
73 assert AttachHTTP.parse_url("http://") is None
74
75
76 def test_attach_http_query_string_dictionary():
77 """
78 API: AttachHTTP() Query String Dictionary
79
80 """
81
82 # Set verify off
83 results = AttachHTTP.parse_url("http://localhost?verify=no&rto=9&cto=8")
84 assert isinstance(results, dict)
85
86 # Create our object
87 obj = AttachHTTP(**results)
88 assert isinstance(obj, AttachHTTP)
89
90 # verify is disabled and therefore set
91 assert re.search(r"[?&]verify=no", obj.url())
92
93 # Our connect timeout flag is set since it differs from the default
94 assert re.search(r"[?&]cto=8", obj.url())
95 # Our read timeout flag is set since it differs from the default
96 assert re.search(r"[?&]rto=9", obj.url())
97
98 # Now lets create a URL with a custom Query String entry
99
100 # some custom qsd entries specified
101 results = AttachHTTP.parse_url("http://localhost?dl=1&_var=test")
102 assert isinstance(results, dict)
103
104 # Create our object
105 obj = AttachHTTP(**results)
106 assert isinstance(obj, AttachHTTP)
107
108 # verify is not in the URL as it is implied (default)
109 assert not re.search(r"[?&]verify=yes", obj.url())
110
111 # But now test that our custom arguments have also been set
112 assert re.search(r"[?&]dl=1", obj.url())
113 assert re.search(r"[?&]_var=test", obj.url())
114
115
116 @mock.patch("requests.request")
117 @mock.patch("requests.get")
118 def test_attach_http(mock_get, mock_request):
119 """
120 API: AttachHTTP() object
121
122 """
123
124 # Define our good:// url
125 class GoodNotification(NotifyBase):
126 def __init__(self, *args, **kwargs):
127 super().__init__(*args, **kwargs)
128
129 def notify(self, *args, **kwargs):
130 # Pretend everything is okay
131 return True
132
133 def url(self):
134 # Support url() function
135 return ""
136
137 # Store our good notification in our schema map
138 N_MGR["good"] = GoodNotification
139
140 # Temporary path
141 path = join(TEST_VAR_DIR, "apprise-test.gif")
142
143 class DummyResponse:
144 """A dummy response used to manage our object."""
145
146 status_code = requests.codes.ok
147 headers: ClassVar[dict[str, str]] = {
148 "Content-Length": getsize(path),
149 "Content-Type": "text/plain",
150 }
151
152 # Pointer to file
153 ptr = None
154
155 # used to return random keep-alive chunks
156 _keepalive_chunk_ref = 0
157
158 def close(self):
159 return
160
161 def iter_content(self, chunk_size=1024):
162 """Lazy function (generator) to read a file piece by piece.
163
164 Default chunk size: 1k.
165 """
166
167 while True:
168 self._keepalive_chunk_ref += 1
169 if 16 % self._keepalive_chunk_ref == 0:
170 # Yield a keep-alive block
171 yield ""
172
173 data = self.ptr.read(chunk_size)
174 if not data:
175 break
176 yield data
177
178 def raise_for_status(self):
179 return
180
181 def __enter__(self):
182 self.ptr = open(path, "rb")
183 return self
184
185 def __exit__(self, *args, **kwargs):
186 self.ptr.close()
187
188 # Prepare Mock
189 dummy_response = DummyResponse()
190 mock_get.return_value = dummy_response
191
192 # Test custom url get parameters
193 results = AttachHTTP.parse_url(
194 "http://user:pass@localhost/apprise.gif?DL=1&cache=300"
195 )
196 assert isinstance(results, dict)
197 attachment = AttachHTTP(**results)
198 assert isinstance(attachment.url(), str) is True
199
200 # Test that our extended variables are passed along
201 assert mock_get.call_count == 0
202 assert attachment
203 assert mock_get.call_count == 1
204 assert "params" in mock_get.call_args_list[0][1]
205 assert "DL" in mock_get.call_args_list[0][1]["params"]
206
207 # Verify that arguments that are reserved for apprise are not
208 # passed along
209 assert "cache" not in mock_get.call_args_list[0][1]["params"]
210
211 with mock.patch("os.unlink", side_effect=OSError()):
212 # Test invalidation with exception thrown
213 attachment.invalidate()
214
215 results = AttachHTTP.parse_url(
216 "http://user:pass@localhost/apprise.gif?+key=value&cache=True"
217 )
218 assert isinstance(results, dict)
219 attachment = AttachHTTP(**results)
220 assert isinstance(attachment.url(), str) is True
221 # No mime-type and/or filename over-ride was specified, so therefore it
222 # won't show up in the generated URL
223 assert re.search(r"[?&]mime=", attachment.url()) is None
224 assert re.search(r"[?&]name=", attachment.url()) is None
225 # No Content-Disposition; so we use filename from path
226 assert attachment.name == "apprise.gif"
227 # Format is text/plain because of the Content-Type in the HTTP Query
228 assert attachment.mimetype == "text/plain"
229
230 # To get our desired effect, we'd have to have had to detect everything
231 attachment.detected_mimetype = None
232 attachment._mimetype = None
233
234 # Now a call would yield a detected result that we'd agree with:
235 assert attachment.mimetype == "image/gif"
236
237 # had it not been there and it was forced to detect it on it's own
238 # we would have had a different result; the below forces it to detect it
239 # again:
240 attachment.detected_mimetype = None
241
242 # Now we get what we would have expected:
243 assert attachment.mimetype == "image/gif"
244
245 results = AttachHTTP.parse_url(
246 "http://localhost:3000/noname.gif?name=usethis.jpg&mime=image/jpeg"
247 )
248 assert isinstance(results, dict)
249 attachment = AttachHTTP(**results)
250 assert isinstance(attachment.url(), str) is True
251 # both mime and name over-ridden
252 assert re.search(r"[?&]mime=image/jpeg", attachment.url())
253 assert re.search(r"[?&]name=usethis.jpg", attachment.url())
254 # No Content-Disposition; so we use filename from path
255 assert attachment.name == "usethis.jpg"
256 assert attachment.mimetype == "image/jpeg"
257
258 # Edge case; download called a second time when content already retrieved
259 assert attachment.download()
260 assert attachment
261 assert len(attachment) == getsize(path)
262
263 # Test case where location is simply set to INACCESSIBLE
264 # Below is a bad example, but it proves the section of code properly works.
265 # Ideally a server admin may wish to just disable all HTTP based
266 # attachments entirely. In this case, they simply just need to change the
267 # global singleton at the start of their program like:
268 #
269 # import apprise
270 # apprise.attachment.AttachHTTP.location = \
271 # apprise.ContentLocation.INACCESSIBLE
272 attachment = AttachHTTP(**results)
273 attachment.location = ContentLocation.INACCESSIBLE
274 assert attachment.path is None
275 # Downloads just don't work period
276 assert attachment.download() is False
277
278 # No path specified
279 # No Content-Disposition specified
280 # No filename (because no path)
281 results = AttachHTTP.parse_url("http://localhost")
282 assert isinstance(results, dict)
283 attachment = AttachHTTP(**results)
284 assert isinstance(attachment.url(), str) is True
285 # No mime-type and/or filename over-ride was specified, so therefore it
286 # won't show up in the generated URL
287 assert re.search(r"[?&]mime=", attachment.url()) is None
288 assert re.search(r"[?&]name=", attachment.url()) is None
289 # Format is text/plain because of the Content-Type in the HTTP Query
290 assert attachment.mimetype == "text/plain"
291
292 # To get our desired effect, we'd have to have had to detect everything
293 attachment.detected_mimetype = None
294 attachment._mimetype = None
295
296 # Now we are unable to detect our file without enough data to do it with
297 assert attachment.mimetype == "application/octet-stream"
298
299 # Because we could determine our mime type, we could build an extension
300 # for our unknown filename
301 assert (
302 attachment.name == f"{AttachHTTP.unknown_filename}"
303 f"{mimetypes.guess_extension(attachment.mimetype)}"
304 )
305 assert attachment
306 assert len(attachment) == getsize(path)
307
308 # Set Content-Length to a value that exceeds our maximum allowable
309 dummy_response.headers["Content-Length"] = AttachHTTP.max_file_size + 1
310 results = AttachHTTP.parse_url("http://localhost/toobig.jpg")
311 assert isinstance(results, dict)
312 attachment = AttachHTTP(**results)
313 # we can not download this attachment
314 assert not attachment
315 assert isinstance(attachment.url(), str) is True
316 # No mime-type and/or filename over-ride was specified, so therefore it
317 # won't show up in the generated URL
318 assert re.search(r"[?&]mime=", attachment.url()) is None
319 assert re.search(r"[?&]name=", attachment.url()) is None
320 assert attachment.mimetype is None
321 assert attachment.name is None
322 assert len(attachment) == 0
323
324 # Handle cases where we have no Content-Length and we need to rely
325 # on what is read as it is streamed
326 del dummy_response.headers["Content-Length"]
327 # No path specified
328 # No Content-Disposition specified
329 # No Content-Length specified
330 # No filename (because no path)
331 results = AttachHTTP.parse_url("http://localhost/no-length.gif")
332 assert isinstance(results, dict)
333 attachment = AttachHTTP(**results)
334 assert isinstance(attachment.url(), str) is True
335 # No mime-type and/or filename over-ride was specified, so therefore it
336 # won't show up in the generated URL
337 assert re.search(r"[?&]mime=", attachment.url()) is None
338 assert re.search(r"[?&]name=", attachment.url()) is None
339
340 # Format is text/plain because of the Content-Type in the HTTP Query
341 assert attachment.mimetype == "text/plain"
342
343 # Because we could determine our mime type, we could build an extension
344 # for our unknown filename
345 assert attachment.name == "no-length.gif"
346 assert attachment
347 assert len(attachment) == getsize(path)
348
349 # Set our limit to be the length of our image; everything should work
350 # without a problem
351 max_file_size = AttachHTTP.max_file_size
352 AttachHTTP.max_file_size = getsize(path)
353 # Set ourselves a Content-Disposition (providing a filename)
354 dummy_response.headers["Content-Disposition"] = (
355 'attachment; filename="myimage.gif"'
356 )
357 # Remove our content type so we're forced to guess it from our filename
358 # specified in our Content-Disposition
359 del dummy_response.headers["Content-Type"]
360 # No path specified
361 # No Content-Length specified
362 # Filename in Content-Disposition (over-rides one found in path
363 results = AttachHTTP.parse_url("http://user@localhost/ignore-filename.gif")
364 assert isinstance(results, dict)
365 attachment = AttachHTTP(**results)
366 assert isinstance(attachment.url(), str) is True
367 # No mime-type and/or filename over-ride was specified, so therefore it
368 # won't show up in the generated URL
369 assert re.search(r"[?&]mime=", attachment.url()) is None
370 assert re.search(r"[?&]name=", attachment.url()) is None
371 assert attachment.mimetype == "image/gif"
372 # Because we could determine our mime type, we could build an extension
373 # for our unknown filename
374 assert attachment.name == "myimage.gif"
375 assert attachment
376 assert len(attachment) == getsize(path)
377
378 # Similar to test above except we make our max message size just 1 byte
379 # smaller then our gif file. This will cause us to fail to read the
380 # attachment
381 AttachHTTP.max_file_size = getsize(path) - 1
382 results = AttachHTTP.parse_url("http://localhost/toobig.jpg")
383 assert isinstance(results, dict)
384 attachment = AttachHTTP(**results)
385 # we can not download this attachment
386 assert not attachment
387 assert isinstance(attachment.url(), str) is True
388 # No mime-type and/or filename over-ride was specified, so therefore it
389 # won't show up in the generated URL
390 assert re.search(r"[?&]mime=", attachment.url()) is None
391 assert re.search(r"[?&]name=", attachment.url()) is None
392 assert attachment.mimetype is None
393 assert attachment.name is None
394 assert len(attachment) == 0
395
396 # Disable our file size limitations
397 AttachHTTP.max_file_size = 0
398 results = AttachHTTP.parse_url("http://user@localhost")
399 assert isinstance(results, dict)
400 attachment = AttachHTTP(**results)
401 assert isinstance(attachment.url(), str) is True
402 # No mime-type and/or filename over-ride was specified, so therefore it
403 # won't show up in the generated URL
404 assert re.search(r"[?&]mime=", attachment.url()) is None
405 assert re.search(r"[?&]name=", attachment.url()) is None
406 assert attachment.mimetype == "image/gif"
407 # Because we could determine our mime type, we could build an extension
408 # for our unknown filename
409 assert attachment.name == "myimage.gif"
410 assert attachment
411 assert len(attachment) == getsize(path)
412
413 # Set our header up with an invalid Content-Length; we can still process
414 # this data. It just means we track it lower when reading back content
415 dummy_response.headers = {"Content-Length": "invalid"}
416 results = AttachHTTP.parse_url("http://localhost/invalid-length.gif")
417 assert isinstance(results, dict)
418 attachment = AttachHTTP(**results)
419 assert isinstance(attachment.url(), str) is True
420 # No mime-type and/or filename over-ride was specified, so therefore it
421 # won't show up in the generated URL
422 assert re.search(r"[?&]mime=", attachment.url()) is None
423 assert re.search(r"[?&]name=", attachment.url()) is None
424 assert attachment.mimetype == "image/gif"
425 # Because we could determine our mime type, we could build an extension
426 # for our unknown filename
427 assert attachment.name == "invalid-length.gif"
428 assert attachment
429
430 # Give ourselves nothing to work with
431 dummy_response.headers = {}
432 results = AttachHTTP.parse_url("http://user@localhost")
433 assert isinstance(results, dict)
434 attachment = AttachHTTP(**results)
435 # we can not download this attachment
436 assert attachment
437 assert isinstance(attachment.url(), str) is True
438 # No mime-type and/or filename over-ride was specified, so therefore it
439 # won't show up in the generated URL
440 assert re.search(r"[?&]mime=", attachment.url()) is None
441 assert re.search(r"[?&]name=", attachment.url()) is None
442
443 # Handle edge-case where detected_name is None for whatever reason
444 attachment.detected_name = None
445 assert attachment.mimetype == attachment.unknown_mimetype
446 assert attachment.name.startswith(AttachHTTP.unknown_filename)
447 assert len(attachment) == getsize(path)
448
449 # Exception handling
450 mock_get.return_value = None
451 for exception_ in REQUEST_EXCEPTIONS:
452 aa = AppriseAttachment.instantiate(
453 "http://localhost/exception.gif?cache=30"
454 )
455 assert isinstance(aa, AttachHTTP)
456
457 mock_get.side_effect = exception_
458 assert not aa
459
460 # Restore value
461 AttachHTTP.max_file_size = max_file_size
462
463 # Multi Message Testing
464 mock_get.side_effect = None
465 mock_get.return_value = DummyResponse()
466
467 # Prepare our POST response (from notify call)
468 response = requests.Request()
469 response.status_code = requests.codes.ok
470 response.content = ""
471 mock_request.return_value = response
472
473 mock_get.reset_mock()
474 mock_request.reset_mock()
475 assert mock_get.call_count == 0
476
477 apobj = Apprise()
478 assert apobj.add("form://localhost")
479 assert apobj.add("json://localhost")
480 assert apobj.add("xml://localhost")
481 assert len(apobj) == 3
482 assert (
483 apobj.notify(
484 body="one attachment split 3 times",
485 attach="http://localhost/test.gif",
486 )
487 is True
488 )
489
490 # We posted 3 times
491 assert mock_request.call_count == 3
492 # We only fetched once and re-used the same fetch for all posts
493 assert mock_get.call_count == 1
494
495 mock_get.reset_mock()
496 mock_request.reset_mock()
497 apobj = Apprise()
498 for n in range(10):
499 assert apobj.add(f"json://localhost?:entry={n}&method=post")
500 assert apobj.add(f"form://localhost?:entry={n}&method=post")
501 assert apobj.add(f"xml://localhost?:entry={n}&method=post")
502
503 assert (
504 apobj.notify(
505 body="one attachment split 30 times",
506 attach="http://localhost/test.gif",
507 )
508 is True
509 )
510
511 # We posted 30 times
512 assert mock_request.call_count == 30
513 # We only fetched once and re-used the same fetch for all posts
514 assert mock_get.call_count == 1
515
516 #
517 # We will test our base64 handling now
518 #
519 mock_get.reset_mock()
520 mock_request.reset_mock()
521
522 AttachHTTP.max_file_size = getsize(path)
523 # Set ourselves a Content-Disposition (providing a filename)
524 dummy_response.headers["Content-Disposition"] = (
525 'attachment; filename="myimage.gif"'
526 )
527 results = AttachHTTP.parse_url("http://user@localhost/filename.gif")
528 assert isinstance(results, dict)
529 obj = AttachHTTP(**results)
530
531 # now test our base64 output
532 assert isinstance(obj.base64(), str)
533 # No encoding if we choose
534 assert isinstance(obj.base64(encoding=None), bytes)
535
536 # Test that a 3xx redirect is rejected when redirect=no is set; a
537 # status-code range guard (300-399) catches what raise_for_status() misses.
538 class RedirectResponse:
539 """Simulates a 301 response returned when allow_redirects=False."""
540
541 status_code = requests.codes.moved_permanently
542 headers: ClassVar[dict[str, str]] = {}
543
544 def raise_for_status(self):
545 return
546
547 def __enter__(self):
548 return self
549
550 def __exit__(self, *args, **kwargs):
551 return
552
553 mock_get.return_value = RedirectResponse()
554 results = AttachHTTP.parse_url(
555 "http://user@localhost/filename.gif?redirect=no"
556 )
557 assert isinstance(results, dict)
558 obj_no_redir = AttachHTTP(**results)
559 assert obj_no_redir.redirects is False
560 # Download must fail -- streaming a redirect stub would be wrong
561 assert obj_no_redir.download() is False
562 # Restore for downstream tests
563 mock_get.return_value = dummy_response
564
565 # Error cases:
566 with mock.patch(
567 "builtins.open",
568 new_callable=mock.mock_open,
569 read_data="mocked file content",
570 ) as mock_file:
571 mock_file.side_effect = FileNotFoundError
572 with pytest.raises(exception.AppriseFileNotFound):
573 obj.base64()
574
575 mock_file.side_effect = OSError
576 with pytest.raises(exception.AppriseDiskIOError):
577 obj.base64()