Debian Codegraph @

tests/test_notify_send.py

raw
1 # This program is free software; you can redistribute it and/or modify it under
2 # the terms of the GNU Lesser General Public License as published by the Free
3 # Software Foundation; either version 3 of the License, or (at your option) any
4 # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text
5 # of the license.
6
7 __author__ = "Martin Pitt"
8 __copyright__ = """
9 (c) 2012 Canonical Ltd.
10 (c) 2017 - 2022 Martin Pitt <[email protected]>
11 (c) 2025 Marco Trevisan <[email protected]>
12 """
13
14 import dbus
15 import dbusmock
16 import fcntl
17 import os
18 import shutil
19 import subprocess
20 import signal
21 import sys
22 import tempfile
23 import unittest
24
25 DBUS_IFACE = "org.freedesktop.Notifications"
26
27 DEFAULT_CAPS = [
28 "body",
29 "body-markup",
30 "icon-static",
31 "image/svg+xml",
32 "private-synchronous",
33 "append",
34 "private-icon-only",
35 "truncation",
36 ]
37
38 notify_send = os.environ.get("NOTIFY_SEND", None)
39
40 if not notify_send:
41 notify_send = shutil.which("notify-send")
42
43 subprocess.check_output([notify_send, "--version"], text=True)
44
45 class TemporaryFD:
46 """ Create a temporary FD, do not use memfd as it may be less portable """
47 def __init__(self, prefix="temporary-fd"):
48 self.prefix = prefix
49 self.fd = -1
50 self.temporary = None
51
52 def __enter__(self):
53 self.temporary = tempfile.NamedTemporaryFile(prefix=self.prefix)
54 self.fd = os.open(self.temporary.name, os.O_RDWR|os.O_CREAT)
55 return [self.fd, self.temporary]
56
57 def __exit__(self, exc_type, exc_value, traceback):
58 os.close(self.fd)
59 self.temporary.close()
60
61
62
63 class TestBaseNotifySend(dbusmock.DBusTestCase):
64 """Test mocking notification-daemon"""
65
66 @classmethod
67 def setUpClass(cls):
68 cls.start_session_bus()
69 cls.dbus_con = cls.get_dbus(False)
70 cls.caps = DEFAULT_CAPS.copy()
71 cls.template = None
72 cls.env = os.environ.copy()
73
74 @classmethod
75 def get_local_asset(self, *args):
76 path = os.path.join(os.path.dirname(__file__), *args)
77 self.assertTrue(os.path.exists(path), f"{path} does not exist")
78 return path
79
80 def setUp(self):
81 (self.p_mock, self.obj_daemon) = self.spawn_server_template(
82 self.template, {"capabilities": " ".join(self.caps)},
83 stdout=subprocess.PIPE,
84 )
85 # set log to nonblocking
86 flags = fcntl.fcntl(self.p_mock.stdout, fcntl.F_GETFL)
87 fcntl.fcntl(self.p_mock.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK)
88
89 def tearDown(self):
90 self.p_mock.stdout.close()
91 self.p_mock.terminate()
92 self.p_mock.wait()
93
94 def assertDaemonCall(self, method):
95 calls = self.obj_daemon.GetMethodCalls(method)
96 self.assertEqual(len(calls), 1)
97 [ret, args] = calls[0]
98 print(method, "Called with:", args, "=>", ret)
99 return args
100
101 def assertNoDaemonCall(self, method):
102 self.assertFalse(self.obj_daemon.GetMethodCalls(method))
103
104 def notify_send_proc(self, args=[], stdout=None, stderr=None, pass_fds=[]):
105 print("Launching", [notify_send] + args, "With FDs", pass_fds)
106 ns_proc = subprocess.Popen([notify_send] + args, env=self.env,
107 stdout=stdout, stderr=stderr,
108 pass_fds=pass_fds)
109 return ns_proc
110
111 def notify_send(self, args=[]):
112 ns_proc = self.notify_send_proc(args)
113 ns_proc.wait()
114 self.assertEqual(ns_proc.returncode, 0)
115 return ns_proc
116
117 def notify_send_wait_id(self, args=[], stdout=None, stderr=None, pass_fds=[]):
118 with TemporaryFD("notification-id") as tmpfd:
119 [fd, tmp] = tmpfd
120 ns_proc = self.notify_send_proc([f"--id-fd={fd}"] + args,
121 stdout=stdout,
122 stderr=stderr,
123 pass_fds=pass_fds + [fd])
124
125 fd_value = self.wait_for_output(ns_proc, tmp)
126
127 self.assertIsNone(ns_proc.poll())
128 return [ns_proc, int(fd_value.strip())]
129
130 def wait_for_output(self, process, io_channel, want_value=None):
131 while True:
132 line = io_channel.readline()
133 if (not want_value and line) or (
134 want_value and want_value.encode() in line) or process.poll():
135 break
136
137 try:
138 process.communicate(timeout=0.5)
139 except subprocess.TimeoutExpired:
140 pass
141
142 line = line.decode('utf-8')
143
144 if want_value:
145 self.assertIn(want_value, line)
146 else:
147 self.assertTrue(line)
148
149 return line.strip()
150
151
152 class TestBaseFDONotifySend(TestBaseNotifySend):
153 """Test mocking notification-daemon"""
154
155 @classmethod
156 def setUpClass(cls):
157 TestBaseNotifySend.setUpClass()
158 cls.caps = DEFAULT_CAPS.copy()
159 cls.template = "notification_daemon"
160 cls.env["NOTIFY_IGNORE_PORTAL"] = "1"
161
162 def assertNotificationMatches(
163 self,
164 notification,
165 exp_app_name="notify-send",
166 exp_replaces_id=0,
167 exp_app_icon="",
168 exp_summary="",
169 exp_body="",
170 exp_actions=[],
171 exp_hints={},
172 exp_expire_timeout=-1,
173 ):
174 [
175 app_name,
176 replaces_id,
177 app_icon,
178 summary,
179 body,
180 actions,
181 hints,
182 expire_timeout,
183 ] = notification
184
185 self.assertEqual(app_name, exp_app_name)
186 self.assertEqual(replaces_id, exp_replaces_id)
187 self.assertEqual(app_icon, exp_app_icon)
188 self.assertEqual(summary, exp_summary)
189 self.assertEqual(body, exp_body)
190 self.assertEqual(actions, exp_actions)
191 self.assertEqual(hints, exp_hints)
192 self.assertEqual(expire_timeout, exp_expire_timeout)
193
194
195 class TestNotifySend(TestBaseFDONotifySend):
196 """Test mocking notification-daemon"""
197
198 def test_no_options(self):
199 """notify-send with no options"""
200
201 ns_proc = self.notify_send(["title", "my text"])
202
203 notification = self.assertDaemonCall("Notify")
204 self.assertNotificationMatches(
205 notification,
206 exp_summary="title",
207 exp_body="my text",
208 exp_hints={
209 "urgency": 1,
210 "sender-pid": ns_proc.pid,
211 },
212 )
213
214 def test_options(self):
215 """notify-send with some options"""
216
217 ns_proc = self.notify_send(
218 [
219 "--replace-id", "1234",
220 "--expire-time", "27",
221 "--app-name", "foo.App",
222 "--app-icon", "some-app-icon",
223 "--icon", "some-icon",
224 "--category", "some.category",
225 "--transient",
226 "--hint", "string:desktop-entry:notify-send-app",
227 "--urgency", "critical",
228 "title",
229 "my text",
230 ]
231 )
232
233 notification = self.assertDaemonCall("Notify")
234 self.assertNotificationMatches(
235 notification,
236 exp_replaces_id=1234,
237 exp_app_name="foo.App",
238 exp_app_icon="some-app-icon",
239 exp_summary="title",
240 exp_body="my text",
241 exp_expire_timeout=27,
242 exp_hints={
243 "urgency": 2,
244 "sender-pid": ns_proc.pid,
245 "image_path": "some-icon",
246 "category": "some.category",
247 "desktop-entry": "notify-send-app",
248 "transient": True,
249 },
250 )
251
252 def test_image_only(self):
253 """notify-send with image"""
254
255 ns_proc = self.notify_send(["image-only", "-i", "my-image"])
256
257 notification = self.assertDaemonCall("Notify")
258 self.assertNotificationMatches(
259 notification,
260 exp_summary="image-only",
261 exp_hints={
262 "urgency": 1,
263 "sender-pid": ns_proc.pid,
264 "image_path": "my-image",
265 },
266 )
267
268 def test_file_image_only(self):
269 """notify-send with local image"""
270
271 image_file = self.get_local_asset("applet-critical.png")
272 ns_proc = self.notify_send(["image-only", "-i", image_file])
273
274 notification = self.assertDaemonCall("Notify")
275 self.assertNotificationMatches(
276 notification,
277 exp_summary="image-only",
278 exp_hints={
279 "urgency": 1,
280 "sender-pid": ns_proc.pid,
281 "image_path": image_file,
282 },
283 )
284
285 def test_app_icon_only(self):
286 """notify-send with app-icon"""
287
288 ns_proc = self.notify_send(["app-icon-only", "-n", "my-app-icon"])
289
290 notification = self.assertDaemonCall("Notify")
291 self.assertNotificationMatches(
292 notification,
293 exp_summary="app-icon-only",
294 exp_app_icon="my-app-icon",
295 exp_hints={
296 "urgency": 1,
297 "sender-pid": ns_proc.pid,
298 },
299 )
300
301 def test_custom_hints(self):
302 """notify-send with some custom hints"""
303
304 ns_proc = self.notify_send(
305 [
306 "-h", "int:int-hint:55",
307 "-h", "double:double-hint:5.5",
308 "-h", "byte:byte-hint:255",
309 "-h", "byte:byte-hex-hint:0x11",
310 "-h", "boolean:boolean-hint-true:true",
311 "-h", "boolean:boolean-hint-TRUE:TRUE",
312 "-h", "boolean:boolean-hint-not-true:not-true",
313 "-h", "boolean:boolean-hint-false:false",
314 "-h", "boolean:boolean-hint-FALSE:FALSE",
315 "-h", "variant:variant-hint-dict:{'a': 1, 'b': 2}",
316 "-h", "string:string-hint:string-hint-value",
317 "hints!"
318 ]
319 )
320
321 notification = self.assertDaemonCall("Notify")
322 self.assertNotificationMatches(
323 notification,
324 exp_summary="hints!",
325 exp_hints={
326 "urgency": 1,
327 "sender-pid": ns_proc.pid,
328 "int-hint": 55,
329 "double-hint": 5.5,
330 "byte-hint": 0xff,
331 "byte-hex-hint": 0x11,
332 "boolean-hint-true": True,
333 "boolean-hint-TRUE": True,
334 "boolean-hint-not-true": False,
335 "boolean-hint-false": False,
336 "boolean-hint-FALSE": False,
337 "variant-hint-dict": {'a': 1, 'b': 2},
338 "string-hint": "string-hint-value",
339 },
340 )
341
342 def test_actions_not_supported(self):
343 """notify-send with action not supported"""
344
345 ns_proc = self.notify_send_proc([
346 "action!", "Chose it",
347 "--print-id",
348 "--action=Foo",
349 "--action=Bar=bar-item",
350 ], stderr=subprocess.PIPE)
351
352 [_, stderr] = ns_proc.communicate(timeout=5)
353 ns_proc.wait()
354
355 self.assertEqual(ns_proc.returncode, 1)
356 self.assertIn("Actions are not supported by this notifications server. " +
357 "Displaying non-interactively", stderr.decode("utf-8"))
358
359 notification = self.assertDaemonCall("Notify")
360 self.assertNotificationMatches(
361 notification,
362 exp_summary="action!",
363 exp_body="Chose it",
364 exp_hints={
365 "urgency": 1,
366 "sender-pid": ns_proc.pid,
367 },
368 )
369
370 def test_close_notification(self):
371 [ns_proc, notification_id] = self.notify_send_wait_id([
372 "Wait me", "--wait",
373 ], stdout=subprocess.PIPE)
374
375 self.obj_daemon.EmitSignal(DBUS_IFACE, "NotificationClosed", "uu",
376 (notification_id, 3))
377 [stdout, _] = ns_proc.communicate(timeout=5)
378 self.assertFalse(stdout.decode("utf-8").strip())
379 self.assertEqual(ns_proc.returncode, 0)
380
381 def test_sigint_while_notifying(self):
382 [ns_proc, _] = self.notify_send_wait_id([
383 "Wait and cancel me", "--wait",
384 ], stderr=subprocess.PIPE)
385
386 ns_proc.send_signal(signal.SIGINT)
387 [_, stderr] = ns_proc.communicate()
388
389 self.assertEqual(ns_proc.returncode, 0)
390 self.assertIn("Wait cancelled, closing notification",
391 stderr.decode("utf-8"))
392
393
394 class TestNotifySendActions(TestBaseFDONotifySend):
395 """Test mocking notification-daemon with actions"""
396
397 @classmethod
398 def setUpClass(cls):
399 TestBaseFDONotifySend.setUpClass()
400 cls.caps.append("actions")
401
402 def show_actions_notification(self, actions, stdout=subprocess.PIPE, stderr=None,
403 selected_action_fd=None, activation_token_fd=None):
404 args = ["action!", "Choose it"]
405
406 exp_actions = []
407 for action in actions:
408 label = action[0]
409 if len(action) > 1:
410 action_id = action[1]
411 args.append(f"--action={action_id}={label}")
412 else:
413 action_id = str(int(len(exp_actions) / 2))
414 args.append(f"--action={label}")
415
416 if action_id in exp_actions:
417 action_idx = exp_actions.index(action_id)
418 del exp_actions[action_idx + 1]
419 exp_actions.insert(action_idx + 1, label)
420 continue
421
422 exp_actions.append(action_id)
423 exp_actions.append(label)
424
425 pass_fds=[]
426 if selected_action_fd:
427 args.append(f"--selected-action-fd={selected_action_fd}")
428 pass_fds.append(selected_action_fd)
429 if activation_token_fd:
430 args.append(f"--activation-token-fd={activation_token_fd}")
431 pass_fds.append(activation_token_fd)
432
433 [ns_proc, notification_id] = self.notify_send_wait_id(args,
434 stdout=stdout,
435 stderr=stderr,
436 pass_fds=pass_fds)
437
438 notification = self.assertDaemonCall("Notify")
439 self.assertNotificationMatches(
440 notification,
441 exp_summary="action!",
442 exp_body="Choose it",
443 exp_actions=exp_actions,
444 exp_hints={
445 "urgency": 1,
446 "sender-pid": ns_proc.pid,
447 },
448 )
449
450 return [ns_proc, notification_id]
451
452 def check_activate_action(self, action_id, actions=[("Foo",), ("Bar", "bar-action")],
453 activation_token="activation-token"):
454 with TemporaryFD("action-id") as tmpfd:
455 [action_fd, action_tmp] = tmpfd
456 with TemporaryFD("token-id") as tmptokenfd:
457 [token_fd, token_tmp] = tmptokenfd
458 [ns_proc, notification_id] = self.show_actions_notification(actions,
459 selected_action_fd=action_fd,
460 activation_token_fd=token_fd)
461 if activation_token:
462 activation_token += f"-{action_fd}-{token_fd}"
463 self.obj_daemon.EmitSignal(DBUS_IFACE, "ActivationToken", "us",
464 (notification_id, activation_token))
465
466 action_id = str(action_id)
467 self.obj_daemon.EmitSignal(DBUS_IFACE, "ActionInvoked", "us",
468 (notification_id, action_id))
469
470 action_value = self.wait_for_output(ns_proc, action_tmp)
471 token_value = self.wait_for_output(ns_proc, token_tmp)
472
473 [stdout, _] = ns_proc.communicate(timeout=5)
474 self.assertEqual(action_value, action_id)
475 self.assertIn(action_id, stdout.decode('utf-8'))
476 self.assertEqual(ns_proc.returncode, 0)
477
478 if activation_token:
479 self.assertEqual(token_value, activation_token)
480 else:
481 self.assertFalse(token_value)
482
483 def test_activate_numeric_action(self):
484 """notify-send with action"""
485 self.check_activate_action(0)
486
487 def test_activate_named_action(self):
488 """notify-send with action"""
489 self.check_activate_action("bar-action")
490
491 def test_activate_third_unnamed_action(self):
492 """notify-send with action"""
493 self.check_activate_action(action_id=2, actions=[
494 ("foo",), ("default", "id"), ("baz",)])
495
496 def test_activate_replaced_action(self):
497 """notify-send with action"""
498 self.check_activate_action(action_id="foo-action", actions=[
499 ("Foo", "foo-action"), ("FooBar", "foo-action")])
500
501 def test_activate_invalid_action(self):
502 with TemporaryFD("action-id") as tmpfd:
503 [fd, tmp] = tmpfd
504 [ns_proc, notification_id] = self.show_actions_notification([("Foo", "foo")],
505 stderr=subprocess.PIPE,
506 selected_action_fd=fd)
507 action_id = "bar"
508 self.obj_daemon.EmitSignal(DBUS_IFACE, "ActionInvoked", "us",
509 (notification_id, action_id))
510
511 self.wait_for_output(ns_proc, ns_proc.stderr,
512 f"Received unknown action {action_id}")
513
514 ns_proc.send_signal(signal.SIGINT)
515 [stdout, stderr] = ns_proc.communicate(timeout=5)
516 self.assertNotIn(action_id, stdout.decode("utf-8").strip())
517 self.assertIn("Wait cancelled, closing notification",
518 stderr.decode("utf-8").strip())
519 self.assertEqual(ns_proc.returncode, 0)
520
521 self.assertFalse(tmp.readlines())
522
523 def test_close_notification(self):
524 [ns_proc, notification_id] = self.show_actions_notification([("Foo",)])
525
526 self.obj_daemon.EmitSignal(DBUS_IFACE, "NotificationClosed", "uu",
527 (notification_id, 2))
528 [stdout, _] = ns_proc.communicate(timeout=5)
529 self.assertFalse(stdout.decode("utf-8").strip())
530 self.assertEqual(ns_proc.returncode, 0)
531
532
533 class TestBasePortalNotifySend(TestBaseNotifySend):
534 """Test notify-send with portal"""
535
536 def assertNotificationMatches(
537 self,
538 args,
539 exp_id=0,
540 exp_notification={},
541 ):
542 [
543 notification_id,
544 notification,
545 ] = args
546
547 self.assertEqual(notification_id, exp_id)
548 self.assertEqual(notification, exp_notification)
549
550 @classmethod
551 def setUpClass(cls):
552 TestBaseNotifySend.setUpClass()
553 cls.caps = DEFAULT_CAPS.copy()
554 cls.template = cls.get_local_asset("portal_template.py")
555 cls.env["NOTIFY_FORCE_PORTAL"] = "1"
556
557
558 class TestPortalNotifySend(TestBasePortalNotifySend):
559 """Test notify-send with portal"""
560
561 def test_no_options(self):
562 """notify-send with no options"""
563
564 self.notify_send(["title", "my text"])
565
566 notification = self.assertDaemonCall("AddNotification")
567 self.assertNotificationMatches(
568 notification,
569 exp_id="libnotify-flatpak.(null)-notify-send-1",
570 exp_notification={
571 "title": "title",
572 "body": "my text",
573 "priority": "normal",
574 },
575 )
576
577 def test_options(self):
578 """notify-send with some options"""
579
580 self.notify_send(
581 [
582 "--replace-id", "1234",
583 "--expire-time", "27",
584 "--app-name", "foo.App",
585 "--app-icon", "some-app-icon",
586 "--icon", "some-icon",
587 "--category", "some.category",
588 "--transient",
589 "--hint", "string:desktop-entry:notify-send-app",
590 "--urgency", "critical",
591 "title",
592 "my text",
593 ]
594 )
595
596 notification = self.assertDaemonCall("AddNotification")
597 self.assertNotificationMatches(
598 notification,
599 exp_id="libnotify-flatpak.(null)-notify-send-1234",
600 exp_notification={
601 "title": "title",
602 "body": "my text",
603 "priority": "urgent",
604 "icon": ("themed", (["some-icon", "some-icon-symbolic"])),
605 },
606 )
607
608 def test_image_only(self):
609 """notify-send with image"""
610
611 self.notify_send(["image-only", "-i", "my-image"])
612
613 notification = self.assertDaemonCall("AddNotification")
614 self.assertNotificationMatches(
615 notification,
616 exp_id="libnotify-flatpak.(null)-notify-send-1",
617 exp_notification={
618 "title": "image-only",
619 "body": "",
620 "priority": "normal",
621 "icon": ("themed", (["my-image", "my-image-symbolic"])),
622 },
623 )
624
625 def test_file_image_only(self):
626 """notify-send with local image"""
627
628 image_path = self.get_local_asset("applet-critical.png")
629 self.notify_send(["image-path-only", "-i", image_path])
630
631 with open(image_path, 'rb') as image_file:
632 image_bytes = image_file.read()
633 notification = self.assertDaemonCall("AddNotification")
634 self.assertNotificationMatches(
635 notification,
636 exp_id="libnotify-flatpak.(null)-notify-send-1",
637 exp_notification={
638 "title": "image-path-only",
639 "body": "",
640 "priority": "normal",
641 "icon": ("bytes", dbus.Array(image_bytes, signature="y")),
642 },
643 )
644
645 def test_missing_file_image_only(self):
646 """notify-send with missing local image"""
647
648 ns_proc = self.notify_send_proc(["image-path-only", "-i",
649 "file:///this-must-not|exist"])
650 ns_proc.wait()
651 self.assertEqual(ns_proc.returncode, 1)
652 self.assertNoDaemonCall("AddNotification")
653
654 def test_app_icon_only(self):
655 """notify-send with app-icon"""
656
657 self.notify_send(["app-icon-only", "-n", "my-app-icon"])
658
659 notification = self.assertDaemonCall("AddNotification")
660 self.assertNotificationMatches(
661 notification,
662 exp_id="libnotify-flatpak.(null)-notify-send-1",
663 exp_notification={
664 "title": "app-icon-only",
665 "body": "",
666 "priority": "normal",
667 },
668 )
669
670 def test_custom_hints(self):
671 """notify-send with some custom hints"""
672
673 self.notify_send(
674 [
675 "-h", "int:int-hint:55",
676 "-h", "double:double-hint:5.5",
677 "-h", "byte:byte-hint:255",
678 "-h", "byte:byte-hex-hint:0x11",
679 "-h", "boolean:boolean-hint-true:true",
680 "-h", "boolean:boolean-hint-TRUE:TRUE",
681 "-h", "boolean:boolean-hint-not-true:not-true",
682 "-h", "boolean:boolean-hint-false:false",
683 "-h", "boolean:boolean-hint-FALSE:FALSE",
684 "-h", "variant:variant-hint-dict:{'a': 1, 'b': 2}",
685 "-h", "string:string-hint:string-hint-value",
686 "hints!"
687 ]
688 )
689
690 notification = self.assertDaemonCall("AddNotification")
691 self.assertNotificationMatches(
692 notification,
693 exp_id="libnotify-flatpak.(null)-notify-send-1",
694 exp_notification={
695 "title": "hints!",
696 "body": "",
697 "priority": "normal",
698 },
699 )
700
701
702 class TestPortalNotifySendActions(TestBasePortalNotifySend):
703 """Test notify-send using portal with actions"""
704
705 def show_actions_notification(self, actions, stdout=subprocess.PIPE, stderr=None,
706 selected_action_fd=None, activation_token_fd=None):
707 args = ["action!", "Choose it"]
708
709 exp_actions = []
710 for action in actions:
711 label = action[0]
712 if len(action) > 1:
713 action_id = action[1]
714 args.append(f"--action={action_id}={label}")
715 else:
716 action_id = str(int(len(exp_actions)))
717 args.append(f"--action={label}")
718
719 other = [a for a in exp_actions if a["action"] == action_id]
720 if other:
721 other[0]["label"] = label
722 continue
723
724 exp_actions.append({"label": label, "action": action_id})
725
726 pass_fds=[]
727 if selected_action_fd:
728 args.append(f"--selected-action-fd={selected_action_fd}")
729 pass_fds.append(selected_action_fd)
730 if activation_token_fd:
731 args.append(f"--activation-token-fd={activation_token_fd}")
732 pass_fds.append(activation_token_fd)
733
734 [ns_proc, _] = self.notify_send_wait_id(args, stdout=stdout, stderr=stderr,
735 pass_fds=pass_fds)
736
737 notification = self.assertDaemonCall("AddNotification")
738
739 self.assertNotificationMatches(
740 notification,
741 exp_id="libnotify-flatpak.(null)-notify-send-1",
742 exp_notification={
743 "title": "action!",
744 "body": "Choose it",
745 "priority": "normal",
746 "buttons": dbus.Array(exp_actions, signature="a{sv}"),
747 },
748 )
749
750 return [ns_proc, notification[0]]
751
752 def check_activate_action(self, action_id, actions=[("Foo",), ("Bar", "bar-action")]):
753 with TemporaryFD("action-id") as tmpfd:
754 [fd, tmp] = tmpfd
755 [ns_proc, notification_id] = self.show_actions_notification(actions,
756 selected_action_fd=fd)
757 action_id = str(action_id)
758 self.obj_daemon.EmitActionInvoked(notification_id, action_id,
759 dbus.Array((), signature="v"))
760
761 fd_value = self.wait_for_output(ns_proc, tmp)
762
763 [stdout, _] = ns_proc.communicate(timeout=5)
764 self.assertEqual(fd_value, action_id)
765 self.assertIn(action_id, stdout.decode('utf-8'))
766 self.assertEqual(ns_proc.returncode, 0)
767
768 def test_activate_numeric_action(self):
769 """notify-send with action"""
770 self.check_activate_action(0)
771
772 def test_activate_named_action(self):
773 """notify-send with action"""
774 self.check_activate_action("bar-action")
775
776 def test_activate_third_unnamed_action(self):
777 """notify-send with action"""
778 self.check_activate_action(action_id=2, actions=[
779 ("foo",), ("default", "id"), ("baz",)])
780
781 def test_activate_replaced_action(self):
782 """notify-send with action"""
783 self.check_activate_action(action_id="foo-action", actions=[
784 ("Foo", "foo-action"), ("FooBar", "foo-action")])
785
786 def test_activate_invalid_action(self):
787 with TemporaryFD("action-id") as tmpfd:
788 [fd, tmp] = tmpfd
789
790 [ns_proc, notification_id] = self.show_actions_notification([("Foo", "foo")],
791 stderr=subprocess.PIPE,
792 selected_action_fd=fd)
793
794 action_id = "bar"
795 self.obj_daemon.EmitActionInvoked(notification_id, action_id,
796 dbus.Array((), signature="v"))
797
798 self.wait_for_output(ns_proc, ns_proc.stderr,
799 f"Received unknown action {action_id}")
800
801 ns_proc.send_signal(signal.SIGINT)
802 [stdout, _] = ns_proc.communicate(timeout=5)
803 self.assertNotIn(action_id, stdout.decode("utf-8").strip())
804 self.assertEqual(ns_proc.returncode, 0)
805
806 self.assertFalse(tmp.readlines())
807
808
809 if __name__ == "__main__":
810 # avoid writing to stderr
811 unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout))