Debian Codegraph @

tests/test_plugin_macosx.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 os
30 import subprocess
31 import sys
32 from unittest.mock import Mock
33
34 from helpers import reload_plugin
35 import pytest
36
37 import apprise
38 from apprise.exception import AppriseImproperlyConfigured
39 from apprise.plugins.macosx import NotifyMacOSX
40
41 # Disable logging for a cleaner testing output.
42 logging.disable(logging.CRITICAL)
43
44
45 if sys.platform not in ["darwin", "linux"]:
46 pytest.skip(
47 "Only makes sense on macOS, but testable in Linux",
48 allow_module_level=True,
49 )
50
51
52 @pytest.fixture
53 def pretend_macos(mocker):
54 """Fixture to simulate a macOS environment."""
55 mocker.patch("platform.system", return_value="Darwin")
56 mocker.patch("platform.mac_ver", return_value=("10.8", ("", "", ""), ""))
57
58 # Reload plugin module, in order to re-run module-level code.
59 reload_plugin("macosx")
60
61
62 @pytest.fixture
63 def terminal_notifier(mocker, tmp_path):
64 """Provide a temporary terminal-notifier program for tests."""
65 notifier_program = tmp_path.joinpath("terminal-notifier")
66 notifier_program.write_text(
67 "#!/bin/sh\n\n"
68 'if [ "$1" = "-version" ]; then\n'
69 ' echo "terminal-notifier 3.1.0."\n'
70 " exit 0\n"
71 "fi\n"
72 "echo hello\n"
73 )
74
75 # Set execute bit.
76 os.chmod(notifier_program, 0o755)
77
78 # Make the notifier use the temporary file instead of `terminal-notifier`.
79 mocker.patch(
80 "apprise.plugins.macosx.NotifyMacOSX.notify_paths",
81 (str(notifier_program),),
82 )
83
84 yield notifier_program
85
86
87 @pytest.fixture
88 def macos_notify_environment(pretend_macos, terminal_notifier):
89 """Prepare a simulated macOS system with terminal-notifier.
90
91 Use the individual fixtures when a test needs direct access to them.
92 """
93 pass
94
95
96 def test_plugin_macosx_general_success(macos_notify_environment):
97 """NotifyMacOSX() general checks."""
98
99 # Toggle Enable Flag
100 obj = apprise.Apprise.instantiate(
101 "macosx://_/?image=True", suppress_exceptions=False
102 )
103 assert isinstance(obj, NotifyMacOSX) is True
104
105 # Test url() call
106 assert isinstance(obj.url(), str) is True
107
108 # URL Identifier has been disabled as this isn't unique enough
109 # to be mapped to more the 1 end point; verify that None is always
110 # returned
111 assert obj.url_id() is None
112
113 # test notifications
114 assert (
115 bool(
116 obj.notify(
117 title="title", body="body", notify_type=apprise.NotifyType.INFO
118 )
119 )
120 is True
121 )
122
123 # test notification without a title
124 assert (
125 bool(
126 obj.notify(
127 title="", body="body", notify_type=apprise.NotifyType.INFO
128 )
129 )
130 is True
131 )
132
133 obj = apprise.Apprise.instantiate(
134 "macosx://_/?image=True", suppress_exceptions=False
135 )
136 assert isinstance(obj, NotifyMacOSX) is True
137 assert (
138 bool(
139 obj.notify(
140 title="title", body="body", notify_type=apprise.NotifyType.INFO
141 )
142 )
143 is True
144 )
145
146 obj = apprise.Apprise.instantiate(
147 "macosx://_/?image=False", suppress_exceptions=False
148 )
149 assert isinstance(obj, NotifyMacOSX) is True
150 assert isinstance(obj.url(), str) is True
151 assert (
152 bool(
153 obj.notify(
154 title="title", body="body", notify_type=apprise.NotifyType.INFO
155 )
156 )
157 is True
158 )
159
160 # Test Sound
161 obj = apprise.Apprise.instantiate(
162 "macosx://_/?sound=default", suppress_exceptions=False
163 )
164 assert isinstance(obj, NotifyMacOSX) is True
165 assert obj.sound == "default"
166 assert isinstance(obj.url(), str) is True
167 assert (
168 bool(
169 obj.notify(
170 title="title", body="body", notify_type=apprise.NotifyType.INFO
171 )
172 )
173 is True
174 )
175
176 # Test Click (-open support)
177 obj = apprise.Apprise.instantiate(
178 "macosx://_/?click=http://google.com", suppress_exceptions=False
179 )
180 assert isinstance(obj, NotifyMacOSX) is True
181 assert obj.click == "http://google.com"
182 assert isinstance(obj.url(), str) is True
183 assert (
184 bool(
185 obj.notify(
186 title="title", body="body", notify_type=apprise.NotifyType.INFO
187 )
188 )
189 is True
190 )
191
192
193 def test_plugin_macosx_not_executable(pretend_macos, terminal_notifier):
194 """Notifications fail when terminal-notifier is not executable."""
195
196 obj = apprise.Apprise.instantiate("macosx://", suppress_exceptions=False)
197
198 # Unset the executable bit.
199 os.chmod(terminal_notifier, 0o644)
200
201 assert (
202 bool(
203 obj.notify(
204 title="title", body="body", notify_type=apprise.NotifyType.INFO
205 )
206 )
207 is False
208 )
209
210
211 def test_plugin_macosx_invalid_path(macos_notify_environment):
212 """Notifications fail when terminal-notifier cannot be found."""
213
214 obj = apprise.Apprise.instantiate("macosx://", suppress_exceptions=False)
215
216 # Let's disrupt the path location.
217 obj.notify_path = "invalid_missing-file"
218 assert not os.path.isfile(obj.notify_path)
219
220 assert (
221 bool(
222 obj.notify(
223 title="title", body="body", notify_type=apprise.NotifyType.INFO
224 )
225 )
226 is False
227 )
228
229
230 def test_plugin_macosx_command_failure(mocker, macos_notify_environment):
231 """Notifications fail when terminal-notifier returns an error."""
232
233 # Emulate a failing program.
234 mocker.patch(
235 "subprocess.run",
236 return_value=Mock(returncode=1, stdout=b"", stderr=b"boom"),
237 )
238
239 obj = apprise.Apprise.instantiate("macosx://", suppress_exceptions=False)
240 assert isinstance(obj, NotifyMacOSX) is True
241 assert (
242 bool(
243 obj.notify(
244 title="title", body="body", notify_type=apprise.NotifyType.INFO
245 )
246 )
247 is False
248 )
249
250
251 def test_plugin_macosx_pretend_linux(mocker, pretend_macos):
252 """The notification object is disabled when pretending to run on Linux."""
253
254 # When patching something which has a side effect on the module-level code
255 # of a plugin, make sure to reload it.
256 mocker.patch("platform.system", return_value="Linux")
257 reload_plugin("macosx")
258
259 # Our object is disabled.
260 obj = apprise.Apprise.instantiate("macosx://", suppress_exceptions=False)
261 assert obj is None
262
263
264 @pytest.mark.parametrize("macos_version", ["9.12", "10.7"])
265 def test_plugin_macosx_pretend_old_macos(mocker, macos_version):
266 """The notification object is disabled when pretending to run on older
267 macOS."""
268
269 # When patching something which has a side effect on the module-level code
270 # of a plugin, make sure to reload it.
271 mocker.patch(
272 "platform.mac_ver", return_value=(macos_version, ("", "", ""), "")
273 )
274 reload_plugin("macosx")
275
276 obj = apprise.Apprise.instantiate("macosx://", suppress_exceptions=False)
277 assert obj is None
278
279
280 def test_plugin_macosx_sender(mocker, macos_notify_environment):
281 """Pass `-sender` through and preserve it in generated URLs."""
282
283 mock_run = mocker.patch(
284 "subprocess.run",
285 return_value=Mock(
286 returncode=0, stdout=b"terminal-notifier 2.0.0.", stderr=b""
287 ),
288 )
289
290 obj = apprise.Apprise.instantiate(
291 "macosx://_/?sender=me", suppress_exceptions=False
292 )
293 assert isinstance(obj, NotifyMacOSX) is True
294 assert obj.sender == "me"
295 assert "sender=me" in obj.url()
296
297 assert (
298 obj.notify(
299 title="title", body="body", notify_type=apprise.NotifyType.INFO
300 )
301 is True
302 )
303
304 cmd = mock_run.call_args[0][0]
305 assert "-sender" in cmd
306 assert cmd[cmd.index("-sender") + 1] == "\\me"
307
308
309 def test_plugin_macosx_sender_default(mocker, macos_notify_environment):
310 """Without an explicit override, `-sender` falls back to our own
311 app_id so notifications work out of the box."""
312
313 mock_run = mocker.patch(
314 "subprocess.run",
315 return_value=Mock(
316 returncode=0, stdout=b"terminal-notifier 2.0.0.", stderr=b""
317 ),
318 )
319
320 obj = apprise.Apprise.instantiate("macosx://", suppress_exceptions=False)
321 assert obj.sender is None
322
323 # The default isn't baked into the URL; it is resolved at send time
324 assert "sender=" not in obj.url()
325
326 assert (
327 obj.notify(
328 title="title", body="body", notify_type=apprise.NotifyType.INFO
329 )
330 is True
331 )
332
333 cmd = mock_run.call_args[0][0]
334 assert "-sender" in cmd
335 assert cmd[cmd.index("-sender") + 1] == "\\{}".format(obj.app_id)
336
337
338 def test_plugin_macosx_sender_empty_app_id(mocker, macos_notify_environment):
339 """When both `sender` and our own app_id are unset, `-sender` is
340 left off the command entirely rather than being sent empty."""
341
342 mock_run = mocker.patch(
343 "subprocess.run",
344 return_value=Mock(
345 returncode=0, stdout=b"terminal-notifier 2.0.0.", stderr=b""
346 ),
347 )
348
349 asset = apprise.AppriseAsset(app_id="")
350 obj = apprise.Apprise.instantiate(
351 "macosx://", asset=asset, suppress_exceptions=False
352 )
353 assert obj.app_id == ""
354
355 assert (
356 obj.notify(
357 title="title", body="body", notify_type=apprise.NotifyType.INFO
358 )
359 is True
360 )
361
362 assert "-sender" not in mock_run.call_args[0][0]
363
364
365 def test_plugin_macosx_version_3(mocker, macos_notify_environment):
366 """`version=3` skips options that only version 2 supports."""
367
368 mock_run = mocker.patch(
369 "subprocess.run",
370 return_value=Mock(
371 returncode=0, stdout=b"terminal-notifier 2.0.0.", stderr=b""
372 ),
373 )
374
375 obj = apprise.Apprise.instantiate(
376 "macosx://_/?version=3&sender=me&image=yes",
377 suppress_exceptions=False,
378 )
379 assert isinstance(obj, NotifyMacOSX) is True
380 assert obj.version == 3
381 assert "version=3" in obj.url()
382
383 assert (
384 obj.notify(
385 title="title", body="body", notify_type=apprise.NotifyType.INFO
386 )
387 is True
388 )
389
390 cmd = mock_run.call_args[0][0]
391 assert "-sender" not in cmd
392 assert "-appIcon" not in cmd
393
394
395 def test_plugin_macosx_version_2(mocker, macos_notify_environment):
396 """`version=2` includes the sender option."""
397
398 mock_run = mocker.patch(
399 "subprocess.run",
400 return_value=Mock(
401 returncode=0, stdout=b"terminal-notifier 2.0.0.", stderr=b""
402 ),
403 )
404
405 obj = apprise.Apprise.instantiate(
406 "macosx://_/?version=2", suppress_exceptions=False
407 )
408 assert isinstance(obj, NotifyMacOSX) is True
409 assert obj.version == 2
410
411 assert (
412 obj.notify(
413 title="title", body="body", notify_type=apprise.NotifyType.INFO
414 )
415 is True
416 )
417
418 cmd = mock_run.call_args[0][0]
419 assert "-sender" in cmd
420
421
422 @pytest.mark.parametrize("bad_version", ["99", "abc"])
423 def test_plugin_macosx_version_invalid(macos_notify_environment, bad_version):
424 """An unsupported or non-numeric `version=` value is rejected
425 outright."""
426
427 with pytest.raises(AppriseImproperlyConfigured):
428 apprise.Apprise.instantiate(
429 "macosx://_/?version={}".format(bad_version),
430 suppress_exceptions=False,
431 )
432
433
434 def test_plugin_macosx_version_detection(mocker, macos_notify_environment):
435 """Without an explicit override, terminal-notifier is asked which
436 version it is."""
437
438 obj = apprise.Apprise.instantiate("macosx://", suppress_exceptions=False)
439
440 # Nothing is pinned, so nothing is carried in the URL
441 assert obj.version is None
442 assert "version=" not in obj.url()
443
444 # Our surrogate program reports 3.1.0
445 assert obj.tn_version == 3
446
447 # The answer is remembered rather than probed again
448 mock_run = mocker.patch("subprocess.run")
449 assert obj.tn_version == 3
450 assert mock_run.call_count == 0
451
452
453 @pytest.mark.parametrize(
454 ("reported", "expected"),
455 [
456 (b"terminal-notifier 2.0.0.", 2),
457 (b"terminal-notifier 3.1.0.", 3),
458 (b"terminal-notifier 4.0.0.", 3),
459 (b"", 3),
460 ],
461 )
462 def test_plugin_macosx_version_probe(
463 mocker, macos_notify_environment, reported, expected
464 ):
465 """The major version reported by terminal-notifier picks the dialect."""
466
467 mocker.patch(
468 "subprocess.run", return_value=Mock(returncode=0, stdout=reported)
469 )
470
471 obj = apprise.Apprise.instantiate("macosx://", suppress_exceptions=False)
472 assert obj.tn_version == expected
473
474
475 def test_plugin_macosx_probe_failure(mocker, macos_notify_environment):
476 """A probe that never answers falls back to the current release."""
477
478 mocker.patch("subprocess.run", side_effect=OSError("nope"))
479
480 obj = apprise.Apprise.instantiate("macosx://", suppress_exceptions=False)
481 assert obj.tn_version == 3
482
483
484 def test_plugin_macosx_escaping(mocker, macos_notify_environment):
485 """Values are escaped so terminal-notifier reads them as text."""
486
487 mock_run = mocker.patch(
488 "subprocess.run",
489 return_value=Mock(returncode=0, stdout=b"terminal-notifier 3.1.0."),
490 )
491
492 obj = apprise.Apprise.instantiate(
493 "macosx://_/?sound=default&click=http://google.com&image=no",
494 suppress_exceptions=False,
495 )
496 assert obj.notify(title="[Alert]", body="12345") is True
497
498 cmd = mock_run.call_args[0][0]
499 assert cmd[cmd.index("-message") + 1] == "\\12345"
500 assert cmd[cmd.index("-title") + 1] == "\\[Alert]"
501 assert cmd[cmd.index("-sound") + 1] == "\\default"
502 assert cmd[cmd.index("-open") + 1] == "\\http://google.com"
503
504
505 def test_plugin_macosx_image_switch(mocker, macos_notify_environment):
506 """Version 2 sets the app icon; version 3 attaches a local image."""
507
508 mock_run = mocker.patch(
509 "subprocess.run",
510 return_value=Mock(returncode=0, stdout=b"terminal-notifier 3.1.0."),
511 )
512
513 obj = apprise.Apprise.instantiate(
514 "macosx://_/?version=2&image=yes", suppress_exceptions=False
515 )
516 assert obj.notify(title="title", body="body") is True
517 assert "-appIcon" in mock_run.call_args[0][0]
518
519 obj = apprise.Apprise.instantiate(
520 "macosx://_/?version=3&image=yes", suppress_exceptions=False
521 )
522 assert obj.notify(title="title", body="body") is True
523
524 cmd = mock_run.call_args[0][0]
525 assert "-appIcon" not in cmd
526 assert "-contentImage" in cmd
527
528 # A local file terminal-notifier can actually read
529 assert os.path.isfile(cmd[cmd.index("-contentImage") + 1][1:])
530
531
532 @pytest.mark.parametrize("exit_code", [1, 2, 3, 4, 5, 6, 99])
533 def test_plugin_macosx_exit_codes(mocker, macos_notify_environment, exit_code):
534 """Any non-zero exit from terminal-notifier is reported as a failure."""
535
536 mocker.patch(
537 "subprocess.run",
538 return_value=Mock(
539 returncode=exit_code,
540 stdout=b"terminal-notifier 3.1.0.",
541 stderr=b"Notifications are not allowed for this application",
542 ),
543 )
544
545 obj = apprise.Apprise.instantiate("macosx://", suppress_exceptions=False)
546 assert obj.notify(title="title", body="body") is False
547
548
549 def test_plugin_macosx_probe_timeout(mocker, macos_notify_environment):
550 """A probe that hangs falls back to the current release."""
551
552 mocker.patch(
553 "subprocess.run",
554 side_effect=subprocess.TimeoutExpired(
555 cmd="terminal-notifier", timeout=5
556 ),
557 )
558
559 obj = apprise.Apprise.instantiate("macosx://", suppress_exceptions=False)
560 assert obj.tn_version == 3
561
562
563 def test_plugin_macosx_probe_unclean_exit(mocker, macos_notify_environment):
564 """A version reported alongside a non-zero exit isn't trusted."""
565
566 mocker.patch(
567 "subprocess.run",
568 return_value=Mock(returncode=1, stdout=b"terminal-notifier 2.0.0."),
569 )
570
571 obj = apprise.Apprise.instantiate("macosx://", suppress_exceptions=False)
572 assert obj.tn_version == 3
573
574
575 def test_plugin_macosx_probe_absurd_version(mocker, macos_notify_environment):
576 """A version too large to convert falls back instead of raising."""
577
578 mocker.patch(
579 "subprocess.run",
580 return_value=Mock(
581 returncode=0, stdout=b"terminal-notifier " + b"9" * 5000 + b".0"
582 ),
583 )
584
585 obj = apprise.Apprise.instantiate("macosx://", suppress_exceptions=False)
586 assert obj.tn_version == 3
587
588
589 @pytest.mark.parametrize(
590 "failure",
591 [
592 OSError("vanished"),
593 subprocess.TimeoutExpired(cmd="terminal-notifier", timeout=30),
594 ],
595 )
596 def test_plugin_macosx_run_failure(mocker, macos_notify_environment, failure):
597 """A program that disappears or hangs is reported, not raised."""
598
599 mocker.patch("subprocess.run", side_effect=failure)
600
601 obj = apprise.Apprise.instantiate(
602 "macosx://_/?version=3", suppress_exceptions=False
603 )
604 assert obj.notify(title="title", body="body") is False