Debian Codegraph @

tests/test_plugin_gnome.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 importlib
29 import logging
30 import sys
31 import types
32 from unittest import mock
33 from unittest.mock import ANY, Mock, call
34
35 from helpers import reload_plugin
36 import pytest
37
38 import apprise
39 from apprise.plugins.gnome import GnomeUrgency, NotifyGnome
40
41 # Disable logging for a cleaner testing output
42 logging.disable(logging.CRITICAL)
43
44
45 def setup_glib_environment():
46 """Setup a heavily mocked Glib environment."""
47
48 # Our module base
49 gi_name = "gi"
50
51 # First we do an import without the gi library available to ensure
52 # we can handle cases when the library simply isn't available
53
54 if gi_name in sys.modules:
55 # Test cases where the gi library exists; we want to remove it
56 # for the purpose of testing and capture the handling of the
57 # library when it is missing
58 del sys.modules[gi_name]
59 reload_plugin("gnome")
60
61 # We need to fake our gnome environment for testing purposes since
62 # the gi library isn't available on CI
63 gi = types.ModuleType(gi_name)
64 gi.repository = types.ModuleType(gi_name + ".repository")
65 gi.module = types.ModuleType(gi_name + ".module")
66
67 mock_pixbuf = mock.Mock()
68 mock_notify = mock.Mock()
69
70 gi.repository.GdkPixbuf = types.ModuleType(
71 gi_name + ".repository.GdkPixbuf"
72 )
73 gi.repository.GdkPixbuf.Pixbuf = mock_pixbuf
74 gi.repository.Notify = mock.Mock()
75 gi.repository.Notify.init.return_value = True
76 gi.repository.Notify.Notification = mock_notify
77
78 # Emulate require_version function:
79 gi.require_version = mock.Mock(name=gi_name + ".require_version")
80
81 # Force the fake module to exist
82 sys.modules[gi_name] = gi
83 sys.modules[gi_name + ".repository"] = gi.repository
84 sys.modules[gi_name + ".repository.Notify"] = gi.repository.Notify
85
86 # Notify Object
87 notify_obj = mock.Mock()
88 notify_obj.set_urgency.return_value = True
89 notify_obj.set_icon_from_pixbuf.return_value = True
90 notify_obj.set_image_from_pixbuf.return_value = True
91 notify_obj.show.return_value = True
92 mock_notify.new.return_value = notify_obj
93 mock_pixbuf.new_from_file.return_value = True
94
95 # When patching something which has a side effect on the module-level code
96 # of a plugin, make sure to reload it.
97 reload_plugin("gnome")
98
99
100 @pytest.fixture
101 def glib_environment():
102 """Fixture to provide a mocked Glib environment to test case functions."""
103 setup_glib_environment()
104
105
106 @pytest.fixture
107 def obj(glib_environment):
108 """Fixture to provide a mocked Apprise instance."""
109
110 # Create our instance
111 obj = apprise.Apprise.instantiate("gnome://", suppress_exceptions=False)
112 assert obj is not None
113 assert isinstance(obj, NotifyGnome) is True
114
115 # Set our duration to 0 to speed up timeouts (for testing)
116 obj.duration = 0
117
118 # Check that it found our mocked environments
119 assert obj.enabled is True
120
121 return obj
122
123
124 def test_plugin_gnome_general_success(obj):
125 """NotifyGnome() general checks."""
126
127 # Test url() call
128 assert isinstance(obj.url(), str) is True
129
130 # our URL Identifier is disabled
131 assert obj.url_id() is None
132
133 # test notifications
134 assert (
135 obj.notify(
136 title="title", body="body", notify_type=apprise.NotifyType.INFO
137 )
138 is True
139 )
140
141 # test notification without a title
142 assert (
143 obj.notify(title="", body="body", notify_type=apprise.NotifyType.INFO)
144 is True
145 )
146
147
148 def test_plugin_gnome_image_success(glib_environment):
149 """Verify using the `image` query argument works as intended."""
150
151 obj = apprise.Apprise.instantiate(
152 "gnome://_/?image=True", suppress_exceptions=False
153 )
154 assert isinstance(obj, NotifyGnome) is True
155 assert (
156 obj.notify(
157 title="title", body="body", notify_type=apprise.NotifyType.INFO
158 )
159 is True
160 )
161
162 obj = apprise.Apprise.instantiate(
163 "gnome://_/?image=False", suppress_exceptions=False
164 )
165 assert isinstance(obj, NotifyGnome) is True
166 assert (
167 obj.notify(
168 title="title", body="body", notify_type=apprise.NotifyType.INFO
169 )
170 is True
171 )
172
173
174 def test_plugin_gnome_priority(glib_environment):
175 """Verify correctness of the `priority` query argument."""
176
177 # Test Priority (alias of urgency)
178 obj = apprise.Apprise.instantiate(
179 "gnome://_/?priority=invalid", suppress_exceptions=False
180 )
181 assert isinstance(obj, NotifyGnome) is True
182 assert obj.urgency == 1
183 assert (
184 obj.notify(
185 title="title", body="body", notify_type=apprise.NotifyType.INFO
186 )
187 is True
188 )
189
190 obj = apprise.Apprise.instantiate(
191 "gnome://_/?priority=high", suppress_exceptions=False
192 )
193 assert isinstance(obj, NotifyGnome) is True
194 assert obj.urgency == 2
195 assert (
196 obj.notify(
197 title="title", body="body", notify_type=apprise.NotifyType.INFO
198 )
199 is True
200 )
201
202 obj = apprise.Apprise.instantiate(
203 "gnome://_/?priority=2", suppress_exceptions=False
204 )
205 assert isinstance(obj, NotifyGnome) is True
206 assert obj.urgency == 2
207 assert (
208 obj.notify(
209 title="title", body="body", notify_type=apprise.NotifyType.INFO
210 )
211 is True
212 )
213
214
215 def test_plugin_gnome_urgency(glib_environment):
216 """Verify correctness of the `urgency` query argument."""
217
218 # Test Urgeny
219 obj = apprise.Apprise.instantiate(
220 "gnome://_/?urgency=invalid", suppress_exceptions=False
221 )
222 assert obj.urgency == 1
223 assert isinstance(obj, NotifyGnome) is True
224 assert (
225 obj.notify(
226 title="title", body="body", notify_type=apprise.NotifyType.INFO
227 )
228 is True
229 )
230
231 obj = apprise.Apprise.instantiate(
232 "gnome://_/?urgency=high", suppress_exceptions=False
233 )
234 assert obj.urgency == 2
235 assert isinstance(obj, NotifyGnome) is True
236 assert (
237 obj.notify(
238 title="title", body="body", notify_type=apprise.NotifyType.INFO
239 )
240 is True
241 )
242
243 obj = apprise.Apprise.instantiate(
244 "gnome://_/?urgency=2", suppress_exceptions=False
245 )
246 assert isinstance(obj, NotifyGnome) is True
247 assert obj.urgency == 2
248 assert (
249 obj.notify(
250 title="title", body="body", notify_type=apprise.NotifyType.INFO
251 )
252 is True
253 )
254
255
256 def test_plugin_gnome_parse_configuration(obj):
257 """Verify configuration parsing works correctly."""
258
259 # Test configuration parsing
260 content = """
261 urls:
262 - gnome://:
263 - priority: 0
264 tag: gnome_int low
265 - priority: "0"
266 tag: gnome_str_int low
267 - priority: low
268 tag: gnome_str low
269 - urgency: 0
270 tag: gnome_int low
271 - urgency: "0"
272 tag: gnome_str_int low
273 - urgency: low
274 tag: gnome_str low
275
276 # These will take on normal (default) urgency
277 - priority: invalid
278 tag: gnome_invalid
279 - urgency: invalid
280 tag: gnome_invalid
281
282 - gnome://:
283 - priority: 2
284 tag: gnome_int high
285 - priority: "2"
286 tag: gnome_str_int high
287 - priority: high
288 tag: gnome_str high
289 - urgency: 2
290 tag: gnome_int high
291 - urgency: "2"
292 tag: gnome_str_int high
293 - urgency: high
294 tag: gnome_str high
295 """
296
297 # Create ourselves a config object
298 ac = apprise.AppriseConfig()
299 assert ac.add_config(content=content) is True
300
301 aobj = apprise.Apprise()
302
303 # Add our configuration
304 aobj.add(ac)
305
306 # We should be able to read our 14 servers from that
307 # 6x low
308 # 6x high
309 # 2x invalid (so takes on normal urgency)
310 assert len(ac.servers()) == 14
311 assert len(aobj) == 14
312 assert len(list(aobj.find(tag="low"))) == 6
313 for s in aobj.find(tag="low"):
314 assert s.urgency == GnomeUrgency.LOW
315
316 assert len(list(aobj.find(tag="high"))) == 6
317 for s in aobj.find(tag="high"):
318 assert s.urgency == GnomeUrgency.HIGH
319
320 assert len(list(aobj.find(tag="gnome_str"))) == 4
321 assert len(list(aobj.find(tag="gnome_str_int"))) == 4
322 assert len(list(aobj.find(tag="gnome_int"))) == 4
323
324 assert len(list(aobj.find(tag="gnome_invalid"))) == 2
325 for s in aobj.find(tag="gnome_invalid"):
326 assert s.urgency == GnomeUrgency.NORMAL
327
328
329 def test_plugin_gnome_missing_icon(mocker, obj):
330 """Verify the notification will be submitted, even if loading the icon
331 fails."""
332
333 # Inject error when loading icon.
334 gi = importlib.import_module("gi")
335 gi.repository.GdkPixbuf.Pixbuf.new_from_file.side_effect = AttributeError(
336 "Something failed"
337 )
338
339 logger: Mock = mocker.spy(obj, "logger")
340 assert (
341 obj.notify(
342 title="title", body="body", notify_type=apprise.NotifyType.INFO
343 )
344 is True
345 )
346 assert logger.mock_calls == [
347 call.warning("Could not load notification icon (%s).", ANY),
348 call.debug("Gnome Exception: Something failed"),
349 call.info("Sent Gnome notification."),
350 ]
351
352
353 def test_plugin_gnome_disabled_plugin(obj):
354 """Verify notification will not be submitted if plugin is disabled."""
355 obj.enabled = False
356 assert (
357 obj.notify(
358 title="title", body="body", notify_type=apprise.NotifyType.INFO
359 )
360 is False
361 )
362
363
364 def test_plugin_gnome_set_urgency():
365 """Test the setting of an urgency, through `priority` keyword argument."""
366 NotifyGnome(priority=0)
367
368
369 @pytest.mark.skipif("gi" not in sys.modules, reason="Requires gi library")
370 def test_plugin_gnome_gi_croaks():
371 """Verify notification fails when `gi.require_version()` croaks."""
372
373 # Make `require_version` function raise an error.
374 gi = importlib.import_module("gi")
375 gi.require_version.side_effect = ValueError("Something failed")
376
377 # When patching something which has a side effect on the module-level code
378 # of a plugin, make sure to reload it.
379 reload_plugin("gnome")
380
381 # Create instance.
382 obj = apprise.Apprise.instantiate("gnome://", suppress_exceptions=False)
383
384 # The notifier is marked disabled.
385 assert obj is None
386
387
388 @pytest.mark.skipif("gi" not in sys.modules, reason="Requires gi library")
389 def test_plugin_gnome_notify_croaks(mocker, obj):
390 """Fail gracefully if underlying object croaks for whatever reason."""
391
392 # Inject an error when invoking `gi.repository.Notify`.
393 mocker.patch(
394 "gi.repository.Notify.Notification.new",
395 side_effect=AttributeError("Something failed"),
396 )
397
398 logger: Mock = mocker.spy(obj, "logger")
399 assert (
400 obj.notify(
401 title="title", body="body", notify_type=apprise.NotifyType.INFO
402 )
403 is False
404 )
405 assert logger.mock_calls == [
406 call.warning("Failed to send Gnome notification."),
407 call.debug("Gnome Exception: Something failed"),
408 ]
409
410
411 def test_plugin_gnome_show_exception(mocker, obj):
412 """
413 Test that an exception raised during notification.show() is caught
414 by the outer try/except block.
415 """
416 # 1. Import the mocked 'gi' library.
417 # The 'obj' fixture (via 'glib_environment') has already set this up
418 # in sys.modules, so this import works even if Gnome isn't installed.
419 import gi
420
421 # 2. Retrieve the mocked notification instance.
422 # Your setup_glib_environment() sets
423 # 'gi.repository.Notify.Notification.new' to return a mock object.
424 notification_instance = gi.repository.Notify.Notification.new.return_value
425
426 # 3. Force the .show() method to raise an exception.
427 notification_instance.show.side_effect = Exception(
428 "Simulated Gnome Show Failure"
429 )
430
431 # 4. Spy on the logger to verify the output.
432 logger_spy = mocker.spy(obj, "logger")
433
434 # 5. Execute the notification.
435 # It should crash at .show(), catch the exception, and return False.
436 assert obj.notify(title="Title", body="Body") is False
437
438 # 6. Verify the specific log message.
439 logger_spy.warning.assert_called_with("Failed to send Gnome notification.")