Debian Codegraph @

tests/test_mainloop.py

raw
1 import os
2 import select
3 import signal
4 import unittest
5 import warnings
6
7 from gi.repository import GLib
8
9 from .helper import capture_exceptions
10
11
12 class TestMainLoop(unittest.TestCase):
13 @unittest.skipUnless(hasattr(os, "fork"), "no os.fork available")
14 def test_exception_handling(self):
15 pipe_r, pipe_w = os.pipe()
16
17 with warnings.catch_warnings():
18 warnings.filterwarnings("ignore", ".*may lead to deadlock.*")
19 pid = os.fork()
20 if pid == 0:
21 os.close(pipe_w)
22 select.select([pipe_r], [], [])
23 os.close(pipe_r)
24 os._exit(1)
25
26 def child_died(pid, status, loop):
27 loop.quit()
28 raise Exception("deadbabe")
29
30 loop = GLib.MainLoop()
31 GLib.child_watch_add(GLib.PRIORITY_DEFAULT, pid, child_died, loop)
32
33 os.close(pipe_r)
34 os.write(pipe_w, b"Y")
35 os.close(pipe_w)
36
37 with capture_exceptions() as exc:
38 loop.run()
39
40 assert len(exc) == 1
41 assert exc[0].type is Exception
42 assert exc[0].value.args[0] == "deadbabe"
43
44 @unittest.skipUnless(hasattr(os, "fork"), "no os.fork available")
45 @unittest.skipIf(os.environ.get("PYGI_TEST_GDB"), "SIGINT stops gdb")
46 def test_sigint(self):
47 r, w = os.pipe()
48 with warnings.catch_warnings():
49 warnings.filterwarnings("ignore", ".*may lead to deadlock.*")
50 pid = os.fork()
51 if pid == 0:
52 # wait for the parent process loop to start
53 os.read(r, 1)
54 os.close(r)
55
56 os.kill(os.getppid(), signal.SIGINT)
57 os._exit(0)
58
59 def notify_child():
60 # tell the child that it can kill the parent
61 os.write(w, b"X")
62 os.close(w)
63
64 GLib.idle_add(notify_child)
65 loop = GLib.MainLoop()
66 try:
67 loop.run()
68 self.fail("expected KeyboardInterrupt exception")
69 except KeyboardInterrupt:
70 pass
71 self.assertFalse(loop.is_running())
72 os.waitpid(pid, 0)