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