Debian Codegraph @

tests/test_plugin_dbus.py

raw
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 sys
30 import types
31 from unittest.mock import ANY, Mock
32
33 from helpers import reload_plugin
34 import pytest
35
36 import apprise
37 from apprise.exception import AppriseImproperlyConfigured
38
39 # Disable logging for a cleaner testing output
40 logging.disable(logging.CRITICAL)
41
42
43 @pytest.fixture
44 def mock_dbus_module(mocker):
45 """
46 Creates a completely fake 'dbus' module structure in sys.modules
47 so that we can test the plugin even if dbus is not installed.
48 """
49 # 1. Create the base 'dbus' module
50 dbus = types.ModuleType("dbus")
51 dbus.DBusException = type("DBusException", (Exception,), {})
52 dbus.Byte = lambda x: x
53 dbus.ByteArray = lambda x: x
54 dbus.Interface = Mock(name="Interface")
55 dbus.SessionBus = Mock(name="SessionBus")
56
57 # 2. Mock the mainloops
58 # We create the structure: dbus.mainloop.glib.DBusGMainLoop
59 glib_module = types.ModuleType("dbus.mainloop.glib")
60 glib_module.DBusGMainLoop = Mock(name="DBusGMainLoop")
61
62 qt_module = types.ModuleType("dbus.mainloop.qt")
63 qt_module.DBusQtMainLoop = Mock(name="DBusQtMainLoop")
64
65 mainloop_pkg = types.ModuleType("dbus.mainloop")
66 mainloop_pkg.glib = glib_module
67 mainloop_pkg.qt = qt_module
68
69 # Attach mainloop to the dbus module object so tests can access
70 # mock_dbus_module.mainloop
71 dbus.mainloop = mainloop_pkg
72
73 # 3. Create the GI/GdkPixbuf mocks (for image support)
74 gi = types.ModuleType("gi")
75 gi.require_version = Mock()
76 gi.repository = types.SimpleNamespace(
77 GdkPixbuf=types.SimpleNamespace(Pixbuf=Mock(name="Pixbuf"))
78 )
79 # Setup standard Pixbuf behavior
80 mock_image = Mock()
81 mock_image.get_width.return_value = 10
82 mock_image.get_height.return_value = 10
83 mock_image.get_rowstride.return_value = 1
84 mock_image.get_has_alpha.return_value = False
85 mock_image.get_bits_per_sample.return_value = 8
86 mock_image.get_n_channels.return_value = 3
87 mock_image.get_pixels.return_value = b"pixeldata"
88
89 gi.repository.GdkPixbuf.Pixbuf.new_from_file.return_value = mock_image
90
91 # 4. Patch everything into sys.modules
92 mocker.patch.dict(
93 sys.modules,
94 {
95 "dbus": dbus,
96 "dbus.mainloop": mainloop_pkg,
97 "dbus.mainloop.glib": glib_module,
98 "dbus.mainloop.qt": qt_module,
99 "gi": gi,
100 "gi.repository": gi.repository,
101 },
102 )
103
104 return dbus
105
106
107 def test_plugin_dbus_initialization_strategies(mock_dbus_module, mocker):
108 """
109 Test the import logic
110 1. GLib present, Qt missing
111 2. Qt present, GLib missing
112 3. Both missing
113 """
114 # Scenario A: GLib works, Qt fails
115 # We simulate Qt missing by raising ImportError when accessing it
116 sys.modules["dbus.mainloop.qt"] = None
117 reload_plugin("dbus")
118 from apprise.plugins.dbus import LOOP_GLIB, LOOP_QT, NotifyDBus
119
120 assert LOOP_GLIB is not None
121 assert LOOP_QT is None
122 assert NotifyDBus.enabled is True
123
124 # Scenario B: Qt works, GLib fails
125 # Reset modules
126 mock_dbus_module.mainloop.qt.DBusQtMainLoop.return_value = "qt_loop"
127
128 mocker.patch.dict(
129 sys.modules,
130 {
131 "dbus.mainloop.glib": None,
132 "dbus.mainloop.qt": mock_dbus_module.mainloop.qt,
133 },
134 )
135
136 reload_plugin("dbus")
137 from apprise.plugins.dbus import LOOP_GLIB, LOOP_QT, NotifyDBus
138
139 assert LOOP_GLIB is None
140 assert LOOP_QT is not None
141 assert NotifyDBus.enabled is True
142
143 # Scenario C: Both fail
144 mocker.patch.dict(
145 sys.modules, {"dbus.mainloop.glib": None, "dbus.mainloop.qt": None}
146 )
147 reload_plugin("dbus")
148 from apprise.plugins.dbus import NotifyDBus
149
150 assert NotifyDBus.enabled is False
151
152
153 def test_plugin_dbus_image_support_initialization(mock_dbus_module, mocker):
154 """
155 Test the GdkPixbuf import logic
156 """
157 # Case 1: Success (Already set up by fixture)
158 reload_plugin("dbus")
159 from apprise.plugins.dbus import NOTIFY_DBUS_IMAGE_SUPPORT
160
161 assert NOTIFY_DBUS_IMAGE_SUPPORT is True
162
163 # Case 2: GI missing
164 mocker.patch.dict(sys.modules, {"gi": None})
165 reload_plugin("dbus")
166 from apprise.plugins.dbus import NOTIFY_DBUS_IMAGE_SUPPORT
167
168 assert NOTIFY_DBUS_IMAGE_SUPPORT is False
169
170
171 def test_plugin_dbus_send_success(mock_dbus_module, mocker):
172 """
173 Test the happy path for send()
174 """
175 reload_plugin("dbus")
176 from apprise.plugins.dbus import NotifyDBus
177
178 # Setup the mock chain: SessionBus() ->
179 # .get_object() -> Interface() -> .Notify()
180 mock_bus = mock_dbus_module.SessionBus.return_value
181 mock_proxy = mock_bus.get_object.return_value
182 mock_interface = mock_dbus_module.Interface.return_value
183
184 obj = NotifyDBus()
185
186 # Send notification
187 assert bool(obj.notify(title="Title", body="Body")) is True
188
189 # VERIFICATION
190 # Check SessionBus was called
191 mock_dbus_module.SessionBus.assert_called()
192 # Check Interface was created
193 mock_dbus_module.Interface.assert_called_with(
194 mock_proxy, dbus_interface="org.freedesktop.Notifications"
195 )
196 # Check Notify was called
197 assert mock_interface.Notify.called
198 args, _ = mock_interface.Notify.call_args
199 # Arg 3 is Title, Arg 4 is Body
200 assert args[3] == "Title"
201 assert args[4] == "Body"
202
203
204 def test_plugin_dbus_send_no_title(mock_dbus_module):
205 """
206 Test the 'if not title' swap logic
207 """
208 reload_plugin("dbus")
209 from apprise.plugins.dbus import NotifyDBus
210
211 mock_interface = mock_dbus_module.Interface.return_value
212
213 obj = NotifyDBus()
214 obj.notify(title="", body="OnlyBody")
215
216 args, _ = mock_interface.Notify.call_args
217 # Title (Arg 3) should now be "OnlyBody", Body (Arg 4) empty
218 assert args[3] == "OnlyBody"
219 assert args[4] == ""
220
221
222 def test_plugin_dbus_send_connection_failure(mock_dbus_module):
223 """
224 Test SessionBus raising DBusException
225 """
226 reload_plugin("dbus")
227 from apprise.plugins.dbus import NotifyDBus
228
229 # Force constructor to crash
230 mock_dbus_module.SessionBus.side_effect = mock_dbus_module.DBusException(
231 "Connection Refused"
232 )
233
234 obj = NotifyDBus()
235 # Should handle exception and return False
236 assert bool(obj.notify(title="T", body="B")) is False
237
238
239 def test_plugin_dbus_send_notify_failure(mock_dbus_module):
240 """
241 Test Interface.Notify raising Exception
242 """
243 reload_plugin("dbus")
244 from apprise.plugins.dbus import NotifyDBus
245
246 # Force Notify to crash
247 mock_interface = mock_dbus_module.Interface.return_value
248 mock_interface.Notify.side_effect = Exception("Generic Failure")
249
250 obj = NotifyDBus()
251 assert bool(obj.notify(title="T", body="B")) is False
252
253
254 def test_plugin_dbus_image_loading_failure(mock_dbus_module, mocker):
255 """
256 Test image loading exception
257 """
258 reload_plugin("dbus")
259 # Force GdkPixbuf to crash
260 import gi
261
262 gi.repository.GdkPixbuf.Pixbuf.new_from_file.side_effect = Exception(
263 "Bad Image"
264 )
265
266 # Use Apprise.instantiate to handle parsing cleanly
267 obj = apprise.Apprise.instantiate(
268 "dbus://?image=yes", suppress_exceptions=False
269 )
270 spy_logger = mocker.spy(obj, "logger")
271
272 # Notification should still succeed (return True), just log a warning
273 assert bool(obj.notify(title="T", body="B")) is True
274
275 # Verify the warning was logged
276 spy_logger.warning.assert_called_with(
277 "Could not load notification icon (%s).", ANY
278 )
279
280
281 def test_plugin_dbus_url_parsing(mock_dbus_module):
282 """
283 Test various URL parameters and instantiation.
284 """
285 reload_plugin("dbus")
286 from apprise.plugins.dbus import DBusUrgency, NotifyDBus
287
288 # Test Urgency mapping
289 obj = apprise.Apprise.instantiate(
290 "dbus://?urgency=high", suppress_exceptions=False
291 )
292 assert isinstance(obj, NotifyDBus)
293 assert obj.urgency == DBusUrgency.HIGH
294 assert "urgency=high" in obj.url()
295
296 obj = apprise.Apprise.instantiate(
297 "dbus://?priority=low", suppress_exceptions=False
298 )
299 assert isinstance(obj, NotifyDBus)
300 assert obj.urgency == DBusUrgency.LOW
301 assert "urgency=low" in obj.url()
302
303 # Test X/Y coords
304 obj = apprise.Apprise.instantiate(
305 "dbus://?x=100&y=200", suppress_exceptions=False
306 )
307 assert obj.x_axis == 100
308 assert obj.y_axis == 200
309 assert "x=100" in obj.url()
310 assert "y=200" in obj.url()
311
312 # Test Invalid X/Y
313 with pytest.raises(AppriseImproperlyConfigured):
314 NotifyDBus(x_axis="invalid")
315
316
317 def test_plugin_dbus_zero_coordinate_round_trip(mock_dbus_module):
318 """
319 Coordinate 0 is a valid screen edge (send() emits it via an `is None`
320 guard); url() must preserve it so the configuration survives a
321 save/reload cycle instead of being silently dropped.
322 """
323 reload_plugin("dbus")
324 from apprise.plugins.dbus import NotifyDBus
325
326 obj = apprise.Apprise.instantiate(
327 "dbus://_/?x=0&y=0", suppress_exceptions=False
328 )
329 assert isinstance(obj, NotifyDBus)
330 assert obj.x_axis == 0
331 assert obj.y_axis == 0
332
333 url = obj.url()
334 assert "x=0" in url
335 assert "y=0" in url
336
337 # The rendered URL must round-trip back to an identical object rather
338 # than dropping x=0 (which previously also raised a TypeError on reload
339 # whenever the surviving axis kept the guard truthy).
340 reloaded = apprise.Apprise.instantiate(url, suppress_exceptions=False)
341 assert isinstance(reloaded, NotifyDBus)
342 assert reloaded.x_axis == 0
343 assert reloaded.y_axis == 0
344
345 # A single zero axis must also survive without dropping the other value.
346 obj = apprise.Apprise.instantiate(
347 "dbus://_/?x=0&y=5", suppress_exceptions=False
348 )
349 reloaded = apprise.Apprise.instantiate(
350 obj.url(), suppress_exceptions=False
351 )
352 assert reloaded.x_axis == 0
353 assert reloaded.y_axis == 5
354
355
356 def test_plugin_dbus_schema_not_supported(mock_dbus_module, mocker):
357 """
358 Dbus test for unsupported schema warning
359 """
360 reload_plugin("dbus")
361 from apprise.plugins.dbus import NotifyDBus
362
363 with pytest.raises(AppriseImproperlyConfigured):
364 NotifyDBus(schema="not-a-real-schema")
365
366 # Assert warning emitted (message content is stable)
367 with pytest.raises(AppriseImproperlyConfigured):
368 NotifyDBus(schema="still-not-real")
369
370
371 def test_plugin_dbus_send_sets_xy_meta_payload(mock_dbus_module):
372 """
373 Covers setting x-y payload setting
374 """
375 reload_plugin("dbus")
376 from apprise.plugins.dbus import NotifyDBus
377
378 mock_interface = mock_dbus_module.Interface.return_value
379 obj = NotifyDBus(x_axis=100, y_axis=200)
380
381 assert bool(obj.notify(title="T", body="B")) is True
382
383 args, _ = mock_interface.Notify.call_args
384 # meta output (app, id, icon, title, body, actions, meta, timeout)
385 meta = args[6]
386 assert meta["x"] == 100
387 assert meta["y"] == 200
388
389
390 def test_plugin_dbus_send_image_condition_false_skips_pixbuf(
391 mock_dbus_module, mocker
392 ):
393 """
394 Covers NOTIFY_DBUS_IMAGE_SUPPORT and icon_path flag
395 """
396 reload_plugin("dbus")
397 import gi
398
399 from apprise.plugins.dbus import NotifyDBus
400
401 mock_interface = mock_dbus_module.Interface.return_value
402
403 obj = NotifyDBus(include_image=False)
404
405 # Ensure image_path is not even consulted when include_image=False
406 spy_image_path = mocker.spy(obj, "image_path")
407
408 assert bool(obj.notify(title="T", body="B")) is True
409
410 assert mock_interface.Notify.called
411 assert gi.repository.GdkPixbuf.Pixbuf.new_from_file.called is False
412 assert spy_image_path.called is False