| 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 |
import asyncio |
| 29 |
from contextlib import contextmanager |
| 30 |
import logging |
| 31 |
import threading |
| 32 |
import time |
| 33 |
from unittest import mock |
| 34 |
|
| 35 |
import pytest |
| 36 |
|
| 37 |
from apprise import LOGGER_NAME, Apprise, AppriseAsset, AppriseResultStatus |
| 38 |
from apprise.common import ( |
| 39 |
APPRISE_MAX_SERVICE_RETRY, |
| 40 |
APPRISE_MAX_SERVICE_WAIT, |
| 41 |
MATCH_ALL_TAG, |
| 42 |
) |
| 43 |
from apprise.config.base import ConfigBase |
| 44 |
from apprise.exception import AppriseImproperlyConfigured |
| 45 |
from apprise.manager_plugins import NotificationManager |
| 46 |
from apprise.plugins import NotifyBase |
| 47 |
from apprise.tag import AppriseTag |
| 48 |
|
| 49 |
logging.disable(logging.CRITICAL) |
| 50 |
|
| 51 |
N_MGR = NotificationManager() |
| 52 |
|
| 53 |
|
| 54 |
@contextmanager |
| 55 |
def apprise_logs_enabled(level=logging.TRACE): |
| 56 |
"""Re-enable apprise logging so a test can inspect captured entries.""" |
| 57 |
# This module silences logging outright, which would keep every record |
| 58 |
# away from the captures a result is built from. |
| 59 |
apprise_logger = logging.getLogger(LOGGER_NAME) |
| 60 |
restore_level = apprise_logger.level |
| 61 |
apprise_logger.setLevel(level) |
| 62 |
logging.disable(logging.NOTSET) |
| 63 |
|
| 64 |
try: |
| 65 |
yield |
| 66 |
|
| 67 |
finally: |
| 68 |
# Put the module back the way the rest of the file expects it. |
| 69 |
logging.disable(logging.CRITICAL) |
| 70 |
apprise_logger.setLevel(restore_level) |
| 71 |
|
| 72 |
|
| 73 |
class _TestNotify(NotifyBase): |
| 74 |
"""Test notification plugin -- controlled pass/fail via side_effect.""" |
| 75 |
|
| 76 |
app_id = "TestApp" |
| 77 |
app_desc = "Test" |
| 78 |
notify_url = "test://" |
| 79 |
|
| 80 |
title_maxlen = 250 |
| 81 |
body_maxlen = 32768 |
| 82 |
|
| 83 |
# Override so NotifyBase doesn't reject the URL |
| 84 |
def url(self, privacy=False, *args, **kwargs): |
| 85 |
return "test://localhost" |
| 86 |
|
| 87 |
def send(self, **kwargs): |
| 88 |
return True |
| 89 |
|
| 90 |
@staticmethod |
| 91 |
def parse_url(url): |
| 92 |
results = NotifyBase.parse_url(url, verify_host=False) |
| 93 |
return results |
| 94 |
|
| 95 |
|
| 96 |
class TestWaitValidation: |
| 97 |
"""Tests for the wait= parameter accepted by NotifyBase.""" |
| 98 |
|
| 99 |
def _make(self, **kwargs): |
| 100 |
return _TestNotify(host="localhost", **kwargs) |
| 101 |
|
| 102 |
@pytest.mark.parametrize( |
| 103 |
"value,expected", |
| 104 |
[ |
| 105 |
(0, 0.0), |
| 106 |
(0.0, 0.0), |
| 107 |
(0.5, 0.5), |
| 108 |
(1, 1.0), |
| 109 |
(1.0, 1.0), |
| 110 |
("0.5", 0.5), |
| 111 |
("1", 1.0), |
| 112 |
("1.4", 1.4), |
| 113 |
("20", 20.0), |
| 114 |
(APPRISE_MAX_SERVICE_WAIT, APPRISE_MAX_SERVICE_WAIT), |
| 115 |
], |
| 116 |
) |
| 117 |
def test_valid_wait(self, value, expected): |
| 118 |
nb = self._make(wait=value) |
| 119 |
assert nb.wait == pytest.approx(expected) |
| 120 |
|
| 121 |
def test_wait_clamped_to_max(self): |
| 122 |
# Values above the cap are clamped, not rejected |
| 123 |
nb = self._make(wait=APPRISE_MAX_SERVICE_WAIT + 9999) |
| 124 |
assert nb.wait == pytest.approx(APPRISE_MAX_SERVICE_WAIT) |
| 125 |
|
| 126 |
@pytest.mark.parametrize( |
| 127 |
"bad_value", |
| 128 |
[ |
| 129 |
"-3", |
| 130 |
"-0.1", |
| 131 |
"1.3.3.", |
| 132 |
"abc", |
| 133 |
"inf", |
| 134 |
"-inf", |
| 135 |
"nan", |
| 136 |
None, # None means "use asset default" -- tested separately |
| 137 |
], |
| 138 |
) |
| 139 |
def test_invalid_wait_uses_asset_default(self, bad_value): |
| 140 |
if bad_value is None: |
| 141 |
# Not passing wait= at all should use asset default |
| 142 |
asset = AppriseAsset(default_service_wait=1.25) |
| 143 |
nb = _TestNotify(host="localhost", asset=asset) |
| 144 |
assert nb.wait == pytest.approx(1.25) |
| 145 |
return |
| 146 |
|
| 147 |
asset = AppriseAsset(default_service_wait=0.75) |
| 148 |
nb = self._make(wait=bad_value, asset=asset) |
| 149 |
# Falls back to asset default on invalid input |
| 150 |
assert nb.wait == pytest.approx(0.75) |
| 151 |
|
| 152 |
def test_negative_wait_falls_back(self): |
| 153 |
asset = AppriseAsset(default_service_wait=2.0) |
| 154 |
nb = self._make(wait=-1.0, asset=asset) |
| 155 |
assert nb.wait == pytest.approx(2.0) |
| 156 |
|
| 157 |
def test_asset_default_zero(self): |
| 158 |
asset = AppriseAsset(default_service_wait=0.0) |
| 159 |
nb = _TestNotify(host="localhost", asset=asset) |
| 160 |
assert nb.wait == pytest.approx(0.0) |
| 161 |
|
| 162 |
def test_asset_default_clamped_to_max(self): |
| 163 |
asset = AppriseAsset(default_service_wait=APPRISE_MAX_SERVICE_WAIT + 1) |
| 164 |
nb = _TestNotify(host="localhost", asset=asset) |
| 165 |
assert nb.wait == pytest.approx(APPRISE_MAX_SERVICE_WAIT) |
| 166 |
|
| 167 |
|
| 168 |
class TestRetryValidation: |
| 169 |
"""Sanity checks for the retry= parameter.""" |
| 170 |
|
| 171 |
def _make(self, **kwargs): |
| 172 |
return _TestNotify(host="localhost", **kwargs) |
| 173 |
|
| 174 |
@pytest.mark.parametrize( |
| 175 |
"value,expected", |
| 176 |
[ |
| 177 |
(0, 0), |
| 178 |
(1, 1), |
| 179 |
("3", 3), |
| 180 |
(APPRISE_MAX_SERVICE_RETRY, APPRISE_MAX_SERVICE_RETRY), |
| 181 |
], |
| 182 |
) |
| 183 |
def test_valid_retry(self, value, expected): |
| 184 |
nb = self._make(retry=value) |
| 185 |
assert nb.retry == expected |
| 186 |
|
| 187 |
def test_retry_clamped_to_max(self): |
| 188 |
nb = self._make(retry=APPRISE_MAX_SERVICE_RETRY + 999) |
| 189 |
assert nb.retry == APPRISE_MAX_SERVICE_RETRY |
| 190 |
|
| 191 |
@pytest.mark.parametrize("bad", ["-1", "abc", "1.3.3."]) |
| 192 |
def test_invalid_retry_uses_asset_default(self, bad): |
| 193 |
asset = AppriseAsset(default_service_retry=2) |
| 194 |
nb = self._make(retry=bad, asset=asset) |
| 195 |
assert nb.retry == 2 |
| 196 |
|
| 197 |
|
| 198 |
class TestUrlRoundTrip: |
| 199 |
def test_wait_in_url_parameters(self): |
| 200 |
nb = _TestNotify(host="localhost", wait=1.5, retry=2) |
| 201 |
params = nb.url_parameters() |
| 202 |
assert "wait" in params |
| 203 |
assert params["wait"] == "1.5" |
| 204 |
assert "retry" in params |
| 205 |
assert params["retry"] == "2" |
| 206 |
|
| 207 |
def test_wait_zero_always_in_url_parameters(self): |
| 208 |
"""retry= and wait= are always present, even at their zero defaults.""" |
| 209 |
nb = _TestNotify(host="localhost", wait=0.0, retry=0) |
| 210 |
params = nb.url_parameters() |
| 211 |
assert "wait" in params |
| 212 |
assert params["wait"] == "0.0" |
| 213 |
assert "retry" in params |
| 214 |
assert params["retry"] == "0" |
| 215 |
|
| 216 |
def test_parse_url_extracts_wait(self): |
| 217 |
results = _TestNotify.parse_url("test://localhost?wait=2.5&retry=3") |
| 218 |
assert results is not None |
| 219 |
assert results.get("wait") == "2.5" |
| 220 |
assert results.get("retry") == "3" |
| 221 |
|
| 222 |
def test_parse_url_no_wait_key_absent(self): |
| 223 |
results = _TestNotify.parse_url("test://localhost") |
| 224 |
assert results is not None |
| 225 |
assert "wait" not in results |
| 226 |
|
| 227 |
|
| 228 |
class _FailThenSucceedNotify(NotifyBase): |
| 229 |
"""Fails the first N calls, then succeeds.""" |
| 230 |
|
| 231 |
app_id = "FailThenSucceed" |
| 232 |
app_desc = "Test" |
| 233 |
notify_url = "failpass://" |
| 234 |
title_maxlen = 250 |
| 235 |
body_maxlen = 32768 |
| 236 |
|
| 237 |
def __init__(self, fail_times=1, **kwargs): |
| 238 |
super().__init__(**kwargs) |
| 239 |
self._fail_times = fail_times |
| 240 |
self._calls = 0 |
| 241 |
|
| 242 |
def url(self, *args, **kwargs): |
| 243 |
return "failpass://localhost" |
| 244 |
|
| 245 |
def send(self, **kwargs): |
| 246 |
self._calls += 1 |
| 247 |
return not self._calls <= self._fail_times |
| 248 |
|
| 249 |
async def async_notify(self, **kwargs): |
| 250 |
return self.send(**kwargs) |
| 251 |
|
| 252 |
@staticmethod |
| 253 |
def parse_url(url): |
| 254 |
return NotifyBase.parse_url(url, verify_host=False) |
| 255 |
|
| 256 |
|
| 257 |
class TestSequentialSleep: |
| 258 |
"""time.sleep is called between retries in sequential dispatch.""" |
| 259 |
|
| 260 |
def test_sleep_called_on_retry(self): |
| 261 |
"""A failed attempt waits once before its successful retry.""" |
| 262 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 263 |
|
| 264 |
try: |
| 265 |
asset = AppriseAsset(async_mode=False) |
| 266 |
a = Apprise(asset=asset) |
| 267 |
|
| 268 |
service = _FailThenSucceedNotify( |
| 269 |
host="localhost", |
| 270 |
asset=asset, |
| 271 |
retry=2, |
| 272 |
wait=0.3, |
| 273 |
) |
| 274 |
a.add(service) |
| 275 |
|
| 276 |
with mock.patch("apprise.apprise.time.sleep") as mock_sleep: |
| 277 |
result = a.notify(body="test") |
| 278 |
|
| 279 |
assert bool(result) is True |
| 280 |
# Failed once -> sleep once before retry |
| 281 |
mock_sleep.assert_called_once_with(pytest.approx(0.3)) |
| 282 |
finally: |
| 283 |
N_MGR.unload_modules() |
| 284 |
|
| 285 |
def test_sleep_not_called_when_wait_zero(self): |
| 286 |
"""A zero wait setting retries without calling sleep.""" |
| 287 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 288 |
|
| 289 |
try: |
| 290 |
asset = AppriseAsset(async_mode=False) |
| 291 |
a = Apprise(asset=asset) |
| 292 |
|
| 293 |
service = _FailThenSucceedNotify( |
| 294 |
host="localhost", |
| 295 |
asset=asset, |
| 296 |
retry=2, |
| 297 |
wait=0.0, |
| 298 |
) |
| 299 |
a.add(service) |
| 300 |
|
| 301 |
with mock.patch("apprise.apprise.time.sleep") as mock_sleep: |
| 302 |
result = a.notify(body="test") |
| 303 |
|
| 304 |
assert bool(result) is True |
| 305 |
mock_sleep.assert_not_called() |
| 306 |
finally: |
| 307 |
N_MGR.unload_modules() |
| 308 |
|
| 309 |
def test_sleep_not_called_when_no_retry(self): |
| 310 |
"""A service without retries never sleeps after failure.""" |
| 311 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 312 |
|
| 313 |
try: |
| 314 |
asset = AppriseAsset(async_mode=False) |
| 315 |
a = Apprise(asset=asset) |
| 316 |
|
| 317 |
# retry=0 means only one attempt; with wait=1.0 sleep should |
| 318 |
# never fire since there are no retries |
| 319 |
service = _FailThenSucceedNotify( |
| 320 |
host="localhost", |
| 321 |
asset=asset, |
| 322 |
retry=0, |
| 323 |
wait=1.0, |
| 324 |
fail_times=0, # always succeeds |
| 325 |
) |
| 326 |
a.add(service) |
| 327 |
|
| 328 |
with mock.patch("apprise.apprise.time.sleep") as mock_sleep: |
| 329 |
result = a.notify(body="test") |
| 330 |
|
| 331 |
assert bool(result) is True |
| 332 |
mock_sleep.assert_not_called() |
| 333 |
finally: |
| 334 |
N_MGR.unload_modules() |
| 335 |
|
| 336 |
def test_sleep_called_multiple_times(self): |
| 337 |
"""Fails twice, succeeds on third attempt -> sleep called twice.""" |
| 338 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 339 |
|
| 340 |
try: |
| 341 |
asset = AppriseAsset(async_mode=False) |
| 342 |
a = Apprise(asset=asset) |
| 343 |
|
| 344 |
service = _FailThenSucceedNotify( |
| 345 |
host="localhost", |
| 346 |
asset=asset, |
| 347 |
retry=3, |
| 348 |
wait=0.5, |
| 349 |
fail_times=2, |
| 350 |
) |
| 351 |
a.add(service) |
| 352 |
|
| 353 |
with mock.patch("apprise.apprise.time.sleep") as mock_sleep: |
| 354 |
result = a.notify(body="test") |
| 355 |
|
| 356 |
assert bool(result) is True |
| 357 |
assert mock_sleep.call_count == 2 |
| 358 |
for call in mock_sleep.call_args_list: |
| 359 |
assert call == mock.call(pytest.approx(0.5)) |
| 360 |
finally: |
| 361 |
N_MGR.unload_modules() |
| 362 |
|
| 363 |
|
| 364 |
class TestThreadPoolSleep: |
| 365 |
"""time.sleep is called between retries in threadpool dispatch.""" |
| 366 |
|
| 367 |
def test_sleep_called_in_threadpool(self): |
| 368 |
"""A thread-pool retry honors the configured wait interval.""" |
| 369 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 370 |
|
| 371 |
try: |
| 372 |
# async_mode=True -> uses threadpool when > 1 service; |
| 373 |
# but with a single service it falls through to sequential. |
| 374 |
# Use two services so we actually hit the threadpool path. |
| 375 |
asset = AppriseAsset(async_mode=True) |
| 376 |
|
| 377 |
# Two separate service objects so a threadpool is used |
| 378 |
s1 = _FailThenSucceedNotify( |
| 379 |
host="localhost", |
| 380 |
asset=asset, |
| 381 |
retry=2, |
| 382 |
wait=0.2, |
| 383 |
fail_times=1, |
| 384 |
) |
| 385 |
s2 = _FailThenSucceedNotify( |
| 386 |
host="localhost2", |
| 387 |
asset=asset, |
| 388 |
retry=0, |
| 389 |
wait=0.0, |
| 390 |
fail_times=0, |
| 391 |
) |
| 392 |
|
| 393 |
a = Apprise(asset=asset) |
| 394 |
a.add(s1) |
| 395 |
a.add(s2) |
| 396 |
|
| 397 |
with mock.patch("apprise.apprise.time.sleep") as mock_sleep: |
| 398 |
result = a.notify(body="test") |
| 399 |
|
| 400 |
assert bool(result) is True |
| 401 |
# s1 fails once -> sleep once |
| 402 |
mock_sleep.assert_called_once_with(pytest.approx(0.2)) |
| 403 |
finally: |
| 404 |
N_MGR.unload_modules() |
| 405 |
|
| 406 |
def test_sleep_not_called_in_threadpool_when_wait_zero(self): |
| 407 |
"""A zero thread-pool wait retries without calling sleep.""" |
| 408 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 409 |
|
| 410 |
try: |
| 411 |
asset = AppriseAsset(async_mode=True) |
| 412 |
|
| 413 |
s1 = _FailThenSucceedNotify( |
| 414 |
host="localhost", |
| 415 |
asset=asset, |
| 416 |
retry=2, |
| 417 |
wait=0.0, |
| 418 |
fail_times=1, |
| 419 |
) |
| 420 |
s2 = _FailThenSucceedNotify( |
| 421 |
host="localhost2", |
| 422 |
asset=asset, |
| 423 |
retry=0, |
| 424 |
wait=0.0, |
| 425 |
fail_times=0, |
| 426 |
) |
| 427 |
|
| 428 |
a = Apprise(asset=asset) |
| 429 |
a.add(s1) |
| 430 |
a.add(s2) |
| 431 |
|
| 432 |
with mock.patch("apprise.apprise.time.sleep") as mock_sleep: |
| 433 |
result = a.notify(body="test") |
| 434 |
|
| 435 |
assert bool(result) is True |
| 436 |
mock_sleep.assert_not_called() |
| 437 |
finally: |
| 438 |
N_MGR.unload_modules() |
| 439 |
|
| 440 |
|
| 441 |
class TestAsyncioSleep: |
| 442 |
"""asyncio.sleep is called between retries in async dispatch.""" |
| 443 |
|
| 444 |
def test_asyncio_sleep_called(self): |
| 445 |
"""An asynchronous retry honors the configured wait interval.""" |
| 446 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 447 |
|
| 448 |
try: |
| 449 |
asset = AppriseAsset() |
| 450 |
|
| 451 |
service = _FailThenSucceedNotify( |
| 452 |
host="localhost", |
| 453 |
asset=asset, |
| 454 |
retry=2, |
| 455 |
wait=0.4, |
| 456 |
fail_times=1, |
| 457 |
) |
| 458 |
|
| 459 |
a = Apprise(asset=asset) |
| 460 |
a.add(service) |
| 461 |
|
| 462 |
async def run(): |
| 463 |
"""Dispatch while capturing the asynchronous retry sleep.""" |
| 464 |
with mock.patch("apprise.apprise.asyncio.sleep") as mock_sleep: |
| 465 |
mock_sleep.return_value = None |
| 466 |
result = await a.async_notify(body="test") |
| 467 |
return result, mock_sleep |
| 468 |
|
| 469 |
result, mock_sleep = asyncio.run(run()) |
| 470 |
|
| 471 |
assert bool(result) is True |
| 472 |
mock_sleep.assert_called_once_with(pytest.approx(0.4)) |
| 473 |
finally: |
| 474 |
N_MGR.unload_modules() |
| 475 |
|
| 476 |
def test_asyncio_sleep_not_called_when_wait_zero(self): |
| 477 |
"""A zero asynchronous wait retries without calling sleep.""" |
| 478 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 479 |
|
| 480 |
try: |
| 481 |
asset = AppriseAsset() |
| 482 |
|
| 483 |
service = _FailThenSucceedNotify( |
| 484 |
host="localhost", |
| 485 |
asset=asset, |
| 486 |
retry=2, |
| 487 |
wait=0.0, |
| 488 |
fail_times=1, |
| 489 |
) |
| 490 |
|
| 491 |
a = Apprise(asset=asset) |
| 492 |
a.add(service) |
| 493 |
|
| 494 |
async def run(): |
| 495 |
"""Dispatch while checking that asyncio.sleep is unused.""" |
| 496 |
with mock.patch("apprise.apprise.asyncio.sleep") as mock_sleep: |
| 497 |
mock_sleep.return_value = None |
| 498 |
result = await a.async_notify(body="test") |
| 499 |
return result, mock_sleep |
| 500 |
|
| 501 |
result, mock_sleep = asyncio.run(run()) |
| 502 |
|
| 503 |
assert bool(result) is True |
| 504 |
mock_sleep.assert_not_called() |
| 505 |
finally: |
| 506 |
N_MGR.unload_modules() |
| 507 |
|
| 508 |
|
| 509 |
class TestAssetDefault: |
| 510 |
def test_asset_wait_default_used(self): |
| 511 |
asset = AppriseAsset(default_service_wait=1.5) |
| 512 |
nb = _TestNotify(host="localhost", asset=asset) |
| 513 |
assert nb.wait == pytest.approx(1.5) |
| 514 |
|
| 515 |
def test_explicit_wait_overrides_asset(self): |
| 516 |
asset = AppriseAsset(default_service_wait=1.5) |
| 517 |
nb = _TestNotify(host="localhost", asset=asset, wait=0.2) |
| 518 |
assert nb.wait == pytest.approx(0.2) |
| 519 |
|
| 520 |
def test_asset_retry_default_used(self): |
| 521 |
asset = AppriseAsset(default_service_retry=3) |
| 522 |
nb = _TestNotify(host="localhost", asset=asset) |
| 523 |
assert nb.retry == 3 |
| 524 |
|
| 525 |
def test_explicit_retry_overrides_asset(self): |
| 526 |
asset = AppriseAsset(default_service_retry=3) |
| 527 |
nb = _TestNotify(host="localhost", asset=asset, retry=1) |
| 528 |
assert nb.retry == 1 |
| 529 |
|
| 530 |
|
| 531 |
class _RaisingNotify(NotifyBase): |
| 532 |
"""Plugin that raises a bare Exception from notify().""" |
| 533 |
|
| 534 |
app_id = "RaisingApp" |
| 535 |
app_desc = "Test" |
| 536 |
notify_url = "raise://" |
| 537 |
title_maxlen = 250 |
| 538 |
body_maxlen = 32768 |
| 539 |
|
| 540 |
def url(self, *args, **kwargs): |
| 541 |
"""Return the stable URL for this raising test plugin.""" |
| 542 |
return "raise://localhost" |
| 543 |
|
| 544 |
def send(self, **kwargs): |
| 545 |
"""Raise a delivery error for synchronous exception tests.""" |
| 546 |
raise RuntimeError("plugin exploded") |
| 547 |
|
| 548 |
async def async_notify(self, **kwargs): |
| 549 |
"""Raise a delivery error for asynchronous exception tests.""" |
| 550 |
raise RuntimeError("plugin exploded async") |
| 551 |
|
| 552 |
@staticmethod |
| 553 |
def parse_url(url): |
| 554 |
"""Parse the synthetic URL without requiring a real host.""" |
| 555 |
return NotifyBase.parse_url(url, verify_host=False) |
| 556 |
|
| 557 |
|
| 558 |
class _BadFormatNotify(NotifyBase): |
| 559 |
"""Plugin that raises while its content is prepared. |
| 560 |
|
| 561 |
The failure lands before any service is dispatched. ``error`` picks |
| 562 |
what resolve_format() raises, so a test can show the guard is not |
| 563 |
limited to TypeError. |
| 564 |
""" |
| 565 |
|
| 566 |
app_id = "BadFormatApp" |
| 567 |
app_desc = "Test" |
| 568 |
service_name = "BadFormat" |
| 569 |
notify_url = "badformat://" |
| 570 |
title_maxlen = 250 |
| 571 |
body_maxlen = 32768 |
| 572 |
|
| 573 |
def __init__(self, error=None, **kwargs): |
| 574 |
"""Initialize with the exception preparation should raise.""" |
| 575 |
super().__init__(**kwargs) |
| 576 |
self._error = error or TypeError("bad format resolution") |
| 577 |
|
| 578 |
def resolve_format(self, body_format=None): |
| 579 |
"""Fail the way a buggy plugin would, before anything is sent.""" |
| 580 |
raise self._error |
| 581 |
|
| 582 |
def url(self, *args, **kwargs): |
| 583 |
"""Return the stable URL for this misbehaving test plugin.""" |
| 584 |
return "badformat://localhost" |
| 585 |
|
| 586 |
def send(self, **kwargs): |
| 587 |
"""Never reached; preparation fails before delivery starts.""" |
| 588 |
return True |
| 589 |
|
| 590 |
@staticmethod |
| 591 |
def parse_url(url): |
| 592 |
"""Parse the synthetic URL without requiring a real host.""" |
| 593 |
return NotifyBase.parse_url(url, verify_host=False) |
| 594 |
|
| 595 |
|
| 596 |
class _SlowNotify(NotifyBase): |
| 597 |
"""Plugin whose send() blocks for a configurable delay before |
| 598 |
reporting success -- used to exercise AppriseAsset._service_timeout |
| 599 |
and notify(timeout=...) enforcement with real wall-clock timing.""" |
| 600 |
|
| 601 |
app_id = "SlowApp" |
| 602 |
app_desc = "Test" |
| 603 |
notify_url = "slow://" |
| 604 |
title_maxlen = 250 |
| 605 |
body_maxlen = 32768 |
| 606 |
|
| 607 |
def __init__(self, delay=0.0, **kwargs): |
| 608 |
"""Initialize the test plugin with its artificial delay.""" |
| 609 |
super().__init__(**kwargs) |
| 610 |
self._delay = delay |
| 611 |
self.calls = 0 |
| 612 |
|
| 613 |
def url(self, *args, **kwargs): |
| 614 |
"""Return a stable URL containing the test host.""" |
| 615 |
return "slow://{}".format(self.host) |
| 616 |
|
| 617 |
def send(self, **kwargs): |
| 618 |
"""Simulate blocking delivery before reporting success.""" |
| 619 |
self.calls += 1 |
| 620 |
time.sleep(self._delay) |
| 621 |
return True |
| 622 |
|
| 623 |
async def async_notify(self, **kwargs): |
| 624 |
"""Simulate asynchronous delivery before reporting success.""" |
| 625 |
self.calls += 1 |
| 626 |
await asyncio.sleep(self._delay) |
| 627 |
return True |
| 628 |
|
| 629 |
@staticmethod |
| 630 |
def parse_url(url): |
| 631 |
"""Parse the synthetic URL without requiring a real host.""" |
| 632 |
return NotifyBase.parse_url(url, verify_host=False) |
| 633 |
|
| 634 |
|
| 635 |
class TestAppriseTag: |
| 636 |
"""Full branch coverage for AppriseTag.""" |
| 637 |
|
| 638 |
def test_parse_returns_same_instance(self): |
| 639 |
"""parse() short-circuits when the input is already an AppriseTag.""" |
| 640 |
t = AppriseTag("alerts", priority=2) |
| 641 |
# Must return the exact same object, not a copy |
| 642 |
assert AppriseTag.parse(t) is t |
| 643 |
|
| 644 |
def test_parse_fallback_for_unrecognised_input(self): |
| 645 |
"""parse() falls back to a raw-name tag when the regex has no match.""" |
| 646 |
# Input starting with '@' does not match _RE_TAG; the fallback branch |
| 647 |
# stores the whole input as the name. |
| 648 |
t = AppriseTag.parse("@invalid") |
| 649 |
assert str(t) == "@invalid" |
| 650 |
assert t.priority == 0 |
| 651 |
assert t.retry is None |
| 652 |
|
| 653 |
# --- __repr__ --- |
| 654 |
|
| 655 |
def test_repr_plain(self): |
| 656 |
"""repr() with default priority and no retry is minimal.""" |
| 657 |
assert repr(AppriseTag("simple")) == "AppriseTag('simple')" |
| 658 |
|
| 659 |
def test_repr_with_priority(self): |
| 660 |
"""repr() includes priority= when the priority is non-zero.""" |
| 661 |
r = repr(AppriseTag("test", priority=3)) |
| 662 |
assert "priority=3" in r |
| 663 |
|
| 664 |
def test_repr_with_retry(self): |
| 665 |
"""repr() includes retry= when a retry count is set.""" |
| 666 |
r = repr(AppriseTag("test", retry=5)) |
| 667 |
assert "retry=5" in r |
| 668 |
|
| 669 |
def test_repr_with_priority_and_retry(self): |
| 670 |
"""repr() includes both fields when both are non-default.""" |
| 671 |
r = repr(AppriseTag("test", priority=2, retry=3)) |
| 672 |
assert "priority=2" in r |
| 673 |
assert "retry=3" in r |
| 674 |
|
| 675 |
# --- __eq__ --- |
| 676 |
|
| 677 |
def test_eq_two_apprisetags_same_name(self): |
| 678 |
"""Two AppriseTag objects are equal when their names match, |
| 679 |
regardless of priority or retry.""" |
| 680 |
assert AppriseTag("abc") == AppriseTag("abc", priority=5) |
| 681 |
assert AppriseTag("ABC") == AppriseTag("abc") |
| 682 |
|
| 683 |
def test_eq_with_string(self): |
| 684 |
"""An AppriseTag equals a plain str by name.""" |
| 685 |
assert AppriseTag("hello") == "hello" |
| 686 |
assert AppriseTag("HELLO") == "hello" |
| 687 |
|
| 688 |
def test_eq_not_equal_different_name(self): |
| 689 |
assert AppriseTag("abc") != AppriseTag("xyz") |
| 690 |
assert AppriseTag("abc") != "xyz" |
| 691 |
|
| 692 |
def test_eq_returns_notimplemented_for_other_types(self): |
| 693 |
"""Comparing to a non-str/AppriseTag returns NotImplemented""" |
| 694 |
result = AppriseTag("abc").__eq__(42) |
| 695 |
assert result is NotImplemented |
| 696 |
|
| 697 |
# --- __lt__ --- |
| 698 |
|
| 699 |
def test_lt_two_apprisetags(self): |
| 700 |
"""__lt__ sorts two AppriseTag objects by tag name.""" |
| 701 |
assert AppriseTag("abc") < AppriseTag("def") |
| 702 |
assert not (AppriseTag("def") < AppriseTag("abc")) |
| 703 |
|
| 704 |
def test_lt_with_string(self): |
| 705 |
"""AppriseTag can be ordered against a plain string.""" |
| 706 |
assert AppriseTag("abc") < "def" |
| 707 |
assert not (AppriseTag("zzz") < "aaa") |
| 708 |
|
| 709 |
def test_lt_returns_notimplemented_for_other_types(self): |
| 710 |
"""__lt__ with non-str/AppriseTag returns NotImplemented""" |
| 711 |
result = AppriseTag("abc").__lt__(42) |
| 712 |
assert result is NotImplemented |
| 713 |
|
| 714 |
# --- __bool__ --- |
| 715 |
|
| 716 |
def test_bool_empty_tag_is_false(self): |
| 717 |
"""An AppriseTag with an empty name is falsy""" |
| 718 |
assert not AppriseTag("") |
| 719 |
assert bool(AppriseTag("")) is False |
| 720 |
|
| 721 |
def test_bool_nonempty_tag_is_true(self): |
| 722 |
assert bool(AppriseTag("something")) is True |
| 723 |
|
| 724 |
# --- set / dict integration --- |
| 725 |
|
| 726 |
def test_apprisetag_in_set_with_plain_string(self): |
| 727 |
"""AppriseTag in a set is found by plain string membership test.""" |
| 728 |
s = {AppriseTag("endpoint")} |
| 729 |
assert "endpoint" in s |
| 730 |
|
| 731 |
def test_plain_string_in_set_with_apprisetag(self): |
| 732 |
"""A plain string is found in a set containing AppriseTag.""" |
| 733 |
s = {"endpoint"} |
| 734 |
assert AppriseTag("endpoint") in s |
| 735 |
|
| 736 |
|
| 737 |
class TestStaticHelpers: |
| 738 |
"""Cover priority helpers not reached by integration tests.""" |
| 739 |
|
| 740 |
def test_set_filter_tokens_are_ordered(self): |
| 741 |
"""A set filter yields the same token order every run. |
| 742 |
|
| 743 |
Sorting prevents Python's changing set order from selecting a |
| 744 |
different retry value in another process. |
| 745 |
""" |
| 746 |
tokens = Apprise._parse_filter_tokens({"b:2", "a:1", "c:3"}) |
| 747 |
assert [str(t) for t in tokens] == ["a", "b", "c"] |
| 748 |
|
| 749 |
# The same filter written as a list keeps the caller's own order. |
| 750 |
tokens = Apprise._parse_filter_tokens(["b:2", "a:1", "c:3"]) |
| 751 |
assert [str(t) for t in tokens] == ["b", "a", "c"] |
| 752 |
|
| 753 |
def test_set_filter_chains_are_ordered(self): |
| 754 |
"""A set filter puts a service in the same chain every run. |
| 755 |
|
| 756 |
A service with several matching tags must not move between chains |
| 757 |
when the process restarts. |
| 758 |
""" |
| 759 |
|
| 760 |
class _MultiTagged: |
| 761 |
"""Service carrying both tags the filter names.""" |
| 762 |
|
| 763 |
tags = {"alpha", "beta"} |
| 764 |
|
| 765 |
chains = Apprise._build_tag_chains( |
| 766 |
[(_MultiTagged(), {})], {"beta", "alpha"} |
| 767 |
) |
| 768 |
assert sorted(chains) == ["alpha"] |
| 769 |
|
| 770 |
def test_service_priority_for_tag_name_absent(self): |
| 771 |
"""Returns 0 when no tag in service.tags matches tag_name.""" |
| 772 |
service = mock.Mock() |
| 773 |
service.tags = {AppriseTag("alerts", priority=3, has_priority=True)} |
| 774 |
assert Apprise._service_priority_for_tag_name(service, "backup") == 0 |
| 775 |
|
| 776 |
def test_match_service_retry_plain_string_tag(self): |
| 777 |
"""Plain string in service.tags matched by a priority-prefixed token. |
| 778 |
|
| 779 |
Covers the string fallback when a matching service tag is not an |
| 780 |
AppriseTag instance. |
| 781 |
""" |
| 782 |
service = mock.Mock() |
| 783 |
service.tags = {"alerts"} # plain string, not an AppriseTag |
| 784 |
# "3:alerts:2" carries priority=3 + retry=2; plain "alerts" matches |
| 785 |
retry_tokens = Apprise._parse_retry_filter_tokens("3:alerts:2") |
| 786 |
result = Apprise._match_service_retry(service, retry_tokens) |
| 787 |
assert result == 2 |
| 788 |
|
| 789 |
def test_match_service_retry_plain_string_tag_no_match(self): |
| 790 |
"""Plain string in service.tags that does not match returns None.""" |
| 791 |
service = mock.Mock() |
| 792 |
service.tags = {"other"} # plain string -- does not match "alerts" |
| 793 |
retry_tokens = Apprise._parse_retry_filter_tokens("3:alerts:2") |
| 794 |
result = Apprise._match_service_retry(service, retry_tokens) |
| 795 |
assert result is None |
| 796 |
|
| 797 |
def test_inject_per_service_retries_mixed_matches(self): |
| 798 |
"""Only matching services receive the retry override.""" |
| 799 |
matching = mock.Mock() |
| 800 |
matching.tags = {"alerts"} |
| 801 |
other = mock.Mock() |
| 802 |
other.tags = {"other"} |
| 803 |
|
| 804 |
all_calls = [(matching, {}), (other, {})] |
| 805 |
result = Apprise._inject_per_service_retries(all_calls, "3:alerts:2") |
| 806 |
|
| 807 |
matching_kwargs = next(k for s, k in result if s is matching) |
| 808 |
other_kwargs = next(k for s, k in result if s is other) |
| 809 |
assert matching_kwargs["_retry_override"] == 2 |
| 810 |
assert "_retry_override" not in other_kwargs |
| 811 |
|
| 812 |
def test_inject_per_service_retries_no_retry_tokens(self): |
| 813 |
"""A tag filter with no retry suffix leaves every call unchanged.""" |
| 814 |
service = mock.Mock() |
| 815 |
service.tags = {"alerts"} |
| 816 |
all_calls = [(service, {})] |
| 817 |
|
| 818 |
result = Apprise._inject_per_service_retries(all_calls, "alerts") |
| 819 |
assert result == all_calls |
| 820 |
|
| 821 |
def test_resolve_retry_count_clamps_override(self): |
| 822 |
"""Clamp tag retry overrides to the same limit as plugin URLs.""" |
| 823 |
from apprise.common import APPRISE_MAX_SERVICE_RETRY |
| 824 |
from apprise.dispatch import resolve_retry_count |
| 825 |
|
| 826 |
service = mock.Mock() |
| 827 |
service.retry = 0 |
| 828 |
|
| 829 |
# A huge override is clamped down to the documented ceiling. |
| 830 |
kwargs = {"_retry_override": 1000000000} |
| 831 |
assert ( |
| 832 |
resolve_retry_count(service, kwargs) == APPRISE_MAX_SERVICE_RETRY |
| 833 |
) |
| 834 |
# The override key is always consumed, even when clamped. |
| 835 |
assert "_retry_override" not in kwargs |
| 836 |
|
| 837 |
# A negative override is clamped up to zero, not left negative. |
| 838 |
assert resolve_retry_count(service, {"_retry_override": -5}) == 0 |
| 839 |
|
| 840 |
# A within-range override passes through unchanged. |
| 841 |
assert resolve_retry_count(service, {"_retry_override": 3}) == 3 |
| 842 |
|
| 843 |
# No override at all falls back to the plugin's own (already |
| 844 |
# clamped) retry attribute. |
| 845 |
service.retry = 4 |
| 846 |
assert resolve_retry_count(service, {}) == 4 |
| 847 |
|
| 848 |
# Invalid overrides fall back to the service's retry value. |
| 849 |
service.retry = 2 |
| 850 |
assert resolve_retry_count(service, {"_retry_override": "x"}) == 2 |
| 851 |
|
| 852 |
def test_configured_max_attempts_preserves_override(self): |
| 853 |
"""Read timeout metadata without consuming the worker's override.""" |
| 854 |
from apprise.dispatch import configured_max_attempts |
| 855 |
|
| 856 |
service = mock.Mock() |
| 857 |
service.retry = 1 |
| 858 |
|
| 859 |
# The timeout result and worker must see the same retry limit. |
| 860 |
kwargs = {"_retry_override": 3} |
| 861 |
assert configured_max_attempts(service, kwargs) == 4 |
| 862 |
assert kwargs == {"_retry_override": 3} |
| 863 |
|
| 864 |
def test_configured_max_attempts_handles_bad_metadata(self): |
| 865 |
"""Leave invalid plugin metadata for the worker safety net.""" |
| 866 |
from apprise.dispatch import configured_max_attempts |
| 867 |
|
| 868 |
class BrokenRetry: |
| 869 |
@property |
| 870 |
def retry(self): |
| 871 |
# A plugin property may fail before its worker starts. |
| 872 |
raise RuntimeError("bad retry metadata") |
| 873 |
|
| 874 |
assert configured_max_attempts(BrokenRetry(), {}) == 1 |
| 875 |
|
| 876 |
def test_retry_override_end_to_end_is_bounded(self): |
| 877 |
"""Prevent a huge tag retry suffix from creating an unbounded loop.""" |
| 878 |
from apprise.common import APPRISE_MAX_SERVICE_RETRY |
| 879 |
|
| 880 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 881 |
|
| 882 |
try: |
| 883 |
asset = AppriseAsset(async_mode=False, service_timeout=0) |
| 884 |
# fail_times higher than the clamp so every attempt fails and |
| 885 |
# the loop runs out its full (clamped) retry budget. |
| 886 |
service = _FailThenSucceedNotify( |
| 887 |
host="x", asset=asset, fail_times=10**9 |
| 888 |
) |
| 889 |
service.tags = {"alerts"} |
| 890 |
|
| 891 |
a = Apprise(asset=asset) |
| 892 |
a.add(service) |
| 893 |
|
| 894 |
result = a.notify(body="test", tag="alerts:1000000000") |
| 895 |
|
| 896 |
assert bool(result) is False |
| 897 |
assert service._calls == APPRISE_MAX_SERVICE_RETRY + 1 |
| 898 |
assert ( |
| 899 |
result.results[0].max_attempts == APPRISE_MAX_SERVICE_RETRY + 1 |
| 900 |
) |
| 901 |
finally: |
| 902 |
N_MGR.unload_modules() |
| 903 |
|
| 904 |
def test_apprise_tag_parse_rejects_absurd_digit_runs(self): |
| 905 |
"""Ignore numeric tag fields that exceed Python's conversion limit.""" |
| 906 |
huge_digits = "9" * 5000 |
| 907 |
|
| 908 |
# An absurd retry suffix falls back to retry=None instead of |
| 909 |
# raising ValueError out of parse(). |
| 910 |
parsed = AppriseTag.parse(f"alerts:{huge_digits}") |
| 911 |
assert str(parsed) == "alerts" |
| 912 |
assert parsed.retry is None |
| 913 |
|
| 914 |
# An unusable priority is absent and must not select flat dispatch. |
| 915 |
parsed = AppriseTag.parse(f"{huge_digits}:alerts") |
| 916 |
assert str(parsed) == "alerts" |
| 917 |
assert parsed.priority == 0 |
| 918 |
assert parsed.has_priority is False |
| 919 |
assert ( |
| 920 |
Apprise._filter_has_explicit_priority([f"{huge_digits}:alerts"]) |
| 921 |
is False |
| 922 |
) |
| 923 |
|
| 924 |
# A normal, reasonably-sized value is unaffected by the guard. |
| 925 |
parsed = AppriseTag.parse("3:alerts:5") |
| 926 |
assert parsed.priority == 3 |
| 927 |
assert parsed.retry == 5 |
| 928 |
assert parsed.has_priority is True |
| 929 |
assert Apprise._filter_has_explicit_priority(["3:alerts:5"]) is True |
| 930 |
|
| 931 |
def test_service_metadata_survives_bad_tag_str(self): |
| 932 |
"""Fall back safely when a custom tag cannot convert to text.""" |
| 933 |
from apprise.dispatch import service_metadata |
| 934 |
|
| 935 |
class _BadTag: |
| 936 |
def __str__(self): |
| 937 |
raise RuntimeError("boom") |
| 938 |
|
| 939 |
service = mock.Mock() |
| 940 |
service.service_name = "Test" |
| 941 |
service.url.return_value = "test://" |
| 942 |
service.url_id.return_value = "abc" |
| 943 |
service.__len__ = mock.Mock(return_value=1) |
| 944 |
service.tags = {_BadTag()} |
| 945 |
|
| 946 |
name, url, url_id, tag, weight = service_metadata(service) |
| 947 |
assert name == "Test" |
| 948 |
assert url == "test://" |
| 949 |
assert url_id == "abc" |
| 950 |
assert tag == () |
| 951 |
assert weight == 1 |
| 952 |
|
| 953 |
def test_notify_succeeds_despite_bad_tag_str(self): |
| 954 |
"""Keep a successful result when custom tag conversion fails.""" |
| 955 |
|
| 956 |
class _BadTag: |
| 957 |
def __str__(self): |
| 958 |
raise RuntimeError("boom") |
| 959 |
|
| 960 |
class _AlwaysSucceed(NotifyBase): |
| 961 |
def send(self, body, title="", notify_type=None, **kwargs): |
| 962 |
return True |
| 963 |
|
| 964 |
service = _AlwaysSucceed(host="x", asset=AppriseAsset()) |
| 965 |
service.tags = {_BadTag()} |
| 966 |
|
| 967 |
a = Apprise() |
| 968 |
a.add(service) |
| 969 |
result = a.notify(body="test") |
| 970 |
|
| 971 |
assert bool(result) is True |
| 972 |
assert result.results[0].tag == () |
| 973 |
|
| 974 |
def test_has_priority_nested_list(self): |
| 975 |
"""A priority prefix is found inside a nested list.""" |
| 976 |
assert Apprise._filter_has_explicit_priority([["2:alerts"]]) |
| 977 |
|
| 978 |
def test_has_priority_list_of_strings(self): |
| 979 |
"""A priority prefix is found in a plain-string list.""" |
| 980 |
assert Apprise._filter_has_explicit_priority(["2:alerts"]) |
| 981 |
|
| 982 |
def test_has_priority_false_no_prefix(self): |
| 983 |
"""Filters without a prefix do not carry explicit priority.""" |
| 984 |
assert not Apprise._filter_has_explicit_priority("alerts") |
| 985 |
assert not Apprise._filter_has_explicit_priority(["alerts"]) |
| 986 |
|
| 987 |
def test_has_priority_false_for_match_all(self): |
| 988 |
"""Match-all filters do not carry an explicit priority.""" |
| 989 |
assert not Apprise._filter_has_explicit_priority(MATCH_ALL_TAG) |
| 990 |
assert not Apprise._filter_has_explicit_priority(None) |
| 991 |
|
| 992 |
# _notify_parallel_threadpool / _notify_parallel_asyncio zero-length ----- |
| 993 |
|
| 994 |
def test_threadpool_zero_services_returns_true(self): |
| 995 |
"""Empty service list returns (True, []) immediately.""" |
| 996 |
ok, results = Apprise._notify_parallel_threadpool() |
| 997 |
assert ok is True |
| 998 |
assert results == [] |
| 999 |
|
| 1000 |
def test_asyncio_zero_services_returns_true(self): |
| 1001 |
"""Empty service list returns (True, []) immediately.""" |
| 1002 |
ok, results = asyncio.run(Apprise._notify_parallel_asyncio()) |
| 1003 |
assert ok is True |
| 1004 |
assert results == [] |
| 1005 |
|
| 1006 |
|
| 1007 |
class TestDispatchIntegration: |
| 1008 |
"""End-to-end notify() tests covering the new priority/retry dispatch.""" |
| 1009 |
|
| 1010 |
def _make_service(self, host, priority, asset, fail_times=0): |
| 1011 |
"""Create a _FailThenSucceedNotify with an AppriseTag in its tags.""" |
| 1012 |
s = _FailThenSucceedNotify( |
| 1013 |
host=host, asset=asset, fail_times=fail_times |
| 1014 |
) |
| 1015 |
# Assign a fresh instance-level set rather than mutating the |
| 1016 |
# class-level tags set. URLBase.tags is a class attribute (set()); |
| 1017 |
# .add() would mutate it and share state across all instances. |
| 1018 |
# Assignment shadows the class attribute and gives each service its |
| 1019 |
# own set with the correct priority stored in the AppriseTag object. |
| 1020 |
s.tags = {AppriseTag("alerts", priority=priority, has_priority=True)} |
| 1021 |
return s |
| 1022 |
|
| 1023 |
def test_filter_retry_override_via_tag_suffix(self): |
| 1024 |
"""tag suffix ':N' overrides per-service retry for this call only.""" |
| 1025 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 1026 |
|
| 1027 |
try: |
| 1028 |
asset = AppriseAsset(async_mode=False) |
| 1029 |
# Service's own retry=0; tag suffix of 2 should allow 3 attempts |
| 1030 |
service = _FailThenSucceedNotify( |
| 1031 |
host="localhost", |
| 1032 |
asset=asset, |
| 1033 |
retry=0, |
| 1034 |
wait=0.0, |
| 1035 |
fail_times=2, |
| 1036 |
) |
| 1037 |
# Tag the service so the filter "failpass:2" (tag name "failpass", |
| 1038 |
# retry override 2) can match it via is_exclusive_match. |
| 1039 |
service.tags = {"failpass"} |
| 1040 |
a = Apprise(asset=asset) |
| 1041 |
a.add(service) |
| 1042 |
|
| 1043 |
# "failpass:2" -> retry override of 2 (3 total attempts) |
| 1044 |
result = a.notify(body="test", tag="failpass:2") |
| 1045 |
assert bool(result) is True |
| 1046 |
assert service._calls == 3 |
| 1047 |
finally: |
| 1048 |
N_MGR.unload_modules() |
| 1049 |
|
| 1050 |
def test_exclusive_priority_dispatch_skips_other_priorities(self): |
| 1051 |
"""An explicit priority dispatches only matching-priority services.""" |
| 1052 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 1053 |
|
| 1054 |
try: |
| 1055 |
asset = AppriseAsset(async_mode=False) |
| 1056 |
s1 = self._make_service("host1", priority=1, asset=asset) |
| 1057 |
s2 = self._make_service("host2", priority=2, asset=asset) |
| 1058 |
|
| 1059 |
a = Apprise(asset=asset) |
| 1060 |
a.add(s1) |
| 1061 |
a.add(s2) |
| 1062 |
|
| 1063 |
# "2:alerts" -> only priority-2 service fires |
| 1064 |
result = a.notify(body="test", tag="2:alerts") |
| 1065 |
assert bool(result) is True |
| 1066 |
assert s1._calls == 0 # priority-1, not contacted |
| 1067 |
assert s2._calls == 1 # priority-2, contacted once |
| 1068 |
finally: |
| 1069 |
N_MGR.unload_modules() |
| 1070 |
|
| 1071 |
def test_escalation_stops_after_priority_success(self): |
| 1072 |
"""If priority-1 group all succeed, priority-2 group is not run.""" |
| 1073 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 1074 |
|
| 1075 |
try: |
| 1076 |
asset = AppriseAsset(async_mode=False) |
| 1077 |
s1 = self._make_service("host1", priority=1, asset=asset) |
| 1078 |
s2 = self._make_service("host2", priority=2, asset=asset) |
| 1079 |
|
| 1080 |
a = Apprise(asset=asset) |
| 1081 |
a.add(s1) |
| 1082 |
a.add(s2) |
| 1083 |
|
| 1084 |
result = a.notify(body="test", tag="alerts") |
| 1085 |
assert bool(result) is True |
| 1086 |
assert s1._calls == 1 # priority 1 succeeded |
| 1087 |
assert s2._calls == 0 # never escalated to |
| 1088 |
finally: |
| 1089 |
N_MGR.unload_modules() |
| 1090 |
|
| 1091 |
def test_escalation_triggers_on_priority_group_failure(self): |
| 1092 |
"""Priority-1 group failure escalates to priority-2 group.""" |
| 1093 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 1094 |
|
| 1095 |
try: |
| 1096 |
asset = AppriseAsset(async_mode=False) |
| 1097 |
# priority-1 always fails |
| 1098 |
s1 = self._make_service( |
| 1099 |
"host1", priority=1, asset=asset, fail_times=999 |
| 1100 |
) |
| 1101 |
# priority-2 always succeeds |
| 1102 |
s2 = self._make_service("host2", priority=2, asset=asset) |
| 1103 |
|
| 1104 |
a = Apprise(asset=asset) |
| 1105 |
a.add(s1) |
| 1106 |
a.add(s2) |
| 1107 |
|
| 1108 |
result = a.notify(body="test", tag="alerts") |
| 1109 |
assert bool(result) is True |
| 1110 |
assert s1._calls == 1 |
| 1111 |
assert s2._calls == 1 |
| 1112 |
finally: |
| 1113 |
N_MGR.unload_modules() |
| 1114 |
|
| 1115 |
def test_async_notify_filter_retry_and_explicit_priority(self): |
| 1116 |
"""async_notify() supports escalation and exclusive priority paths.""" |
| 1117 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 1118 |
|
| 1119 |
try: |
| 1120 |
asset = AppriseAsset() |
| 1121 |
s1 = self._make_service("host1", priority=1, asset=asset) |
| 1122 |
s2 = self._make_service("host2", priority=2, asset=asset) |
| 1123 |
|
| 1124 |
a = Apprise(asset=asset) |
| 1125 |
a.add(s1) |
| 1126 |
a.add(s2) |
| 1127 |
|
| 1128 |
async def run_exclusive(): |
| 1129 |
"""Dispatch only the explicitly selected priority.""" |
| 1130 |
return await a.async_notify(body="test", tag="2:alerts") |
| 1131 |
|
| 1132 |
async def run_escalation(): |
| 1133 |
"""Dispatch the first successful escalation group.""" |
| 1134 |
return await a.async_notify(body="test", tag="alerts") |
| 1135 |
|
| 1136 |
# exclusive: only priority-2 fires |
| 1137 |
r = asyncio.run(run_exclusive()) |
| 1138 |
assert bool(r) is True |
| 1139 |
assert s1._calls == 0 |
| 1140 |
assert s2._calls == 1 |
| 1141 |
|
| 1142 |
# escalation: priority-1 succeeds, priority-2 skipped |
| 1143 |
s1._calls = 0 |
| 1144 |
s2._calls = 0 |
| 1145 |
r = asyncio.run(run_escalation()) |
| 1146 |
assert bool(r) is True |
| 1147 |
assert s1._calls == 1 |
| 1148 |
assert s2._calls == 0 |
| 1149 |
finally: |
| 1150 |
N_MGR.unload_modules() |
| 1151 |
|
| 1152 |
def test_plain_and_zero_prefix_are_equivalent(self): |
| 1153 |
"""'family' and '0:family' are identical at priority 0. |
| 1154 |
A filter of '0:family' must match services tagged with plain |
| 1155 |
'family', and both forms must land in the same escalation group.""" |
| 1156 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 1157 |
|
| 1158 |
try: |
| 1159 |
asset = AppriseAsset(async_mode=False) |
| 1160 |
|
| 1161 |
# s1: tagged with plain "family" (priority=0, has_priority=False) |
| 1162 |
s1 = _FailThenSucceedNotify( |
| 1163 |
host="host1", asset=asset, fail_times=0 |
| 1164 |
) |
| 1165 |
s1.tags = {AppriseTag.parse("family")} |
| 1166 |
|
| 1167 |
# s2: tagged with explicit "0:family" (priority=0, |
| 1168 |
# has_priority=True) |
| 1169 |
s2 = _FailThenSucceedNotify( |
| 1170 |
host="host2", asset=asset, fail_times=0 |
| 1171 |
) |
| 1172 |
s2.tags = {AppriseTag.parse("0:family")} |
| 1173 |
|
| 1174 |
# s3: lower-urgency fallback -- should never fire when p-0 succeeds |
| 1175 |
s3 = _FailThenSucceedNotify( |
| 1176 |
host="host3", asset=asset, fail_times=0 |
| 1177 |
) |
| 1178 |
s3.tags = {AppriseTag.parse("1:family")} |
| 1179 |
|
| 1180 |
a = Apprise(asset=asset) |
| 1181 |
a.add(s1) |
| 1182 |
a.add(s2) |
| 1183 |
a.add(s3) |
| 1184 |
|
| 1185 |
# Exclusive "0:family": plain "family" and "0:family" services |
| 1186 |
# are both priority 0 and must both fire; priority-1 service is |
| 1187 |
# skipped. |
| 1188 |
result = a.notify(body="test", tag="0:family") |
| 1189 |
assert bool(result) is True |
| 1190 |
assert s1._calls == 1 # plain "family" matched by "0:family" |
| 1191 |
assert s2._calls == 1 # explicit "0:family" matched |
| 1192 |
assert s3._calls == 0 # priority 1, not priority 0 -- skipped |
| 1193 |
|
| 1194 |
# Escalation "family": s1 and s2 are both in the priority-0 |
| 1195 |
# group. Both succeed, so s3 (priority 1) is never escalated to. |
| 1196 |
s1._calls = s2._calls = s3._calls = 0 |
| 1197 |
result = a.notify(body="test", tag="family") |
| 1198 |
assert bool(result) is True |
| 1199 |
assert s1._calls == 1 # priority-0 group |
| 1200 |
assert s2._calls == 1 # same priority-0 group |
| 1201 |
assert s3._calls == 0 # not escalated to |
| 1202 |
finally: |
| 1203 |
N_MGR.unload_modules() |
| 1204 |
|
| 1205 |
|
| 1206 |
class TestRetryWarningMessage: |
| 1207 |
"""Retry warnings show total attempts in sync and async dispatch.""" |
| 1208 |
|
| 1209 |
def test_sync_attempt_denominator_counts_total_attempts(self, caplog): |
| 1210 |
"""Sequential dispatch: one retry means two total attempts.""" |
| 1211 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 1212 |
|
| 1213 |
try: |
| 1214 |
# Older pytest releases (e.g. the one shipped with EL9) do |
| 1215 |
# not un-disable logging on our behalf when |
| 1216 |
# caplog.set_level() is called, so a prior module-level |
| 1217 |
# logging.disable(logging.CRITICAL) call would otherwise |
| 1218 |
# silently swallow this warning. Clear it explicitly. |
| 1219 |
logging.disable(logging.NOTSET) |
| 1220 |
caplog.set_level(logging.WARNING, logger=LOGGER_NAME) |
| 1221 |
|
| 1222 |
asset = AppriseAsset(async_mode=False) |
| 1223 |
# Fail once, then succeed on the only retry. |
| 1224 |
service = _FailThenSucceedNotify( |
| 1225 |
host="localhost", |
| 1226 |
asset=asset, |
| 1227 |
retry=1, |
| 1228 |
wait=0.0, |
| 1229 |
fail_times=1, |
| 1230 |
) |
| 1231 |
a = Apprise(asset=asset) |
| 1232 |
a.add(service) |
| 1233 |
|
| 1234 |
result = a.notify(body="test") |
| 1235 |
assert bool(result) is True |
| 1236 |
assert service._calls == 2 |
| 1237 |
|
| 1238 |
# The denominator must be retry + 1 (2), not retry (1). |
| 1239 |
assert "Attempt 1/2" in caplog.text |
| 1240 |
assert "Attempt 1/1" not in caplog.text |
| 1241 |
finally: |
| 1242 |
logging.disable(logging.CRITICAL) |
| 1243 |
N_MGR.unload_modules() |
| 1244 |
|
| 1245 |
def test_async_attempt_denominator_counts_total_attempts(self, caplog): |
| 1246 |
"""Asyncio dispatch: one retry means two total attempts.""" |
| 1247 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 1248 |
|
| 1249 |
try: |
| 1250 |
# See the sync test above for why this reset is needed. |
| 1251 |
logging.disable(logging.NOTSET) |
| 1252 |
caplog.set_level(logging.WARNING, logger=LOGGER_NAME) |
| 1253 |
|
| 1254 |
asset = AppriseAsset(async_mode=True) |
| 1255 |
service = _FailThenSucceedNotify( |
| 1256 |
host="localhost", |
| 1257 |
asset=asset, |
| 1258 |
retry=1, |
| 1259 |
wait=0.0, |
| 1260 |
fail_times=1, |
| 1261 |
) |
| 1262 |
a = Apprise(asset=asset) |
| 1263 |
a.add(service) |
| 1264 |
|
| 1265 |
result = asyncio.run(a.async_notify(body="test")) |
| 1266 |
assert bool(result) is True |
| 1267 |
assert service._calls == 2 |
| 1268 |
|
| 1269 |
# The denominator must be retry + 1 (2), not retry (1). |
| 1270 |
assert "Attempt 1/2" in caplog.text |
| 1271 |
assert "Attempt 1/1" not in caplog.text |
| 1272 |
finally: |
| 1273 |
logging.disable(logging.CRITICAL) |
| 1274 |
N_MGR.unload_modules() |
| 1275 |
|
| 1276 |
|
| 1277 |
class TestDispatchSafetyNets: |
| 1278 |
"""Dispatch crashes are reported as failures, never raised at callers.""" |
| 1279 |
|
| 1280 |
class _ExplodingAsset(AppriseAsset): |
| 1281 |
"""Asset whose mode lookup fails inside batch dispatch.""" |
| 1282 |
|
| 1283 |
@property |
| 1284 |
def async_mode(self): |
| 1285 |
"""Raise the injected failure when dispatch reads mode.""" |
| 1286 |
raise RuntimeError("injected async_mode access") |
| 1287 |
|
| 1288 |
def _tagged_service(self): |
| 1289 |
"""Build one tagged service whose dispatch will raise.""" |
| 1290 |
# Reading async_mode later will trigger the test failure. |
| 1291 |
service = _FailThenSucceedNotify( |
| 1292 |
host="solo", asset=self._ExplodingAsset(), fail_times=0 |
| 1293 |
) |
| 1294 |
service.tags = {"alerts"} |
| 1295 |
|
| 1296 |
# Return the public object used by both sync and async tests. |
| 1297 |
a = Apprise() |
| 1298 |
a.add(service) |
| 1299 |
return a |
| 1300 |
|
| 1301 |
def test_flat_dispatch_exception(self): |
| 1302 |
"""A crash during flat dispatch becomes a failed result. |
| 1303 |
|
| 1304 |
An explicit priority skips the escalation chain, so this batch has |
| 1305 |
no later group to fall back on. |
| 1306 |
""" |
| 1307 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 1308 |
|
| 1309 |
try: |
| 1310 |
# An exact priority uses flat dispatch instead of escalation. |
| 1311 |
result = self._tagged_service().notify(body="test", tag="0:alerts") |
| 1312 |
# The caller receives a normal failed result, not an exception. |
| 1313 |
assert bool(result) is False |
| 1314 |
finally: |
| 1315 |
N_MGR.unload_modules() |
| 1316 |
|
| 1317 |
def test_async_flat_dispatch_exception(self): |
| 1318 |
"""The asynchronous flat dispatch contains a crash the same way.""" |
| 1319 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 1320 |
|
| 1321 |
try: |
| 1322 |
# The asynchronous public API must provide the same safe result. |
| 1323 |
result = asyncio.run( |
| 1324 |
self._tagged_service().async_notify( |
| 1325 |
body="test", tag="0:alerts" |
| 1326 |
) |
| 1327 |
) |
| 1328 |
# The caller receives a normal failed result, not an exception. |
| 1329 |
assert bool(result) is False |
| 1330 |
finally: |
| 1331 |
N_MGR.unload_modules() |
| 1332 |
|
| 1333 |
def test_async_base_exception_result(self): |
| 1334 |
"""A BaseException from one service still produces its result. |
| 1335 |
|
| 1336 |
asyncio.gather() hands back BaseException subclasses, and |
| 1337 |
CancelledError is the one seen in practice. These are not Exception |
| 1338 |
subclasses, so they must not reach tuple unpacking. |
| 1339 |
""" |
| 1340 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 1341 |
|
| 1342 |
try: |
| 1343 |
|
| 1344 |
class _Fatal(BaseException): |
| 1345 |
"""Stands in for CancelledError, which is not Exception.""" |
| 1346 |
|
| 1347 |
class _FatalNotify(_FailThenSucceedNotify): |
| 1348 |
"""Plugin whose asynchronous send raises a BaseException.""" |
| 1349 |
|
| 1350 |
async def async_notify(self, **kwargs): |
| 1351 |
"""Fail in a way ordinary handlers do not catch.""" |
| 1352 |
raise _Fatal("plugin cancelled") |
| 1353 |
|
| 1354 |
# Use asynchronous mode so gather() receives the raised object. |
| 1355 |
service = _FatalNotify( |
| 1356 |
host="solo", |
| 1357 |
asset=AppriseAsset(async_mode=True), |
| 1358 |
fail_times=0, |
| 1359 |
) |
| 1360 |
|
| 1361 |
# Exercise the batch helper directly to inspect its result list. |
| 1362 |
ok, results = asyncio.run( |
| 1363 |
Apprise._notify_parallel_asyncio((service, {"body": "test"})) |
| 1364 |
) |
| 1365 |
|
| 1366 |
# The crash is recorded rather than losing the service entirely. |
| 1367 |
assert ok is False |
| 1368 |
assert len(results) == 1 |
| 1369 |
finally: |
| 1370 |
N_MGR.unload_modules() |
| 1371 |
|
| 1372 |
def test_bad_metadata_fallbacks(self): |
| 1373 |
"""Result building tolerates a plugin whose metadata raises. |
| 1374 |
|
| 1375 |
These helpers exist to describe an already-misbehaving plugin, so |
| 1376 |
they must not raise a second time while doing it. |
| 1377 |
""" |
| 1378 |
from apprise.dispatch import ( |
| 1379 |
RetryRunner, |
| 1380 |
finalize_service_result, |
| 1381 |
resolve_retry_count, |
| 1382 |
service_crashed, |
| 1383 |
service_metadata, |
| 1384 |
timeout_result, |
| 1385 |
) |
| 1386 |
from apprise.result import NotifyAttempt |
| 1387 |
|
| 1388 |
class _Hostile: |
| 1389 |
"""Stand-in whose every plugin-supplied detail raises.""" |
| 1390 |
|
| 1391 |
@property |
| 1392 |
def service_name(self): |
| 1393 |
"""Raise instead of naming the service.""" |
| 1394 |
raise RuntimeError("no name") |
| 1395 |
|
| 1396 |
@property |
| 1397 |
def optional(self): |
| 1398 |
"""Raise instead of reporting optional status.""" |
| 1399 |
raise RuntimeError("no optional") |
| 1400 |
|
| 1401 |
@property |
| 1402 |
def retry(self): |
| 1403 |
"""Raise instead of reporting a retry count.""" |
| 1404 |
raise RuntimeError("no retry") |
| 1405 |
|
| 1406 |
@property |
| 1407 |
def wait(self): |
| 1408 |
"""Raise instead of reporting a retry wait.""" |
| 1409 |
raise RuntimeError("no wait") |
| 1410 |
|
| 1411 |
@property |
| 1412 |
def tags(self): |
| 1413 |
"""Raise instead of listing tags.""" |
| 1414 |
raise RuntimeError("no tags") |
| 1415 |
|
| 1416 |
def url(self, **kwargs): |
| 1417 |
"""Raise instead of returning a URL.""" |
| 1418 |
raise RuntimeError("no url") |
| 1419 |
|
| 1420 |
def url_id(self): |
| 1421 |
"""Raise instead of returning a URL identifier.""" |
| 1422 |
raise RuntimeError("no url_id") |
| 1423 |
|
| 1424 |
def __len__(self): |
| 1425 |
"""Raise instead of reporting a target count.""" |
| 1426 |
raise RuntimeError("no length") |
| 1427 |
|
| 1428 |
# Every result helper below receives the same broken plugin. |
| 1429 |
service = _Hostile() |
| 1430 |
failed = [NotifyAttempt(status=AppriseResultStatus.FAILURE)] |
| 1431 |
|
| 1432 |
# The metadata helper supplies its documented safe values. |
| 1433 |
assert service_metadata(service) == ( |
| 1434 |
"Unknown", |
| 1435 |
"unknown://", |
| 1436 |
None, |
| 1437 |
(), |
| 1438 |
1, |
| 1439 |
) |
| 1440 |
|
| 1441 |
# Error results remain required failures when optional cannot be read. |
| 1442 |
assert bool(service_crashed(service, ValueError("boom"))) is False |
| 1443 |
|
| 1444 |
# The timeout and completed-attempt paths fall back the same way. |
| 1445 |
assert timeout_result(service, 1.0, 1).optional is False |
| 1446 |
|
| 1447 |
ok, result = finalize_service_result(service, 0, failed) |
| 1448 |
assert ok is False |
| 1449 |
assert result.optional is False |
| 1450 |
|
| 1451 |
# A broken retry property must not throw away a valid override. |
| 1452 |
assert resolve_retry_count(service, {"_retry_override": 3}) == 3 |
| 1453 |
assert resolve_retry_count(service, {}) == 0 |
| 1454 |
assert resolve_retry_count(service, {"_retry_override": "x"}) == 0 |
| 1455 |
|
| 1456 |
class _BadRetryValue: |
| 1457 |
"""Plugin whose retry is readable but not a usable number.""" |
| 1458 |
|
| 1459 |
retry = "bad" |
| 1460 |
|
| 1461 |
# A non-numeric retry is treated as none rather than reaching the |
| 1462 |
# comparison that clamps it. |
| 1463 |
bad = _BadRetryValue() |
| 1464 |
assert resolve_retry_count(bad, {}) == 0 |
| 1465 |
assert resolve_retry_count(bad, {"_retry_override": "x"}) == 0 |
| 1466 |
assert resolve_retry_count(bad, {"_retry_override": 2}) == 2 |
| 1467 |
|
| 1468 |
class _InfiniteRetry: |
| 1469 |
"""Plugin whose retry has no whole-number form.""" |
| 1470 |
|
| 1471 |
retry = float("inf") |
| 1472 |
|
| 1473 |
# Infinity and NaN have no integer form, so they clamp to none too. |
| 1474 |
infinite = _InfiniteRetry() |
| 1475 |
assert resolve_retry_count(infinite, {}) == 0 |
| 1476 |
assert ( |
| 1477 |
resolve_retry_count(infinite, {"_retry_override": float("inf")}) |
| 1478 |
== 0 |
| 1479 |
) |
| 1480 |
assert ( |
| 1481 |
resolve_retry_count(infinite, {"_retry_override": float("nan")}) |
| 1482 |
== 0 |
| 1483 |
) |
| 1484 |
|
| 1485 |
# The runner reads the name once, so its log lines stay usable. |
| 1486 |
assert RetryRunner(service, {}, None).name == "Unknown" |
| 1487 |
|
| 1488 |
|
| 1489 |
class TestExceptionHandling: |
| 1490 |
"""Verify that plugin exceptions are caught and retried, not propagated.""" |
| 1491 |
|
| 1492 |
def test_sequential_exception_treated_as_failure(self): |
| 1493 |
"""A plugin raising Exception is caught; delivery is marked failed.""" |
| 1494 |
N_MGR["raise"] = _RaisingNotify |
| 1495 |
|
| 1496 |
try: |
| 1497 |
asset = AppriseAsset(async_mode=False) |
| 1498 |
service = _RaisingNotify(host="localhost", asset=asset, retry=0) |
| 1499 |
a = Apprise(asset=asset) |
| 1500 |
a.add(service) |
| 1501 |
|
| 1502 |
result = a.notify(body="test") |
| 1503 |
assert bool(result) is False |
| 1504 |
finally: |
| 1505 |
N_MGR.unload_modules() |
| 1506 |
|
| 1507 |
def test_sequential_exception_retried(self): |
| 1508 |
"""Exception on first attempt is retried; later success counts.""" |
| 1509 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 1510 |
N_MGR["raise"] = _RaisingNotify |
| 1511 |
|
| 1512 |
try: |
| 1513 |
asset = AppriseAsset(async_mode=False) |
| 1514 |
# Use a plugin that raises on the first attempt then succeeds |
| 1515 |
service = _FailThenSucceedNotify( |
| 1516 |
host="localhost", asset=asset, retry=1, wait=0.0, fail_times=1 |
| 1517 |
) |
| 1518 |
# Patch notify to raise on the first call then succeed |
| 1519 |
call_count = [0] |
| 1520 |
|
| 1521 |
def raising_then_ok(**kwargs): |
| 1522 |
call_count[0] += 1 |
| 1523 |
if call_count[0] == 1: |
| 1524 |
raise RuntimeError("transient error") |
| 1525 |
return True |
| 1526 |
|
| 1527 |
service.send = raising_then_ok |
| 1528 |
a = Apprise(asset=asset) |
| 1529 |
a.add(service) |
| 1530 |
|
| 1531 |
result = a.notify(body="test") |
| 1532 |
assert bool(result) is True |
| 1533 |
assert call_count[0] == 2 |
| 1534 |
finally: |
| 1535 |
N_MGR.unload_modules() |
| 1536 |
|
| 1537 |
def test_threadpool_future_exception_caught(self): |
| 1538 |
"""An exception escaping a thread future is caught gracefully.""" |
| 1539 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 1540 |
|
| 1541 |
try: |
| 1542 |
asset = AppriseAsset(async_mode=True) |
| 1543 |
# Need 2 services to trigger the thread pool path |
| 1544 |
s1 = _FailThenSucceedNotify( |
| 1545 |
host="host1", asset=asset, fail_times=0 |
| 1546 |
) |
| 1547 |
s2 = _FailThenSucceedNotify( |
| 1548 |
host="host2", asset=asset, fail_times=0 |
| 1549 |
) |
| 1550 |
a = Apprise(asset=asset) |
| 1551 |
a.add(s1) |
| 1552 |
a.add(s2) |
| 1553 |
|
| 1554 |
# Inject one failed future so the outer safety net is exercised. |
| 1555 |
import concurrent.futures as cf |
| 1556 |
|
| 1557 |
real_executor_cls = cf.ThreadPoolExecutor |
| 1558 |
|
| 1559 |
class _PatchedExecutor: |
| 1560 |
"""Delegate to a real executor while injecting one failure.""" |
| 1561 |
|
| 1562 |
def __init__(self, *args, **kwargs): |
| 1563 |
"""Create the wrapped executor with the same arguments.""" |
| 1564 |
self._real = real_executor_cls(*args, **kwargs) |
| 1565 |
|
| 1566 |
def __enter__(self): |
| 1567 |
"""Return this wrapper when entering the context.""" |
| 1568 |
return self |
| 1569 |
|
| 1570 |
def __exit__(self, *exc): |
| 1571 |
"""Forward context cleanup to the wrapped executor.""" |
| 1572 |
return self._real.__exit__(*exc) |
| 1573 |
|
| 1574 |
def submit( |
| 1575 |
self, context_run, fn, service, kwargs, call_deadline |
| 1576 |
): |
| 1577 |
"""Return a failed future for ``s1`` and submit others.""" |
| 1578 |
if service is s1: |
| 1579 |
fut = cf.Future() |
| 1580 |
fut.set_exception(RuntimeError("future boom")) |
| 1581 |
return fut |
| 1582 |
return self._real.submit( |
| 1583 |
context_run, fn, service, kwargs, call_deadline |
| 1584 |
) |
| 1585 |
|
| 1586 |
def shutdown(self, *args, **kwargs): |
| 1587 |
"""Forward shutdown behavior to the wrapped executor.""" |
| 1588 |
return self._real.shutdown(*args, **kwargs) |
| 1589 |
|
| 1590 |
# Reset the shared executor so the patched class is used here. |
| 1591 |
import apprise.apprise as apprise_module |
| 1592 |
|
| 1593 |
with ( |
| 1594 |
mock.patch("apprise.apprise._shared_executor", None), |
| 1595 |
mock.patch( |
| 1596 |
"apprise.apprise.cf.ThreadPoolExecutor", _PatchedExecutor |
| 1597 |
), |
| 1598 |
): |
| 1599 |
result = a.notify(body="test") |
| 1600 |
|
| 1601 |
# Clean up the real executor wrapped by _PatchedExecutor. |
| 1602 |
apprise_module._shared_executor._real.shutdown(wait=True) |
| 1603 |
|
| 1604 |
# One future raised -> overall result is False |
| 1605 |
assert bool(result) is False |
| 1606 |
finally: |
| 1607 |
N_MGR.unload_modules() |
| 1608 |
|
| 1609 |
def test_sequential_future_exception_caught(self): |
| 1610 |
"""An exception escaping a sequential dispatch's thread future is |
| 1611 |
caught by the outer safety net, same as the thread-pool path.""" |
| 1612 |
N_MGR["slow"] = _SlowNotify |
| 1613 |
|
| 1614 |
try: |
| 1615 |
asset = AppriseAsset(async_mode=False, service_timeout=0.05) |
| 1616 |
service = _SlowNotify(host="x", asset=asset, delay=0.0) |
| 1617 |
a = Apprise(asset=asset) |
| 1618 |
a.add(service) |
| 1619 |
|
| 1620 |
import concurrent.futures as cf |
| 1621 |
|
| 1622 |
real_executor_cls = cf.ThreadPoolExecutor |
| 1623 |
|
| 1624 |
class _PatchedExecutor: |
| 1625 |
"""Delegate to a real executor while always failing.""" |
| 1626 |
|
| 1627 |
def __init__(self, *args, **kwargs): |
| 1628 |
"""Create the wrapped executor with the same args.""" |
| 1629 |
self._real = real_executor_cls(*args, **kwargs) |
| 1630 |
|
| 1631 |
def __enter__(self): |
| 1632 |
"""Return this wrapper when entering the context.""" |
| 1633 |
return self |
| 1634 |
|
| 1635 |
def __exit__(self, *exc): |
| 1636 |
"""Forward context cleanup to the wrapped executor.""" |
| 1637 |
return self._real.__exit__(*exc) |
| 1638 |
|
| 1639 |
def submit( |
| 1640 |
self, context_run, fn, service, kwargs, call_deadline |
| 1641 |
): |
| 1642 |
"""Return a future that raises instead of running.""" |
| 1643 |
fut = cf.Future() |
| 1644 |
fut.set_exception(RuntimeError("future boom")) |
| 1645 |
return fut |
| 1646 |
|
| 1647 |
def shutdown(self, *args, **kwargs): |
| 1648 |
"""Forward shutdown behavior to the wrapped executor.""" |
| 1649 |
return self._real.shutdown(*args, **kwargs) |
| 1650 |
|
| 1651 |
# Reset the shared executor so the patched class is used here. |
| 1652 |
import apprise.apprise as apprise_module |
| 1653 |
|
| 1654 |
with ( |
| 1655 |
mock.patch("apprise.apprise._shared_executor", None), |
| 1656 |
mock.patch( |
| 1657 |
"apprise.apprise.cf.ThreadPoolExecutor", _PatchedExecutor |
| 1658 |
), |
| 1659 |
): |
| 1660 |
result = a.notify(body="test") |
| 1661 |
|
| 1662 |
# Clean up the real executor wrapped by _PatchedExecutor. |
| 1663 |
apprise_module._shared_executor._real.shutdown(wait=True) |
| 1664 |
|
| 1665 |
assert bool(result) is False |
| 1666 |
finally: |
| 1667 |
N_MGR.unload_modules() |
| 1668 |
|
| 1669 |
def test_asyncio_exception_in_do_call_treated_as_failure(self): |
| 1670 |
"""An exception inside do_call marks the service as failed.""" |
| 1671 |
N_MGR["raise"] = _RaisingNotify |
| 1672 |
|
| 1673 |
try: |
| 1674 |
asset = AppriseAsset() |
| 1675 |
service = _RaisingNotify(host="localhost", asset=asset, retry=0) |
| 1676 |
a = Apprise(asset=asset) |
| 1677 |
a.add(service) |
| 1678 |
|
| 1679 |
async def run(): |
| 1680 |
"""Execute async notification with the patched gather.""" |
| 1681 |
return await a.async_notify(body="test") |
| 1682 |
|
| 1683 |
result = asyncio.run(run()) |
| 1684 |
assert bool(result) is False |
| 1685 |
finally: |
| 1686 |
N_MGR.unload_modules() |
| 1687 |
|
| 1688 |
def test_asyncio_gather_unhandled_exception(self): |
| 1689 |
"""An Exception escaping the outer gather() round is caught as a |
| 1690 |
safety net and treated as a batch failure.""" |
| 1691 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 1692 |
|
| 1693 |
try: |
| 1694 |
asset = AppriseAsset() |
| 1695 |
service = _FailThenSucceedNotify( |
| 1696 |
host="localhost", asset=asset, fail_times=0 |
| 1697 |
) |
| 1698 |
a = Apprise(asset=asset) |
| 1699 |
a.add(service) |
| 1700 |
|
| 1701 |
# Mock asyncio.gather to return an escaped exception object. |
| 1702 |
# Close any unawaited coroutines passed to the mock to avoid |
| 1703 |
# "coroutine was never awaited" RuntimeWarnings. |
| 1704 |
async def fake_gather(*args, **kw): |
| 1705 |
"""Return an escaped error while closing input coroutines.""" |
| 1706 |
for arg in args: |
| 1707 |
if asyncio.iscoroutine(arg): |
| 1708 |
arg.close() |
| 1709 |
return [RuntimeError("escaped")] |
| 1710 |
|
| 1711 |
async def run(): |
| 1712 |
"""Dispatch while gather returns an escaped exception.""" |
| 1713 |
with mock.patch("apprise.apprise.asyncio.gather", fake_gather): |
| 1714 |
return await a.async_notify(body="test") |
| 1715 |
|
| 1716 |
result = asyncio.run(run()) |
| 1717 |
assert bool(result) is False |
| 1718 |
finally: |
| 1719 |
N_MGR.unload_modules() |
| 1720 |
|
| 1721 |
def test_asyncio_gather_type_error(self): |
| 1722 |
"""A TypeError in gather results is caught and returns False.""" |
| 1723 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 1724 |
|
| 1725 |
try: |
| 1726 |
asset = AppriseAsset() |
| 1727 |
service = _FailThenSucceedNotify( |
| 1728 |
host="localhost", asset=asset, fail_times=0 |
| 1729 |
) |
| 1730 |
a = Apprise(asset=asset) |
| 1731 |
a.add(service) |
| 1732 |
|
| 1733 |
async def fake_gather(*args, **kw): |
| 1734 |
"""Return a validation error as a gathered result.""" |
| 1735 |
for arg in args: |
| 1736 |
if asyncio.iscoroutine(arg): |
| 1737 |
arg.close() |
| 1738 |
return [TypeError("validation")] |
| 1739 |
|
| 1740 |
async def run(): |
| 1741 |
"""Dispatch while gather returns a validation error.""" |
| 1742 |
with mock.patch("apprise.apprise.asyncio.gather", fake_gather): |
| 1743 |
return await a.async_notify(body="test") |
| 1744 |
|
| 1745 |
result = asyncio.run(run()) |
| 1746 |
assert bool(result) is False |
| 1747 |
finally: |
| 1748 |
N_MGR.unload_modules() |
| 1749 |
|
| 1750 |
def test_sequential_raise_does_not_block_other_services(self): |
| 1751 |
"""A raising service is marked failed but every other service in |
| 1752 |
the same sequential batch is still attempted and reported.""" |
| 1753 |
N_MGR["raise"] = _RaisingNotify |
| 1754 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 1755 |
|
| 1756 |
try: |
| 1757 |
asset = AppriseAsset(async_mode=False) |
| 1758 |
bad = _RaisingNotify(host="bad", asset=asset) |
| 1759 |
good1 = _FailThenSucceedNotify( |
| 1760 |
host="good1", asset=asset, fail_times=0 |
| 1761 |
) |
| 1762 |
good2 = _FailThenSucceedNotify( |
| 1763 |
host="good2", asset=asset, fail_times=0 |
| 1764 |
) |
| 1765 |
|
| 1766 |
a = Apprise(asset=asset) |
| 1767 |
a.add(good1) |
| 1768 |
a.add(bad) |
| 1769 |
a.add(good2) |
| 1770 |
|
| 1771 |
result = a.notify(body="test") |
| 1772 |
assert bool(result) is False |
| 1773 |
assert len(result) == 3 |
| 1774 |
|
| 1775 |
# Order matches add() order: good1, bad, good2. |
| 1776 |
results = list(result) |
| 1777 |
assert bool(results[0]) is True |
| 1778 |
assert bool(results[1]) is False |
| 1779 |
assert bool(results[2]) is True |
| 1780 |
# good2 was still attempted despite bad raising before it |
| 1781 |
assert good2._calls == 1 |
| 1782 |
finally: |
| 1783 |
N_MGR.unload_modules() |
| 1784 |
|
| 1785 |
def test_threadpool_raise_does_not_block_other_services(self): |
| 1786 |
"""Same guarantee as above, but across the thread-pool dispatch |
| 1787 |
path (async_mode=True, >1 service).""" |
| 1788 |
N_MGR["raise"] = _RaisingNotify |
| 1789 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 1790 |
|
| 1791 |
try: |
| 1792 |
asset = AppriseAsset(async_mode=True) |
| 1793 |
bad = _RaisingNotify(host="bad", asset=asset) |
| 1794 |
good1 = _FailThenSucceedNotify( |
| 1795 |
host="good1", asset=asset, fail_times=0 |
| 1796 |
) |
| 1797 |
good2 = _FailThenSucceedNotify( |
| 1798 |
host="good2", asset=asset, fail_times=0 |
| 1799 |
) |
| 1800 |
|
| 1801 |
a = Apprise(asset=asset) |
| 1802 |
a.add(good1) |
| 1803 |
a.add(bad) |
| 1804 |
a.add(good2) |
| 1805 |
|
| 1806 |
result = a.notify(body="test") |
| 1807 |
assert bool(result) is False |
| 1808 |
assert len(result) == 3 |
| 1809 |
|
| 1810 |
# Threadpool dispatch preserves original submission order. |
| 1811 |
results = list(result) |
| 1812 |
assert bool(results[0]) is True |
| 1813 |
assert bool(results[1]) is False |
| 1814 |
assert bool(results[2]) is True |
| 1815 |
assert good2._calls == 1 |
| 1816 |
finally: |
| 1817 |
N_MGR.unload_modules() |
| 1818 |
|
| 1819 |
def test_asyncio_raise_does_not_block_other_services(self): |
| 1820 |
"""Same guarantee as above, but across the asyncio dispatch path.""" |
| 1821 |
N_MGR["raise"] = _RaisingNotify |
| 1822 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 1823 |
|
| 1824 |
try: |
| 1825 |
asset = AppriseAsset(async_mode=True) |
| 1826 |
bad = _RaisingNotify(host="bad", asset=asset) |
| 1827 |
good1 = _FailThenSucceedNotify( |
| 1828 |
host="good1", asset=asset, fail_times=0 |
| 1829 |
) |
| 1830 |
good2 = _FailThenSucceedNotify( |
| 1831 |
host="good2", asset=asset, fail_times=0 |
| 1832 |
) |
| 1833 |
|
| 1834 |
a = Apprise(asset=asset) |
| 1835 |
a.add(good1) |
| 1836 |
a.add(bad) |
| 1837 |
a.add(good2) |
| 1838 |
|
| 1839 |
result = asyncio.run(a.async_notify(body="test")) |
| 1840 |
assert bool(result) is False |
| 1841 |
assert len(result) == 3 |
| 1842 |
|
| 1843 |
# asyncio dispatch preserves original submission order too. |
| 1844 |
results = list(result) |
| 1845 |
assert bool(results[0]) is True |
| 1846 |
assert bool(results[1]) is False |
| 1847 |
assert bool(results[2]) is True |
| 1848 |
assert good2._calls == 1 |
| 1849 |
finally: |
| 1850 |
N_MGR.unload_modules() |
| 1851 |
|
| 1852 |
def test_notify_preparation_typeerror(self): |
| 1853 |
"""A TypeError raised while preparing content explains itself.""" |
| 1854 |
N_MGR["badformat"] = _BadFormatNotify |
| 1855 |
|
| 1856 |
try: |
| 1857 |
asset = AppriseAsset(async_mode=False) |
| 1858 |
a = Apprise(asset=asset) |
| 1859 |
a.add(_BadFormatNotify(host="localhost", asset=asset)) |
| 1860 |
|
| 1861 |
with apprise_logs_enabled(): |
| 1862 |
result = a.notify(body="test") |
| 1863 |
finally: |
| 1864 |
N_MGR.unload_modules() |
| 1865 |
|
| 1866 |
assert result.status == AppriseResultStatus.FAILURE |
| 1867 |
|
| 1868 |
# The service that broke reports itself rather than vanishing. |
| 1869 |
assert [(r.name, r.status) for r in result.results] == [ |
| 1870 |
("BadFormat", AppriseResultStatus.FAILURE) |
| 1871 |
] |
| 1872 |
|
| 1873 |
# The reason has to reach the caller; a silent FAILURE here used |
| 1874 |
# to leave nothing at all behind to diagnose. |
| 1875 |
assert any( |
| 1876 |
"raised an exception" in e.message for e in result.call_logs() |
| 1877 |
) |
| 1878 |
|
| 1879 |
def test_async_notify_preparation_typeerror(self): |
| 1880 |
"""The asynchronous path explains a preparation TypeError too.""" |
| 1881 |
N_MGR["badformat"] = _BadFormatNotify |
| 1882 |
|
| 1883 |
try: |
| 1884 |
asset = AppriseAsset(async_mode=True) |
| 1885 |
a = Apprise(asset=asset) |
| 1886 |
a.add(_BadFormatNotify(host="localhost", asset=asset)) |
| 1887 |
|
| 1888 |
with apprise_logs_enabled(): |
| 1889 |
result = asyncio.run(a.async_notify(body="test")) |
| 1890 |
finally: |
| 1891 |
N_MGR.unload_modules() |
| 1892 |
|
| 1893 |
assert result.status == AppriseResultStatus.FAILURE |
| 1894 |
assert [(r.name, r.status) for r in result.results] == [ |
| 1895 |
("BadFormat", AppriseResultStatus.FAILURE) |
| 1896 |
] |
| 1897 |
assert any( |
| 1898 |
"raised an exception" in e.message for e in result.call_logs() |
| 1899 |
) |
| 1900 |
|
| 1901 |
def test_async_notify_unknown_argument(self): |
| 1902 |
"""async_notify() names the argument it could not accept.""" |
| 1903 |
N_MGR["test"] = _TestNotify |
| 1904 |
|
| 1905 |
try: |
| 1906 |
asset = AppriseAsset(async_mode=True) |
| 1907 |
a = Apprise(asset=asset) |
| 1908 |
a.add(_TestNotify(host="localhost", asset=asset)) |
| 1909 |
|
| 1910 |
with apprise_logs_enabled(): |
| 1911 |
result = asyncio.run(a.async_notify(body="test", bogus=1)) |
| 1912 |
finally: |
| 1913 |
N_MGR.unload_modules() |
| 1914 |
|
| 1915 |
assert result.status == AppriseResultStatus.FAILURE |
| 1916 |
assert len(result.results) == 0 |
| 1917 |
assert any("bogus" in e.message for e in result.call_logs()) |
| 1918 |
|
| 1919 |
def test_notify_preparation_crash(self): |
| 1920 |
"""A plugin crashing during preparation fails the call, not the |
| 1921 |
caller.""" |
| 1922 |
N_MGR["badformat"] = _BadFormatNotify |
| 1923 |
|
| 1924 |
try: |
| 1925 |
asset = AppriseAsset(async_mode=False) |
| 1926 |
a = Apprise(asset=asset) |
| 1927 |
a.add( |
| 1928 |
_BadFormatNotify( |
| 1929 |
host="localhost", |
| 1930 |
asset=asset, |
| 1931 |
error=RuntimeError("plugin blew up"), |
| 1932 |
) |
| 1933 |
) |
| 1934 |
|
| 1935 |
with apprise_logs_enabled(): |
| 1936 |
result = a.notify(body="test", log_level=logging.DEBUG) |
| 1937 |
finally: |
| 1938 |
N_MGR.unload_modules() |
| 1939 |
|
| 1940 |
# Anything raised while preparing content belongs in the result, |
| 1941 |
# not thrown at whoever called notify(). |
| 1942 |
assert result.status == AppriseResultStatus.FAILURE |
| 1943 |
assert [(r.name, r.status) for r in result.results] == [ |
| 1944 |
("BadFormat", AppriseResultStatus.FAILURE) |
| 1945 |
] |
| 1946 |
|
| 1947 |
# DEBUG carries the original text behind the summary warning. |
| 1948 |
assert any("plugin blew up" in e.message for e in result.call_logs()) |
| 1949 |
|
| 1950 |
def test_async_notify_preparation_crash(self): |
| 1951 |
"""The asynchronous path contains a preparation crash too.""" |
| 1952 |
N_MGR["badformat"] = _BadFormatNotify |
| 1953 |
|
| 1954 |
try: |
| 1955 |
asset = AppriseAsset(async_mode=True) |
| 1956 |
a = Apprise(asset=asset) |
| 1957 |
a.add( |
| 1958 |
_BadFormatNotify( |
| 1959 |
host="localhost", |
| 1960 |
asset=asset, |
| 1961 |
error=RuntimeError("plugin blew up"), |
| 1962 |
) |
| 1963 |
) |
| 1964 |
|
| 1965 |
with apprise_logs_enabled(): |
| 1966 |
result = asyncio.run( |
| 1967 |
a.async_notify(body="test", log_level=logging.DEBUG) |
| 1968 |
) |
| 1969 |
finally: |
| 1970 |
N_MGR.unload_modules() |
| 1971 |
|
| 1972 |
assert result.status == AppriseResultStatus.FAILURE |
| 1973 |
assert [(r.name, r.status) for r in result.results] == [ |
| 1974 |
("BadFormat", AppriseResultStatus.FAILURE) |
| 1975 |
] |
| 1976 |
assert any("plugin blew up" in e.message for e in result.call_logs()) |
| 1977 |
|
| 1978 |
def test_delivery_typeerror_reported(self): |
| 1979 |
"""A TypeError raised while delivering is reported like any crash.""" |
| 1980 |
N_MGR["slow"] = _SlowNotify |
| 1981 |
|
| 1982 |
try: |
| 1983 |
asset = AppriseAsset(async_mode=False) |
| 1984 |
service = _SlowNotify(host="x", asset=asset, delay=0.0) |
| 1985 |
|
| 1986 |
def _raise_type_error(**kwargs): |
| 1987 |
"""Fail the way a plugin with a signature bug would.""" |
| 1988 |
raise TypeError("delivery-time type error") |
| 1989 |
|
| 1990 |
service.send = _raise_type_error |
| 1991 |
a = Apprise(asset=asset) |
| 1992 |
a.add(service) |
| 1993 |
|
| 1994 |
with apprise_logs_enabled(): |
| 1995 |
result = a.notify(body="test") |
| 1996 |
finally: |
| 1997 |
N_MGR.unload_modules() |
| 1998 |
|
| 1999 |
assert result.status == AppriseResultStatus.FAILURE |
| 2000 |
|
| 2001 |
# A failed result with no logs at all cannot be diagnosed. |
| 2002 |
messages = [e.message for r in result.results for e in r.logs()] |
| 2003 |
assert any("raised an exception" in m for m in messages) |
| 2004 |
|
| 2005 |
def test_async_delivery_typeerror_reported(self): |
| 2006 |
"""Native async delivery reports a TypeError the same way.""" |
| 2007 |
N_MGR["slow"] = _SlowNotify |
| 2008 |
|
| 2009 |
try: |
| 2010 |
asset = AppriseAsset(async_mode=True) |
| 2011 |
service = _SlowNotify(host="x", asset=asset, delay=0.0) |
| 2012 |
|
| 2013 |
async def _raise_type_error(**kwargs): |
| 2014 |
"""Fail the way a plugin with a signature bug would.""" |
| 2015 |
raise TypeError("delivery-time type error") |
| 2016 |
|
| 2017 |
service.async_notify = _raise_type_error |
| 2018 |
a = Apprise(asset=asset) |
| 2019 |
a.add(service) |
| 2020 |
|
| 2021 |
with apprise_logs_enabled(): |
| 2022 |
result = asyncio.run(a.async_notify(body="test")) |
| 2023 |
finally: |
| 2024 |
N_MGR.unload_modules() |
| 2025 |
|
| 2026 |
assert result.status == AppriseResultStatus.FAILURE |
| 2027 |
|
| 2028 |
messages = [e.message for r in result.results for e in r.logs()] |
| 2029 |
assert any("raised an exception" in m for m in messages) |
| 2030 |
|
| 2031 |
def test_preparation_crash_isolated(self): |
| 2032 |
"""One plugin failing preparation does not silence the others.""" |
| 2033 |
N_MGR["badformat"] = _BadFormatNotify |
| 2034 |
N_MGR["slow"] = _SlowNotify |
| 2035 |
|
| 2036 |
try: |
| 2037 |
asset = AppriseAsset(async_mode=False) |
| 2038 |
healthy = _SlowNotify(host="a", asset=asset, delay=0.0) |
| 2039 |
a = Apprise(asset=asset) |
| 2040 |
a.add(healthy) |
| 2041 |
a.add( |
| 2042 |
_BadFormatNotify( |
| 2043 |
host="localhost", |
| 2044 |
asset=asset, |
| 2045 |
error=RuntimeError("plugin blew up"), |
| 2046 |
) |
| 2047 |
) |
| 2048 |
|
| 2049 |
result = a.notify(body="test") |
| 2050 |
finally: |
| 2051 |
N_MGR.unload_modules() |
| 2052 |
|
| 2053 |
# The healthy service was still contacted. |
| 2054 |
assert healthy.calls == 1 |
| 2055 |
|
| 2056 |
# Mixed outcome: one real delivery, one service that never ran. |
| 2057 |
assert result.status == AppriseResultStatus.PARTIAL |
| 2058 |
statuses = {r.name: r.status for r in result.results} |
| 2059 |
assert statuses["BadFormat"] == AppriseResultStatus.FAILURE |
| 2060 |
assert len(result.results) == 2 |
| 2061 |
|
| 2062 |
def test_async_preparation_crash_isolated(self): |
| 2063 |
"""The asynchronous path isolates a preparation crash too.""" |
| 2064 |
N_MGR["badformat"] = _BadFormatNotify |
| 2065 |
N_MGR["slow"] = _SlowNotify |
| 2066 |
|
| 2067 |
try: |
| 2068 |
asset = AppriseAsset(async_mode=True) |
| 2069 |
healthy = _SlowNotify(host="a", asset=asset, delay=0.0) |
| 2070 |
a = Apprise(asset=asset) |
| 2071 |
a.add(healthy) |
| 2072 |
a.add( |
| 2073 |
_BadFormatNotify( |
| 2074 |
host="localhost", |
| 2075 |
asset=asset, |
| 2076 |
error=RuntimeError("plugin blew up"), |
| 2077 |
) |
| 2078 |
) |
| 2079 |
|
| 2080 |
result = asyncio.run(a.async_notify(body="test")) |
| 2081 |
finally: |
| 2082 |
N_MGR.unload_modules() |
| 2083 |
|
| 2084 |
assert healthy.calls == 1 |
| 2085 |
assert result.status == AppriseResultStatus.PARTIAL |
| 2086 |
assert len(result.results) == 2 |
| 2087 |
|
| 2088 |
def test_flat_dispatch_preparation_crash(self): |
| 2089 |
"""An explicit priority filter isolates a crash the same way.""" |
| 2090 |
N_MGR["badformat"] = _BadFormatNotify |
| 2091 |
N_MGR["slow"] = _SlowNotify |
| 2092 |
|
| 2093 |
try: |
| 2094 |
asset = AppriseAsset(async_mode=False) |
| 2095 |
healthy = _SlowNotify(host="a", asset=asset, delay=0.0, tag="ops") |
| 2096 |
a = Apprise(asset=asset) |
| 2097 |
a.add(healthy) |
| 2098 |
a.add( |
| 2099 |
_BadFormatNotify( |
| 2100 |
host="localhost", |
| 2101 |
asset=asset, |
| 2102 |
tag="ops", |
| 2103 |
error=RuntimeError("plugin blew up"), |
| 2104 |
) |
| 2105 |
) |
| 2106 |
|
| 2107 |
# A priority prefix sends one flat batch, skipping escalation. |
| 2108 |
result = a.notify(body="test", tag="0:ops") |
| 2109 |
finally: |
| 2110 |
N_MGR.unload_modules() |
| 2111 |
|
| 2112 |
assert healthy.calls == 1 |
| 2113 |
|
| 2114 |
# The batch itself succeeded, but a broken service still counts. |
| 2115 |
assert result.status == AppriseResultStatus.PARTIAL |
| 2116 |
assert len(result.results) == 2 |
| 2117 |
|
| 2118 |
def test_every_service_broken(self): |
| 2119 |
"""A call where nothing could be prepared is a failure, not a |
| 2120 |
no-match.""" |
| 2121 |
N_MGR["badformat"] = _BadFormatNotify |
| 2122 |
|
| 2123 |
try: |
| 2124 |
asset = AppriseAsset(async_mode=False) |
| 2125 |
a = Apprise(asset=asset) |
| 2126 |
for _ in range(2): |
| 2127 |
a.add( |
| 2128 |
_BadFormatNotify( |
| 2129 |
host="localhost", |
| 2130 |
asset=asset, |
| 2131 |
error=RuntimeError("plugin blew up"), |
| 2132 |
) |
| 2133 |
) |
| 2134 |
|
| 2135 |
result = a.notify(body="test") |
| 2136 |
finally: |
| 2137 |
N_MGR.unload_modules() |
| 2138 |
|
| 2139 |
# Nothing was dispatched, but services did match, so NOMATCH would |
| 2140 |
# be misleading here. |
| 2141 |
assert result.status == AppriseResultStatus.FAILURE |
| 2142 |
assert len(result.results) == 2 |
| 2143 |
|
| 2144 |
def test_bad_content_still_stops_everything(self): |
| 2145 |
"""Content Apprise cannot use is the caller's error, not a |
| 2146 |
service's.""" |
| 2147 |
N_MGR["slow"] = _SlowNotify |
| 2148 |
|
| 2149 |
try: |
| 2150 |
asset = AppriseAsset(async_mode=False) |
| 2151 |
healthy = _SlowNotify(host="a", asset=asset, delay=0.0) |
| 2152 |
a = Apprise(asset=asset) |
| 2153 |
a.add(healthy) |
| 2154 |
|
| 2155 |
# A list cannot be escaped; that is a mistake in the call, so |
| 2156 |
# no service is blamed and none is contacted. |
| 2157 |
result = a.notify( |
| 2158 |
body=["not", "a", "string"], interpret_escapes=True |
| 2159 |
) |
| 2160 |
finally: |
| 2161 |
N_MGR.unload_modules() |
| 2162 |
|
| 2163 |
assert result.status == AppriseResultStatus.FAILURE |
| 2164 |
assert len(result.results) == 0 |
| 2165 |
assert healthy.calls == 0 |
| 2166 |
|
| 2167 |
def test_unreached_fallback_not_blamed(self): |
| 2168 |
"""A broken fallback escalation never reaches is never reported.""" |
| 2169 |
N_MGR["badformat"] = _BadFormatNotify |
| 2170 |
N_MGR["slow"] = _SlowNotify |
| 2171 |
|
| 2172 |
try: |
| 2173 |
asset = AppriseAsset(async_mode=False) |
| 2174 |
primary = _SlowNotify( |
| 2175 |
host="a", asset=asset, delay=0.0, tag="1:ops" |
| 2176 |
) |
| 2177 |
a = Apprise(asset=asset) |
| 2178 |
a.add(primary) |
| 2179 |
# Only ever tried if the priority-1 group fails. |
| 2180 |
a.add( |
| 2181 |
_BadFormatNotify( |
| 2182 |
host="localhost", |
| 2183 |
asset=asset, |
| 2184 |
tag="9:ops", |
| 2185 |
error=RuntimeError("plugin blew up"), |
| 2186 |
) |
| 2187 |
) |
| 2188 |
|
| 2189 |
result = a.notify(body="test", tag="ops") |
| 2190 |
finally: |
| 2191 |
N_MGR.unload_modules() |
| 2192 |
|
| 2193 |
assert primary.calls == 1 |
| 2194 |
|
| 2195 |
# The chain stopped at the group that worked, so the broken |
| 2196 |
# fallback is neither dispatched nor counted against the call. |
| 2197 |
assert result.status == AppriseResultStatus.SUCCESS |
| 2198 |
assert len(result.results) == 1 |
| 2199 |
assert "BadFormat" not in [r.name for r in result.results] |
| 2200 |
|
| 2201 |
def test_optional_service_preparation_crash(self): |
| 2202 |
"""A broken optional service stays optional.""" |
| 2203 |
N_MGR["badformat"] = _BadFormatNotify |
| 2204 |
N_MGR["slow"] = _SlowNotify |
| 2205 |
|
| 2206 |
try: |
| 2207 |
asset = AppriseAsset(async_mode=False) |
| 2208 |
required = _SlowNotify(host="a", asset=asset, delay=0.0) |
| 2209 |
a = Apprise(asset=asset) |
| 2210 |
a.add(required) |
| 2211 |
a.add( |
| 2212 |
_BadFormatNotify( |
| 2213 |
host="localhost", |
| 2214 |
asset=asset, |
| 2215 |
optional=True, |
| 2216 |
error=RuntimeError("plugin blew up"), |
| 2217 |
) |
| 2218 |
) |
| 2219 |
|
| 2220 |
result = a.notify(body="test") |
| 2221 |
|
| 2222 |
# Alone, it must not drag the call down either. |
| 2223 |
b = Apprise(asset=asset) |
| 2224 |
b.add( |
| 2225 |
_BadFormatNotify( |
| 2226 |
host="localhost", |
| 2227 |
asset=asset, |
| 2228 |
optional=True, |
| 2229 |
error=RuntimeError("plugin blew up"), |
| 2230 |
) |
| 2231 |
) |
| 2232 |
alone = b.notify(body="test") |
| 2233 |
finally: |
| 2234 |
N_MGR.unload_modules() |
| 2235 |
|
| 2236 |
assert required.calls == 1 |
| 2237 |
|
| 2238 |
# An optional service that fails is allowed to, so the overall |
| 2239 |
# status must agree with the entry's own SUCCESS. |
| 2240 |
assert result.status == AppriseResultStatus.SUCCESS |
| 2241 |
assert all(bool(r) for r in result.results) |
| 2242 |
assert alone.status == AppriseResultStatus.SUCCESS |
| 2243 |
|
| 2244 |
def test_preparation_crash_keeps_position(self): |
| 2245 |
"""A broken service stays where it was added, not first.""" |
| 2246 |
N_MGR["badformat"] = _BadFormatNotify |
| 2247 |
N_MGR["slow"] = _SlowNotify |
| 2248 |
|
| 2249 |
try: |
| 2250 |
asset = AppriseAsset(async_mode=False) |
| 2251 |
a = Apprise(asset=asset) |
| 2252 |
a.add(_SlowNotify(host="first", asset=asset, delay=0.0)) |
| 2253 |
a.add( |
| 2254 |
_BadFormatNotify( |
| 2255 |
host="localhost", |
| 2256 |
asset=asset, |
| 2257 |
error=RuntimeError("plugin blew up"), |
| 2258 |
) |
| 2259 |
) |
| 2260 |
a.add(_SlowNotify(host="third", asset=asset, delay=0.0)) |
| 2261 |
|
| 2262 |
result = a.notify(body="test") |
| 2263 |
finally: |
| 2264 |
N_MGR.unload_modules() |
| 2265 |
|
| 2266 |
# Results follow dispatch order, so the broken one is in the |
| 2267 |
# middle where it was added. |
| 2268 |
assert [r.status for r in result.results] == [ |
| 2269 |
AppriseResultStatus.SUCCESS, |
| 2270 |
AppriseResultStatus.FAILURE, |
| 2271 |
AppriseResultStatus.SUCCESS, |
| 2272 |
] |
| 2273 |
|
| 2274 |
|
| 2275 |
class TestConfigTagRetry: |
| 2276 |
"""Config parsers must reject a retry suffix in service tag definitions. |
| 2277 |
|
| 2278 |
A tag like 'alerts:3' is only valid at call-time (notify() filter / CLI). |
| 2279 |
Putting it in a config file creates ambiguity with the URL ?retry= param |
| 2280 |
and the YAML retry: key, so both parsers must warn and skip the entry. |
| 2281 |
""" |
| 2282 |
|
| 2283 |
def test_text_rejects_retry_suffix(self): |
| 2284 |
"""'alerts:3=json://...' is rejected; no service loaded.""" |
| 2285 |
services, _ = ConfigBase.config_parse_text("alerts:3=json://localhost") |
| 2286 |
assert services == [] |
| 2287 |
|
| 2288 |
def test_text_rejects_priority_and_retry_in_tag(self): |
| 2289 |
"""'1:alerts:3=json://...' is rejected (priority + retry suffix).""" |
| 2290 |
services, _ = ConfigBase.config_parse_text( |
| 2291 |
"1:alerts:3=json://localhost" |
| 2292 |
) |
| 2293 |
assert services == [] |
| 2294 |
|
| 2295 |
def test_text_accepts_priority_tag_without_retry(self): |
| 2296 |
"""'1:alerts=json://...' loads normally (priority prefix, no retry).""" |
| 2297 |
services, _ = ConfigBase.config_parse_text("1:alerts=json://localhost") |
| 2298 |
assert len(services) == 1 |
| 2299 |
|
| 2300 |
def test_text_accepts_plain_tag(self): |
| 2301 |
"""'alerts=json://...' loads normally (no prefix, no retry).""" |
| 2302 |
services, _ = ConfigBase.config_parse_text("alerts=json://localhost") |
| 2303 |
assert len(services) == 1 |
| 2304 |
|
| 2305 |
def test_yaml_rejects_retry_suffix(self): |
| 2306 |
"""YAML 'tag: alerts:3' is rejected; no service loaded.""" |
| 2307 |
services, _ = ConfigBase.config_parse_yaml( |
| 2308 |
"version: 1\nurls:\n - json://localhost:\n tag: alerts:3\n" |
| 2309 |
) |
| 2310 |
assert services == [] |
| 2311 |
|
| 2312 |
def test_yaml_rejects_priority_and_retry_in_tag(self): |
| 2313 |
"""YAML 'tag: 1:alerts:3' is rejected (priority + retry suffix).""" |
| 2314 |
services, _ = ConfigBase.config_parse_yaml( |
| 2315 |
"version: 1\nurls:\n - json://localhost:\n tag: 1:alerts:3\n" |
| 2316 |
) |
| 2317 |
assert services == [] |
| 2318 |
|
| 2319 |
def test_yaml_accepts_priority_tag_without_retry(self): |
| 2320 |
"""YAML 'tag: 1:alerts' loads normally (priority prefix, no retry).""" |
| 2321 |
services, _ = ConfigBase.config_parse_yaml( |
| 2322 |
"version: 1\nurls:\n - json://localhost:\n tag: 1:alerts\n" |
| 2323 |
) |
| 2324 |
assert len(services) == 1 |
| 2325 |
|
| 2326 |
def test_yaml_accepts_plain_tag(self): |
| 2327 |
"""YAML 'tag: alerts' loads normally (no prefix, no retry).""" |
| 2328 |
services, _ = ConfigBase.config_parse_yaml( |
| 2329 |
"version: 1\nurls:\n - json://localhost:\n tag: alerts\n" |
| 2330 |
) |
| 2331 |
assert len(services) == 1 |
| 2332 |
|
| 2333 |
def test_text_valid_entry_after_rejected_one_still_loads(self): |
| 2334 |
"""A valid entry that follows a rejected one is still loaded.""" |
| 2335 |
services, _ = ConfigBase.config_parse_text( |
| 2336 |
"alerts:3=json://localhost\nalerts=json://localhost\n" |
| 2337 |
) |
| 2338 |
assert len(services) == 1 |
| 2339 |
|
| 2340 |
def test_yaml_valid_entry_after_rejected_one_still_loads(self): |
| 2341 |
"""A valid entry that follows a rejected one is still loaded.""" |
| 2342 |
services, _ = ConfigBase.config_parse_yaml( |
| 2343 |
"version: 1\n" |
| 2344 |
"urls:\n" |
| 2345 |
" - json://localhost:\n" |
| 2346 |
" tag: alerts:3\n" |
| 2347 |
" - json://localhost:\n" |
| 2348 |
" tag: alerts\n" |
| 2349 |
) |
| 2350 |
assert len(services) == 1 |
| 2351 |
|
| 2352 |
|
| 2353 |
class TestMultiTagDispatch: |
| 2354 |
"""Exercise independent escalation chains in multi-tag OR filters. |
| 2355 |
|
| 2356 |
Each service receives the retry count from the filter token it matched. |
| 2357 |
""" |
| 2358 |
|
| 2359 |
def _make_tagged(self, tag_str, asset, fail_times=0): |
| 2360 |
"""Create a _FailThenSucceedNotify tagged with a single AppriseTag.""" |
| 2361 |
s = _FailThenSucceedNotify( |
| 2362 |
host=tag_str, asset=asset, fail_times=fail_times |
| 2363 |
) |
| 2364 |
# Assign instance-level set to avoid class-level mutation. |
| 2365 |
s.tags = {AppriseTag.parse(tag_str)} |
| 2366 |
return s |
| 2367 |
|
| 2368 |
def _make_priority_tagged(self, tag_str, asset, fail_times=0): |
| 2369 |
"""Create a service whose tag is an explicit-priority AppriseTag.""" |
| 2370 |
ft = AppriseTag.parse(tag_str) |
| 2371 |
s = _FailThenSucceedNotify( |
| 2372 |
host=str(ft), asset=asset, fail_times=fail_times |
| 2373 |
) |
| 2374 |
s.tags = {ft} |
| 2375 |
return s |
| 2376 |
|
| 2377 |
# ------------------------------------------------------------------ |
| 2378 |
# Per-service retry via space-separated string |
| 2379 |
# ------------------------------------------------------------------ |
| 2380 |
|
| 2381 |
def test_per_service_retry_space_separated_string(self): |
| 2382 |
"""'devops:3 management:2' applies retry=3 to devops services and |
| 2383 |
retry=2 to management services independently.""" |
| 2384 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 2385 |
|
| 2386 |
try: |
| 2387 |
asset = AppriseAsset(async_mode=False) |
| 2388 |
|
| 2389 |
# devops service: fails 3 times; needs retry=3 to succeed |
| 2390 |
s_devops = _FailThenSucceedNotify( |
| 2391 |
host="devops", asset=asset, fail_times=3 |
| 2392 |
) |
| 2393 |
s_devops.tags = {"devops"} |
| 2394 |
|
| 2395 |
# management service: fails 2 times; needs retry=2 to succeed |
| 2396 |
s_mgmt = _FailThenSucceedNotify( |
| 2397 |
host="mgmt", asset=asset, fail_times=2 |
| 2398 |
) |
| 2399 |
s_mgmt.tags = {"management"} |
| 2400 |
|
| 2401 |
a = Apprise(asset=asset) |
| 2402 |
a.add(s_devops) |
| 2403 |
a.add(s_mgmt) |
| 2404 |
|
| 2405 |
result = a.notify(body="test", tag="devops:3 management:2") |
| 2406 |
assert bool(result) is True |
| 2407 |
# devops: 1 initial + 3 retries = 4 total calls |
| 2408 |
assert s_devops._calls == 4 |
| 2409 |
# management: 1 initial + 2 retries = 3 total calls |
| 2410 |
assert s_mgmt._calls == 3 |
| 2411 |
finally: |
| 2412 |
N_MGR.unload_modules() |
| 2413 |
|
| 2414 |
def test_per_service_retry_list_of_tokens(self): |
| 2415 |
"""['devops:3', 'management:2'] gives the same per-service retry |
| 2416 |
result as a space-separated string.""" |
| 2417 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 2418 |
|
| 2419 |
try: |
| 2420 |
asset = AppriseAsset(async_mode=False) |
| 2421 |
|
| 2422 |
s_devops = _FailThenSucceedNotify( |
| 2423 |
host="devops", asset=asset, fail_times=3 |
| 2424 |
) |
| 2425 |
s_devops.tags = {"devops"} |
| 2426 |
|
| 2427 |
s_mgmt = _FailThenSucceedNotify( |
| 2428 |
host="mgmt", asset=asset, fail_times=2 |
| 2429 |
) |
| 2430 |
s_mgmt.tags = {"management"} |
| 2431 |
|
| 2432 |
a = Apprise(asset=asset) |
| 2433 |
a.add(s_devops) |
| 2434 |
a.add(s_mgmt) |
| 2435 |
|
| 2436 |
result = a.notify(body="test", tag=["devops:3", "management:2"]) |
| 2437 |
assert bool(result) is True |
| 2438 |
assert s_devops._calls == 4 |
| 2439 |
assert s_mgmt._calls == 3 |
| 2440 |
finally: |
| 2441 |
N_MGR.unload_modules() |
| 2442 |
|
| 2443 |
# ------------------------------------------------------------------ |
| 2444 |
# Independent escalation chains |
| 2445 |
# ------------------------------------------------------------------ |
| 2446 |
|
| 2447 |
def test_independent_chains_do_not_skip(self): |
| 2448 |
"""When devops chain succeeds at priority-1, management chain still |
| 2449 |
dispatches independently -- its priority-1 failure escalates to its |
| 2450 |
priority-2 service.""" |
| 2451 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 2452 |
|
| 2453 |
try: |
| 2454 |
asset = AppriseAsset(async_mode=False) |
| 2455 |
|
| 2456 |
# devops chain: priority-1 succeeds; priority-2 must not fire |
| 2457 |
s_devops_p1 = _FailThenSucceedNotify( |
| 2458 |
host="d1", asset=asset, fail_times=0 |
| 2459 |
) |
| 2460 |
s_devops_p1.tags = { |
| 2461 |
AppriseTag("devops", priority=1, has_priority=True) |
| 2462 |
} |
| 2463 |
s_devops_p2 = _FailThenSucceedNotify( |
| 2464 |
host="d2", asset=asset, fail_times=0 |
| 2465 |
) |
| 2466 |
s_devops_p2.tags = { |
| 2467 |
AppriseTag("devops", priority=2, has_priority=True) |
| 2468 |
} |
| 2469 |
|
| 2470 |
# management chain: priority-1 always fails; must escalate to |
| 2471 |
# priority-2 |
| 2472 |
s_mgmt_p1 = _FailThenSucceedNotify( |
| 2473 |
host="m1", asset=asset, fail_times=999 |
| 2474 |
) |
| 2475 |
s_mgmt_p1.tags = { |
| 2476 |
AppriseTag("management", priority=1, has_priority=True) |
| 2477 |
} |
| 2478 |
s_mgmt_p2 = _FailThenSucceedNotify( |
| 2479 |
host="m2", asset=asset, fail_times=0 |
| 2480 |
) |
| 2481 |
s_mgmt_p2.tags = { |
| 2482 |
AppriseTag("management", priority=2, has_priority=True) |
| 2483 |
} |
| 2484 |
|
| 2485 |
a = Apprise(asset=asset) |
| 2486 |
a.add(s_devops_p1) |
| 2487 |
a.add(s_devops_p2) |
| 2488 |
a.add(s_mgmt_p1) |
| 2489 |
a.add(s_mgmt_p2) |
| 2490 |
|
| 2491 |
result = a.notify(body="test", tag="devops management") |
| 2492 |
assert bool(result) is True |
| 2493 |
assert s_devops_p1._calls == 1 # devops chain: p1 succeeded |
| 2494 |
assert s_devops_p2._calls == 0 # never escalated to |
| 2495 |
assert s_mgmt_p1._calls == 1 # management chain: p1 failed |
| 2496 |
assert s_mgmt_p2._calls == 1 # escalated to p2, succeeded |
| 2497 |
finally: |
| 2498 |
N_MGR.unload_modules() |
| 2499 |
|
| 2500 |
def test_both_chains_must_succeed_for_true(self): |
| 2501 |
"""notify() returns False when one chain exhausts all priority groups |
| 2502 |
without any group fully succeeding.""" |
| 2503 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 2504 |
|
| 2505 |
try: |
| 2506 |
asset = AppriseAsset(async_mode=False) |
| 2507 |
|
| 2508 |
# devops chain: always succeeds |
| 2509 |
s_devops = _FailThenSucceedNotify( |
| 2510 |
host="d", asset=asset, fail_times=0 |
| 2511 |
) |
| 2512 |
s_devops.tags = {"devops"} |
| 2513 |
|
| 2514 |
# management chain: always fails |
| 2515 |
s_mgmt = _FailThenSucceedNotify( |
| 2516 |
host="m", asset=asset, fail_times=999 |
| 2517 |
) |
| 2518 |
s_mgmt.tags = {"management"} |
| 2519 |
|
| 2520 |
a = Apprise(asset=asset) |
| 2521 |
a.add(s_devops) |
| 2522 |
a.add(s_mgmt) |
| 2523 |
|
| 2524 |
result = a.notify(body="test", tag="devops management") |
| 2525 |
assert bool(result) is False |
| 2526 |
assert s_devops._calls == 1 # its chain succeeded |
| 2527 |
assert s_mgmt._calls == 1 # its chain failed |
| 2528 |
finally: |
| 2529 |
N_MGR.unload_modules() |
| 2530 |
|
| 2531 |
# ------------------------------------------------------------------ |
| 2532 |
# Explicit-priority list with per-service retry (flat dispatch) |
| 2533 |
# ------------------------------------------------------------------ |
| 2534 |
|
| 2535 |
def test_explicit_priority_list_per_service_retry(self): |
| 2536 |
"""['1:tag:2', '2:tag:0'] flat-dispatches both services; each gets its |
| 2537 |
own retry: the priority-1 service gets retry=2 and the priority-2 |
| 2538 |
service gets retry=0 (one attempt only).""" |
| 2539 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 2540 |
|
| 2541 |
try: |
| 2542 |
asset = AppriseAsset(async_mode=False) |
| 2543 |
|
| 2544 |
# priority-1 service: fails twice; needs retry=2 to succeed |
| 2545 |
s1 = _FailThenSucceedNotify(host="h1", asset=asset, fail_times=2) |
| 2546 |
s1.tags = {AppriseTag("tag", priority=1, has_priority=True)} |
| 2547 |
|
| 2548 |
# priority-2 service: always succeeds; retry=0 means one attempt |
| 2549 |
s2 = _FailThenSucceedNotify(host="h2", asset=asset, fail_times=0) |
| 2550 |
s2.tags = {AppriseTag("tag", priority=2, has_priority=True)} |
| 2551 |
|
| 2552 |
a = Apprise(asset=asset) |
| 2553 |
a.add(s1) |
| 2554 |
a.add(s2) |
| 2555 |
|
| 2556 |
result = a.notify(body="test", tag=["1:tag:2", "2:tag:0"]) |
| 2557 |
assert bool(result) is True |
| 2558 |
# s1: 1 initial + 2 retries = 3 total |
| 2559 |
assert s1._calls == 3 |
| 2560 |
# s2: retry=0 -> exactly 1 attempt |
| 2561 |
assert s2._calls == 1 |
| 2562 |
finally: |
| 2563 |
N_MGR.unload_modules() |
| 2564 |
|
| 2565 |
# ------------------------------------------------------------------ |
| 2566 |
# CLI OR format (list of single-element lists) |
| 2567 |
# ------------------------------------------------------------------ |
| 2568 |
|
| 2569 |
def test_cli_or_format_independent_chains(self): |
| 2570 |
"""CLI --tag 'devops:3' --tag 'management:2' generates |
| 2571 |
[['devops:3'], ['management:2']] -- single-element inner lists that |
| 2572 |
must be treated as independent OR chains, not AND groups.""" |
| 2573 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 2574 |
|
| 2575 |
try: |
| 2576 |
asset = AppriseAsset(async_mode=False) |
| 2577 |
|
| 2578 |
s_devops = _FailThenSucceedNotify( |
| 2579 |
host="devops", asset=asset, fail_times=3 |
| 2580 |
) |
| 2581 |
s_devops.tags = {"devops"} |
| 2582 |
|
| 2583 |
s_mgmt = _FailThenSucceedNotify( |
| 2584 |
host="mgmt", asset=asset, fail_times=2 |
| 2585 |
) |
| 2586 |
s_mgmt.tags = {"management"} |
| 2587 |
|
| 2588 |
a = Apprise(asset=asset) |
| 2589 |
a.add(s_devops) |
| 2590 |
a.add(s_mgmt) |
| 2591 |
|
| 2592 |
# Simulate CLI: --tag "devops:3" --tag "management:2" |
| 2593 |
cli_tag = [["devops:3"], ["management:2"]] |
| 2594 |
result = a.notify(body="test", tag=cli_tag) |
| 2595 |
assert bool(result) is True |
| 2596 |
assert s_devops._calls == 4 # 1 initial + 3 retries |
| 2597 |
assert s_mgmt._calls == 3 # 1 initial + 2 retries |
| 2598 |
finally: |
| 2599 |
N_MGR.unload_modules() |
| 2600 |
|
| 2601 |
def test_cli_and_format_shared_chain(self): |
| 2602 |
"""CLI --tag 'devops, management' generates [['devops', 'management']] |
| 2603 |
-- a multi-element inner list that is an AND condition and uses a |
| 2604 |
single shared escalation chain.""" |
| 2605 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 2606 |
|
| 2607 |
try: |
| 2608 |
asset = AppriseAsset(async_mode=False) |
| 2609 |
|
| 2610 |
# Service must carry BOTH tags to match |
| 2611 |
s_both = _FailThenSucceedNotify( |
| 2612 |
host="both", asset=asset, fail_times=0 |
| 2613 |
) |
| 2614 |
s_both.tags = {"devops", "management"} |
| 2615 |
|
| 2616 |
# Service with only "devops" -- must NOT match AND filter |
| 2617 |
s_devonly = _FailThenSucceedNotify( |
| 2618 |
host="devonly", asset=asset, fail_times=0 |
| 2619 |
) |
| 2620 |
s_devonly.tags = {"devops"} |
| 2621 |
|
| 2622 |
a = Apprise(asset=asset) |
| 2623 |
a.add(s_both) |
| 2624 |
a.add(s_devonly) |
| 2625 |
|
| 2626 |
# Simulate CLI: --tag "devops, management" (AND condition) |
| 2627 |
cli_tag = [["devops", "management"]] |
| 2628 |
result = a.notify(body="test", tag=cli_tag) |
| 2629 |
assert bool(result) is True |
| 2630 |
assert s_both._calls == 1 # has both tags -- matched |
| 2631 |
assert s_devonly._calls == 0 # missing "management" -- not matched |
| 2632 |
finally: |
| 2633 |
N_MGR.unload_modules() |
| 2634 |
|
| 2635 |
# ------------------------------------------------------------------ |
| 2636 |
# Edge cases: explicit priority + AND, 3-chain OR, chain exhaustion |
| 2637 |
# ------------------------------------------------------------------ |
| 2638 |
|
| 2639 |
def test_and_filter_explicit_priority_no_match_returns_none(self): |
| 2640 |
"""AND filter with an explicit priority that no service satisfies |
| 2641 |
returns AppriseResultStatus.NOMATCH (no services dispatched at |
| 2642 |
all).""" |
| 2643 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 2644 |
|
| 2645 |
try: |
| 2646 |
asset = AppriseAsset(async_mode=False) |
| 2647 |
|
| 2648 |
# Service is tagged 'alerts' at priority 2 |
| 2649 |
s = _FailThenSucceedNotify(host="s", asset=asset, fail_times=0) |
| 2650 |
s.tags = {AppriseTag("alerts", priority=2, has_priority=True)} |
| 2651 |
|
| 2652 |
a = Apprise(asset=asset) |
| 2653 |
a.add(s) |
| 2654 |
|
| 2655 |
# Request 'alerts' at priority 1 AND 'backup' -- service has |
| 2656 |
# 'alerts' but at priority 2, not 1; nothing matches. |
| 2657 |
result = a.notify(body="test", tag=[["1:alerts", "backup"]]) |
| 2658 |
assert result.status == AppriseResultStatus.NOMATCH |
| 2659 |
assert len(result) == 0 |
| 2660 |
assert s._calls == 0 |
| 2661 |
finally: |
| 2662 |
N_MGR.unload_modules() |
| 2663 |
|
| 2664 |
def test_three_or_chains_all_succeed(self): |
| 2665 |
"""Three independent OR chains each succeed at their first priority |
| 2666 |
group; notify() returns True and each service is called once.""" |
| 2667 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 2668 |
|
| 2669 |
try: |
| 2670 |
asset = AppriseAsset(async_mode=False) |
| 2671 |
|
| 2672 |
s_a = _FailThenSucceedNotify(host="a", asset=asset, fail_times=0) |
| 2673 |
s_a.tags = {"alpha"} |
| 2674 |
|
| 2675 |
s_b = _FailThenSucceedNotify(host="b", asset=asset, fail_times=0) |
| 2676 |
s_b.tags = {"beta"} |
| 2677 |
|
| 2678 |
s_c = _FailThenSucceedNotify(host="c", asset=asset, fail_times=0) |
| 2679 |
s_c.tags = {"gamma"} |
| 2680 |
|
| 2681 |
a = Apprise(asset=asset) |
| 2682 |
a.add(s_a) |
| 2683 |
a.add(s_b) |
| 2684 |
a.add(s_c) |
| 2685 |
|
| 2686 |
result = a.notify(body="test", tag=["alpha", "beta", "gamma"]) |
| 2687 |
assert bool(result) is True |
| 2688 |
assert s_a._calls == 1 |
| 2689 |
assert s_b._calls == 1 |
| 2690 |
assert s_c._calls == 1 |
| 2691 |
finally: |
| 2692 |
N_MGR.unload_modules() |
| 2693 |
|
| 2694 |
def test_three_or_chains_one_fails_overall_false(self): |
| 2695 |
"""Three OR chains: two succeed, one exhausts all priority groups. |
| 2696 |
notify() returns False even though the other chains succeeded.""" |
| 2697 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 2698 |
|
| 2699 |
try: |
| 2700 |
asset = AppriseAsset(async_mode=False) |
| 2701 |
|
| 2702 |
s_a = _FailThenSucceedNotify(host="a", asset=asset, fail_times=0) |
| 2703 |
s_a.tags = {"alpha"} |
| 2704 |
|
| 2705 |
# beta always fails (fail_times > any possible retry) |
| 2706 |
s_b = _FailThenSucceedNotify(host="b", asset=asset, fail_times=99) |
| 2707 |
s_b.tags = {"beta"} |
| 2708 |
|
| 2709 |
s_c = _FailThenSucceedNotify(host="c", asset=asset, fail_times=0) |
| 2710 |
s_c.tags = {"gamma"} |
| 2711 |
|
| 2712 |
a = Apprise(asset=asset) |
| 2713 |
a.add(s_a) |
| 2714 |
a.add(s_b) |
| 2715 |
a.add(s_c) |
| 2716 |
|
| 2717 |
result = a.notify(body="test", tag=["alpha", "beta", "gamma"]) |
| 2718 |
assert bool(result) is False |
| 2719 |
assert s_a._calls == 1 # alpha succeeded |
| 2720 |
assert s_c._calls == 1 # gamma succeeded |
| 2721 |
finally: |
| 2722 |
N_MGR.unload_modules() |
| 2723 |
|
| 2724 |
def test_chain_escalation_to_second_priority_group(self): |
| 2725 |
"""A chain whose priority-0 group fails escalates to the priority-1 |
| 2726 |
group; the second group succeeds so notify() returns True.""" |
| 2727 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 2728 |
|
| 2729 |
try: |
| 2730 |
asset = AppriseAsset(async_mode=False) |
| 2731 |
|
| 2732 |
# priority-0 service: always fails (no retry configured) |
| 2733 |
s_p0 = _FailThenSucceedNotify( |
| 2734 |
host="p0", asset=asset, fail_times=99 |
| 2735 |
) |
| 2736 |
s_p0.tags = {AppriseTag("alerts", priority=0, has_priority=False)} |
| 2737 |
|
| 2738 |
# priority-1 service: succeeds on first attempt |
| 2739 |
s_p1 = _FailThenSucceedNotify(host="p1", asset=asset, fail_times=0) |
| 2740 |
s_p1.tags = {AppriseTag("alerts", priority=1, has_priority=True)} |
| 2741 |
|
| 2742 |
a = Apprise(asset=asset) |
| 2743 |
a.add(s_p0) |
| 2744 |
a.add(s_p1) |
| 2745 |
|
| 2746 |
result = a.notify(body="test", tag="alerts") |
| 2747 |
assert bool(result) is True |
| 2748 |
# priority-0 group was attempted once and failed |
| 2749 |
assert s_p0._calls == 1 |
| 2750 |
# priority-1 group was then tried as fallback |
| 2751 |
assert s_p1._calls == 1 |
| 2752 |
finally: |
| 2753 |
N_MGR.unload_modules() |
| 2754 |
|
| 2755 |
def test_all_priority_groups_exhausted_returns_false(self): |
| 2756 |
"""When every priority group in a chain fails, notify() returns False |
| 2757 |
and all groups were attempted in order.""" |
| 2758 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 2759 |
|
| 2760 |
try: |
| 2761 |
asset = AppriseAsset(async_mode=False) |
| 2762 |
|
| 2763 |
# priority-0 service: always fails |
| 2764 |
s_p0 = _FailThenSucceedNotify( |
| 2765 |
host="p0", asset=asset, fail_times=99 |
| 2766 |
) |
| 2767 |
s_p0.tags = {AppriseTag("alerts", priority=0, has_priority=False)} |
| 2768 |
|
| 2769 |
# priority-1 service: also always fails |
| 2770 |
s_p1 = _FailThenSucceedNotify( |
| 2771 |
host="p1", asset=asset, fail_times=99 |
| 2772 |
) |
| 2773 |
s_p1.tags = {AppriseTag("alerts", priority=1, has_priority=True)} |
| 2774 |
|
| 2775 |
a = Apprise(asset=asset) |
| 2776 |
a.add(s_p0) |
| 2777 |
a.add(s_p1) |
| 2778 |
|
| 2779 |
result = a.notify(body="test", tag="alerts") |
| 2780 |
assert bool(result) is False |
| 2781 |
# Both groups were attempted |
| 2782 |
assert s_p0._calls == 1 |
| 2783 |
assert s_p1._calls == 1 |
| 2784 |
finally: |
| 2785 |
N_MGR.unload_modules() |
| 2786 |
|
| 2787 |
def test_chain_dispatch_future_exception_treated_as_failure(self): |
| 2788 |
"""Treat an exception from a concurrent tag chain as failure. |
| 2789 |
|
| 2790 |
Multiple chains force the executor path. An asset that raises during |
| 2791 |
dispatch reaches its fallback without cross-thread method patching. |
| 2792 |
""" |
| 2793 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 2794 |
|
| 2795 |
try: |
| 2796 |
# _ExplodingAsset.async_mode raises RuntimeError. _run_batch |
| 2797 |
# reads s.asset.async_mode to split seq/par, so a batch with |
| 2798 |
# one of these services raises and the future captures it. |
| 2799 |
class _ExplodingAsset(AppriseAsset): |
| 2800 |
"""Asset whose mode lookup fails inside chain dispatch.""" |
| 2801 |
|
| 2802 |
@property |
| 2803 |
def async_mode(self): |
| 2804 |
"""Raise the injected failure when dispatch reads mode.""" |
| 2805 |
raise RuntimeError("injected async_mode access") |
| 2806 |
|
| 2807 |
# Two services with distinct tags -> two independent chains so |
| 2808 |
# the ThreadPoolExecutor path (len(active) > 1) is taken. |
| 2809 |
s_a = _FailThenSucceedNotify( |
| 2810 |
host="a", asset=_ExplodingAsset(), fail_times=0 |
| 2811 |
) |
| 2812 |
s_a.tags = {"alpha"} |
| 2813 |
|
| 2814 |
s_b = _FailThenSucceedNotify( |
| 2815 |
host="b", asset=_ExplodingAsset(), fail_times=0 |
| 2816 |
) |
| 2817 |
s_b.tags = {"beta"} |
| 2818 |
|
| 2819 |
a = Apprise() |
| 2820 |
a.add(s_a) |
| 2821 |
a.add(s_b) |
| 2822 |
|
| 2823 |
result = a.notify(body="test", tag=["alpha", "beta"]) |
| 2824 |
|
| 2825 |
# Both chains raised instead of returning True -- overall False. |
| 2826 |
assert bool(result) is False |
| 2827 |
finally: |
| 2828 |
N_MGR.unload_modules() |
| 2829 |
|
| 2830 |
def test_single_chain_exception(self): |
| 2831 |
"""Treat a direct-dispatch chain exception as a failure.""" |
| 2832 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 2833 |
|
| 2834 |
try: |
| 2835 |
|
| 2836 |
class _ExplodingAsset(AppriseAsset): |
| 2837 |
"""Asset whose mode lookup fails inside chain dispatch.""" |
| 2838 |
|
| 2839 |
@property |
| 2840 |
def async_mode(self): |
| 2841 |
"""Raise the injected failure when dispatch reads mode.""" |
| 2842 |
raise RuntimeError("injected async_mode access") |
| 2843 |
|
| 2844 |
# One untagged chain dispatches without the coordinator pool. |
| 2845 |
service = _FailThenSucceedNotify( |
| 2846 |
host="solo", asset=_ExplodingAsset(), fail_times=0 |
| 2847 |
) |
| 2848 |
|
| 2849 |
a = Apprise() |
| 2850 |
a.add(service) |
| 2851 |
|
| 2852 |
result = a.notify(body="test") |
| 2853 |
|
| 2854 |
# The chain raised instead of returning True -- overall False. |
| 2855 |
assert bool(result) is False |
| 2856 |
finally: |
| 2857 |
N_MGR.unload_modules() |
| 2858 |
|
| 2859 |
def test_async_chain_base_exception(self): |
| 2860 |
"""Treat a BaseException returned by gather() as a chain failure.""" |
| 2861 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 2862 |
|
| 2863 |
try: |
| 2864 |
|
| 2865 |
class _FatalDispatch(BaseException): |
| 2866 |
"""Stands in for CancelledError, which is not Exception.""" |
| 2867 |
|
| 2868 |
class _CancellingAsset(AppriseAsset): |
| 2869 |
"""Asset whose mode lookup fails inside chain dispatch.""" |
| 2870 |
|
| 2871 |
@property |
| 2872 |
def async_mode(self): |
| 2873 |
"""Raise the injected failure when dispatch reads mode.""" |
| 2874 |
raise _FatalDispatch("injected chain cancellation") |
| 2875 |
|
| 2876 |
service = _FailThenSucceedNotify( |
| 2877 |
host="solo", asset=_CancellingAsset(), fail_times=0 |
| 2878 |
) |
| 2879 |
|
| 2880 |
a = Apprise() |
| 2881 |
a.add(service) |
| 2882 |
|
| 2883 |
result = asyncio.run(a.async_notify(body="test")) |
| 2884 |
|
| 2885 |
# The chain escalated instead of the result being unpacked. |
| 2886 |
assert bool(result) is False |
| 2887 |
finally: |
| 2888 |
N_MGR.unload_modules() |
| 2889 |
|
| 2890 |
|
| 2891 |
class TestAbortOnChainFailure: |
| 2892 |
"""Exercise optional early exit when one tag chain is exhausted. |
| 2893 |
|
| 2894 |
By default all chains finish. Enabling the setting stops later escalation |
| 2895 |
rounds after a chain fails. |
| 2896 |
""" |
| 2897 |
|
| 2898 |
def _make_tagged(self, tag_str, asset, fail_times=0): |
| 2899 |
s = _FailThenSucceedNotify( |
| 2900 |
host=tag_str, asset=asset, fail_times=fail_times |
| 2901 |
) |
| 2902 |
s.tags = {tag_str} |
| 2903 |
return s |
| 2904 |
|
| 2905 |
def test_default_false_all_chains_complete(self): |
| 2906 |
"""With abort_on_chain_failure=False (default), all chains run to |
| 2907 |
completion even if one chain has already failed.""" |
| 2908 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 2909 |
|
| 2910 |
try: |
| 2911 |
asset = AppriseAsset(async_mode=False) |
| 2912 |
|
| 2913 |
# alpha always succeeds |
| 2914 |
s_a = self._make_tagged("alpha", asset, fail_times=0) |
| 2915 |
|
| 2916 |
# beta always fails (exhausts its only group immediately) |
| 2917 |
s_b = self._make_tagged("beta", asset, fail_times=99) |
| 2918 |
|
| 2919 |
# gamma always succeeds |
| 2920 |
s_c = self._make_tagged("gamma", asset, fail_times=0) |
| 2921 |
|
| 2922 |
a = Apprise(asset=asset) |
| 2923 |
a.add(s_a) |
| 2924 |
a.add(s_b) |
| 2925 |
a.add(s_c) |
| 2926 |
|
| 2927 |
result = a.notify(body="test", tag=["alpha", "beta", "gamma"]) |
| 2928 |
assert bool(result) is False |
| 2929 |
# alpha and gamma were still dispatched despite beta failing |
| 2930 |
assert s_a._calls == 1 |
| 2931 |
assert s_b._calls == 1 |
| 2932 |
assert s_c._calls == 1 |
| 2933 |
finally: |
| 2934 |
N_MGR.unload_modules() |
| 2935 |
|
| 2936 |
def test_abort_on_chain_failure_true_stops_early(self): |
| 2937 |
"""With abort_on_chain_failure=True, once beta exhausts all priority |
| 2938 |
groups without success, further escalation rounds for other chains |
| 2939 |
are skipped.""" |
| 2940 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 2941 |
|
| 2942 |
try: |
| 2943 |
asset = AppriseAsset(async_mode=False, abort_on_chain_failure=True) |
| 2944 |
|
| 2945 |
# alpha: two priority levels; priority-0 always fails |
| 2946 |
s_a_p0 = _FailThenSucceedNotify( |
| 2947 |
host="a0", asset=asset, fail_times=99 |
| 2948 |
) |
| 2949 |
s_a_p0.tags = {AppriseTag("alpha", priority=0, has_priority=False)} |
| 2950 |
|
| 2951 |
s_a_p1 = _FailThenSucceedNotify( |
| 2952 |
host="a1", asset=asset, fail_times=0 |
| 2953 |
) |
| 2954 |
s_a_p1.tags = {AppriseTag("alpha", priority=1, has_priority=True)} |
| 2955 |
|
| 2956 |
# beta: one priority level; always fails |
| 2957 |
s_b = _FailThenSucceedNotify(host="b", asset=asset, fail_times=99) |
| 2958 |
s_b.tags = {"beta"} |
| 2959 |
|
| 2960 |
a = Apprise(asset=asset) |
| 2961 |
a.add(s_a_p0) |
| 2962 |
a.add(s_a_p1) |
| 2963 |
a.add(s_b) |
| 2964 |
|
| 2965 |
result = a.notify(body="test", tag=["alpha", "beta"]) |
| 2966 |
assert bool(result) is False |
| 2967 |
# beta failed in round 1 and was exhausted -- abort triggered. |
| 2968 |
# alpha's p1 (escalation) should NOT have been attempted. |
| 2969 |
assert s_b._calls == 1 |
| 2970 |
assert s_a_p0._calls == 1 |
| 2971 |
assert s_a_p1._calls == 0 # skipped due to early abort |
| 2972 |
finally: |
| 2973 |
N_MGR.unload_modules() |
| 2974 |
|
| 2975 |
def test_abort_on_chain_failure_true_async(self): |
| 2976 |
"""abort_on_chain_failure=True triggers the same early-abort in |
| 2977 |
async_notify()""" |
| 2978 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 2979 |
|
| 2980 |
try: |
| 2981 |
asset = AppriseAsset(async_mode=True, abort_on_chain_failure=True) |
| 2982 |
|
| 2983 |
# alpha has two priority levels; priority-0 always fails |
| 2984 |
s_a_p0 = _FailThenSucceedNotify( |
| 2985 |
host="a0", asset=asset, fail_times=99 |
| 2986 |
) |
| 2987 |
s_a_p0.tags = {AppriseTag("alpha", priority=0, has_priority=False)} |
| 2988 |
|
| 2989 |
s_a_p1 = _FailThenSucceedNotify( |
| 2990 |
host="a1", asset=asset, fail_times=0 |
| 2991 |
) |
| 2992 |
s_a_p1.tags = {AppriseTag("alpha", priority=1, has_priority=True)} |
| 2993 |
|
| 2994 |
# beta has one priority level; always fails |
| 2995 |
s_b = _FailThenSucceedNotify(host="b", asset=asset, fail_times=99) |
| 2996 |
s_b.tags = {"beta"} |
| 2997 |
|
| 2998 |
a = Apprise(asset=asset) |
| 2999 |
a.add(s_a_p0) |
| 3000 |
a.add(s_a_p1) |
| 3001 |
a.add(s_b) |
| 3002 |
|
| 3003 |
result = asyncio.run( |
| 3004 |
a.async_notify(body="test", tag=["alpha", "beta"]) |
| 3005 |
) |
| 3006 |
assert bool(result) is False |
| 3007 |
# beta was exhausted in round 1 -- abort fires before alpha's p1 |
| 3008 |
assert s_b._calls == 1 |
| 3009 |
assert s_a_p0._calls == 1 |
| 3010 |
assert s_a_p1._calls == 0 |
| 3011 |
finally: |
| 3012 |
N_MGR.unload_modules() |
| 3013 |
|
| 3014 |
|
| 3015 |
class TestOptionalService: |
| 3016 |
"""optional=True silently absorbs per-service delivery failures. |
| 3017 |
|
| 3018 |
The overall notify()/async_notify() result evaluates truthy even when |
| 3019 |
an optional service cannot be reached, so callers are not penalised |
| 3020 |
for "nice to have" endpoints (e.g. home screens, debug logging). |
| 3021 |
""" |
| 3022 |
|
| 3023 |
def test_optional_default_false(self): |
| 3024 |
"""optional defaults to False on a freshly constructed plugin.""" |
| 3025 |
nb = _TestNotify(host="localhost") |
| 3026 |
assert nb.optional is False |
| 3027 |
|
| 3028 |
def test_optional_url_includes_flag(self): |
| 3029 |
"""url_parameters() always emits optional=yes or optional=no.""" |
| 3030 |
nb = _TestNotify(host="localhost") |
| 3031 |
params = nb.url_parameters() |
| 3032 |
assert "optional" in params |
| 3033 |
assert params["optional"] == "no" |
| 3034 |
|
| 3035 |
nb_opt = _TestNotify(host="localhost", optional=True) |
| 3036 |
params_opt = nb_opt.url_parameters() |
| 3037 |
assert params_opt["optional"] == "yes" |
| 3038 |
|
| 3039 |
def test_optional_parse_url_yes(self): |
| 3040 |
"""parse_url propagates optional=yes into the results dict.""" |
| 3041 |
results = _TestNotify.parse_url("test://localhost?optional=yes") |
| 3042 |
assert results is not None |
| 3043 |
assert results.get("optional") is True |
| 3044 |
|
| 3045 |
def test_optional_parse_url_no(self): |
| 3046 |
"""parse_url propagates optional=no into the results dict.""" |
| 3047 |
results = _TestNotify.parse_url("test://localhost?optional=no") |
| 3048 |
assert results is not None |
| 3049 |
assert results.get("optional") is False |
| 3050 |
|
| 3051 |
def test_optional_kwarg_sets_attribute(self): |
| 3052 |
"""Passing optional=True/False to __init__ sets .optional.""" |
| 3053 |
nb_yes = _TestNotify(host="localhost", optional=True) |
| 3054 |
assert nb_yes.optional is True |
| 3055 |
|
| 3056 |
nb_no = _TestNotify(host="localhost", optional=False) |
| 3057 |
assert nb_no.optional is False |
| 3058 |
|
| 3059 |
def test_optional_sequential_failure_absorbed(self): |
| 3060 |
"""Sequential dispatch: failed optional service -> overall True.""" |
| 3061 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 3062 |
|
| 3063 |
try: |
| 3064 |
asset = AppriseAsset(async_mode=False) |
| 3065 |
s = _FailThenSucceedNotify(host="s1", asset=asset, fail_times=99) |
| 3066 |
s.optional = True |
| 3067 |
|
| 3068 |
a = Apprise(asset=asset) |
| 3069 |
a.add(s) |
| 3070 |
|
| 3071 |
result = a.notify(body="test") |
| 3072 |
assert bool(result) is True |
| 3073 |
assert s._calls == 1 |
| 3074 |
finally: |
| 3075 |
N_MGR.unload_modules() |
| 3076 |
|
| 3077 |
def test_optional_threadpool_failure_absorbed(self): |
| 3078 |
"""Thread-pool dispatch: failed optional services -> overall True. |
| 3079 |
|
| 3080 |
Two async_mode=True services ensure _notify_parallel_threadpool |
| 3081 |
uses the actual thread pool (n_calls==1 falls back to sequential). |
| 3082 |
""" |
| 3083 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 3084 |
|
| 3085 |
try: |
| 3086 |
asset = AppriseAsset(async_mode=True) |
| 3087 |
s1 = _FailThenSucceedNotify(host="s1", asset=asset, fail_times=99) |
| 3088 |
s1.optional = True |
| 3089 |
s2 = _FailThenSucceedNotify(host="s2", asset=asset, fail_times=99) |
| 3090 |
s2.optional = True |
| 3091 |
|
| 3092 |
a = Apprise(asset=asset) |
| 3093 |
a.add(s1) |
| 3094 |
a.add(s2) |
| 3095 |
|
| 3096 |
result = a.notify(body="test") |
| 3097 |
assert bool(result) is True |
| 3098 |
finally: |
| 3099 |
N_MGR.unload_modules() |
| 3100 |
|
| 3101 |
def test_optional_asyncio_failure_absorbed(self): |
| 3102 |
"""Asyncio dispatch: failed optional service -> overall True.""" |
| 3103 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 3104 |
|
| 3105 |
try: |
| 3106 |
asset = AppriseAsset(async_mode=True) |
| 3107 |
s = _FailThenSucceedNotify(host="s1", asset=asset, fail_times=99) |
| 3108 |
s.optional = True |
| 3109 |
|
| 3110 |
a = Apprise(asset=asset) |
| 3111 |
a.add(s) |
| 3112 |
|
| 3113 |
result = asyncio.run(a.async_notify(body="test")) |
| 3114 |
assert bool(result) is True |
| 3115 |
finally: |
| 3116 |
N_MGR.unload_modules() |
| 3117 |
|
| 3118 |
def test_optional_all_fail_all_optional_returns_true(self): |
| 3119 |
"""When every service is optional and every service fails -> True.""" |
| 3120 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 3121 |
|
| 3122 |
try: |
| 3123 |
asset = AppriseAsset(async_mode=False) |
| 3124 |
a = Apprise(asset=asset) |
| 3125 |
for i in range(3): |
| 3126 |
s = _FailThenSucceedNotify( |
| 3127 |
host=f"s{i}", asset=asset, fail_times=99 |
| 3128 |
) |
| 3129 |
s.optional = True |
| 3130 |
a.add(s) |
| 3131 |
|
| 3132 |
result = a.notify(body="test") |
| 3133 |
assert bool(result) is True |
| 3134 |
finally: |
| 3135 |
N_MGR.unload_modules() |
| 3136 |
|
| 3137 |
def test_optional_mixed_required_fails_returns_false(self): |
| 3138 |
"""Required service failure taints result even with optional peers.""" |
| 3139 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 3140 |
|
| 3141 |
try: |
| 3142 |
asset = AppriseAsset(async_mode=False) |
| 3143 |
s_opt = _FailThenSucceedNotify( |
| 3144 |
host="opt", asset=asset, fail_times=99 |
| 3145 |
) |
| 3146 |
s_opt.optional = True |
| 3147 |
|
| 3148 |
s_req = _FailThenSucceedNotify( |
| 3149 |
host="req", asset=asset, fail_times=99 |
| 3150 |
) |
| 3151 |
# s_req.optional is False (default) |
| 3152 |
|
| 3153 |
a = Apprise(asset=asset) |
| 3154 |
a.add(s_opt) |
| 3155 |
a.add(s_req) |
| 3156 |
|
| 3157 |
result = a.notify(body="test") |
| 3158 |
assert bool(result) is False |
| 3159 |
finally: |
| 3160 |
N_MGR.unload_modules() |
| 3161 |
|
| 3162 |
def test_optional_success_unaffected(self): |
| 3163 |
"""An optional service that succeeds is still counted as True.""" |
| 3164 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 3165 |
|
| 3166 |
try: |
| 3167 |
asset = AppriseAsset(async_mode=False) |
| 3168 |
s = _FailThenSucceedNotify(host="s1", asset=asset, fail_times=0) |
| 3169 |
s.optional = True |
| 3170 |
|
| 3171 |
a = Apprise(asset=asset) |
| 3172 |
a.add(s) |
| 3173 |
|
| 3174 |
result = a.notify(body="test") |
| 3175 |
assert bool(result) is True |
| 3176 |
assert s._calls == 1 |
| 3177 |
finally: |
| 3178 |
N_MGR.unload_modules() |
| 3179 |
|
| 3180 |
|
| 3181 |
class TestPartialStatus: |
| 3182 |
"""AppriseResultStatus.PARTIAL: a batch where at least one service |
| 3183 |
genuinely delivered and at least one did not, in the same call.""" |
| 3184 |
|
| 3185 |
def test_mixed_success_and_failure_is_partial(self): |
| 3186 |
"""One service succeeds, one fails outright -> PARTIAL, not |
| 3187 |
FAILURE.""" |
| 3188 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 3189 |
|
| 3190 |
try: |
| 3191 |
asset = AppriseAsset(async_mode=False) |
| 3192 |
s_ok = _FailThenSucceedNotify(host="ok", asset=asset, fail_times=0) |
| 3193 |
s_fail = _FailThenSucceedNotify( |
| 3194 |
host="fail", asset=asset, fail_times=99 |
| 3195 |
) |
| 3196 |
|
| 3197 |
a = Apprise(asset=asset) |
| 3198 |
a.add(s_ok) |
| 3199 |
a.add(s_fail) |
| 3200 |
|
| 3201 |
result = a.notify(body="test") |
| 3202 |
assert result.status == AppriseResultStatus.PARTIAL |
| 3203 |
# PARTIAL is not the truthy SUCCESS value. |
| 3204 |
assert bool(result) is False |
| 3205 |
finally: |
| 3206 |
N_MGR.unload_modules() |
| 3207 |
|
| 3208 |
def test_all_succeed_is_success_not_partial(self): |
| 3209 |
"""Every service succeeding stays SUCCESS -- PARTIAL requires at |
| 3210 |
least one non-delivery in the same batch.""" |
| 3211 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 3212 |
|
| 3213 |
try: |
| 3214 |
asset = AppriseAsset(async_mode=False) |
| 3215 |
s1 = _FailThenSucceedNotify(host="s1", asset=asset, fail_times=0) |
| 3216 |
s2 = _FailThenSucceedNotify(host="s2", asset=asset, fail_times=0) |
| 3217 |
|
| 3218 |
a = Apprise(asset=asset) |
| 3219 |
a.add(s1) |
| 3220 |
a.add(s2) |
| 3221 |
|
| 3222 |
result = a.notify(body="test") |
| 3223 |
assert result.status == AppriseResultStatus.SUCCESS |
| 3224 |
finally: |
| 3225 |
N_MGR.unload_modules() |
| 3226 |
|
| 3227 |
def test_all_fail_is_failure_not_partial(self): |
| 3228 |
"""Every service failing outright stays FAILURE -- there is no |
| 3229 |
genuine success in the batch to make it PARTIAL.""" |
| 3230 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 3231 |
|
| 3232 |
try: |
| 3233 |
asset = AppriseAsset(async_mode=False) |
| 3234 |
s1 = _FailThenSucceedNotify(host="s1", asset=asset, fail_times=99) |
| 3235 |
s2 = _FailThenSucceedNotify(host="s2", asset=asset, fail_times=99) |
| 3236 |
|
| 3237 |
a = Apprise(asset=asset) |
| 3238 |
a.add(s1) |
| 3239 |
a.add(s2) |
| 3240 |
|
| 3241 |
result = a.notify(body="test") |
| 3242 |
assert result.status == AppriseResultStatus.FAILURE |
| 3243 |
finally: |
| 3244 |
N_MGR.unload_modules() |
| 3245 |
|
| 3246 |
def test_optional_absorbed_failure_does_not_count_as_partial(self): |
| 3247 |
"""A forgiven optional=yes failure does not count as a 'genuine' |
| 3248 |
success -- an optional service that never actually delivered, |
| 3249 |
paired with a required service that also failed, is still a |
| 3250 |
clean FAILURE, not PARTIAL.""" |
| 3251 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 3252 |
|
| 3253 |
try: |
| 3254 |
asset = AppriseAsset(async_mode=False) |
| 3255 |
s_opt = _FailThenSucceedNotify( |
| 3256 |
host="opt", asset=asset, fail_times=99 |
| 3257 |
) |
| 3258 |
s_opt.optional = True |
| 3259 |
s_req = _FailThenSucceedNotify( |
| 3260 |
host="req", asset=asset, fail_times=99 |
| 3261 |
) |
| 3262 |
|
| 3263 |
a = Apprise(asset=asset) |
| 3264 |
a.add(s_opt) |
| 3265 |
a.add(s_req) |
| 3266 |
|
| 3267 |
result = a.notify(body="test") |
| 3268 |
assert result.status == AppriseResultStatus.FAILURE |
| 3269 |
finally: |
| 3270 |
N_MGR.unload_modules() |
| 3271 |
|
| 3272 |
def test_success_plus_timeout_is_partial(self): |
| 3273 |
"""Report PARTIAL when one parallel service succeeds and one times out. |
| 3274 |
|
| 3275 |
Two asynchronous services force bounded parallel dispatch, which can |
| 3276 |
stop waiting for an in-flight call; sequential dispatch cannot. |
| 3277 |
""" |
| 3278 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 3279 |
N_MGR["slow"] = _SlowNotify |
| 3280 |
|
| 3281 |
try: |
| 3282 |
asset = AppriseAsset(async_mode=True, service_timeout=0.05) |
| 3283 |
s_ok = _FailThenSucceedNotify(host="ok", asset=asset, fail_times=0) |
| 3284 |
s_slow = _SlowNotify(host="slow", asset=asset, delay=0.3) |
| 3285 |
|
| 3286 |
a = Apprise(asset=asset) |
| 3287 |
a.add(s_ok) |
| 3288 |
a.add(s_slow) |
| 3289 |
|
| 3290 |
result = a.notify(body="test") |
| 3291 |
assert result.status == AppriseResultStatus.PARTIAL |
| 3292 |
finally: |
| 3293 |
N_MGR.unload_modules() |
| 3294 |
|
| 3295 |
def test_async_notify_mixed_outcome_is_partial(self): |
| 3296 |
"""The asyncio dispatch path reports PARTIAL the same way as the |
| 3297 |
synchronous paths.""" |
| 3298 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 3299 |
|
| 3300 |
try: |
| 3301 |
asset = AppriseAsset(async_mode=True) |
| 3302 |
s_ok = _FailThenSucceedNotify(host="ok", asset=asset, fail_times=0) |
| 3303 |
s_fail = _FailThenSucceedNotify( |
| 3304 |
host="fail", asset=asset, fail_times=99 |
| 3305 |
) |
| 3306 |
|
| 3307 |
a = Apprise(asset=asset) |
| 3308 |
a.add(s_ok) |
| 3309 |
a.add(s_fail) |
| 3310 |
|
| 3311 |
result = asyncio.run(a.async_notify(body="test")) |
| 3312 |
assert result.status == AppriseResultStatus.PARTIAL |
| 3313 |
finally: |
| 3314 |
N_MGR.unload_modules() |
| 3315 |
|
| 3316 |
|
| 3317 |
class TestCreateNotifyCalls: |
| 3318 |
"""Cover Apprise._create_notify_calls() which splits services into |
| 3319 |
sequential and parallel buckets based on their asset.async_mode flag.""" |
| 3320 |
|
| 3321 |
def test_splits_sequential_and_parallel(self): |
| 3322 |
"""Sequential and parallel services are split into separate lists.""" |
| 3323 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 3324 |
try: |
| 3325 |
# With async_mode=False all loaded services go to the sequential |
| 3326 |
# bucket; the parallel bucket remains empty. |
| 3327 |
asset_seq = AppriseAsset(async_mode=False) |
| 3328 |
s_seq = _FailThenSucceedNotify( |
| 3329 |
host="s1", asset=asset_seq, fail_times=0 |
| 3330 |
) |
| 3331 |
|
| 3332 |
a = Apprise(asset=asset_seq) |
| 3333 |
a.add(s_seq) |
| 3334 |
|
| 3335 |
seq, par = a._create_notify_calls(body="test") |
| 3336 |
assert len(seq) == 1 |
| 3337 |
assert len(par) == 0 |
| 3338 |
|
| 3339 |
# With async_mode=True the same service is placed in the parallel |
| 3340 |
# bucket instead. |
| 3341 |
asset_par = AppriseAsset(async_mode=True) |
| 3342 |
s_par = _FailThenSucceedNotify( |
| 3343 |
host="s2", asset=asset_par, fail_times=0 |
| 3344 |
) |
| 3345 |
|
| 3346 |
b = Apprise(asset=asset_par) |
| 3347 |
b.add(s_par) |
| 3348 |
|
| 3349 |
seq2, par2 = b._create_notify_calls(body="test") |
| 3350 |
assert len(seq2) == 0 |
| 3351 |
assert len(par2) == 1 |
| 3352 |
finally: |
| 3353 |
N_MGR.unload_modules() |
| 3354 |
|
| 3355 |
|
| 3356 |
class TestAsyncioSafetyNet: |
| 3357 |
"""Cover async safety nets for exceptions that escape do_call.""" |
| 3358 |
|
| 3359 |
def test_exception_outside_try_block_triggers_safety_net(self): |
| 3360 |
"""An escaped property failure is reported beside a good service.""" |
| 3361 |
|
| 3362 |
class _RaisingLoggerService: |
| 3363 |
"""Service whose logger fails before delivery starts.""" |
| 3364 |
|
| 3365 |
service_name = "raiser" |
| 3366 |
asset = AppriseAsset(async_mode=True) |
| 3367 |
optional = False |
| 3368 |
|
| 3369 |
@property |
| 3370 |
def logger(self): |
| 3371 |
"""Raise while the attempt's log capture is being built. |
| 3372 |
|
| 3373 |
Result-building reads are guarded, so this uses one that is |
| 3374 |
not: the capture reads the service's own logger before any |
| 3375 |
per-attempt handling exists to catch it. |
| 3376 |
""" |
| 3377 |
# This escapes do_call and is captured by asyncio.gather. |
| 3378 |
raise RuntimeError("injected: property raised outside try") |
| 3379 |
|
| 3380 |
async def async_notify(self, **kwargs): |
| 3381 |
"""Represent delivery that must not be reached in this test.""" |
| 3382 |
return True # pragma: no cover -- never reached |
| 3383 |
|
| 3384 |
class _GoodService: |
| 3385 |
"""Minimal well-behaved service that succeeds immediately.""" |
| 3386 |
|
| 3387 |
service_name = "good" |
| 3388 |
asset = AppriseAsset(async_mode=True) |
| 3389 |
optional = False |
| 3390 |
tags = set() |
| 3391 |
|
| 3392 |
def url(self, privacy=False): |
| 3393 |
"""Return the stable URL used to identify this service.""" |
| 3394 |
return "good://localhost" |
| 3395 |
|
| 3396 |
def url_id(self): |
| 3397 |
"""Return a stable identifier for result assertions.""" |
| 3398 |
return "good-id" |
| 3399 |
|
| 3400 |
def __len__(self): |
| 3401 |
"""Report the single target represented by this service.""" |
| 3402 |
return 1 |
| 3403 |
|
| 3404 |
async def async_notify(self, **kwargs): |
| 3405 |
"""Report immediate successful asynchronous delivery.""" |
| 3406 |
return True |
| 3407 |
|
| 3408 |
raiser = _RaisingLoggerService() |
| 3409 |
good = _GoodService() |
| 3410 |
# Exercise both the escaped-exception and successful-result branches. |
| 3411 |
ok, results = asyncio.run( |
| 3412 |
Apprise._notify_parallel_asyncio((raiser, {}), (good, {})) |
| 3413 |
) |
| 3414 |
assert ok is False |
| 3415 |
assert len(results) == 2 |
| 3416 |
|
| 3417 |
|
| 3418 |
class TestServiceTimeout: |
| 3419 |
"""AppriseAsset._service_timeout / notify(timeout=...) enforcement. |
| 3420 |
|
| 3421 |
Real sleeps are intentional here: these tests protect threaded/async |
| 3422 |
deadline behaviour. Margins stay generous so slower CI hosts fail only for |
| 3423 |
real regressions, not ordinary timing jitter. |
| 3424 |
""" |
| 3425 |
|
| 3426 |
def test_sequential_between_attempts_timeout(self): |
| 3427 |
"""A real failure before timeout remains a FAILURE.""" |
| 3428 |
N_MGR["slow"] = _SlowNotify |
| 3429 |
|
| 3430 |
try: |
| 3431 |
asset = AppriseAsset(async_mode=False, service_timeout=0.5) |
| 3432 |
# First attempt costs 0.1s and fails, leaving ~0.4s of the |
| 3433 |
# 0.5s budget. retry=5 with wait=5.0 would normally sleep |
| 3434 |
# five seconds between attempts, but that must be capped to |
| 3435 |
# the remaining budget, and no second attempt may start. |
| 3436 |
service = _SlowNotify( |
| 3437 |
host="x", asset=asset, delay=0.0, retry=5, wait=5.0 |
| 3438 |
) |
| 3439 |
service.send = lambda **kw: (time.sleep(0.1), False)[1] |
| 3440 |
a = Apprise(asset=asset) |
| 3441 |
a.add(service) |
| 3442 |
|
| 3443 |
t0 = time.monotonic() |
| 3444 |
result = a.notify(body="test") |
| 3445 |
wall = time.monotonic() - t0 |
| 3446 |
finally: |
| 3447 |
N_MGR.unload_modules() |
| 3448 |
|
| 3449 |
r0 = next(iter(result)) |
| 3450 |
# The worker and outer wait share a deadline, so accept either attempt |
| 3451 |
# sequence when slower hosts change which one finishes first. |
| 3452 |
assert len(r0.attempts) in (1, 2) |
| 3453 |
assert r0.attempts[-1].status == AppriseResultStatus.TIMEOUT |
| 3454 |
assert r0.max_attempts == 6 |
| 3455 |
if len(r0.attempts) == 2: |
| 3456 |
assert r0.attempts[0].status == AppriseResultStatus.FAILURE |
| 3457 |
# A real failure takes priority over the synthetic timeout. |
| 3458 |
assert r0.status == AppriseResultStatus.FAILURE |
| 3459 |
else: |
| 3460 |
# The outer wait finished first, leaving only its timeout. |
| 3461 |
assert r0.status == AppriseResultStatus.TIMEOUT |
| 3462 |
assert result.status == r0.status |
| 3463 |
# The retry sleep uses the remaining budget instead of the full 5s. |
| 3464 |
assert wall < 3.0 |
| 3465 |
|
| 3466 |
def test_threadpool_between_attempts_timeout_and_sleep_cap(self): |
| 3467 |
"""Thread-pool retry sleep is capped by the worker deadline.""" |
| 3468 |
N_MGR["slow"] = _SlowNotify |
| 3469 |
|
| 3470 |
try: |
| 3471 |
asset = AppriseAsset(async_mode=True, service_timeout=2.0) |
| 3472 |
# The failed first attempt leaves enough budget for the worker to |
| 3473 |
# cap wait=5.0 itself before the outer bounded wait races it. |
| 3474 |
slow = _SlowNotify( |
| 3475 |
host="slow", asset=asset, delay=0.0, retry=3, wait=5.0 |
| 3476 |
) |
| 3477 |
slow.send = lambda **kw: (time.sleep(0.3), False)[1] |
| 3478 |
fast = _SlowNotify(host="fast", asset=asset, delay=0.0) |
| 3479 |
a = Apprise(asset=asset) |
| 3480 |
a.add(slow) |
| 3481 |
a.add(fast) |
| 3482 |
|
| 3483 |
t0 = time.monotonic() |
| 3484 |
result = a.notify(body="test") |
| 3485 |
wall = time.monotonic() - t0 |
| 3486 |
finally: |
| 3487 |
N_MGR.unload_modules() |
| 3488 |
|
| 3489 |
by_host = {r.url: r for r in result} |
| 3490 |
slow_result = by_host["slow://slow"] |
| 3491 |
# The worker and outer wait share a deadline, so accept either attempt |
| 3492 |
# sequence when slower hosts change which one finishes first. |
| 3493 |
assert len(slow_result.attempts) in (1, 2) |
| 3494 |
assert slow_result.attempts[-1].status == AppriseResultStatus.TIMEOUT |
| 3495 |
assert slow_result.max_attempts == 4 |
| 3496 |
if len(slow_result.attempts) == 2: |
| 3497 |
assert ( |
| 3498 |
slow_result.attempts[0].status == AppriseResultStatus.FAILURE |
| 3499 |
) |
| 3500 |
# A real failure takes priority over the synthetic timeout. |
| 3501 |
assert slow_result.status == AppriseResultStatus.FAILURE |
| 3502 |
else: |
| 3503 |
# The outer wait finished first, leaving only its timeout. |
| 3504 |
assert slow_result.status == AppriseResultStatus.TIMEOUT |
| 3505 |
assert by_host["slow://fast"].status == AppriseResultStatus.SUCCESS |
| 3506 |
# The retry sleep uses the remaining budget instead of the full 5s. |
| 3507 |
assert wall < 5.0 |
| 3508 |
|
| 3509 |
def test_asyncio_between_attempts_timeout_and_sleep_cap(self): |
| 3510 |
"""Same guarantee as the thread-pool test above, for the asyncio |
| 3511 |
do_call() coroutine's own between-attempts deadline check.""" |
| 3512 |
N_MGR["slow"] = _SlowNotify |
| 3513 |
|
| 3514 |
try: |
| 3515 |
asset = AppriseAsset(async_mode=True, service_timeout=2.0) |
| 3516 |
slow = _SlowNotify( |
| 3517 |
host="slow", asset=asset, delay=0.0, retry=3, wait=5.0 |
| 3518 |
) |
| 3519 |
|
| 3520 |
async def _fail_slowly(**kw): |
| 3521 |
"""Delay briefly, then fail so retry waiting consumes time.""" |
| 3522 |
await asyncio.sleep(0.3) |
| 3523 |
return False |
| 3524 |
|
| 3525 |
slow.async_notify = _fail_slowly |
| 3526 |
fast = _SlowNotify(host="fast", asset=asset, delay=0.0) |
| 3527 |
a = Apprise(asset=asset) |
| 3528 |
a.add(slow) |
| 3529 |
a.add(fast) |
| 3530 |
|
| 3531 |
t0 = time.monotonic() |
| 3532 |
result = asyncio.run(a.async_notify(body="test")) |
| 3533 |
wall = time.monotonic() - t0 |
| 3534 |
finally: |
| 3535 |
N_MGR.unload_modules() |
| 3536 |
|
| 3537 |
by_host = {r.url: r for r in result} |
| 3538 |
slow_result = by_host["slow://slow"] |
| 3539 |
# As above, accept either attempt sequence at the shared deadline. |
| 3540 |
assert len(slow_result.attempts) in (1, 2) |
| 3541 |
assert slow_result.attempts[-1].status == AppriseResultStatus.TIMEOUT |
| 3542 |
assert slow_result.max_attempts == 4 |
| 3543 |
if len(slow_result.attempts) == 2: |
| 3544 |
assert ( |
| 3545 |
slow_result.attempts[0].status == AppriseResultStatus.FAILURE |
| 3546 |
) |
| 3547 |
# A real failure takes priority over the synthetic timeout. |
| 3548 |
assert slow_result.status == AppriseResultStatus.FAILURE |
| 3549 |
else: |
| 3550 |
# The outer wait finished first, leaving only its timeout. |
| 3551 |
assert slow_result.status == AppriseResultStatus.TIMEOUT |
| 3552 |
assert by_host["slow://fast"].status == AppriseResultStatus.SUCCESS |
| 3553 |
assert wall < 5.0 |
| 3554 |
|
| 3555 |
def test_sequential_service_timeout_disabled(self): |
| 3556 |
"""service_timeout=0 disables the cap -- a slow service still |
| 3557 |
completes normally.""" |
| 3558 |
N_MGR["slow"] = _SlowNotify |
| 3559 |
|
| 3560 |
try: |
| 3561 |
asset = AppriseAsset(async_mode=False, service_timeout=0) |
| 3562 |
service = _SlowNotify(host="x", asset=asset, delay=0.05) |
| 3563 |
a = Apprise(asset=asset) |
| 3564 |
a.add(service) |
| 3565 |
|
| 3566 |
result = a.notify(body="test") |
| 3567 |
finally: |
| 3568 |
N_MGR.unload_modules() |
| 3569 |
|
| 3570 |
r0 = next(iter(result)) |
| 3571 |
assert r0.status == AppriseResultStatus.SUCCESS |
| 3572 |
assert service.calls == 1 |
| 3573 |
|
| 3574 |
def test_sequential_timeout_disabled_retry_wait(self): |
| 3575 |
"""With service_timeout=0 (no deadline at all), the retry/wait |
| 3576 |
loop keeps its normal uncapped wait behaviour.""" |
| 3577 |
N_MGR["slow"] = _SlowNotify |
| 3578 |
|
| 3579 |
try: |
| 3580 |
asset = AppriseAsset(async_mode=False, service_timeout=0) |
| 3581 |
service = _SlowNotify( |
| 3582 |
host="x", asset=asset, delay=0.0, retry=1, wait=0.01 |
| 3583 |
) |
| 3584 |
call_count = {"n": 0} |
| 3585 |
|
| 3586 |
def _fail_then_succeed(**kw): |
| 3587 |
"""Fail once, then succeed to exercise an uncapped retry.""" |
| 3588 |
call_count["n"] += 1 |
| 3589 |
return call_count["n"] >= 2 |
| 3590 |
|
| 3591 |
service.send = _fail_then_succeed |
| 3592 |
a = Apprise(asset=asset) |
| 3593 |
a.add(service) |
| 3594 |
|
| 3595 |
result = a.notify(body="test") |
| 3596 |
finally: |
| 3597 |
N_MGR.unload_modules() |
| 3598 |
|
| 3599 |
r0 = next(iter(result)) |
| 3600 |
assert r0.status == AppriseResultStatus.SUCCESS |
| 3601 |
assert len(r0.attempts) == 2 |
| 3602 |
|
| 3603 |
def test_threadpool_outer_bound_abandons_slow_service(self): |
| 3604 |
"""A service stuck past its deadline is abandoned by the outer |
| 3605 |
bounded wait; the batch returns promptly and the other service is |
| 3606 |
unaffected.""" |
| 3607 |
N_MGR["slow"] = _SlowNotify |
| 3608 |
|
| 3609 |
try: |
| 3610 |
asset = AppriseAsset(async_mode=True, service_timeout=0.5) |
| 3611 |
slow = _SlowNotify(host="slow", asset=asset, delay=2.0) |
| 3612 |
fast = _SlowNotify(host="fast", asset=asset, delay=0.0) |
| 3613 |
a = Apprise(asset=asset) |
| 3614 |
a.add(slow) |
| 3615 |
a.add(fast) |
| 3616 |
|
| 3617 |
t0 = time.monotonic() |
| 3618 |
result = a.notify(body="test") |
| 3619 |
wall = time.monotonic() - t0 |
| 3620 |
finally: |
| 3621 |
N_MGR.unload_modules() |
| 3622 |
|
| 3623 |
# The whole call returned promptly -- nowhere near the slow |
| 3624 |
# service's 2.0s delay -- even though that thread is still |
| 3625 |
# running in the background because Python cannot stop the worker. |
| 3626 |
assert wall < 3.0 |
| 3627 |
by_host = {r.url: r for r in result} |
| 3628 |
assert by_host["slow://slow"].status == (AppriseResultStatus.TIMEOUT) |
| 3629 |
assert by_host["slow://fast"].status == (AppriseResultStatus.SUCCESS) |
| 3630 |
|
| 3631 |
def test_asyncio_outer_bound_abandons_slow_service(self): |
| 3632 |
"""Same guarantee as the thread-pool test, for async_notify().""" |
| 3633 |
N_MGR["slow"] = _SlowNotify |
| 3634 |
|
| 3635 |
try: |
| 3636 |
asset = AppriseAsset(async_mode=True, service_timeout=0.5) |
| 3637 |
slow = _SlowNotify(host="slow", asset=asset, delay=2.0) |
| 3638 |
fast = _SlowNotify(host="fast", asset=asset, delay=0.0) |
| 3639 |
a = Apprise(asset=asset) |
| 3640 |
a.add(slow) |
| 3641 |
a.add(fast) |
| 3642 |
|
| 3643 |
t0 = time.monotonic() |
| 3644 |
result = asyncio.run(a.async_notify(body="test")) |
| 3645 |
wall = time.monotonic() - t0 |
| 3646 |
finally: |
| 3647 |
N_MGR.unload_modules() |
| 3648 |
|
| 3649 |
assert wall < 3.0 |
| 3650 |
by_host = {r.url: r for r in result} |
| 3651 |
assert by_host["slow://slow"].status == (AppriseResultStatus.TIMEOUT) |
| 3652 |
assert by_host["slow://fast"].status == (AppriseResultStatus.SUCCESS) |
| 3653 |
|
| 3654 |
def test_threadpool_timeout_disabled_retry_wait(self): |
| 3655 |
"""With service_timeout=0, the thread-pool worker's retry/wait |
| 3656 |
loop keeps its normal uncapped wait behaviour.""" |
| 3657 |
N_MGR["slow"] = _SlowNotify |
| 3658 |
|
| 3659 |
try: |
| 3660 |
asset = AppriseAsset(async_mode=True, service_timeout=0) |
| 3661 |
call_count = {"n": 0} |
| 3662 |
|
| 3663 |
def _fail_then_succeed(**kw): |
| 3664 |
"""Fail once, then succeed in the thread-pool retry loop.""" |
| 3665 |
call_count["n"] += 1 |
| 3666 |
return call_count["n"] >= 2 |
| 3667 |
|
| 3668 |
flaky = _SlowNotify( |
| 3669 |
host="flaky", asset=asset, delay=0.0, retry=1, wait=0.01 |
| 3670 |
) |
| 3671 |
flaky.send = _fail_then_succeed |
| 3672 |
other = _SlowNotify(host="other", asset=asset, delay=0.0) |
| 3673 |
a = Apprise(asset=asset) |
| 3674 |
a.add(flaky) |
| 3675 |
a.add(other) |
| 3676 |
|
| 3677 |
result = a.notify(body="test") |
| 3678 |
finally: |
| 3679 |
N_MGR.unload_modules() |
| 3680 |
|
| 3681 |
by_host = {r.url: r for r in result} |
| 3682 |
assert by_host["slow://flaky"].status == AppriseResultStatus.SUCCESS |
| 3683 |
assert len(by_host["slow://flaky"].attempts) == 2 |
| 3684 |
assert by_host["slow://other"].status == AppriseResultStatus.SUCCESS |
| 3685 |
|
| 3686 |
def test_asyncio_timeout_disabled_retry_wait(self): |
| 3687 |
"""Same guarantee as the thread-pool test above, for the asyncio |
| 3688 |
do_call() coroutine's retry/wait loop.""" |
| 3689 |
N_MGR["slow"] = _SlowNotify |
| 3690 |
|
| 3691 |
try: |
| 3692 |
asset = AppriseAsset(async_mode=True, service_timeout=0) |
| 3693 |
call_count = {"n": 0} |
| 3694 |
|
| 3695 |
async def _fail_then_succeed(**kw): |
| 3696 |
"""Fail once, then succeed in the asyncio retry loop.""" |
| 3697 |
call_count["n"] += 1 |
| 3698 |
return call_count["n"] >= 2 |
| 3699 |
|
| 3700 |
flaky = _SlowNotify( |
| 3701 |
host="flaky", asset=asset, delay=0.0, retry=1, wait=0.01 |
| 3702 |
) |
| 3703 |
flaky.async_notify = _fail_then_succeed |
| 3704 |
other = _SlowNotify(host="other", asset=asset, delay=0.0) |
| 3705 |
a = Apprise(asset=asset) |
| 3706 |
a.add(flaky) |
| 3707 |
a.add(other) |
| 3708 |
|
| 3709 |
result = asyncio.run(a.async_notify(body="test")) |
| 3710 |
finally: |
| 3711 |
N_MGR.unload_modules() |
| 3712 |
|
| 3713 |
by_host = {r.url: r for r in result} |
| 3714 |
assert by_host["slow://flaky"].status == AppriseResultStatus.SUCCESS |
| 3715 |
assert len(by_host["slow://flaky"].attempts) == 2 |
| 3716 |
assert by_host["slow://other"].status == AppriseResultStatus.SUCCESS |
| 3717 |
|
| 3718 |
def test_notify_timeout_overrides_longer_asset_default(self): |
| 3719 |
"""notify(timeout=...) can cut a call short even when the asset |
| 3720 |
default would have allowed more time.""" |
| 3721 |
N_MGR["slow"] = _SlowNotify |
| 3722 |
|
| 3723 |
try: |
| 3724 |
# Asset default is generous (10s); the call-level override |
| 3725 |
# of 0.5s must win since it is the sooner of the two. |
| 3726 |
asset = AppriseAsset(async_mode=True, service_timeout=10) |
| 3727 |
slow1 = _SlowNotify(host="one", asset=asset, delay=2.0) |
| 3728 |
slow2 = _SlowNotify(host="two", asset=asset, delay=2.0) |
| 3729 |
a = Apprise(asset=asset) |
| 3730 |
a.add(slow1) |
| 3731 |
a.add(slow2) |
| 3732 |
|
| 3733 |
t0 = time.monotonic() |
| 3734 |
result = a.notify(body="test", timeout=0.5) |
| 3735 |
wall = time.monotonic() - t0 |
| 3736 |
finally: |
| 3737 |
N_MGR.unload_modules() |
| 3738 |
|
| 3739 |
assert wall < 3.0 |
| 3740 |
assert all(r.status == AppriseResultStatus.TIMEOUT for r in result) |
| 3741 |
|
| 3742 |
def test_notify_timeout_keeps_stricter_asset_default(self): |
| 3743 |
"""The reverse also holds: a short asset default still applies |
| 3744 |
even when notify(timeout=...) allows much more time.""" |
| 3745 |
N_MGR["slow"] = _SlowNotify |
| 3746 |
|
| 3747 |
try: |
| 3748 |
asset = AppriseAsset(async_mode=True, service_timeout=0.5) |
| 3749 |
slow1 = _SlowNotify(host="one", asset=asset, delay=2.0) |
| 3750 |
slow2 = _SlowNotify(host="two", asset=asset, delay=2.0) |
| 3751 |
a = Apprise(asset=asset) |
| 3752 |
a.add(slow1) |
| 3753 |
a.add(slow2) |
| 3754 |
|
| 3755 |
t0 = time.monotonic() |
| 3756 |
result = a.notify(body="test", timeout=60) |
| 3757 |
wall = time.monotonic() - t0 |
| 3758 |
finally: |
| 3759 |
N_MGR.unload_modules() |
| 3760 |
|
| 3761 |
assert wall < 3.0 |
| 3762 |
assert all(r.status == AppriseResultStatus.TIMEOUT for r in result) |
| 3763 |
|
| 3764 |
def test_notify_negative_timeout_raises(self): |
| 3765 |
"""notify(timeout=-1) is a caller error, not a silent no-op.""" |
| 3766 |
a = Apprise() |
| 3767 |
a.add("json://localhost") |
| 3768 |
with pytest.raises(ValueError): |
| 3769 |
a.notify(body="test", timeout=-1) |
| 3770 |
|
| 3771 |
def test_async_notify_negative_timeout_raises(self): |
| 3772 |
"""async_notify(timeout=-1) is a caller error, not a silent |
| 3773 |
no-op.""" |
| 3774 |
a = Apprise() |
| 3775 |
a.add("json://localhost") |
| 3776 |
with pytest.raises(ValueError): |
| 3777 |
asyncio.run(a.async_notify(body="test", timeout=-1)) |
| 3778 |
|
| 3779 |
def test_notify_infinite_timeout_raises(self): |
| 3780 |
"""notify(timeout=inf) is rejected; 0 is the unbounded spelling.""" |
| 3781 |
a = Apprise() |
| 3782 |
a.add("json://localhost") |
| 3783 |
with pytest.raises(ValueError): |
| 3784 |
a.notify(body="test", timeout=float("inf")) |
| 3785 |
|
| 3786 |
def test_notify_nan_timeout_raises(self): |
| 3787 |
"""notify(timeout=nan) is rejected instead of disabling the timeout.""" |
| 3788 |
a = Apprise() |
| 3789 |
a.add("json://localhost") |
| 3790 |
with pytest.raises(ValueError): |
| 3791 |
a.notify(body="test", timeout=float("nan")) |
| 3792 |
|
| 3793 |
def test_async_notify_infinite_timeout_raises(self): |
| 3794 |
"""async_notify(timeout=inf) is rejected for the same reason as |
| 3795 |
notify(timeout=inf).""" |
| 3796 |
a = Apprise() |
| 3797 |
a.add("json://localhost") |
| 3798 |
with pytest.raises(ValueError): |
| 3799 |
asyncio.run(a.async_notify(body="test", timeout=float("inf"))) |
| 3800 |
|
| 3801 |
def test_notify_rejects_non_numeric_timeout(self): |
| 3802 |
"""notify() rejects a non-numeric timeout.""" |
| 3803 |
a = Apprise() |
| 3804 |
a.add("json://localhost") |
| 3805 |
with pytest.raises(AppriseImproperlyConfigured): |
| 3806 |
a.notify(body="test", timeout="abc") |
| 3807 |
|
| 3808 |
def test_notify_rejects_bool_timeout(self): |
| 3809 |
"""A bool timeout is rejected even though bool is an int subclass.""" |
| 3810 |
a = Apprise() |
| 3811 |
a.add("json://localhost") |
| 3812 |
with pytest.raises(AppriseImproperlyConfigured): |
| 3813 |
a.notify(body="test", timeout=True) |
| 3814 |
|
| 3815 |
def test_async_notify_rejects_non_numeric_timeout(self): |
| 3816 |
"""async_notify() rejects a non-numeric timeout.""" |
| 3817 |
a = Apprise() |
| 3818 |
a.add("json://localhost") |
| 3819 |
with pytest.raises(AppriseImproperlyConfigured): |
| 3820 |
asyncio.run(a.async_notify(body="test", timeout="abc")) |
| 3821 |
|
| 3822 |
def test_notify_timeout_defaults_to_zero(self): |
| 3823 |
"""timeout defaults to 0 (no call-level override) -- only |
| 3824 |
AppriseAsset._service_timeout controls the default behaviour.""" |
| 3825 |
import inspect |
| 3826 |
|
| 3827 |
signature = inspect.signature(Apprise.notify) |
| 3828 |
assert signature.parameters["timeout"].default == 0 |
| 3829 |
|
| 3830 |
def test_timeout_logs_include_error_entry(self): |
| 3831 |
"""A TIMEOUT attempt includes a matching ERROR log entry. |
| 3832 |
|
| 3833 |
Each attempt takes one second, so the 1.5-second deadline expires |
| 3834 |
during the retry wait or the second attempt. The grace period is |
| 3835 |
widened so a slow test host cannot stop the wait before the worker |
| 3836 |
reports its own attempts. |
| 3837 |
""" |
| 3838 |
N_MGR["slow"] = _SlowNotify |
| 3839 |
|
| 3840 |
try: |
| 3841 |
asset = AppriseAsset(async_mode=False, service_timeout=1.5) |
| 3842 |
service = _SlowNotify(host="x", asset=asset, retry=2) |
| 3843 |
service.send = lambda **kw: (time.sleep(1.0), False)[1] |
| 3844 |
a = Apprise(asset=asset) |
| 3845 |
a.add(service) |
| 3846 |
|
| 3847 |
# Wait long enough for the worker to return its attempts. |
| 3848 |
with mock.patch("apprise.apprise._ABANDON_GRACE_SECONDS", 5.0): |
| 3849 |
result = a.notify(body="test") |
| 3850 |
|
| 3851 |
finally: |
| 3852 |
N_MGR.unload_modules() |
| 3853 |
|
| 3854 |
r0 = next(iter(result)) |
| 3855 |
# The earlier real failures still outrank the later timeout. |
| 3856 |
assert r0.status == AppriseResultStatus.FAILURE |
| 3857 |
assert r0.attempts[-1].status == AppriseResultStatus.TIMEOUT |
| 3858 |
error_logs = [entry for entry in r0.logs() if entry.level == "ERROR"] |
| 3859 |
assert len(error_logs) == 1 |
| 3860 |
assert "did not finish" in error_logs[0].message |
| 3861 |
assert r0.name in error_logs[0].message |
| 3862 |
|
| 3863 |
def test_timeout_result_json_includes_start_end_time(self): |
| 3864 |
"""A TIMEOUT NotifyResult still has start_time/end_time populated.""" |
| 3865 |
N_MGR["slow"] = _SlowNotify |
| 3866 |
|
| 3867 |
try: |
| 3868 |
asset = AppriseAsset(async_mode=True, service_timeout=0.5) |
| 3869 |
slow = _SlowNotify(host="slow", asset=asset, delay=3.0) |
| 3870 |
fast = _SlowNotify(host="fast", asset=asset, delay=0.0) |
| 3871 |
a = Apprise(asset=asset) |
| 3872 |
a.add(slow) |
| 3873 |
a.add(fast) |
| 3874 |
|
| 3875 |
result = a.notify(body="test") |
| 3876 |
finally: |
| 3877 |
N_MGR.unload_modules() |
| 3878 |
|
| 3879 |
by_host = {r.url: r for r in result} |
| 3880 |
r0 = by_host["slow://slow"] |
| 3881 |
assert r0.status == AppriseResultStatus.TIMEOUT |
| 3882 |
assert r0.start_time is not None |
| 3883 |
assert r0.end_time is not None |
| 3884 |
# Datetime arithmetic can differ from float elapsed by tiny rounding. |
| 3885 |
assert (r0.end_time - r0.start_time).total_seconds() == pytest.approx( |
| 3886 |
r0.elapsed, abs=1e-5 |
| 3887 |
) |
| 3888 |
|
| 3889 |
def test_weight_reflects_service_len(self): |
| 3890 |
"""NotifyResult.weight mirrors len(service) (the plugin's own |
| 3891 |
target count).""" |
| 3892 |
N_MGR["slow"] = _SlowNotify |
| 3893 |
|
| 3894 |
try: |
| 3895 |
asset = AppriseAsset(async_mode=False) |
| 3896 |
service = _SlowNotify(host="x", asset=asset, delay=0.0) |
| 3897 |
a = Apprise(asset=asset) |
| 3898 |
a.add(service) |
| 3899 |
|
| 3900 |
result = a.notify(body="test") |
| 3901 |
finally: |
| 3902 |
N_MGR.unload_modules() |
| 3903 |
|
| 3904 |
# _SlowNotify has no targets/list -- NotifyBase.__len__ always |
| 3905 |
# reports at least 1. |
| 3906 |
assert next(iter(result)).weight == len(service) == 1 |
| 3907 |
|
| 3908 |
def test_log_capture_records_warning_message(self): |
| 3909 |
"""A service WARNING is captured in NotifyResult.logs().""" |
| 3910 |
N_MGR["slow"] = _SlowNotify |
| 3911 |
|
| 3912 |
try: |
| 3913 |
asset = AppriseAsset(async_mode=False) |
| 3914 |
service = _SlowNotify(host="x", asset=asset, delay=0.0) |
| 3915 |
|
| 3916 |
def _fail_with_warning(**kw): |
| 3917 |
"""Emit a warning before reporting a delivery failure.""" |
| 3918 |
service.logger.warning("HTTP 429 Too Many Requests") |
| 3919 |
return False |
| 3920 |
|
| 3921 |
service.send = _fail_with_warning |
| 3922 |
a = Apprise(asset=asset) |
| 3923 |
a.add(service) |
| 3924 |
|
| 3925 |
logging.disable(logging.NOTSET) |
| 3926 |
try: |
| 3927 |
result = a.notify(body="test") |
| 3928 |
finally: |
| 3929 |
logging.disable(logging.CRITICAL) |
| 3930 |
finally: |
| 3931 |
N_MGR.unload_modules() |
| 3932 |
|
| 3933 |
r0 = next(iter(result)) |
| 3934 |
assert r0.status == AppriseResultStatus.FAILURE |
| 3935 |
logs = list(r0.logs()) |
| 3936 |
assert len(logs) == 1 |
| 3937 |
assert logs[0].level == "WARNING" |
| 3938 |
assert "429" in logs[0].message |
| 3939 |
assert "429" in str(logs[0]) |
| 3940 |
|
| 3941 |
def test_log_capture_preserves_preexisting_instance_logger(self): |
| 3942 |
"""_ServiceLogCapture does not replace a service's logger.""" |
| 3943 |
N_MGR["slow"] = _SlowNotify |
| 3944 |
|
| 3945 |
try: |
| 3946 |
asset = AppriseAsset(async_mode=False) |
| 3947 |
service = _SlowNotify(host="x", asset=asset, delay=0.0) |
| 3948 |
custom_logger = logging.getLogger("apprise.test.custom") |
| 3949 |
service.logger = custom_logger |
| 3950 |
|
| 3951 |
a = Apprise(asset=asset) |
| 3952 |
a.add(service) |
| 3953 |
a.notify(body="test") |
| 3954 |
finally: |
| 3955 |
N_MGR.unload_modules() |
| 3956 |
|
| 3957 |
assert "logger" in service.__dict__ |
| 3958 |
assert service.__dict__["logger"] is custom_logger |
| 3959 |
|
| 3960 |
def test_notify_log_callback_default_from_apprise_instance(self): |
| 3961 |
"""A log_callback given to Apprise() applies to every notify() |
| 3962 |
call made with that instance, firing live with (entry, service) |
| 3963 |
for each captured entry.""" |
| 3964 |
N_MGR["slow"] = _SlowNotify |
| 3965 |
received = [] |
| 3966 |
|
| 3967 |
def _cb(entry, service): |
| 3968 |
"""Collect the instance-level callback's service/message pair.""" |
| 3969 |
received.append((service.service_name, entry.message)) |
| 3970 |
|
| 3971 |
try: |
| 3972 |
asset = AppriseAsset(async_mode=False) |
| 3973 |
service = _SlowNotify(host="x", asset=asset, delay=0.0) |
| 3974 |
|
| 3975 |
def _fail_with_warning(**kw): |
| 3976 |
"""Emit a warning and report a failed delivery attempt.""" |
| 3977 |
service.logger.warning("HTTP 429 Too Many Requests") |
| 3978 |
return False |
| 3979 |
|
| 3980 |
service.send = _fail_with_warning |
| 3981 |
a = Apprise(asset=asset, log_callback=_cb) |
| 3982 |
a.add(service) |
| 3983 |
|
| 3984 |
logging.disable(logging.NOTSET) |
| 3985 |
try: |
| 3986 |
a.notify(body="test") |
| 3987 |
finally: |
| 3988 |
logging.disable(logging.CRITICAL) |
| 3989 |
finally: |
| 3990 |
N_MGR.unload_modules() |
| 3991 |
|
| 3992 |
assert received == [ |
| 3993 |
(service.service_name, "HTTP 429 Too Many Requests") |
| 3994 |
] |
| 3995 |
|
| 3996 |
def test_notify_log_callback_call_override(self): |
| 3997 |
"""log_callback passed directly to notify() takes priority over |
| 3998 |
the Apprise instance's own default for that one call only.""" |
| 3999 |
N_MGR["slow"] = _SlowNotify |
| 4000 |
default_received = [] |
| 4001 |
override_received = [] |
| 4002 |
|
| 4003 |
def _default_cb(entry, service): |
| 4004 |
"""Collect entries delivered to the instance default callback.""" |
| 4005 |
default_received.append(entry.message) |
| 4006 |
|
| 4007 |
def _override_cb(entry, service): |
| 4008 |
"""Collect entries delivered to the per-call override callback.""" |
| 4009 |
override_received.append(entry.message) |
| 4010 |
|
| 4011 |
try: |
| 4012 |
asset = AppriseAsset(async_mode=False) |
| 4013 |
service = _SlowNotify(host="x", asset=asset, delay=0.0) |
| 4014 |
|
| 4015 |
def _fail_with_warning(**kw): |
| 4016 |
"""Emit a warning and report a failed delivery attempt.""" |
| 4017 |
service.logger.warning("overridden call") |
| 4018 |
return False |
| 4019 |
|
| 4020 |
service.send = _fail_with_warning |
| 4021 |
a = Apprise(asset=asset, log_callback=_default_cb) |
| 4022 |
a.add(service) |
| 4023 |
|
| 4024 |
logging.disable(logging.NOTSET) |
| 4025 |
try: |
| 4026 |
a.notify(body="test", log_callback=_override_cb) |
| 4027 |
finally: |
| 4028 |
logging.disable(logging.CRITICAL) |
| 4029 |
finally: |
| 4030 |
N_MGR.unload_modules() |
| 4031 |
|
| 4032 |
assert default_received == [] |
| 4033 |
assert override_received == ["overridden call"] |
| 4034 |
|
| 4035 |
def test_notify_log_level_default_is_warning(self): |
| 4036 |
"""Without an explicit log_level, captured entries still stop at |
| 4037 |
WARNING -- INFO chatter from the service is not recorded.""" |
| 4038 |
N_MGR["slow"] = _SlowNotify |
| 4039 |
|
| 4040 |
try: |
| 4041 |
asset = AppriseAsset(async_mode=False) |
| 4042 |
service = _SlowNotify(host="x", asset=asset, delay=0.0) |
| 4043 |
|
| 4044 |
def _info_then_warn(**kw): |
| 4045 |
"""Log at both INFO and WARNING, then report failure.""" |
| 4046 |
service.logger.info("delivery attempt starting") |
| 4047 |
service.logger.warning("HTTP 429 Too Many Requests") |
| 4048 |
return False |
| 4049 |
|
| 4050 |
service.send = _info_then_warn |
| 4051 |
a = Apprise(asset=asset) |
| 4052 |
a.add(service) |
| 4053 |
|
| 4054 |
logging.disable(logging.NOTSET) |
| 4055 |
try: |
| 4056 |
result = a.notify(body="test") |
| 4057 |
finally: |
| 4058 |
logging.disable(logging.CRITICAL) |
| 4059 |
finally: |
| 4060 |
N_MGR.unload_modules() |
| 4061 |
|
| 4062 |
service_result = next(iter(result)) |
| 4063 |
messages = [e.message for e in service_result.logs()] |
| 4064 |
assert messages == ["HTTP 429 Too Many Requests"] |
| 4065 |
|
| 4066 |
def test_notify_callback_defaults_to_info(self): |
| 4067 |
"""A callback raises the default capture level to INFO.""" |
| 4068 |
N_MGR["slow"] = _SlowNotify |
| 4069 |
received = [] |
| 4070 |
|
| 4071 |
def _cb(entry, service): |
| 4072 |
"""Collect every entry the callback actually receives.""" |
| 4073 |
received.append(entry.message) |
| 4074 |
|
| 4075 |
try: |
| 4076 |
asset = AppriseAsset(async_mode=False) |
| 4077 |
service = _SlowNotify(host="x", asset=asset, delay=0.0) |
| 4078 |
|
| 4079 |
def _info_then_warn(**kw): |
| 4080 |
"""Log at both INFO and WARNING, then report failure.""" |
| 4081 |
service.logger.info("delivery attempt starting") |
| 4082 |
service.logger.warning("HTTP 429 Too Many Requests") |
| 4083 |
return False |
| 4084 |
|
| 4085 |
service.send = _info_then_warn |
| 4086 |
a = Apprise(asset=asset, log_callback=_cb) |
| 4087 |
a.add(service) |
| 4088 |
|
| 4089 |
apprise_logger = logging.getLogger("apprise") |
| 4090 |
restore_level = apprise_logger.level |
| 4091 |
apprise_logger.setLevel(logging.INFO) |
| 4092 |
logging.disable(logging.NOTSET) |
| 4093 |
try: |
| 4094 |
result = a.notify(body="test") |
| 4095 |
finally: |
| 4096 |
logging.disable(logging.CRITICAL) |
| 4097 |
apprise_logger.setLevel(restore_level) |
| 4098 |
finally: |
| 4099 |
N_MGR.unload_modules() |
| 4100 |
|
| 4101 |
service_result = next(iter(result)) |
| 4102 |
messages = [e.message for e in service_result.logs()] |
| 4103 |
assert messages == [ |
| 4104 |
"delivery attempt starting", |
| 4105 |
"HTTP 429 Too Many Requests", |
| 4106 |
] |
| 4107 |
assert received == [ |
| 4108 |
"delivery attempt starting", |
| 4109 |
"HTTP 429 Too Many Requests", |
| 4110 |
] |
| 4111 |
|
| 4112 |
def test_notify_explicit_log_level_wins(self): |
| 4113 |
"""An explicit log level overrides the callback default.""" |
| 4114 |
N_MGR["slow"] = _SlowNotify |
| 4115 |
received = [] |
| 4116 |
|
| 4117 |
def _cb(entry, service): |
| 4118 |
"""Collect every entry the callback actually receives.""" |
| 4119 |
received.append(entry.message) |
| 4120 |
|
| 4121 |
try: |
| 4122 |
asset = AppriseAsset(async_mode=False) |
| 4123 |
service = _SlowNotify(host="x", asset=asset, delay=0.0) |
| 4124 |
|
| 4125 |
def _info_then_warn(**kw): |
| 4126 |
"""Log at both INFO and WARNING, then report failure.""" |
| 4127 |
service.logger.info("delivery attempt starting") |
| 4128 |
service.logger.warning("HTTP 429 Too Many Requests") |
| 4129 |
return False |
| 4130 |
|
| 4131 |
service.send = _info_then_warn |
| 4132 |
a = Apprise(asset=asset, log_callback=_cb) |
| 4133 |
a.add(service) |
| 4134 |
|
| 4135 |
logging.disable(logging.NOTSET) |
| 4136 |
try: |
| 4137 |
result = a.notify(body="test", log_level=logging.WARNING) |
| 4138 |
finally: |
| 4139 |
logging.disable(logging.CRITICAL) |
| 4140 |
finally: |
| 4141 |
N_MGR.unload_modules() |
| 4142 |
|
| 4143 |
service_result = next(iter(result)) |
| 4144 |
messages = [e.message for e in service_result.logs()] |
| 4145 |
assert messages == ["HTTP 429 Too Many Requests"] |
| 4146 |
assert received == ["HTTP 429 Too Many Requests"] |
| 4147 |
|
| 4148 |
def test_notify_log_level_call_override(self): |
| 4149 |
"""log_level passed directly to notify() captures finer entries |
| 4150 |
for that one call, overriding the Apprise instance's default.""" |
| 4151 |
N_MGR["slow"] = _SlowNotify |
| 4152 |
|
| 4153 |
try: |
| 4154 |
asset = AppriseAsset(async_mode=False) |
| 4155 |
service = _SlowNotify(host="x", asset=asset, delay=0.0) |
| 4156 |
|
| 4157 |
def _info_then_warn(**kw): |
| 4158 |
"""Log at both INFO and WARNING, then report failure.""" |
| 4159 |
service.logger.info("delivery attempt starting") |
| 4160 |
service.logger.warning("HTTP 429 Too Many Requests") |
| 4161 |
return False |
| 4162 |
|
| 4163 |
service.send = _info_then_warn |
| 4164 |
a = Apprise(asset=asset) |
| 4165 |
a.add(service) |
| 4166 |
|
| 4167 |
# log_level only widens what the capture handler keeps; the |
| 4168 |
# 'apprise' logger's own effective level must independently |
| 4169 |
# permit INFO records through before any handler sees them. |
| 4170 |
apprise_logger = logging.getLogger("apprise") |
| 4171 |
restore_level = apprise_logger.level |
| 4172 |
apprise_logger.setLevel(logging.INFO) |
| 4173 |
logging.disable(logging.NOTSET) |
| 4174 |
try: |
| 4175 |
result = a.notify(body="test", log_level=logging.INFO) |
| 4176 |
finally: |
| 4177 |
logging.disable(logging.CRITICAL) |
| 4178 |
apprise_logger.setLevel(restore_level) |
| 4179 |
finally: |
| 4180 |
N_MGR.unload_modules() |
| 4181 |
|
| 4182 |
service_result = next(iter(result)) |
| 4183 |
messages = [e.message for e in service_result.logs()] |
| 4184 |
assert messages == [ |
| 4185 |
"delivery attempt starting", |
| 4186 |
"HTTP 429 Too Many Requests", |
| 4187 |
] |
| 4188 |
|
| 4189 |
def test_notify_log_level_default_from_apprise_instance(self): |
| 4190 |
"""A log_level given to Apprise() applies to every notify() call |
| 4191 |
made with that instance, the same way log_callback does.""" |
| 4192 |
N_MGR["slow"] = _SlowNotify |
| 4193 |
|
| 4194 |
try: |
| 4195 |
asset = AppriseAsset(async_mode=False) |
| 4196 |
service = _SlowNotify(host="x", asset=asset, delay=0.0) |
| 4197 |
|
| 4198 |
def _info_then_warn(**kw): |
| 4199 |
"""Log at both INFO and WARNING, then report failure.""" |
| 4200 |
service.logger.info("delivery attempt starting") |
| 4201 |
service.logger.warning("HTTP 429 Too Many Requests") |
| 4202 |
return False |
| 4203 |
|
| 4204 |
service.send = _info_then_warn |
| 4205 |
a = Apprise(asset=asset, log_level=logging.INFO) |
| 4206 |
a.add(service) |
| 4207 |
|
| 4208 |
apprise_logger = logging.getLogger("apprise") |
| 4209 |
restore_level = apprise_logger.level |
| 4210 |
apprise_logger.setLevel(logging.INFO) |
| 4211 |
logging.disable(logging.NOTSET) |
| 4212 |
try: |
| 4213 |
result = a.notify(body="test") |
| 4214 |
finally: |
| 4215 |
logging.disable(logging.CRITICAL) |
| 4216 |
apprise_logger.setLevel(restore_level) |
| 4217 |
finally: |
| 4218 |
N_MGR.unload_modules() |
| 4219 |
|
| 4220 |
service_result = next(iter(result)) |
| 4221 |
messages = [e.message for e in service_result.logs()] |
| 4222 |
assert messages == [ |
| 4223 |
"delivery attempt starting", |
| 4224 |
"HTTP 429 Too Many Requests", |
| 4225 |
] |
| 4226 |
|
| 4227 |
def test_async_notify_log_level(self): |
| 4228 |
"""log_level works for a plugin's native async_notify() path.""" |
| 4229 |
N_MGR["slow"] = _SlowNotify |
| 4230 |
|
| 4231 |
try: |
| 4232 |
asset = AppriseAsset(async_mode=True) |
| 4233 |
service = _SlowNotify(host="x", asset=asset, delay=0.0) |
| 4234 |
|
| 4235 |
async def _info_then_warn(**kw): |
| 4236 |
"""Log at both INFO and WARNING, then report failure.""" |
| 4237 |
service.logger.info("async attempt starting") |
| 4238 |
service.logger.warning("async 429") |
| 4239 |
return False |
| 4240 |
|
| 4241 |
service.async_notify = _info_then_warn |
| 4242 |
a = Apprise(asset=asset) |
| 4243 |
a.add(service) |
| 4244 |
|
| 4245 |
apprise_logger = logging.getLogger("apprise") |
| 4246 |
restore_level = apprise_logger.level |
| 4247 |
apprise_logger.setLevel(logging.INFO) |
| 4248 |
logging.disable(logging.NOTSET) |
| 4249 |
try: |
| 4250 |
result = asyncio.run( |
| 4251 |
a.async_notify(body="test", log_level=logging.INFO) |
| 4252 |
) |
| 4253 |
finally: |
| 4254 |
logging.disable(logging.CRITICAL) |
| 4255 |
apprise_logger.setLevel(restore_level) |
| 4256 |
finally: |
| 4257 |
N_MGR.unload_modules() |
| 4258 |
|
| 4259 |
service_result = next(iter(result)) |
| 4260 |
messages = [e.message for e in service_result.logs()] |
| 4261 |
assert messages == ["async attempt starting", "async 429"] |
| 4262 |
|
| 4263 |
def test_async_notify_callback_defaults_to_info(self): |
| 4264 |
"""Async callbacks also default to INFO capture.""" |
| 4265 |
N_MGR["slow"] = _SlowNotify |
| 4266 |
received = [] |
| 4267 |
|
| 4268 |
def _cb(entry, service): |
| 4269 |
"""Collect service entries and ignore orchestration logs.""" |
| 4270 |
if service is not None: |
| 4271 |
received.append(entry.message) |
| 4272 |
|
| 4273 |
try: |
| 4274 |
asset = AppriseAsset(async_mode=True) |
| 4275 |
service = _SlowNotify(host="x", asset=asset, delay=0.0) |
| 4276 |
|
| 4277 |
async def _info_then_warn(**kw): |
| 4278 |
"""Log at both INFO and WARNING, then report failure.""" |
| 4279 |
service.logger.info("async attempt starting") |
| 4280 |
service.logger.warning("async 429") |
| 4281 |
return False |
| 4282 |
|
| 4283 |
service.async_notify = _info_then_warn |
| 4284 |
a = Apprise(asset=asset, log_callback=_cb) |
| 4285 |
a.add(service) |
| 4286 |
|
| 4287 |
apprise_logger = logging.getLogger("apprise") |
| 4288 |
restore_level = apprise_logger.level |
| 4289 |
apprise_logger.setLevel(logging.INFO) |
| 4290 |
logging.disable(logging.NOTSET) |
| 4291 |
try: |
| 4292 |
result = asyncio.run(a.async_notify(body="test")) |
| 4293 |
finally: |
| 4294 |
logging.disable(logging.CRITICAL) |
| 4295 |
apprise_logger.setLevel(restore_level) |
| 4296 |
finally: |
| 4297 |
N_MGR.unload_modules() |
| 4298 |
|
| 4299 |
service_result = next(iter(result)) |
| 4300 |
messages = [e.message for e in service_result.logs()] |
| 4301 |
assert messages == ["async attempt starting", "async 429"] |
| 4302 |
assert received == ["async attempt starting", "async 429"] |
| 4303 |
|
| 4304 |
def test_notify_call_logs_no_services(self): |
| 4305 |
"""Call logs include the warning when no services are loaded.""" |
| 4306 |
a = Apprise() |
| 4307 |
|
| 4308 |
logging.disable(logging.NOTSET) |
| 4309 |
try: |
| 4310 |
result = a.notify(body="test") |
| 4311 |
finally: |
| 4312 |
logging.disable(logging.CRITICAL) |
| 4313 |
|
| 4314 |
assert result.status == AppriseResultStatus.NOMATCH |
| 4315 |
assert any( |
| 4316 |
"no service" in e.message.lower() for e in result.call_logs() |
| 4317 |
) |
| 4318 |
# Merged into the combined timeline too. |
| 4319 |
assert any("no service" in e.message.lower() for e in result.logs()) |
| 4320 |
|
| 4321 |
def test_notify_empty_content_returns_failure(self): |
| 4322 |
"""Invalid empty content returns a failure result without dispatch.""" |
| 4323 |
a = Apprise() |
| 4324 |
a.add(_TestNotify(host="localhost")) |
| 4325 |
|
| 4326 |
result = a.notify(body="") |
| 4327 |
|
| 4328 |
assert result.status == AppriseResultStatus.FAILURE |
| 4329 |
assert len(result) == 0 |
| 4330 |
|
| 4331 |
def test_async_notify_validation_results(self): |
| 4332 |
"""Async validation distinguishes invalid content from no services.""" |
| 4333 |
a = Apprise() |
| 4334 |
a.add(_TestNotify(host="localhost")) |
| 4335 |
|
| 4336 |
invalid = asyncio.run(a.async_notify(body="")) |
| 4337 |
no_services = asyncio.run(Apprise().async_notify(body="test")) |
| 4338 |
|
| 4339 |
assert invalid.status == AppriseResultStatus.FAILURE |
| 4340 |
assert no_services.status == AppriseResultStatus.NOMATCH |
| 4341 |
|
| 4342 |
def test_notify_call_logs_retry_trace(self): |
| 4343 |
"""Call logs include retry details at TRACE level.""" |
| 4344 |
N_MGR["slow"] = _SlowNotify |
| 4345 |
|
| 4346 |
try: |
| 4347 |
asset = AppriseAsset(async_mode=False) |
| 4348 |
service = _SlowNotify(host="x", asset=asset, delay=0.0, retry=1) |
| 4349 |
|
| 4350 |
def _always_fail(**kw): |
| 4351 |
"""Report failure on every attempt.""" |
| 4352 |
return False |
| 4353 |
|
| 4354 |
service.send = _always_fail |
| 4355 |
a = Apprise(asset=asset) |
| 4356 |
a.add(service) |
| 4357 |
|
| 4358 |
apprise_logger = logging.getLogger("apprise") |
| 4359 |
restore_level = apprise_logger.level |
| 4360 |
apprise_logger.setLevel(logging.TRACE) |
| 4361 |
logging.disable(logging.NOTSET) |
| 4362 |
try: |
| 4363 |
result = a.notify(body="test", log_level=logging.TRACE) |
| 4364 |
finally: |
| 4365 |
logging.disable(logging.CRITICAL) |
| 4366 |
apprise_logger.setLevel(restore_level) |
| 4367 |
finally: |
| 4368 |
N_MGR.unload_modules() |
| 4369 |
|
| 4370 |
call_messages = [e.message for e in result.call_logs()] |
| 4371 |
assert any("Starting attempt" in m for m in call_messages) |
| 4372 |
assert any("trying again" in m for m in call_messages) |
| 4373 |
|
| 4374 |
def test_async_notify_call_logs(self): |
| 4375 |
"""Async notifications also collect call-level logs.""" |
| 4376 |
N_MGR["slow"] = _SlowNotify |
| 4377 |
|
| 4378 |
try: |
| 4379 |
asset = AppriseAsset(async_mode=True) |
| 4380 |
service = _SlowNotify(host="x", asset=asset, delay=0.0) |
| 4381 |
|
| 4382 |
async def _fail(**kw): |
| 4383 |
"""Report failure without logging anything itself.""" |
| 4384 |
return False |
| 4385 |
|
| 4386 |
service.async_notify = _fail |
| 4387 |
a = Apprise(asset=asset) |
| 4388 |
a.add(service) |
| 4389 |
|
| 4390 |
apprise_logger = logging.getLogger("apprise") |
| 4391 |
restore_level = apprise_logger.level |
| 4392 |
apprise_logger.setLevel(logging.TRACE) |
| 4393 |
logging.disable(logging.NOTSET) |
| 4394 |
try: |
| 4395 |
result = asyncio.run( |
| 4396 |
a.async_notify(body="test", log_level=logging.TRACE) |
| 4397 |
) |
| 4398 |
finally: |
| 4399 |
logging.disable(logging.CRITICAL) |
| 4400 |
apprise_logger.setLevel(restore_level) |
| 4401 |
finally: |
| 4402 |
N_MGR.unload_modules() |
| 4403 |
|
| 4404 |
call_messages = [e.message for e in result.call_logs()] |
| 4405 |
assert any("Starting attempt" in m for m in call_messages) |
| 4406 |
|
| 4407 |
def test_async_notify_log_callback(self): |
| 4408 |
"""log_callback works for a plugin's native async_notify().""" |
| 4409 |
N_MGR["slow"] = _SlowNotify |
| 4410 |
received = [] |
| 4411 |
|
| 4412 |
def _cb(entry, service): |
| 4413 |
"""Collect callback entries produced by async_notify().""" |
| 4414 |
received.append((service.service_name, entry.message)) |
| 4415 |
|
| 4416 |
try: |
| 4417 |
asset = AppriseAsset(async_mode=True) |
| 4418 |
service = _SlowNotify(host="x", asset=asset, delay=0.0) |
| 4419 |
|
| 4420 |
async def _fail_with_warning(**kw): |
| 4421 |
"""Emit a warning from the native async_notify override.""" |
| 4422 |
service.logger.warning("async 429") |
| 4423 |
return False |
| 4424 |
|
| 4425 |
service.async_notify = _fail_with_warning |
| 4426 |
a = Apprise(asset=asset, log_callback=_cb) |
| 4427 |
a.add(service) |
| 4428 |
|
| 4429 |
logging.disable(logging.NOTSET) |
| 4430 |
try: |
| 4431 |
asyncio.run(a.async_notify(body="test")) |
| 4432 |
finally: |
| 4433 |
logging.disable(logging.CRITICAL) |
| 4434 |
finally: |
| 4435 |
N_MGR.unload_modules() |
| 4436 |
|
| 4437 |
assert received == [(service.service_name, "async 429")] |
| 4438 |
|
| 4439 |
def test_notify_log_callback_thread_attribution(self): |
| 4440 |
"""Concurrent log callbacks are attributed to the right service.""" |
| 4441 |
N_MGR["slow"] = _SlowNotify |
| 4442 |
received = [] |
| 4443 |
lock = threading.Lock() |
| 4444 |
|
| 4445 |
def _cb(entry, service): |
| 4446 |
"""Append callback data under a lock.""" |
| 4447 |
with lock: |
| 4448 |
received.append((service.host, entry.message)) |
| 4449 |
|
| 4450 |
def _make_send(service): |
| 4451 |
"""Build a send() replacement bound to one service instance.""" |
| 4452 |
|
| 4453 |
def _send(**kw): |
| 4454 |
"""Emit a host-specific warning from the bound service.""" |
| 4455 |
service.logger.warning("warning from %s", service.host) |
| 4456 |
return True |
| 4457 |
|
| 4458 |
return _send |
| 4459 |
|
| 4460 |
try: |
| 4461 |
asset = AppriseAsset(async_mode=True) |
| 4462 |
a = Apprise(asset=asset, log_callback=_cb) |
| 4463 |
services = [] |
| 4464 |
for i in range(6): |
| 4465 |
service = _SlowNotify(host=f"host{i}", asset=asset, delay=0.02) |
| 4466 |
service.send = _make_send(service) |
| 4467 |
services.append(service) |
| 4468 |
a.add(service) |
| 4469 |
|
| 4470 |
logging.disable(logging.NOTSET) |
| 4471 |
try: |
| 4472 |
a.notify(body="test") |
| 4473 |
finally: |
| 4474 |
logging.disable(logging.CRITICAL) |
| 4475 |
finally: |
| 4476 |
N_MGR.unload_modules() |
| 4477 |
|
| 4478 |
assert sorted(received) == sorted( |
| 4479 |
(s.host, f"warning from {s.host}") for s in services |
| 4480 |
) |
| 4481 |
|
| 4482 |
def test_timeout_result_defensive_on_malformed_service(self): |
| 4483 |
"""Timeout metadata falls back when service helpers are missing.""" |
| 4484 |
|
| 4485 |
class _MalformedSlowService: |
| 4486 |
"""A service missing url()/url_id()/__len__ that never finishes |
| 4487 |
in time, exercising timeout_result's defensive except paths. |
| 4488 |
""" |
| 4489 |
|
| 4490 |
service_name = "malformed" |
| 4491 |
asset = AppriseAsset(async_mode=True, service_timeout=0.1) |
| 4492 |
optional = False |
| 4493 |
tags: set = set() |
| 4494 |
retry = 0 |
| 4495 |
wait = 0.0 |
| 4496 |
|
| 4497 |
async def async_notify(self, **kwargs): |
| 4498 |
"""Remain active long enough to exceed the test deadline.""" |
| 4499 |
await asyncio.sleep(1.0) |
| 4500 |
return True # pragma: no cover -- never reached in time |
| 4501 |
|
| 4502 |
good = _SlowNotify( |
| 4503 |
host="good", asset=AppriseAsset(async_mode=True), delay=0.0 |
| 4504 |
) |
| 4505 |
malformed = _MalformedSlowService() |
| 4506 |
|
| 4507 |
ok, results = asyncio.run( |
| 4508 |
Apprise._notify_parallel_asyncio( |
| 4509 |
(malformed, {}), |
| 4510 |
(good, {}), |
| 4511 |
) |
| 4512 |
) |
| 4513 |
|
| 4514 |
assert ok is False |
| 4515 |
by_url = {r.url: r for r in results} |
| 4516 |
# No url()/url_id()/__len__ on the malformed service -- defensive |
| 4517 |
# fallbacks kick in rather than raising. |
| 4518 |
assert by_url["unknown://"].status == AppriseResultStatus.TIMEOUT |
| 4519 |
assert by_url["unknown://"].url_id is None |
| 4520 |
assert by_url["unknown://"].weight == 1 |
| 4521 |
assert by_url["slow://good"].status == AppriseResultStatus.SUCCESS |
| 4522 |
|
| 4523 |
def test_notify_result_tag_is_sorted(self): |
| 4524 |
"""NotifyResult.tag is sorted for stable output.""" |
| 4525 |
N_MGR["slow"] = _SlowNotify |
| 4526 |
|
| 4527 |
try: |
| 4528 |
service = _SlowNotify( |
| 4529 |
host="x", |
| 4530 |
asset=AppriseAsset(async_mode=False), |
| 4531 |
delay=0.0, |
| 4532 |
tag=["zeta", "alpha", "middle", "beta"], |
| 4533 |
) |
| 4534 |
a = Apprise() |
| 4535 |
a.add(service) |
| 4536 |
result = a.notify(body="test") |
| 4537 |
finally: |
| 4538 |
N_MGR.unload_modules() |
| 4539 |
|
| 4540 |
r0 = next(iter(result)) |
| 4541 |
assert r0.tag == ("alpha", "beta", "middle", "zeta") |
| 4542 |
|
| 4543 |
def test_threadpool_queued_futures_cancelled(self): |
| 4544 |
"""A service still queued behind other work in a size-limited |
| 4545 |
thread pool must not execute later after timeout.""" |
| 4546 |
N_MGR["slow"] = _SlowNotify |
| 4547 |
|
| 4548 |
# More services than the default ThreadPoolExecutor can run at once, |
| 4549 |
# so some work is guaranteed to still be queued at the deadline. |
| 4550 |
n_services = 40 |
| 4551 |
started: list[int] = [] |
| 4552 |
finished: list[int] = [] |
| 4553 |
lock = threading.Lock() |
| 4554 |
|
| 4555 |
def _slow_send(idx): |
| 4556 |
"""Build a send() replacement that records start and finish.""" |
| 4557 |
|
| 4558 |
def _send(**kwargs): |
| 4559 |
"""Simulate slow work so queued futures can be cancelled.""" |
| 4560 |
with lock: |
| 4561 |
started.append(idx) |
| 4562 |
time.sleep(0.3) |
| 4563 |
with lock: |
| 4564 |
finished.append(idx) |
| 4565 |
return True |
| 4566 |
|
| 4567 |
return _send |
| 4568 |
|
| 4569 |
try: |
| 4570 |
asset = AppriseAsset(async_mode=True, service_timeout=0.05) |
| 4571 |
a = Apprise(asset=asset) |
| 4572 |
services = [] |
| 4573 |
for i in range(n_services): |
| 4574 |
service = _SlowNotify(host=f"host{i}", asset=asset, delay=0.0) |
| 4575 |
service.send = _slow_send(i) |
| 4576 |
services.append(service) |
| 4577 |
a.add(service) |
| 4578 |
|
| 4579 |
result = a.notify(body="test") |
| 4580 |
assert result.status == AppriseResultStatus.TIMEOUT |
| 4581 |
|
| 4582 |
with lock: |
| 4583 |
started_at_return = len(started) |
| 4584 |
|
| 4585 |
# Give uncancelled queued work enough time to reveal itself. |
| 4586 |
time.sleep(1.0) |
| 4587 |
with lock: |
| 4588 |
started_later = len(started) |
| 4589 |
finished_later = len(finished) |
| 4590 |
finally: |
| 4591 |
N_MGR.unload_modules() |
| 4592 |
|
| 4593 |
# Some work stayed queued because the pool is size-limited. |
| 4594 |
assert 0 < started_at_return < n_services |
| 4595 |
# And none of the ones that hadn't started yet ever did. |
| 4596 |
assert started_later == started_at_return |
| 4597 |
assert finished_later == started_at_return |
| 4598 |
|
| 4599 |
def test_sequential_queued_future_cancelled(self): |
| 4600 |
"""A sequential service whose future never got a chance to start |
| 4601 |
(still queued behind other work in a size-limited pool) is |
| 4602 |
cancelled outright at the deadline -- nothing is left running, |
| 4603 |
so it is never tracked as abandoned.""" |
| 4604 |
N_MGR["slow"] = _SlowNotify |
| 4605 |
|
| 4606 |
try: |
| 4607 |
import concurrent.futures as cf |
| 4608 |
|
| 4609 |
import apprise.apprise as apprise_module |
| 4610 |
|
| 4611 |
release = threading.Event() |
| 4612 |
|
| 4613 |
with mock.patch( |
| 4614 |
"apprise.apprise._shared_executor", |
| 4615 |
cf.ThreadPoolExecutor(max_workers=1), |
| 4616 |
): |
| 4617 |
executor = apprise_module._shared_executor |
| 4618 |
# Occupy the pool's only worker so the service's own |
| 4619 |
# future stays queued until its deadline has passed. |
| 4620 |
blocker = executor.submit(release.wait, 2.0) |
| 4621 |
|
| 4622 |
asset = AppriseAsset(async_mode=False, service_timeout=0.05) |
| 4623 |
service = _SlowNotify(host="x", asset=asset, delay=0.0) |
| 4624 |
a = Apprise(asset=asset) |
| 4625 |
a.add(service) |
| 4626 |
|
| 4627 |
result = a.notify(body="test") |
| 4628 |
|
| 4629 |
release.set() |
| 4630 |
blocker.result(timeout=2.0) |
| 4631 |
executor.shutdown(wait=True) |
| 4632 |
finally: |
| 4633 |
N_MGR.unload_modules() |
| 4634 |
|
| 4635 |
assert result.status == AppriseResultStatus.TIMEOUT |
| 4636 |
# Still queued when abandoned -- it never actually got to run. |
| 4637 |
assert service.calls == 0 |
| 4638 |
|
| 4639 |
def test_threadpool_shared_across_notify_calls(self): |
| 4640 |
"""Separate notify() calls reuse the shared executor.""" |
| 4641 |
N_MGR["slow"] = _SlowNotify |
| 4642 |
|
| 4643 |
try: |
| 4644 |
import apprise.apprise as apprise_module |
| 4645 |
|
| 4646 |
# Force this test to observe executor construction. |
| 4647 |
with mock.patch("apprise.apprise._shared_executor", None): |
| 4648 |
executors_seen = set() |
| 4649 |
for i in range(3): |
| 4650 |
asset = AppriseAsset(async_mode=True, service_timeout=0.05) |
| 4651 |
a = Apprise(asset=asset) |
| 4652 |
service = _SlowNotify( |
| 4653 |
host=f"host{i}", asset=asset, delay=1.0 |
| 4654 |
) |
| 4655 |
a.add(service) |
| 4656 |
result = a.notify(body="test") |
| 4657 |
assert result.status == AppriseResultStatus.TIMEOUT |
| 4658 |
executors_seen.add(id(apprise_module._shared_executor)) |
| 4659 |
|
| 4660 |
# All three notify() calls reused the same executor. |
| 4661 |
assert len(executors_seen) == 1 |
| 4662 |
|
| 4663 |
# Clean up the temporary executor before mock.patch restores. |
| 4664 |
apprise_module._shared_executor.shutdown(wait=False) |
| 4665 |
finally: |
| 4666 |
N_MGR.unload_modules() |
| 4667 |
|
| 4668 |
def test_abandoned_calls_reflect_running_state(self): |
| 4669 |
"""Tracked abandoned calls clear once their background work ends.""" |
| 4670 |
import apprise.apprise as apprise_module |
| 4671 |
|
| 4672 |
N_MGR["slow"] = _SlowNotify |
| 4673 |
|
| 4674 |
try: |
| 4675 |
asset = AppriseAsset(async_mode=True, service_timeout=0.05) |
| 4676 |
a = Apprise(asset=asset) |
| 4677 |
service = _SlowNotify(host="host", asset=asset, delay=0.5) |
| 4678 |
a.add(service) |
| 4679 |
|
| 4680 |
result = a.notify(body="test") |
| 4681 |
assert result.status == AppriseResultStatus.TIMEOUT |
| 4682 |
|
| 4683 |
# The 0.5s send() is still running in the background -- |
| 4684 |
# notify() only gave up waiting on it, it did not stop it. |
| 4685 |
assert apprise_module.any_abandoned_calls_still_running() is True |
| 4686 |
|
| 4687 |
# Give it a generous window to actually finish. |
| 4688 |
time.sleep(0.7) |
| 4689 |
assert apprise_module.any_abandoned_calls_still_running() is False |
| 4690 |
finally: |
| 4691 |
N_MGR.unload_modules() |
| 4692 |
|
| 4693 |
def test_abandoned_call_descriptions_clear(self): |
| 4694 |
"""Abandoned-call descriptions clear once the service finishes.""" |
| 4695 |
import apprise.apprise as apprise_module |
| 4696 |
|
| 4697 |
N_MGR["slow"] = _SlowNotify |
| 4698 |
|
| 4699 |
try: |
| 4700 |
asset = AppriseAsset(async_mode=True, service_timeout=0.05) |
| 4701 |
a = Apprise(asset=asset) |
| 4702 |
service = _SlowNotify( |
| 4703 |
host="descriptionhost", asset=asset, delay=0.5 |
| 4704 |
) |
| 4705 |
a.add(service) |
| 4706 |
|
| 4707 |
result = a.notify(body="test") |
| 4708 |
assert result.status == AppriseResultStatus.TIMEOUT |
| 4709 |
|
| 4710 |
descriptions = apprise_module.abandoned_call_descriptions() |
| 4711 |
assert len(descriptions) == 1 |
| 4712 |
assert "slow://descriptionhost" in descriptions[0] |
| 4713 |
|
| 4714 |
# Once the service finishes, its abandoned-call description clears. |
| 4715 |
time.sleep(0.7) |
| 4716 |
assert apprise_module.abandoned_call_descriptions() == [] |
| 4717 |
finally: |
| 4718 |
N_MGR.unload_modules() |
| 4719 |
|
| 4720 |
def test_abandoned_calls_false_when_only_queued(self): |
| 4721 |
"""Cancelled queued work does not count as still running.""" |
| 4722 |
import apprise.apprise as apprise_module |
| 4723 |
|
| 4724 |
N_MGR["slow"] = _SlowNotify |
| 4725 |
|
| 4726 |
n_services = 40 |
| 4727 |
try: |
| 4728 |
asset = AppriseAsset(async_mode=True, service_timeout=0.05) |
| 4729 |
a = Apprise(asset=asset) |
| 4730 |
for i in range(n_services): |
| 4731 |
service = _SlowNotify(host=f"host{i}", asset=asset, delay=0.3) |
| 4732 |
a.add(service) |
| 4733 |
|
| 4734 |
result = a.notify(body="test") |
| 4735 |
assert result.status == AppriseResultStatus.TIMEOUT |
| 4736 |
|
| 4737 |
# Queued futures are cancelled before they ever touch the tracked |
| 4738 |
# abandoned-call list; any running work should settle quickly. |
| 4739 |
time.sleep(0.5) |
| 4740 |
assert apprise_module.any_abandoned_calls_still_running() is False |
| 4741 |
finally: |
| 4742 |
N_MGR.unload_modules() |
| 4743 |
|
| 4744 |
def test_timeout_logged_once(self): |
| 4745 |
"""A service timeout is reported once, not once per capture.""" |
| 4746 |
N_MGR["slow"] = _SlowNotify |
| 4747 |
|
| 4748 |
try: |
| 4749 |
asset = AppriseAsset(async_mode=False) |
| 4750 |
# The delay is well past the limit so the wait always wins. |
| 4751 |
service = _SlowNotify(host="x", asset=asset, delay=2.0) |
| 4752 |
a = Apprise(asset=asset) |
| 4753 |
a.add(service) |
| 4754 |
|
| 4755 |
with apprise_logs_enabled(): |
| 4756 |
result = a.notify(body="test", timeout=0.25) |
| 4757 |
finally: |
| 4758 |
N_MGR.unload_modules() |
| 4759 |
|
| 4760 |
assert result.status == AppriseResultStatus.TIMEOUT |
| 4761 |
|
| 4762 |
timeouts = [ |
| 4763 |
e.message |
| 4764 |
for e in result.logs() |
| 4765 |
if "did not finish within" in e.message |
| 4766 |
] |
| 4767 |
assert len(timeouts) == 1 |
| 4768 |
|
| 4769 |
# The entry belongs to the service attempt. Capturing the logged |
| 4770 |
# copy as well would list the same timeout twice above. |
| 4771 |
assert not [ |
| 4772 |
e |
| 4773 |
for e in result.call_logs() |
| 4774 |
if "did not finish within" in e.message |
| 4775 |
] |
| 4776 |
|
| 4777 |
def test_timeout_reaches_log_callback(self): |
| 4778 |
"""A live callback still sees the timeout the result stores once.""" |
| 4779 |
N_MGR["slow"] = _SlowNotify |
| 4780 |
received = [] |
| 4781 |
|
| 4782 |
try: |
| 4783 |
asset = AppriseAsset(async_mode=False) |
| 4784 |
# The delay is well past the limit so the wait always wins. |
| 4785 |
service = _SlowNotify(host="x", asset=asset, delay=2.0) |
| 4786 |
a = Apprise(asset=asset) |
| 4787 |
a.add(service) |
| 4788 |
|
| 4789 |
with apprise_logs_enabled(): |
| 4790 |
result = a.notify( |
| 4791 |
body="test", |
| 4792 |
timeout=0.25, |
| 4793 |
log_callback=lambda entry, svc: received.append( |
| 4794 |
entry.message |
| 4795 |
), |
| 4796 |
) |
| 4797 |
finally: |
| 4798 |
N_MGR.unload_modules() |
| 4799 |
|
| 4800 |
assert result.status == AppriseResultStatus.TIMEOUT |
| 4801 |
|
| 4802 |
# Delivered live exactly once, and kept exactly once. Suppressing |
| 4803 |
# the stored copy must not cost the callback its notice. |
| 4804 |
stored = [ |
| 4805 |
e for e in result.logs() if "did not finish within" in e.message |
| 4806 |
] |
| 4807 |
delivered = [m for m in received if "did not finish within" in m] |
| 4808 |
assert len(stored) == 1 |
| 4809 |
assert len(delivered) == 1 |
| 4810 |
|
| 4811 |
|
| 4812 |
class _SlowFailNotify(NotifyBase): |
| 4813 |
"""Fails after a configurable delay so deadlines can pass mid-attempt.""" |
| 4814 |
|
| 4815 |
app_id = "SlowFailApp" |
| 4816 |
app_desc = "Test" |
| 4817 |
notify_url = "slowfail://" |
| 4818 |
title_maxlen = 250 |
| 4819 |
body_maxlen = 32768 |
| 4820 |
|
| 4821 |
def __init__(self, delay=0.0, **kwargs): |
| 4822 |
"""Initialize the test plugin with its artificial delay.""" |
| 4823 |
super().__init__(**kwargs) |
| 4824 |
self._delay = delay |
| 4825 |
self.calls = 0 |
| 4826 |
|
| 4827 |
def url(self, *args, **kwargs): |
| 4828 |
"""Return a stable URL containing the test host.""" |
| 4829 |
return "slowfail://{}".format(self.host) |
| 4830 |
|
| 4831 |
def send(self, **kwargs): |
| 4832 |
"""Block for the configured delay, then report failure.""" |
| 4833 |
self.calls += 1 |
| 4834 |
time.sleep(self._delay) |
| 4835 |
return False |
| 4836 |
|
| 4837 |
async def async_notify(self, **kwargs): |
| 4838 |
"""Block for the configured delay, then report failure.""" |
| 4839 |
self.calls += 1 |
| 4840 |
await asyncio.sleep(self._delay) |
| 4841 |
return False |
| 4842 |
|
| 4843 |
@staticmethod |
| 4844 |
def parse_url(url): |
| 4845 |
"""Parse the synthetic URL without requiring a real host.""" |
| 4846 |
return NotifyBase.parse_url(url, verify_host=False) |
| 4847 |
|
| 4848 |
|
| 4849 |
class TestDeadlineExpiresDuringAttempt: |
| 4850 |
"""Deadline-expired retries should stop without sleeping first.""" |
| 4851 |
|
| 4852 |
def test_sequential_abandons_service_that_blocks_past_deadline(self): |
| 4853 |
"""A blocking sync service is abandoned once its deadline passes.""" |
| 4854 |
N_MGR["slowfail"] = _SlowFailNotify |
| 4855 |
|
| 4856 |
try: |
| 4857 |
asset = AppriseAsset(async_mode=False, service_timeout=0.05) |
| 4858 |
service = _SlowFailNotify( |
| 4859 |
host="x", asset=asset, retry=1, wait=1.0, delay=1.0 |
| 4860 |
) |
| 4861 |
a = Apprise(asset=asset) |
| 4862 |
a.add(service) |
| 4863 |
|
| 4864 |
t0 = time.monotonic() |
| 4865 |
result = a.notify(body="test") |
| 4866 |
wall = time.monotonic() - t0 |
| 4867 |
|
| 4868 |
# The result returns nowhere near the full blocking send() |
| 4869 |
# delay -- generous slack here for loaded CI runners, since |
| 4870 |
# only the *relative* gap to the 1.0s delay matters. |
| 4871 |
assert wall < 0.6 |
| 4872 |
assert result.status == AppriseResultStatus.TIMEOUT |
| 4873 |
# The first attempt started, but no retry was launched. |
| 4874 |
assert service.calls == 1 |
| 4875 |
finally: |
| 4876 |
N_MGR.unload_modules() |
| 4877 |
|
| 4878 |
def test_asyncio_skips_wait_when_deadline_already_passed(self): |
| 4879 |
"""Async retry skips its wait once the deadline has passed.""" |
| 4880 |
N_MGR["slowfail"] = _SlowFailNotify |
| 4881 |
|
| 4882 |
try: |
| 4883 |
asset = AppriseAsset(async_mode=True, service_timeout=0.05) |
| 4884 |
service = _SlowFailNotify( |
| 4885 |
host="x", asset=asset, retry=1, wait=1.0, delay=0.08 |
| 4886 |
) |
| 4887 |
a = Apprise(asset=asset) |
| 4888 |
a.add(service) |
| 4889 |
|
| 4890 |
# Keep the delay just above service_timeout so do_call() reaches |
| 4891 |
# its retry check before the outer abandon window takes over. |
| 4892 |
result = asyncio.run(a.async_notify(body="test")) |
| 4893 |
|
| 4894 |
assert result.status == AppriseResultStatus.FAILURE |
| 4895 |
assert service.calls == 1 |
| 4896 |
finally: |
| 4897 |
N_MGR.unload_modules() |
| 4898 |
|
| 4899 |
|
| 4900 |
class _SlowThreadedNotify(NotifyBase): |
| 4901 |
"""Test the default async wrapper around a synchronous send.""" |
| 4902 |
|
| 4903 |
app_id = "SlowThreadedApp" |
| 4904 |
app_desc = "Test" |
| 4905 |
notify_url = "slowthreaded://" |
| 4906 |
title_maxlen = 250 |
| 4907 |
body_maxlen = 32768 |
| 4908 |
|
| 4909 |
def __init__(self, delay=0.0, **kwargs): |
| 4910 |
"""Initialize the test plugin with its artificial delay.""" |
| 4911 |
super().__init__(**kwargs) |
| 4912 |
self._delay = delay |
| 4913 |
self.calls = 0 |
| 4914 |
|
| 4915 |
def url(self, *args, **kwargs): |
| 4916 |
"""Return a stable URL containing the test host.""" |
| 4917 |
return "slowthreaded://{}".format(self.host) |
| 4918 |
|
| 4919 |
def send(self, **kwargs): |
| 4920 |
"""Block the calling (executor) thread for the configured delay.""" |
| 4921 |
self.calls += 1 |
| 4922 |
time.sleep(self._delay) |
| 4923 |
return True |
| 4924 |
|
| 4925 |
@staticmethod |
| 4926 |
def parse_url(url): |
| 4927 |
"""Parse the synthetic URL without requiring a real host.""" |
| 4928 |
return NotifyBase.parse_url(url, verify_host=False) |
| 4929 |
|
| 4930 |
|
| 4931 |
class TestAsyncAbandonedCallTracking: |
| 4932 |
"""Track timed-out sends while their worker threads are still running.""" |
| 4933 |
|
| 4934 |
def test_abandoned_async_call_is_tracked_until_it_finishes(self): |
| 4935 |
"""A timed-out send stays tracked until its worker finishes.""" |
| 4936 |
import apprise.apprise as apprise_module |
| 4937 |
|
| 4938 |
N_MGR["slowthreaded"] = _SlowThreadedNotify |
| 4939 |
|
| 4940 |
try: |
| 4941 |
asset = AppriseAsset(async_mode=True, service_timeout=0.05) |
| 4942 |
service = _SlowThreadedNotify(host="x", asset=asset, delay=0.3) |
| 4943 |
a = Apprise(asset=asset) |
| 4944 |
a.add(service) |
| 4945 |
|
| 4946 |
result = asyncio.run(a.async_notify(body="test")) |
| 4947 |
assert result.status == AppriseResultStatus.TIMEOUT |
| 4948 |
|
| 4949 |
# The sleeping worker remains visible after the timeout. |
| 4950 |
assert apprise_module.any_abandoned_calls_still_running() is True |
| 4951 |
descriptions = apprise_module.abandoned_call_descriptions() |
| 4952 |
assert any("x" in d or "slowthreaded" in d for d in descriptions) |
| 4953 |
|
| 4954 |
# Once the real delay elapses, it drops out of the list. |
| 4955 |
deadline = time.monotonic() + 2.0 |
| 4956 |
while ( |
| 4957 |
apprise_module.any_abandoned_calls_still_running() |
| 4958 |
and time.monotonic() < deadline |
| 4959 |
): |
| 4960 |
time.sleep(0.02) |
| 4961 |
assert apprise_module.any_abandoned_calls_still_running() is False |
| 4962 |
assert service.calls == 1 |
| 4963 |
finally: |
| 4964 |
N_MGR.unload_modules() |
| 4965 |
|
| 4966 |
def test_queued_call_not_yet_running_is_not_tracked(self): |
| 4967 |
"""A cancelled send that never started is not tracked.""" |
| 4968 |
import concurrent.futures as cf |
| 4969 |
|
| 4970 |
import apprise.apprise as apprise_module |
| 4971 |
|
| 4972 |
N_MGR["slowthreaded"] = _SlowThreadedNotify |
| 4973 |
|
| 4974 |
busy_executor = cf.ThreadPoolExecutor(max_workers=1) |
| 4975 |
block_event = threading.Event() |
| 4976 |
filler = busy_executor.submit(block_event.wait, 5) |
| 4977 |
|
| 4978 |
try: |
| 4979 |
with mock.patch( |
| 4980 |
"apprise.apprise.get_shared_executor", |
| 4981 |
return_value=busy_executor, |
| 4982 |
): |
| 4983 |
asset = AppriseAsset(async_mode=True, service_timeout=0.05) |
| 4984 |
service = _SlowThreadedNotify(host="x", asset=asset) |
| 4985 |
a = Apprise(asset=asset) |
| 4986 |
a.add(service) |
| 4987 |
|
| 4988 |
result = asyncio.run(a.async_notify(body="test")) |
| 4989 |
assert result.status == AppriseResultStatus.TIMEOUT |
| 4990 |
|
| 4991 |
# The queued call never started, so it is not abandoned work. |
| 4992 |
assert apprise_module.any_abandoned_calls_still_running() is False |
| 4993 |
assert service.calls == 0 |
| 4994 |
finally: |
| 4995 |
block_event.set() |
| 4996 |
filler.result(timeout=5) |
| 4997 |
busy_executor.shutdown(wait=True) |
| 4998 |
N_MGR.unload_modules() |
| 4999 |
|
| 5000 |
|
| 5001 |
class TestSharedExecutorRace: |
| 5002 |
"""get_shared_executor() must reuse an executor created during locking.""" |
| 5003 |
|
| 5004 |
def test_inner_check_skips_creation_if_already_set(self): |
| 5005 |
"""The inner lock check returns the executor another thread created.""" |
| 5006 |
import apprise.apprise as apprise_module |
| 5007 |
|
| 5008 |
sentinel = mock.Mock(name="already-created-executor") |
| 5009 |
|
| 5010 |
class _RaceLock: |
| 5011 |
"""Simulate another thread creating the executor first.""" |
| 5012 |
|
| 5013 |
def __enter__(self): |
| 5014 |
apprise_module._shared_executor = sentinel |
| 5015 |
return self |
| 5016 |
|
| 5017 |
def __exit__(self, *exc): |
| 5018 |
return False |
| 5019 |
|
| 5020 |
with ( |
| 5021 |
mock.patch("apprise.apprise._shared_executor", None), |
| 5022 |
mock.patch("apprise.apprise._shared_executor_lock", _RaceLock()), |
| 5023 |
mock.patch("apprise.apprise.cf.ThreadPoolExecutor") as mock_pool, |
| 5024 |
): |
| 5025 |
result = apprise_module.get_shared_executor() |
| 5026 |
|
| 5027 |
assert result is sentinel |
| 5028 |
mock_pool.assert_not_called() |
| 5029 |
|
| 5030 |
def test_coordinator_inner_check_skips_creation_if_already_set(self): |
| 5031 |
"""Same race-safety guarantee for the coordinator pool.""" |
| 5032 |
import apprise.apprise as apprise_module |
| 5033 |
|
| 5034 |
sentinel = mock.Mock(name="already-created-coordinator-executor") |
| 5035 |
|
| 5036 |
class _RaceLock: |
| 5037 |
"""Simulate another thread creating the executor first.""" |
| 5038 |
|
| 5039 |
def __enter__(self): |
| 5040 |
apprise_module._coordinator_executor = sentinel |
| 5041 |
return self |
| 5042 |
|
| 5043 |
def __exit__(self, *exc): |
| 5044 |
return False |
| 5045 |
|
| 5046 |
with ( |
| 5047 |
mock.patch("apprise.apprise._coordinator_executor", None), |
| 5048 |
mock.patch( |
| 5049 |
"apprise.apprise._coordinator_executor_lock", _RaceLock() |
| 5050 |
), |
| 5051 |
mock.patch("apprise.apprise.cf.ThreadPoolExecutor") as mock_pool, |
| 5052 |
): |
| 5053 |
result = apprise_module.get_coordinator_executor() |
| 5054 |
|
| 5055 |
assert result is sentinel |
| 5056 |
mock_pool.assert_not_called() |
| 5057 |
|
| 5058 |
|
| 5059 |
class TestCoordinatorLeafPoolSeparation: |
| 5060 |
"""Keep coordinators separate from the service calls they await. |
| 5061 |
|
| 5062 |
Single-worker pools make starvation failures deterministic. |
| 5063 |
""" |
| 5064 |
|
| 5065 |
def test_multiple_chains_do_not_starve_their_own_leaf_calls(self): |
| 5066 |
"""Multiple tag chains succeed with one worker in each pool.""" |
| 5067 |
import concurrent.futures as cf |
| 5068 |
|
| 5069 |
import apprise.apprise as apprise_module |
| 5070 |
|
| 5071 |
N_MGR["failpass"] = _FailThenSucceedNotify |
| 5072 |
|
| 5073 |
try: |
| 5074 |
# A finite deadline turns starvation into a test failure. |
| 5075 |
asset = AppriseAsset(async_mode=False, service_timeout=5) |
| 5076 |
|
| 5077 |
s_devops = _FailThenSucceedNotify( |
| 5078 |
host="devops", asset=asset, fail_times=0 |
| 5079 |
) |
| 5080 |
s_devops.tags = {"devops"} |
| 5081 |
|
| 5082 |
s_mgmt = _FailThenSucceedNotify( |
| 5083 |
host="mgmt", asset=asset, fail_times=0 |
| 5084 |
) |
| 5085 |
s_mgmt.tags = {"management"} |
| 5086 |
|
| 5087 |
a = Apprise(asset=asset) |
| 5088 |
a.add(s_devops) |
| 5089 |
a.add(s_mgmt) |
| 5090 |
|
| 5091 |
with ( |
| 5092 |
mock.patch( |
| 5093 |
"apprise.apprise._shared_executor", |
| 5094 |
cf.ThreadPoolExecutor(max_workers=1), |
| 5095 |
), |
| 5096 |
mock.patch( |
| 5097 |
"apprise.apprise._coordinator_executor", |
| 5098 |
cf.ThreadPoolExecutor(max_workers=1), |
| 5099 |
), |
| 5100 |
): |
| 5101 |
# Distinct OR tags exercise the multiple-chain path. |
| 5102 |
result = a.notify(body="test", tag="devops management") |
| 5103 |
|
| 5104 |
assert bool(result) is True |
| 5105 |
assert s_devops._calls == 1 |
| 5106 |
assert s_mgmt._calls == 1 |
| 5107 |
finally: |
| 5108 |
N_MGR.unload_modules() |
| 5109 |
apprise_module._shared_executor = None |
| 5110 |
apprise_module._coordinator_executor = None |
| 5111 |
|
| 5112 |
def test_async_sequential_batch_does_not_starve_itself(self): |
| 5113 |
"""Async dispatch can still run its blocking service batch.""" |
| 5114 |
import concurrent.futures as cf |
| 5115 |
|
| 5116 |
import apprise.apprise as apprise_module |
| 5117 |
|
| 5118 |
# A synchronous service exercises the coordinator-backed blocking path. |
| 5119 |
asset = AppriseAsset(async_mode=False, service_timeout=5) |
| 5120 |
service = _FailThenSucceedNotify( |
| 5121 |
host="solo", asset=asset, fail_times=0 |
| 5122 |
) |
| 5123 |
|
| 5124 |
async def run(): |
| 5125 |
return await Apprise._split_and_dispatch_async( |
| 5126 |
[(service, {"body": "test"})] |
| 5127 |
) |
| 5128 |
|
| 5129 |
with ( |
| 5130 |
mock.patch( |
| 5131 |
"apprise.apprise._shared_executor", |
| 5132 |
cf.ThreadPoolExecutor(max_workers=1), |
| 5133 |
), |
| 5134 |
mock.patch( |
| 5135 |
"apprise.apprise._coordinator_executor", |
| 5136 |
cf.ThreadPoolExecutor(max_workers=1), |
| 5137 |
), |
| 5138 |
): |
| 5139 |
ok, _results = asyncio.run(run()) |
| 5140 |
|
| 5141 |
assert ok is True |
| 5142 |
assert service._calls == 1 |
| 5143 |
|
| 5144 |
apprise_module._shared_executor = None |
| 5145 |
apprise_module._coordinator_executor = None |