| 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 logging |
| 29 |
import re |
| 30 |
import ssl |
| 31 |
import sys |
| 32 |
from unittest.mock import ANY, Mock, call |
| 33 |
|
| 34 |
import pytest |
| 35 |
|
| 36 |
import apprise |
| 37 |
from apprise.exception import AppriseImproperlyConfigured |
| 38 |
from apprise.plugins.mqtt import NotifyMQTT |
| 39 |
|
| 40 |
# Disable logging for a cleaner testing output |
| 41 |
logging.disable(logging.CRITICAL) |
| 42 |
|
| 43 |
|
| 44 |
@pytest.fixture |
| 45 |
def mqtt_client_mock(mocker): |
| 46 |
"""Mocks an MQTT client and response and returns the mocked client.""" |
| 47 |
|
| 48 |
if "paho" not in sys.modules: |
| 49 |
raise pytest.skip("Requires that `paho-mqtt` is installed") |
| 50 |
|
| 51 |
# Establish mock of the `publish()` response object. |
| 52 |
publish_result = Mock( |
| 53 |
**{ |
| 54 |
"rc": 0, |
| 55 |
"is_published.return_value": True, |
| 56 |
} |
| 57 |
) |
| 58 |
|
| 59 |
# Establish mock of the `Client()` object. |
| 60 |
mock_client = Mock( |
| 61 |
**{ |
| 62 |
"connect.return_value": 0, |
| 63 |
"reconnect.return_value": 0, |
| 64 |
"is_connected.return_value": True, |
| 65 |
"publish.return_value": publish_result, |
| 66 |
} |
| 67 |
) |
| 68 |
mocker.patch("paho.mqtt.client.Client", return_value=mock_client) |
| 69 |
|
| 70 |
return mock_client |
| 71 |
|
| 72 |
|
| 73 |
@pytest.mark.skipif( |
| 74 |
"paho" in sys.modules, reason="Requires that `paho-mqtt` is NOT installed" |
| 75 |
) |
| 76 |
def test_plugin_mqtt_paho_import_error(): |
| 77 |
"""Verify `NotifyMQTT` is disabled when `paho.mqtt.client` fails |
| 78 |
loading.""" |
| 79 |
|
| 80 |
# without the library, the object can't be instantiated |
| 81 |
obj = apprise.Apprise.instantiate("mqtt://user:pass@localhost/my/topic") |
| 82 |
assert obj is None |
| 83 |
|
| 84 |
|
| 85 |
def test_plugin_mqtt_default_success(mqtt_client_mock): |
| 86 |
"""Verify `NotifyMQTT` succeeds and has appropriate default settings.""" |
| 87 |
|
| 88 |
# Instantiate the notifier. |
| 89 |
obj = apprise.Apprise.instantiate( |
| 90 |
"mqtt://localhost:1234/my/topic", suppress_exceptions=False |
| 91 |
) |
| 92 |
assert isinstance(obj, NotifyMQTT) |
| 93 |
# We only loaded 1 topic |
| 94 |
assert len(obj) == 1 |
| 95 |
assert obj.url().startswith("mqtt://localhost:1234/my/topic") |
| 96 |
|
| 97 |
# Genrate the URL Identifier |
| 98 |
assert isinstance(obj.url_id(), str) |
| 99 |
|
| 100 |
# Verify default settings. |
| 101 |
assert r"qos=0" in obj.url() |
| 102 |
assert re.search(r"version=v3.1.1", obj.url()) |
| 103 |
assert r"session=no" in obj.url() |
| 104 |
assert r"client_id=" not in obj.url() |
| 105 |
|
| 106 |
# Verify notification succeeds. |
| 107 |
assert bool(obj.notify(body="test=test")) is True |
| 108 |
|
| 109 |
# Send another notification (a new connection isn't attempted to be |
| 110 |
# established as one already exists) |
| 111 |
assert bool(obj.notify(body="foo=bar")) is True |
| 112 |
|
| 113 |
# Verify the right calls have been made to the MQTT client object. |
| 114 |
assert mqtt_client_mock.mock_calls == [ |
| 115 |
call.max_inflight_messages_set(200), |
| 116 |
call.connect("localhost", port=1234, keepalive=30), |
| 117 |
call.loop_start(), |
| 118 |
call.is_connected(), |
| 119 |
call.publish("my/topic", payload="test=test", qos=0, retain=False), |
| 120 |
call.publish().is_published(), |
| 121 |
call.is_connected(), |
| 122 |
call.publish("my/topic", payload="foo=bar", qos=0, retain=False), |
| 123 |
call.publish().is_published(), |
| 124 |
] |
| 125 |
|
| 126 |
|
| 127 |
def test_plugin_mqtt_multiple_topics_success(mqtt_client_mock): |
| 128 |
"""Verify submission to multiple MQTT topics.""" |
| 129 |
|
| 130 |
# Designate multiple topic targets. |
| 131 |
obj = apprise.Apprise.instantiate( |
| 132 |
"mqtt://localhost/my/topic,my/other/topic", suppress_exceptions=False |
| 133 |
) |
| 134 |
|
| 135 |
# Verify we have loaded 2 topics |
| 136 |
assert len(obj) == 2 |
| 137 |
|
| 138 |
assert isinstance(obj, NotifyMQTT) |
| 139 |
assert obj.url().startswith("mqtt://localhost") |
| 140 |
assert r"my/topic" in obj.url() |
| 141 |
assert r"my/other/topic" in obj.url() |
| 142 |
assert bool(obj.notify(body="test=test")) is True |
| 143 |
|
| 144 |
# Verify the right calls have been made to the MQTT client object. |
| 145 |
assert mqtt_client_mock.mock_calls == [ |
| 146 |
call.max_inflight_messages_set(200), |
| 147 |
call.connect("localhost", port=1883, keepalive=30), |
| 148 |
call.loop_start(), |
| 149 |
call.is_connected(), |
| 150 |
call.publish("my/topic", payload="test=test", qos=0, retain=False), |
| 151 |
call.publish().is_published(), |
| 152 |
call.is_connected(), |
| 153 |
call.publish( |
| 154 |
"my/other/topic", payload="test=test", qos=0, retain=False |
| 155 |
), |
| 156 |
call.publish().is_published(), |
| 157 |
] |
| 158 |
|
| 159 |
|
| 160 |
def test_plugin_mqtt_to_success(mqtt_client_mock): |
| 161 |
"""Verify `NotifyMQTT` succeeds with the `to=` parameter.""" |
| 162 |
|
| 163 |
# Leverage the `to=` argument to identify the topic. |
| 164 |
obj = apprise.Apprise.instantiate( |
| 165 |
"mqtt://localhost?to=my/topic", suppress_exceptions=False |
| 166 |
) |
| 167 |
assert isinstance(obj, NotifyMQTT) |
| 168 |
assert obj.url().startswith("mqtt://localhost/my/topic") |
| 169 |
|
| 170 |
# Verify default settings. |
| 171 |
assert r"qos=0" in obj.url() |
| 172 |
assert re.search(r"version=v3.1.1", obj.url()) |
| 173 |
|
| 174 |
# Verify notification succeeds. |
| 175 |
assert bool(obj.notify(body="test=test")) is True |
| 176 |
|
| 177 |
|
| 178 |
def test_plugin_mqtt_valid_settings_success(mqtt_client_mock): |
| 179 |
"""Verify settings as URL parameters will be accepted.""" |
| 180 |
|
| 181 |
# Instantiate the notifier. |
| 182 |
obj = apprise.Apprise.instantiate( |
| 183 |
"mqtt://localhost/my/topic?qos=1&version=v3.1", |
| 184 |
suppress_exceptions=False, |
| 185 |
) |
| 186 |
|
| 187 |
assert isinstance(obj, NotifyMQTT) |
| 188 |
assert obj.url().startswith("mqtt://localhost") |
| 189 |
assert r"qos=1" in obj.url() |
| 190 |
assert re.search(r"version=v3.1", obj.url()) |
| 191 |
|
| 192 |
|
| 193 |
def test_plugin_mqtt_invalid_settings_failure(mqtt_client_mock): |
| 194 |
"""Verify notifier instantiation croaks on invalid settings.""" |
| 195 |
|
| 196 |
# Test case for invalid/unsupported MQTT version. |
| 197 |
with pytest.raises(AppriseImproperlyConfigured): |
| 198 |
apprise.Apprise.instantiate( |
| 199 |
"mqtt://localhost?version=v1.0.0.0", suppress_exceptions=False |
| 200 |
) |
| 201 |
|
| 202 |
# Test case for invalid/unsupported `qos`. |
| 203 |
with pytest.raises(AppriseImproperlyConfigured): |
| 204 |
apprise.Apprise.instantiate( |
| 205 |
"mqtt://localhost?qos=123", suppress_exceptions=False |
| 206 |
) |
| 207 |
|
| 208 |
with pytest.raises(AppriseImproperlyConfigured): |
| 209 |
apprise.Apprise.instantiate( |
| 210 |
"mqtt://localhost?qos=invalid", suppress_exceptions=False |
| 211 |
) |
| 212 |
|
| 213 |
|
| 214 |
def test_plugin_mqtt_bad_url_failure(mqtt_client_mock): |
| 215 |
"""Verify notifier is disabled when using an invalid URL.""" |
| 216 |
obj = apprise.Apprise.instantiate("mqtt://", suppress_exceptions=False) |
| 217 |
assert obj is None |
| 218 |
|
| 219 |
|
| 220 |
def test_plugin_mqtt_no_topic_failure(mqtt_client_mock): |
| 221 |
"""Verify notification fails when no topic is given.""" |
| 222 |
obj = apprise.Apprise.instantiate( |
| 223 |
"mqtt://localhost", suppress_exceptions=False |
| 224 |
) |
| 225 |
assert isinstance(obj, NotifyMQTT) |
| 226 |
assert bool(obj.notify(body="test=test")) is False |
| 227 |
|
| 228 |
|
| 229 |
def test_plugin_mqtt_tls_connect_success(mqtt_client_mock): |
| 230 |
"""Verify TLS encrypted connections work.""" |
| 231 |
|
| 232 |
obj = apprise.Apprise.instantiate( |
| 233 |
"mqtts://user:pass@localhost/my/topic", suppress_exceptions=False |
| 234 |
) |
| 235 |
assert isinstance(obj, NotifyMQTT) |
| 236 |
assert obj.url().startswith("mqtts://user:pass@localhost/my/topic") |
| 237 |
assert bool(obj.notify(body="test=test")) is True |
| 238 |
|
| 239 |
# Verify the right calls have been made to the MQTT client object. |
| 240 |
assert mqtt_client_mock.mock_calls == [ |
| 241 |
call.max_inflight_messages_set(200), |
| 242 |
call.username_pw_set("user", password="pass"), |
| 243 |
call.tls_set( |
| 244 |
ca_certs=ANY, |
| 245 |
certfile=None, |
| 246 |
keyfile=None, |
| 247 |
cert_reqs=ssl.VerifyMode.CERT_REQUIRED, |
| 248 |
tls_version=ssl.PROTOCOL_TLS, |
| 249 |
ciphers=None, |
| 250 |
), |
| 251 |
call.tls_insecure_set(False), |
| 252 |
call.connect("localhost", port=8883, keepalive=30), |
| 253 |
call.loop_start(), |
| 254 |
call.is_connected(), |
| 255 |
call.publish("my/topic", payload="test=test", qos=0, retain=False), |
| 256 |
call.publish().is_published(), |
| 257 |
] |
| 258 |
|
| 259 |
|
| 260 |
def test_plugin_mqtt_tls_no_certificates_failure(mqtt_client_mock, mocker): |
| 261 |
"""Verify TLS does not work without access to CA root certificates.""" |
| 262 |
|
| 263 |
# Clear CA certificates. |
| 264 |
mocker.patch.object(NotifyMQTT, "CA_CERTIFICATE_FILE_LOCATIONS", []) |
| 265 |
|
| 266 |
obj = apprise.Apprise.instantiate( |
| 267 |
"mqtts://user:pass@localhost/my/topic", suppress_exceptions=False |
| 268 |
) |
| 269 |
assert isinstance(obj, NotifyMQTT) |
| 270 |
|
| 271 |
logger: Mock = mocker.spy(obj, "logger") |
| 272 |
|
| 273 |
# Verify notification fails w/o CA certificates. |
| 274 |
assert bool(obj.notify(body="test=test")) is False |
| 275 |
|
| 276 |
assert logger.mock_calls == [ |
| 277 |
call.error( |
| 278 |
"MQTT secure communication can not be verified, " |
| 279 |
"CA certificates file missing" |
| 280 |
), |
| 281 |
call.debug("%s send() completed in %.2fs.", ANY, ANY), |
| 282 |
] |
| 283 |
|
| 284 |
|
| 285 |
def test_plugin_mqtt_tls_no_verify_success(mqtt_client_mock): |
| 286 |
"""Verify TLS encrypted connections work with `verify=False`.""" |
| 287 |
|
| 288 |
# A single user (not password) + no verifying of host |
| 289 |
obj = apprise.Apprise.instantiate( |
| 290 |
"mqtts://user:pass@localhost/my/topic?verify=False", |
| 291 |
suppress_exceptions=False, |
| 292 |
) |
| 293 |
assert isinstance(obj, NotifyMQTT) |
| 294 |
assert bool(obj.notify(body="test=test")) is True |
| 295 |
|
| 296 |
# Chain validation must be disabled via CERT_NONE (not just hostname |
| 297 |
# skipping via tls_insecure_set) so self-signed certs are accepted. |
| 298 |
assert ( |
| 299 |
call.tls_set( |
| 300 |
ca_certs=None, |
| 301 |
certfile=None, |
| 302 |
keyfile=None, |
| 303 |
cert_reqs=ssl.CERT_NONE, |
| 304 |
tls_version=ssl.PROTOCOL_TLS, |
| 305 |
ciphers=None, |
| 306 |
) |
| 307 |
in mqtt_client_mock.mock_calls |
| 308 |
) |
| 309 |
assert call.tls_insecure_set(True) in mqtt_client_mock.mock_calls |
| 310 |
|
| 311 |
|
| 312 |
def test_plugin_mqtt_tls_no_verify_no_ca_success(mqtt_client_mock, mocker): |
| 313 |
"""Verify TLS with verify=False succeeds without CA certificates.""" |
| 314 |
|
| 315 |
# Clear CA certificates -- with verify=False this should not block us |
| 316 |
mocker.patch.object(NotifyMQTT, "CA_CERTIFICATE_FILE_LOCATIONS", []) |
| 317 |
|
| 318 |
obj = apprise.Apprise.instantiate( |
| 319 |
"mqtts://user:pass@localhost/my/topic?verify=False", |
| 320 |
suppress_exceptions=False, |
| 321 |
) |
| 322 |
assert isinstance(obj, NotifyMQTT) |
| 323 |
|
| 324 |
# Should succeed without CA certificates when verify is disabled |
| 325 |
assert bool(obj.notify(body="test=test")) is True |
| 326 |
|
| 327 |
assert ( |
| 328 |
call.tls_set( |
| 329 |
ca_certs=None, |
| 330 |
certfile=None, |
| 331 |
keyfile=None, |
| 332 |
cert_reqs=ssl.CERT_NONE, |
| 333 |
tls_version=ssl.PROTOCOL_TLS, |
| 334 |
ciphers=None, |
| 335 |
) |
| 336 |
in mqtt_client_mock.mock_calls |
| 337 |
) |
| 338 |
|
| 339 |
|
| 340 |
def test_plugin_mqtt_session_client_id_success(mqtt_client_mock): |
| 341 |
"""Verify handling `session=yes` and `client_id=` works.""" |
| 342 |
|
| 343 |
obj = apprise.Apprise.instantiate( |
| 344 |
"mqtt://user@localhost/my/topic?session=yes&client_id=apprise", |
| 345 |
suppress_exceptions=False, |
| 346 |
) |
| 347 |
|
| 348 |
assert isinstance(obj, NotifyMQTT) |
| 349 |
assert obj.url().startswith("mqtt://user@localhost") |
| 350 |
assert r"my/topic" in obj.url() |
| 351 |
assert r"client_id=apprise" in obj.url() |
| 352 |
assert r"session=yes" in obj.url() |
| 353 |
assert r"retain=no" in obj.url() |
| 354 |
assert bool(obj.notify(body="test=test")) is True |
| 355 |
|
| 356 |
|
| 357 |
def test_plugin_mqtt_retain(mqtt_client_mock): |
| 358 |
"""Verify handling of Retain Message Flag.""" |
| 359 |
|
| 360 |
obj = apprise.Apprise.instantiate( |
| 361 |
"mqtt://user@localhost/my/topic?retain=yes", suppress_exceptions=False |
| 362 |
) |
| 363 |
|
| 364 |
assert isinstance(obj, NotifyMQTT) |
| 365 |
assert obj.url().startswith("mqtt://user@localhost") |
| 366 |
assert r"my/topic" in obj.url() |
| 367 |
assert r"session=no" in obj.url() |
| 368 |
assert r"retain=yes" in obj.url() |
| 369 |
assert bool(obj.notify(body="test=test")) is True |
| 370 |
|
| 371 |
|
| 372 |
def test_plugin_mqtt_connect_failure(mqtt_client_mock): |
| 373 |
"""Verify `NotifyMQTT` fails when MQTT `connect()` fails.""" |
| 374 |
|
| 375 |
# Emulate a situation where the `connect()` method fails. |
| 376 |
mqtt_client_mock.connect.return_value = 2 |
| 377 |
|
| 378 |
obj = apprise.Apprise.instantiate( |
| 379 |
"mqtt://localhost/my/topic", suppress_exceptions=False |
| 380 |
) |
| 381 |
|
| 382 |
# Verify notification fails. |
| 383 |
assert bool(obj.notify(body="test=test")) is False |
| 384 |
|
| 385 |
|
| 386 |
def test_plugin_mqtt_reconnect_failure(mqtt_client_mock): |
| 387 |
"""Verify `NotifyMQTT` fails when MQTT `reconnect()` fails.""" |
| 388 |
|
| 389 |
# Emulate a situation where MQTT reconnect fails. |
| 390 |
mqtt_client_mock.reconnect.return_value = 2 |
| 391 |
mqtt_client_mock.is_connected.return_value = False |
| 392 |
|
| 393 |
obj = apprise.Apprise.instantiate( |
| 394 |
"mqtt://localhost/my/topic", suppress_exceptions=False |
| 395 |
) |
| 396 |
|
| 397 |
# Verify notification fails. |
| 398 |
assert bool(obj.notify(body="test=test")) is False |
| 399 |
|
| 400 |
|
| 401 |
def test_plugin_mqtt_publish_failure(mqtt_client_mock): |
| 402 |
"""Verify `NotifyMQTT` fails when MQTT `publish()` fails.""" |
| 403 |
|
| 404 |
# Emulate a situation where the `publish()` method fails. |
| 405 |
mqtt_response = mqtt_client_mock.publish.return_value |
| 406 |
mqtt_response.rc = 2 |
| 407 |
|
| 408 |
obj = apprise.Apprise.instantiate( |
| 409 |
"mqtt://localhost/my/topic", suppress_exceptions=False |
| 410 |
) |
| 411 |
|
| 412 |
# Verify notification fails. |
| 413 |
assert bool(obj.notify(body="test=test")) is False |
| 414 |
|
| 415 |
|
| 416 |
def test_plugin_mqtt_exception_failure(mqtt_client_mock): |
| 417 |
"""Verify `NotifyMQTT` fails when an exception happens.""" |
| 418 |
|
| 419 |
obj = apprise.Apprise.instantiate( |
| 420 |
"mqtt://localhost/my/topic", suppress_exceptions=False |
| 421 |
) |
| 422 |
|
| 423 |
# Emulate a situation where `connect()` raises an exception. |
| 424 |
mqtt_client_mock.connect.return_value = None |
| 425 |
|
| 426 |
# Verify notification fails for every exception type that connect() or |
| 427 |
# the TLS setup can raise (most-specific to least-specific order). |
| 428 |
for side_effect in ( |
| 429 |
ssl.CertificateError, |
| 430 |
ssl.SSLError, |
| 431 |
ConnectionError, |
| 432 |
OSError, |
| 433 |
ValueError, |
| 434 |
): |
| 435 |
mqtt_client_mock.connect.side_effect = side_effect |
| 436 |
assert bool(obj.notify(body="test=test")) is False |
| 437 |
|
| 438 |
|
| 439 |
def test_plugin_mqtt_not_published_failure(mqtt_client_mock, mocker): |
| 440 |
"""Verify `NotifyMQTT` fails there if the message has not been |
| 441 |
published.""" |
| 442 |
|
| 443 |
# Speed up testing by making `NotifyMQTT` not block anywhere. |
| 444 |
mocker.patch.object(NotifyMQTT, "socket_read_timeout", 0.00025) |
| 445 |
mocker.patch.object(NotifyMQTT, "mqtt_block_time_sec", 0) |
| 446 |
|
| 447 |
# Emulate a situation where `is_published()` returns `False`. |
| 448 |
mqtt_response = mqtt_client_mock.publish.return_value |
| 449 |
mqtt_response.is_published.return_value = False |
| 450 |
|
| 451 |
obj = apprise.Apprise.instantiate( |
| 452 |
"mqtt://localhost/my/topic", suppress_exceptions=False |
| 453 |
) |
| 454 |
|
| 455 |
# Verify notification fails. |
| 456 |
assert bool(obj.notify(body="test=test")) is False |
| 457 |
|
| 458 |
|
| 459 |
def test_plugin_mqtt_not_published_recovery_success(mqtt_client_mock): |
| 460 |
"""Verify `NotifyMQTT` success after recovering from |
| 461 |
is_published==False.""" |
| 462 |
|
| 463 |
# Emulate a situation where `is_published()` returns `False`. |
| 464 |
mqtt_response = mqtt_client_mock.publish.return_value |
| 465 |
mqtt_response.is_published.return_value = None |
| 466 |
mqtt_response.is_published.side_effect = (False, True) |
| 467 |
|
| 468 |
obj = apprise.Apprise.instantiate( |
| 469 |
"mqtt://localhost/my/topic", suppress_exceptions=False |
| 470 |
) |
| 471 |
|
| 472 |
# Verify notification fails. |
| 473 |
assert bool(obj.notify(body="test=test")) is True |