Debian Codegraph @

tests/runner/run-daemon-test.py

raw
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2026 Matthias Klumpp <[email protected]>
4 #
5 # SPDX-License-Identifier: LGPL-2.1-or-later
6 #
7
8 """Run the PackageKit daemon tests.
9
10 The pk-test-e2e binary exercises the client library against a running
11 PackageKit daemon (using the dummy backend) over the system D-Bus.
12 This script forwards the test binary's output straight to stdout/stderr
13 and keeps the daemon's own output in a buffer that is only printed
14 when something goes wrong.
15
16 The script reuses a running system bus and polkit authority if present, and
17 otherwise starts private ones just for the test run (tearing them down again
18 afterwards).
19
20 Prerequisites:
21 * /usr/share/dbus-1/system.d/org.freedesktop.PackageKit.conf (D-Bus policy)
22 * /usr/share/polkit-1/actions/org.freedesktop.packagekit.policy (polkit actions)
23 * run as the configured PackageKit user (root by default)
24
25 When a prerequisite is missing the script exits with code 77 (meson's "skip"
26 code) instead of failing, so it stays out of the way on machines that cannot
27 run it.
28 """
29
30 import os
31 import pty
32 import sys
33 import fcntl
34 import select
35 import shutil
36 import termios
37 import argparse
38 import tempfile
39 import subprocess
40
41 from utils import (
42 terminate,
43 system_bus_reachable,
44 start_polkitd_if_needed,
45 start_system_bus_if_needed,
46 )
47
48 # meson interprets this exit code as "test skipped"
49 EXIT_SKIP = 77
50
51 PK_BUS_NAME = 'org.freedesktop.PackageKit'
52 DBUS_CONF = '/usr/share/dbus-1/system.d/org.freedesktop.PackageKit.conf'
53 POLKIT_POLICY = '/usr/share/polkit-1/actions/org.freedesktop.packagekit.policy'
54
55
56 def check_prerequisites():
57 """Return a list of human-readable reasons the test cannot run, if any."""
58 reasons = []
59 if not os.path.exists(DBUS_CONF):
60 reasons.append(
61 'Missing D-Bus policy {!r}. Install it with:\n'
62 ' sudo cp data/org.freedesktop.PackageKit.conf '
63 '/usr/share/dbus-1/system.d/'.format(DBUS_CONF)
64 )
65 if not os.path.exists(POLKIT_POLICY):
66 reasons.append(
67 'Missing polkit policy {!r}. Install it with:\n'
68 ' sudo cp policy/org.freedesktop.packagekit.policy '
69 '/usr/share/polkit-1/actions/'.format(POLKIT_POLICY)
70 )
71 if not shutil.which('gdbus'):
72 reasons.append('gdbus is missing. Please install it!')
73 if not system_bus_reachable() and shutil.which('dbus-daemon') is None:
74 reasons.append('No system bus running and dbus-daemon is not available ' 'to start one.')
75 return reasons
76
77
78 def wait_for_bus_name(timeout=30):
79 """Block until packagekitd owns its name on the system bus."""
80 try:
81 subprocess.run(
82 ['gdbus', 'wait', '--system', '--timeout', str(timeout), PK_BUS_NAME], check=True
83 )
84 return True
85 except subprocess.CalledProcessError:
86 return False
87
88
89 def _answer_for_prompt(prompt):
90 """Pick the answer for an interactive yes/no prompt.
91
92 Some subtests script specific keystrokes ("press N" expects a 'no', the
93 rest a default 'yes'); every real confirmation (untrusted software, EULAs,
94 "Proceed with changes?", ...) is accepted.
95 """
96 if 'press N' in prompt:
97 return 'N\n'
98 if 'press Y' in prompt:
99 return 'Y\n'
100 if 'press enter' in prompt:
101 return '\n'
102 return 'y\n'
103
104
105 def run_test_with_auto_answers(test_binary, env):
106 """Run the test binary on a pseudo-terminal, answering its prompts.
107
108 pk_console_get_prompt() reads from the controlling terminal (/dev/tty), so the test cannot
109 be driven by a plain pipe. We give it a PTY as its controlling terminal, forward everything
110 it prints to our stdout (so meson still sees the TAP stream) and write a canned answer whenever a
111 "... [Y/n]"/"... [N/y]" prompt appears.
112
113 Returns the test's exit code.
114 """
115 master, slave = pty.openpty()
116
117 def _make_controlling_tty():
118 # Runs in the child after its std fds have been pointed at the slave
119 # PTY; claim it as the controlling terminal so /dev/tty resolves here.
120 fcntl.ioctl(0, termios.TIOCSCTTY, 0)
121
122 proc = subprocess.Popen(
123 [test_binary],
124 stdin=slave,
125 stdout=slave,
126 stderr=slave,
127 env=env,
128 start_new_session=True,
129 preexec_fn=_make_controlling_tty,
130 )
131 os.close(slave)
132
133 line = ''
134 # The last answer we sent, and how many times we have re-sent it. Answering
135 # a prompt the instant it appears can race with the child's terminal setup
136 # and get the reply dropped; if the child then goes silent we re-send rather
137 # than block forever. Any new output means the child consumed the answer and
138 # moved on, so we stop re-sending to avoid leaking a stray answer into a
139 # later prompt.
140 pending_answer = None
141 resends = 0
142 max_resends = 2
143 try:
144 while True:
145 try:
146 readable, _, _ = select.select([master], [], [], 1.0)
147 except (OSError, select.error):
148 break
149 if master in readable:
150 try:
151 data = os.read(master, 4096)
152 except OSError:
153 break # slave closed: the child has exited
154 if not data:
155 break
156 text = data.decode('utf-8', 'replace')
157 sys.stdout.write(text)
158 sys.stdout.flush()
159
160 # Output means the child made progress and consumed whatever we
161 # last sent; stop re-sending it.
162 pending_answer = None
163 resends = 0
164
165 # Track the current (unterminated) line to spot a prompt.
166 line = (line + text).rsplit('\n', 1)[-1]
167 stripped = line.rstrip()
168 if stripped.endswith('[Y/n]') or stripped.endswith('[N/y]'):
169 pending_answer = _answer_for_prompt(line).encode('utf-8')
170 os.write(master, pending_answer)
171 line = ''
172 elif proc.poll() is not None:
173 break
174 elif pending_answer is not None and resends < max_resends:
175 # Child is alive but silent after we answered: the reply was most
176 # likely dropped, so send it again.
177 os.write(master, pending_answer)
178 resends += 1
179 finally:
180 os.close(master)
181
182 return proc.wait()
183
184
185 def main():
186 # Line-buffer stdout so our progress messages stay correctly interleaved
187 sys.stdout.reconfigure(line_buffering=True)
188
189 parser = argparse.ArgumentParser(description='Run the PackageKit daemon test.')
190 parser.add_argument('--daemon', required=True, help='path to the packagekitd binary')
191 parser.add_argument('--test', required=True, help='path to the pk-test-e2e binary')
192 args = parser.parse_args()
193
194 reasons = check_prerequisites()
195 if reasons:
196 print('Skipping daemon test; prerequisites are not met:\n')
197 for reason in reasons:
198 print(' * ' + reason)
199 return EXIT_SKIP
200
201 if os.geteuid() != 0:
202 # The default D-Bus policy only lets the PackageKit user (root) own the
203 # name, so the test cannot meaningfully run otherwise. Skip rather than
204 # fail, so a plain `meson test` stays green for unprivileged developers.
205 print(
206 'Skipping daemon test: must run as root so packagekitd can own '
207 '{!r} on the system bus.'.format(PK_BUS_NAME)
208 )
209 return EXIT_SKIP
210
211 # The local backend loader (PK_BUILD_LOCAL) resolves the backend module
212 # relative to the build tree root, so launch the daemon from there.
213 build_root = os.environ.get('MESON_BUILD_ROOT')
214 if not build_root:
215 build_root = os.path.dirname(os.path.dirname(os.path.abspath(args.daemon)))
216
217 daemon = None
218 bus_proc = None
219 bus_tmpdir = None
220 polkitd_proc = None
221 # Keep the daemon output buffered and only print it on failure
222 daemon_log = tempfile.TemporaryFile()
223
224 def dump_daemon_log():
225 daemon_log.flush()
226 daemon_log.seek(0)
227 data = daemon_log.read().decode('utf-8', 'replace')
228 if data:
229 sys.stderr.write('\n--- daemon output ---\n')
230 sys.stderr.write(data)
231 sys.stderr.write('--- end daemon output ---\n')
232 sys.stderr.flush()
233
234 try:
235 # Reuse a running system bus and polkit authority if present; otherwise
236 # spin up private ones just for this test run.
237 bus_proc, bus_tmpdir = start_system_bus_if_needed(daemon_log)
238 polkitd_proc = start_polkitd_if_needed(daemon_log)
239
240 print('Launching {} with the dummy backend...'.format(args.daemon))
241 daemon = subprocess.Popen(
242 [args.daemon, '--verbose', '--disable-timer', '--keep-environment', '--backend=dummy'],
243 cwd=build_root,
244 stdout=daemon_log,
245 stderr=subprocess.STDOUT,
246 )
247
248 if not wait_for_bus_name():
249 print(
250 'ERROR: packagekitd never claimed {!r} on the system ' 'bus.'.format(PK_BUS_NAME),
251 file=sys.stderr,
252 )
253 if daemon.poll() is not None:
254 print(
255 'The daemon exited early (code {}); common causes are not '
256 'running as the PackageKit user (root), a missing/'
257 'unreachable polkit authority, or the backend failing to '
258 'load.'.format(daemon.returncode),
259 file=sys.stderr,
260 )
261 dump_daemon_log()
262 return 1
263
264 print('Daemon is up; running {}...'.format(args.test))
265
266 # Force a predictable locale so the (otherwise translated) prompt text stays in English
267 test_env = dict(os.environ, LC_ALL='C.UTF-8', LANG='C.UTF-8')
268
269 returncode = run_test_with_auto_answers(args.test, test_env)
270 if returncode != 0:
271 dump_daemon_log()
272 return returncode
273 finally:
274 # Tear down in reverse order, and only what we started ourselves
275 terminate(daemon)
276 terminate(polkitd_proc)
277 terminate(bus_proc)
278 if bus_tmpdir is not None:
279 shutil.rmtree(bus_tmpdir, ignore_errors=True)
280 daemon_log.close()
281
282
283 if __name__ == '__main__':
284 sys.exit(main())