Debian Codegraph @

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