Debian Codegraph @

tests/test_plugin_glib.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 Mock, call
32
33 from helpers import reload_plugin
34 import pytest
35
36 import apprise
37 from apprise.plugins.glib import GLibUrgency, NotifyGLib
38
39 # Disable logging output during testing
40 logging.disable(logging.CRITICAL)
41
42
43 @pytest.fixture
44 def enabled_glib_environment(monkeypatch):
45 """
46 Fully mocked GI/GLib/Gio/GdkPixbuf environment for local and CI.
47 """
48 # Step 1: Fake gi and repository
49 gi = types.ModuleType("gi")
50 gi.require_version = Mock()
51
52 fake_variant = Mock(name="Variant")
53 fake_error = type("GLibError", (Exception,), {})
54 fake_pixbuf = Mock()
55 fake_image = Mock()
56
57 fake_pixbuf.new_from_file.return_value = fake_image
58 fake_image.get_width.return_value = 100
59 fake_image.get_height.return_value = 100
60 fake_image.get_rowstride.return_value = 1
61 fake_image.get_has_alpha.return_value = False
62 fake_image.get_bits_per_sample.return_value = 8
63 fake_image.get_n_channels.return_value = 1
64 fake_image.get_pixels.return_value = b""
65
66 gi.repository = types.SimpleNamespace(
67 Gio=Mock(),
68 GLib=types.SimpleNamespace(Variant=fake_variant, Error=fake_error),
69 GdkPixbuf=types.SimpleNamespace(Pixbuf=fake_pixbuf),
70 )
71
72 # Step 2: Inject into sys.modules
73 sys.modules["gi"] = gi
74 sys.modules["gi.repository"] = gi.repository
75
76 # Step 3: Reload plugin with all mocks in place
77 reload_plugin("glib")
78
79
80 def test_plugin_glib_gdkpixbuf_attribute_error(monkeypatch):
81 """Simulate AttributeError from importing GdkPixbuf"""
82
83 # Create gi module
84 gi = types.ModuleType("gi")
85
86 # Create gi.repository mock, but DO NOT include GdkPixbuf
87 gi.repository = types.SimpleNamespace(
88 Gio=Mock(),
89 GLib=types.SimpleNamespace(
90 Variant=Mock(), Error=type("GLibError", (Exception,), {})
91 ),
92 # GdkPixbuf missing entirely triggers AttributeError
93 )
94
95 def fake_require_version(name, version):
96 if name == "GdkPixbuf":
97 # Simulate success in require_version
98 return
99 return
100
101 gi.require_version = Mock(side_effect=fake_require_version)
102
103 # Inject into sys.modules
104 sys.modules["gi"] = gi
105 sys.modules["gi.repository"] = gi.repository
106
107 # Trigger the plugin reload with our patched environment
108 reload_plugin("glib")
109
110 from apprise.plugins import glib as plugin_glib
111
112 assert plugin_glib.NOTIFY_GLIB_IMAGE_SUPPORT is False
113
114
115 def test_plugin_glib_basic_notify(enabled_glib_environment):
116 """Basic notification path"""
117 obj = apprise.Apprise.instantiate("glib://", suppress_exceptions=False)
118 assert isinstance(obj, NotifyGLib)
119 assert obj.notify("body", title="title") is True
120
121
122 def test_plugin_glib_url_includes_coordinates(enabled_glib_environment):
123 """Test that x/y coordinates appear in the rendered URL."""
124 obj = apprise.Apprise.instantiate(
125 "glib://_/?x=7&y=9", suppress_exceptions=False
126 )
127 url = obj.url(privacy=False)
128
129 assert "x=7" in url
130 assert "y=9" in url
131
132
133 def test_plugin_glib_zero_coordinate_round_trip(enabled_glib_environment):
134 """
135 Coordinate 0 is a valid screen edge (send() emits it via an `is None`
136 guard); url() must preserve it so the configuration survives a
137 save/reload cycle instead of being silently dropped.
138 """
139 obj = apprise.Apprise.instantiate(
140 "glib://_/?x=0&y=0", suppress_exceptions=False
141 )
142 assert isinstance(obj, NotifyGLib)
143 assert obj.x_axis == 0
144 assert obj.y_axis == 0
145
146 url = obj.url()
147 assert "x=0" in url
148 assert "y=0" in url
149
150 # The rendered URL must round-trip back to an identical object rather
151 # than dropping x=0 (which previously also raised a TypeError on reload
152 # whenever the surviving axis kept the guard truthy).
153 reloaded = apprise.Apprise.instantiate(url, suppress_exceptions=False)
154 assert isinstance(reloaded, NotifyGLib)
155 assert reloaded.x_axis == 0
156 assert reloaded.y_axis == 0
157
158 # A single zero axis must also survive without dropping the other value.
159 obj = apprise.Apprise.instantiate(
160 "glib://_/?x=0&y=5", suppress_exceptions=False
161 )
162 reloaded = apprise.Apprise.instantiate(
163 obj.url(), suppress_exceptions=False
164 )
165 assert reloaded.x_axis == 0
166 assert reloaded.y_axis == 5
167
168
169 def test_plugin_glib_icon_fails_gracefully(mocker, enabled_glib_environment):
170 """Simulate image load failure"""
171 import gi
172
173 gi.repository.GdkPixbuf.Pixbuf.new_from_file.side_effect = AttributeError(
174 "fail"
175 )
176 obj = apprise.Apprise.instantiate("glib://", suppress_exceptions=False)
177 spy = mocker.spy(obj, "logger")
178 assert obj.notify("msg", title="t") is True
179 assert any(
180 "Could not load notification icon" in str(x)
181 for x in spy.warning.call_args_list
182 )
183
184
185 def test_plugin_glib_send_raises_glib_error(mocker, enabled_glib_environment):
186 """Simulate GLib.Error in DBusProxy creation"""
187 import gi
188
189 gi.repository.Gio.DBusProxy.new_for_bus_sync.side_effect = (
190 gi.repository.GLib.Error("fail")
191 )
192 obj = apprise.Apprise.instantiate("glib://", suppress_exceptions=False)
193 assert obj.notify("fail test") is False
194
195
196 def test_plugin_glib_send_raises_generic(mocker, enabled_glib_environment):
197 """Simulate generic error in gio_iface.Notify()"""
198 # Re: https://github.com/caronc/apprise/issues/1383
199 # This test validates that the NotifyGLib plugin correctly handles a
200 # generic exception raised by the `Notify()` method call on a mocked
201 # DBus interface. However, it is only meaningful in environments that:
202 #
203 # 1. Do NOT have PyGObject (`gi`) installed, OR
204 # 2. Have `gi`, but without introspection or live bindings activated.
205 #
206 # When PyGObject is installed and active, the `gi.repository` namespace
207 # becomes populated by introspected C-based objects that do not behave
208 # like regular Python functions. This causes mock patching via
209 # `mocker.patch("gi.repository.Gio.DBusProxy.new_for_bus_sync")` to
210 # silently fail or be ignored, as Python's mocking machinery cannot
211 # reliably override these introspected symbols.
212 #
213 # This test exists to ensure coverage of legacy or minimal environments
214 # where Apprise's GLib support can still be used through soft mocks,
215 # such as CI/CD pipelines or headless test setups where PyGObject is
216 # absent or stubbed (as done via `enabled_glib_environment`).
217 #
218 # Note: In production environments with active PyGObject, exception
219 # handling is already tested via `GLib.Error` branches or during actual
220 # usage of `NotifyGLib.send()`. This test supplements that by simulating
221 # the rare fallback case of a non-GLib-related exception during Notify().
222 import gi
223
224 if hasattr(gi, "repository"):
225 pytest.skip(
226 "pygobject introspection active, test won't behave as expected"
227 )
228
229 fake_iface = Mock()
230 fake_iface.Notify.side_effect = RuntimeError("boom")
231
232 mocker.patch(
233 "gi.repository.Gio.DBusProxy.new_for_bus_sync",
234 return_value=fake_iface,
235 )
236
237 obj = apprise.Apprise.instantiate("glib://", suppress_exceptions=False)
238 logger = mocker.spy(obj, "logger")
239 assert obj.notify("boom", title="fail") is False
240 logger.warning.assert_called_with("Failed to send GLib/Gio notification.")
241
242
243 def test_plugin_glib_disabled(mocker, enabled_glib_environment):
244 """Test disabled plugin returns False on notify()"""
245 obj = apprise.Apprise.instantiate("glib://", suppress_exceptions=False)
246 obj.enabled = False
247 assert obj.notify("x") is False
248
249
250 def test_plugin_glib_invalid_coords():
251 """Invalid x/y coordinates cause TypeError"""
252 with pytest.raises(TypeError):
253 NotifyGLib(x_axis="bad", y_axis="1")
254 with pytest.raises(TypeError):
255 NotifyGLib(x_axis="1", y_axis="bad")
256
257
258 def test_plugin_glib_urgency_parsing():
259 """Urgency variants map correctly"""
260 assert NotifyGLib(urgency="high").urgency == GLibUrgency.HIGH
261 assert NotifyGLib(urgency="invalid").urgency == GLibUrgency.NORMAL
262 assert NotifyGLib(urgency="2").urgency == GLibUrgency.HIGH
263 assert NotifyGLib(urgency=0).urgency == GLibUrgency.LOW
264
265
266 def test_plugin_glib_parse_url_fields():
267 url = "glib://_/?x=5&y=5&image=no&priority=high"
268 result = NotifyGLib.parse_url(url)
269 assert result["x_axis"] == "5"
270 assert result["y_axis"] == "5"
271 assert result["include_image"] is False
272 assert result["urgency"] == "high"
273
274
275 def test_plugin_glib_xy_axis_applied_to_variant(enabled_glib_environment):
276 """Ensure x/y values are added to GLib.Variant payload."""
277 obj = apprise.Apprise.instantiate(
278 "glib://_/?x=5&y=10", suppress_exceptions=False
279 )
280
281 # Patch GLib.Variant to track calls
282 import gi
283
284 spy_variant = Mock(wraps=gi.repository.GLib.Variant)
285 gi.repository.GLib.Variant = spy_variant
286
287 assert obj.notify("Test with coords", title="xy") is True
288
289 # Check x and y were added to meta_payload
290 assert call("i", 5) in spy_variant.mock_calls
291 assert call("i", 10) in spy_variant.mock_calls
292
293
294 def test_plugin_glib_no_image_support(monkeypatch, enabled_glib_environment):
295 """Simulate GdkPixbuf unavailable"""
296 monkeypatch.setattr(
297 "apprise.plugins.glib.NOTIFY_GLIB_IMAGE_SUPPORT", False
298 )
299 obj = apprise.Apprise.instantiate("glib://", suppress_exceptions=False)
300 assert obj.notify("no image") is True
301
302
303 def test_plugin_glib_url_redaction(enabled_glib_environment):
304 """url() privacy mode redacts safely"""
305 obj = apprise.Apprise.instantiate(
306 "glib://_/?image=no&urgency=high", suppress_exceptions=False
307 )
308 url = obj.url(privacy=True)
309 assert "image=" in url
310 assert "urgency=" in url
311 assert url.startswith("glib://_/")
312
313
314 def test_plugin_glib_require_version_importerror(monkeypatch):
315 """Simulate gi.require_version() raising ImportError"""
316 gi = types.ModuleType("gi")
317 gi.require_version = Mock(side_effect=ImportError("no gio"))
318 sys.modules["gi"] = gi
319 reload_plugin("glib")
320 obj = apprise.Apprise.instantiate("glib://", suppress_exceptions=False)
321 assert not isinstance(obj, NotifyGLib)
322
323
324 def test_plugin_glib_require_version_valueerror(monkeypatch):
325 """Simulate gi.require_version() raising ValueError without reload
326 crash."""
327
328 import gi
329
330 import apprise.plugins.glib as plugin_glib
331
332 # Patch require_version after import
333 monkeypatch.setattr(
334 gi, "require_version", Mock(side_effect=ValueError("fail"))
335 )
336
337 # Re-evaluate plugin support logic manually
338 try:
339 gi.require_version("Gio", "2.0")
340
341 except Exception:
342 plugin_glib.NOTIFY_GLIB_SUPPORT_ENABLED = False
343 plugin_glib.NotifyGLib.enabled = False
344
345 # Confirm plugin is now marked disabled
346 assert not plugin_glib.NotifyGLib.enabled
347
348 # Apprise will skip this plugin
349 obj = apprise.Apprise.instantiate("glib://", suppress_exceptions=False)
350 assert not isinstance(obj, plugin_glib.NotifyGLib)
351
352
353 def test_plugin_glib_gdkpixbuf_require_version_valueerror(monkeypatch):
354 """Simulate gi.require_version('GdkPixbuf', ...) raising ValueError"""
355
356 # Step 1: Mock GI
357 gi = types.ModuleType("gi")
358 gi.repository = types.ModuleType("gi.repository")
359
360 def fake_require_version(name: str, version: str) -> None:
361 if name == "GdkPixbuf":
362 raise ValueError("GdkPixbuf unavailable")
363
364 gi.require_version = Mock(side_effect=fake_require_version)
365
366 # Step 2: Patch into sys.modules
367 sys.modules["gi"] = gi
368 sys.modules["gi.repository"] = gi.repository
369
370 # Step 3: Reload plugin to trigger branch
371 reload_plugin("glib")
372
373 # Step 4: Confirm GdkPixbuf image support was not enabled
374 from apprise.plugins import glib as plugin_glib
375
376 assert plugin_glib.NOTIFY_GLIB_IMAGE_SUPPORT is False
377
378
379 def test_plugin_glib_notify_generic_exception(
380 mocker, enabled_glib_environment
381 ):
382 """
383 Test that a generic exception occurring during the notification send
384 is caught and handled (returning False).
385 """
386 import gi
387
388 # 1. Create a mock object to act as the DBus Proxy
389 mock_proxy = mocker.Mock()
390
391 # 2. Force the Notify method to raise a generic Exception
392 # This triggers the 'except Exception as e:'
393 mock_proxy.Notify.side_effect = Exception("Simulated Generic Failure")
394
395 # 3. Patch the Gio constructor to return our crashing mock
396 # The code calls: Gio.DBusProxy.new_for_bus_sync(...)
397 gi.repository.Gio.DBusProxy.new_for_bus_sync.return_value = mock_proxy
398
399 # 4. Instantiate the plugin
400 from apprise.plugins.glib import NotifyGLib
401
402 obj = NotifyGLib(targets=["glib://"])
403
404 # 5. Spy on the logger to ensure the warning is logged
405 logger_spy = mocker.spy(obj, "logger")
406
407 # 6. Execute notify()
408 # It should catch the exception and return False
409 assert obj.notify(title="Title", body="Body") is False
410
411 # 7. Verify the specific log message from glib.py
412 logger_spy.warning.assert_called_with(
413 "Failed to send GLib/Gio notification."
414 )