Debian Codegraph @

tests/test_plugin_mqtt.py

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