Debian Codegraph @

runtests.py

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 # Copyright (C) 2001, 2002 by Martin Pool <[email protected]>
4 # Copyright (C) 2003-2022 Wayne Davison
5 # Copyright (C) 2026 Andrew Tridgell
6 #
7 # Rewrite of runtests.sh in Python (runtests.sh is now deprecated).
8 #
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License version
11 # 2 as published by the Free Software Foundation.
12
13 """rsync test runner.
14
15 Invokes test scripts from testsuite/ and reports results.
16 Can be called by 'make check' or directly.
17
18 Usage:
19 ./runtests.py [options] [TEST ...]
20
21 Each TEST is a test name (e.g. 'delete') or glob pattern (e.g. 'xattr*').
22 If no tests are specified, all tests are run.
23 """
24
25 import argparse
26 import concurrent.futures
27 import fnmatch
28 import glob
29 import math
30 import os
31 import signal
32 import subprocess
33 import sys
34 import threading
35 import time
36
37 # Share the test exit-code enum with the test helpers. exitcodes.py lives in
38 # testsuite/ (next to this script); it has no import-time side effects.
39 sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'testsuite'))
40 from exitcodes import Exit
41
42
43 def _race_seconds(text):
44 """argparse type for --race-timeout: a finite, strictly positive number.
45
46 A race test loops `while monotonic() < deadline`, so a budget of 0 (or a
47 negative, or a NaN, which fails every comparison) runs the body ZERO times
48 and the test reports PASS without ever exercising its oracle -- a silently
49 disarmed security test, which is worse than a slow one. Infinity would run
50 until the unrelated per-test timeout. The old max(RACE_TIMEOUT, 10.0) floor
51 used to make this unreachable; validating here restores that guarantee."""
52 try:
53 secs = float(text)
54 except ValueError:
55 raise argparse.ArgumentTypeError(f'not a number: {text!r}')
56 if not math.isfinite(secs) or secs <= 0:
57 raise argparse.ArgumentTypeError(
58 f'must be a finite positive number of seconds, got {text!r}; '
59 'a zero/negative/NaN budget would make every race test pass '
60 'without running its race')
61 return secs
62
63
64 def parse_args():
65 p = argparse.ArgumentParser(description='Run rsync test suite')
66 p.add_argument('tests', nargs='*', metavar='TEST',
67 help='Test names or patterns to run (default: all)')
68 p.add_argument('--exclude', default=None, metavar='LIST',
69 help='Comma-separated test names/globs to skip entirely: '
70 'they are not run and not reported as skipped. Useful '
71 'for tests that cannot work in a given build/CI '
72 'environment (e.g. a restricted buildd chroot). '
73 'Falls back to the RSYNC_EXCLUDE environment variable.')
74 p.add_argument('-j', '--parallel', type=int, default=1, metavar='N',
75 help='Run up to N tests in parallel (default: 1)')
76 p.add_argument('--valgrind', action='store_true',
77 help='Run rsync under valgrind (logs to per-process files)')
78 p.add_argument('--valgrind-opts', default='', metavar='OPTS',
79 help='Extra valgrind options (e.g. "--leak-check=full")')
80 p.add_argument('--preserve-scratch', action='store_true',
81 help='Keep scratch directories after tests complete')
82 p.add_argument('--log-level', type=int, default=1, metavar='N',
83 help='Verbosity level 1-10 (default: 1)')
84 p.add_argument('--always-log', action='store_true',
85 help='Show test logs even for passing tests')
86 p.add_argument('--stop-on-fail', action='store_true',
87 help='Stop after first test failure')
88 p.add_argument('--timing', action='store_true',
89 help='After the run, report each test\'s wall-clock time, '
90 'slowest first. With -j N the report also shows how '
91 'much of the run the slowest test alone accounts for.')
92 p.add_argument('--timeout', type=int, default=300, metavar='SECS',
93 help='Per-test timeout in seconds (default: 300)')
94 p.add_argument('--race-timeout', type=_race_seconds, default=None, metavar='SECS',
95 help='Budget (seconds) a TOCTOU symlink-race test may spend '
96 'trying to win its race before concluding. Overrides '
97 'every such test\'s own default (5-15s, the suite\'s '
98 'slowest tests: a race test always spends its whole '
99 'budget). Lowering it speeds the suite up but weakens '
100 'the oracle. Unset: each test keeps its default.')
101 p.add_argument('--rsync-bin', default=None, metavar='PATH',
102 help='Path to rsync binary (default: ./rsync)')
103 p.add_argument('--rsync-bin2', default=None, metavar='PATH',
104 help='Path to a second ("peer") rsync binary used for the '
105 'daemon side and remote-shell --rsync-path. Lets the '
106 'suite mix two rsync versions over the wire. Default: '
107 'same as --rsync-bin (no version mixing).')
108 p.add_argument('--tooldir', default=None, metavar='DIR',
109 help='Tool/build directory (default: cwd)')
110 p.add_argument('--srcdir', default=None, metavar='DIR',
111 help='Source directory (default: script directory)')
112 p.add_argument('--protocol', type=int, default=None, metavar='VER',
113 help='Force protocol version (adds --protocol=VER to rsync)')
114 p.add_argument('--expect-skipped', default=None, metavar='LIST',
115 help='Comma-separated list of expected-skipped tests. An '
116 '@FILE entry reads a skip list (one test per line, '
117 '"#" comments); relative paths resolve against srcdir '
118 'and several may be composed, e.g. '
119 '@testsuite/skiplist/linux.txt,@testsuite/skiplist/proto29.txt. '
120 'A -NAME entry removes a name the rest of the spec '
121 'added, for a host that can really run a test its '
122 'platform list expects to skip.')
123 p.add_argument('--expect-result', default=None, metavar='FILE',
124 help='Path to an expected-outcome manifest (one '
125 '"<testname> <pass|skip|fail|xfail>" per line). When '
126 'set, ONLY the tests listed in FILE are run, and each '
127 "test's actual outcome is compared against its "
128 'expected one; any mismatch (including an unexpected '
129 'pass) fails the run. Used for version-mixing CI.')
130 p.add_argument('--daemon-tests-only', action='store_true',
131 help='Run only the tests that can reach the daemon '
132 'transport. Intended for a --use-tcp pass that follows '
133 'a full default-transport run: the tests this drops '
134 'never call start_test_daemon(), so they cannot observe '
135 '--use-tcp and would just repeat themselves. Disables '
136 'the expected-skip oracle (it describes a full run).')
137 p.add_argument('--use-tcp', action='store_true',
138 help='Run daemon tests against a real rsyncd bound to '
139 '127.0.0.1 (non-default). The default is the secure '
140 'stdio-pipe transport, which opens no listening '
141 'socket; --use-tcp exposes a loopback port for the '
142 'duration of each daemon test.')
143 return p.parse_args()
144
145
146 def find_setfacl_nodef(scratchbase):
147 """Determine the setfacl command to remove default ACLs."""
148 for cmd in [
149 ['setacl', '-k', 'u::7,g::5,o:5', scratchbase],
150 ['setfacl', '-k', scratchbase],
151 ['setfacl', '-s', 'u::7,g::5,o:5', scratchbase],
152 ]:
153 try:
154 subprocess.run(cmd, capture_output=True, timeout=5)
155 return cmd[:2] if cmd[0] == 'setacl' else cmd[:2]
156 except (FileNotFoundError, subprocess.TimeoutExpired):
157 continue
158 try:
159 r = subprocess.run(['setfacl', '--help'], capture_output=True, text=True, timeout=5)
160 if '-k,' in r.stdout or '-k,' in r.stderr:
161 return ['setfacl', '-k']
162 except (FileNotFoundError, subprocess.TimeoutExpired):
163 pass
164 return None
165
166
167 def get_tls_args(config_h):
168 """Determine TLS_ARGS from config.h."""
169 args = ''
170 try:
171 with open(config_h) as f:
172 text = f.read()
173 if '#define HAVE_LUTIMES 1' in text:
174 args += ' -l'
175 if '#undef CHOWN_MODIFIES_SYMLINK' in text:
176 args += ' -L'
177 except FileNotFoundError:
178 pass
179 return args.strip()
180
181
182 def read_shconfig(path):
183 """Read shell config variables from shconfig."""
184 env = {}
185 try:
186 with open(path) as f:
187 for line in f:
188 line = line.strip()
189 if line.startswith('#') or line.startswith('export') or not line:
190 continue
191 if '=' in line:
192 k, _, v = line.partition('=')
193 env[k.strip()] = v.strip().strip('"')
194 except FileNotFoundError:
195 pass
196 return env
197
198
199 def get_testuser():
200 """Determine the current test user."""
201 for cmd in ['/usr/bin/whoami', '/usr/ucb/whoami', '/bin/whoami']:
202 if os.path.isfile(cmd):
203 try:
204 return subprocess.check_output([cmd], text=True).strip()
205 except subprocess.CalledProcessError:
206 pass
207 try:
208 return subprocess.check_output(['id', '-un'], text=True).strip()
209 except (FileNotFoundError, subprocess.CalledProcessError):
210 return os.environ.get('LOGNAME', os.environ.get('USER', 'UNKNOWN'))
211
212
213 def _move_aside(path):
214 """Rename an un-removable directory to a unique sibling so its name is free.
215
216 A rename-storm symlink-race test can corrupt a directory on some filesystems
217 (OpenBSD FFS soft-updates can leave an "empty" dir that still reports
218 ENOTEMPTY/EPERM and only fsck clears). `rm -rf` then can't remove it, but
219 renaming the top dir aside succeeds even with a corrupted descendant, freeing
220 the original name for a clean scratchdir."""
221 n = 0
222 while os.path.exists(f"{path}.corrupt.{os.getpid()}.{n}"):
223 n += 1
224 try:
225 os.rename(path, f"{path}.corrupt.{os.getpid()}.{n}")
226 except OSError:
227 pass
228
229
230 def prep_scratch(scratchdir, srcdir, tooldir, setfacl_nodef):
231 """Prepare a scratch directory for a test."""
232 if os.path.isdir(scratchdir):
233 subprocess.run(['chmod', '-R', 'u+rwX', scratchdir], capture_output=True)
234 subprocess.run(['rm', '-rf', scratchdir], capture_output=True)
235 if os.path.isdir(scratchdir):
236 _move_aside(scratchdir) # rm -rf left corrupted debris; don't inherit it
237 os.makedirs(scratchdir, exist_ok=True)
238 if setfacl_nodef:
239 subprocess.run(setfacl_nodef + [scratchdir], capture_output=True)
240 try:
241 os.chmod(scratchdir, os.stat(scratchdir).st_mode & ~0o2000) # clear setgid
242 except OSError:
243 pass
244 src_link = os.path.join(scratchdir, 'src')
245 if not os.path.exists(src_link):
246 if os.path.isabs(srcdir):
247 os.symlink(srcdir, src_link)
248 else:
249 os.symlink(os.path.join(tooldir, srcdir), src_link)
250
251
252 # Python tests are identified by a positive "_test.py" suffix so that
253 # helper modules (e.g. rsyncfns.py) sit in testsuite/ without being mistaken
254 # for tests.
255 _PY_TEST_SUFFIX = '_test.py'
256
257
258 def _is_test_path(path):
259 return os.path.basename(path).endswith(_PY_TEST_SUFFIX)
260
261
262 def _testbase(path):
263 """Strip the test extension to get the canonical test name."""
264 base = os.path.basename(path)
265 if base.endswith(_PY_TEST_SUFFIX):
266 return base[:-len(_PY_TEST_SUFFIX)]
267 return base
268
269
270 def collect_tests(suitedir, patterns):
271 """Collect test scripts (_test.py) matching the given patterns."""
272 if not patterns:
273 candidates = glob.glob(os.path.join(suitedir, '*' + _PY_TEST_SUFFIX))
274 tests = sorted(p for p in candidates if _is_test_path(p))
275 else:
276 seen = set()
277 tests = []
278 for pat in patterns:
279 # Accept either bare name ("mkpath"), explicit extension, or glob.
280 if pat.endswith('.py'):
281 pats = [pat]
282 else:
283 pats = [pat + _PY_TEST_SUFFIX]
284 for p in pats:
285 for m in sorted(glob.glob(os.path.join(suitedir, p))):
286 if _is_test_path(m) and m not in seen:
287 seen.add(m)
288 tests.append(m)
289 return tests
290
291
292 # Tokens through which a test can reach the daemon transport. --use-tcp works by
293 # setting RSYNC_TEST_USE_TCP, which is read in exactly one place (rsyncfns
294 # USE_TCP) and acted on in exactly one function (start_test_daemon): a test whose
295 # source mentions none of these never gets there, so it behaves identically with
296 # and without --use-tcp and running it a second time under TCP buys no coverage.
297 #
298 # The list is the closure of every rsyncfns helper that reaches USE_TCP,
299 # start_rsyncd or claim_ports, plus the helper modules that open a daemon
300 # connection themselves and the bare literals a test might use directly. It is
301 # deliberately over-broad: a false positive only costs runtime, while a false
302 # negative would silently drop real coverage.
303 _DAEMON_API = (
304 'USE_TCP', 'require_tcp', 'start_test_daemon', 'start_rsyncd',
305 'claim_ports', 'claim_free_port', 'setup_chroot_inner',
306 'stdio_daemon', 'rsync_proto', 'DaemonClient',
307 'rsync://', '--daemon', 'rsyncd',
308 )
309
310
311 def select_daemon_tests(tests):
312 """Split `tests` into (daemon-transport tests, the rest).
313
314 Used by --daemon-tests-only so a TCP pass need not re-run the whole suite.
315 A test we cannot read is kept, not dropped -- the failure mode of this
316 filter must always be "ran too much"."""
317 keep, dropped = [], []
318 for path in tests:
319 try:
320 with open(path, errors='replace') as f:
321 text = f.read()
322 except OSError:
323 keep.append(path)
324 continue
325 (keep if any(tok in text for tok in _DAEMON_API) else dropped).append(path)
326 return keep, dropped
327
328
329 _VALID_OUTCOMES = ('pass', 'skip', 'fail', 'xfail')
330
331
332 def parse_expect_result(path):
333 """Parse an expected-outcome manifest into {testbase: outcome}.
334
335 One "<testname> <outcome>" entry per line; '#' comments and blank lines
336 are ignored. outcome is one of pass|skip|fail|xfail. The set of listed
337 tests doubles as the run set (see main()). Exits 2 on a malformed file.
338 """
339 expect = {}
340 with open(path) as f:
341 for lineno, raw in enumerate(f, 1):
342 line = raw.split('#', 1)[0].strip()
343 if not line:
344 continue
345 fields = line.split()
346 if len(fields) != 2 or fields[1] not in _VALID_OUTCOMES:
347 sys.stderr.write(
348 f"{path}:{lineno}: expected '<testname> "
349 f"<{'|'.join(_VALID_OUTCOMES)}>', got: {raw.rstrip()}\n"
350 )
351 sys.exit(Exit.ERROR)
352 expect[fields[0]] = fields[1]
353 return expect
354
355
356 def expand_skip_spec(spec, srcdir, suitedir):
357 """Expand an RSYNC_EXPECT_SKIPPED spec into a normalised csv.
358
359 The spec is a comma-separated list of test names, '@FILE' skip-list
360 references, and '-name' removals. A skip-list file holds one test name per line ('#' starts a
361 comment; blank lines are ignored), which is what keeps two branches from
362 colliding: adding a test edits one line of one file rather than a shared
363 3 KB csv. Several may be composed, e.g.
364 RSYNC_EXPECT_SKIPPED=@testsuite/skiplist/linux.txt,@.../proto29.txt
365 Relative paths resolve against srcdir (not the cwd) so out-of-tree builds
366 and `make installcheck` work. A '-name' entry removes a name the rest of
367 the spec added, for a host that can genuinely run a test its platform list
368 expects to skip; it is applied last, and must actually remove something.
369
370 Entries must name a real test, and each file must be non-empty, sorted and
371 free of duplicates: unsorted files defeat the point (everyone appends to
372 the same last line), and a stale name would otherwise fail as a skip
373 mismatch far from its cause. Exits 2 on any of those -- nothing malformed
374 may quietly shrink the expected set, which would disarm the oracle.
375 """
376 def die(msg):
377 sys.stderr.write(msg + '\n')
378 sys.exit(Exit.ERROR)
379
380 # An entirely empty spec is the legitimate "expect no skips at all". An
381 # empty entry *within* a spec is not: it is what an unset shell variable
382 # expands to, and silently dropping it would quietly shrink the expected
383 # set.
384 if not spec.strip():
385 return ''
386
387 names = []
388 drop = []
389 for tok in (t.strip() for t in spec.split(',')):
390 if not tok:
391 die('RSYNC_EXPECT_SKIPPED: empty entry (an unset variable?): '
392 f'{spec!r}')
393 if tok.startswith('-'):
394 # '-name' removes a name a composed list added, for a host that
395 # really can run a test its platform list expects to skip (e.g. a
396 # scratch dir on a second filesystem makes a cross-device copy
397 # work). Subtraction cannot be done by whoever composes the spec,
398 # because the name lives inside an @FILE that is only expanded
399 # here. Applied after every addition, so order does not matter.
400 drop.append((tok[1:], tok))
401 continue
402 if not tok.startswith('@'):
403 names.append((tok, 'RSYNC_EXPECT_SKIPPED'))
404 continue
405 path = tok[1:]
406 if not os.path.isabs(path):
407 path = os.path.join(srcdir, path)
408 try:
409 with open(path) as f:
410 lines = f.readlines()
411 except (OSError, UnicodeDecodeError) as e:
412 die(f'{tok}: cannot read skip list: {e}')
413 prev = None
414 found = 0
415 for lineno, raw in enumerate(lines, 1):
416 name = raw.split('#', 1)[0].strip()
417 if not name:
418 continue
419 where = f'{path}:{lineno}'
420 if len(name.split()) != 1:
421 die(f'{where}: expected one test name per line, got: {raw.rstrip()}')
422 if prev is not None and name <= prev:
423 die(f'{where}: skip lists must be sorted and duplicate-free '
424 f'({name!r} follows {prev!r})')
425 prev = name
426 found += 1
427 names.append((name, where))
428 # A truncated or emptied list must not read as "expect no skips".
429 if not found:
430 die(f'{path}: skip list contains no test names')
431
432 seen = {}
433 for name, where in names:
434 if name in seen:
435 continue
436 seen[name] = where
437 # A plain test name: no path, and no comma (which the expanded csv,
438 # and the summary the fleet parses back, use as the separator).
439 if ',' in name or '/' in name or os.sep in name or name in ('.', '..'):
440 die(f'{where}: not a test name: {name!r}')
441 if not os.path.isfile(os.path.join(suitedir, name + '_test.py')):
442 die(f'{where}: no such test: {name}')
443 for name, tok in drop:
444 # Every removal must remove something. A name the spec never added is
445 # stale (the list stopped expecting that skip, or it is misspelled), and
446 # a repeated removal is the same no-op written twice. Shrinking the
447 # expected set is precisely what must not happen quietly, so neither is
448 # allowed to sit in a config unnoticed.
449 if name not in seen:
450 die(f'RSYNC_EXPECT_SKIPPED: {tok!r} removes a name that nothing '
451 f'added: {name}')
452 del seen[name]
453 return ','.join(sorted(seen))
454
455
456 def read_backport_exclude(tooldir, suitedir):
457 """Test names from the BUILD tree's testsuite/skiplist/backport.txt.
458
459 A stable-backport branch runs a newer suite than its own code, and this
460 file names the tests that base cannot run. It lives in the tree being
461 built, not the suite tree, so it cannot be an @FILE in the expect-skipped
462 spec -- those resolve against srcdir.
463 """
464 path = os.path.join(tooldir, 'testsuite', 'skiplist', 'backport.txt')
465 if not os.path.isfile(path):
466 return set()
467 names = set()
468 with open(path) as f:
469 for lineno, raw in enumerate(f, 1):
470 name = raw.split('#', 1)[0].strip()
471 if not name:
472 continue
473 where = f'{path}:{lineno}'
474 if len(name.split()) != 1:
475 sys.stderr.write(f'{where}: expected one test name per line\n')
476 sys.exit(Exit.ERROR)
477 # A stale name here would silently exclude nothing, which is the
478 # failure this file exists to prevent.
479 if not os.path.isfile(os.path.join(suitedir, name + '_test.py')):
480 sys.stderr.write(f'{where}: no such test: {name}\n')
481 sys.exit(Exit.ERROR)
482 names.add(name)
483 return names
484
485
486 _TIMING_TOP = 25
487
488
489 def print_timing_report(durations, outcomes, run_wall, parallel):
490 """Report per-test wall-clock, slowest first (--timing).
491
492 With -j N the run cannot finish sooner than its slowest single test, so the
493 tail matters as much as the total: a 300s test pins the whole suite to 300s
494 no matter how many workers there are. The footer gives both bounds -- the
495 serial sum (what one worker would take) and that floor -- so it is obvious
496 whether a slow run wants more parallelism or a faster individual test."""
497 if not durations:
498 return
499 ranked = sorted(durations.items(), key=lambda kv: kv[1], reverse=True)
500 total = sum(durations.values())
501 print(f'----- slowest tests (of {len(ranked)}, wall-clock each):')
502 for name, secs in ranked[:_TIMING_TOP]:
503 print(f' {secs:7.1f}s {name:<32} {outcomes.get(name, "?")}')
504 print(f' serial sum {total:.0f}s over {len(ranked)} tests; '
505 f'run took {run_wall:.0f}s with -j{parallel}')
506 slowest, slowest_secs = ranked[0]
507 if parallel > 1:
508 # The floor: even with unlimited workers the suite cannot beat its
509 # longest single test.
510 print(f' floor {slowest_secs:.0f}s ({slowest}) = '
511 f'{100.0 * slowest_secs / run_wall:.0f}% of this run; '
512 f'ideal at -j{parallel} is {total / parallel:.0f}s')
513
514
515 def outcome_of(result):
516 """Map a per-test exit code to an outcome string."""
517 if result == Exit.PASS:
518 return 'pass'
519 if result == Exit.SKIP:
520 return 'skip'
521 if result == Exit.XFAIL:
522 return 'xfail'
523 return 'fail'
524
525
526 def build_rsync_cmd(rsync_bin, args, scratchbase):
527 """Build the RSYNC command string for tests."""
528 parts = []
529 if args.valgrind:
530 # Logs go in a world-writable+sticky subdir so that rsync children
531 # which drop privileges (the setpriv cap-drop in partial_nowrite, a
532 # daemon dropping to the module's uid) can still create their log file
533 # even when scratchbase itself is root-owned.
534 vgdir = os.path.join(scratchbase, 'valgrind-logs')
535 os.makedirs(vgdir, exist_ok=True)
536 os.chmod(vgdir, 0o1777)
537 vlog = os.path.join(vgdir, 'valgrind.%p.log')
538 vopts = f'--log-file={vlog}'
539 supp = os.path.join(os.path.dirname(os.path.abspath(__file__)),
540 'testsuite', 'valgrind.supp')
541 if os.path.exists(supp):
542 vopts += f' --suppressions={supp}'
543 if args.valgrind_opts:
544 vopts += ' ' + args.valgrind_opts
545 parts.append(f'valgrind {vopts}')
546 parts.append(rsync_bin)
547 if args.protocol is not None:
548 parts.append(f'--protocol={args.protocol}')
549 return ' '.join(parts)
550
551
552 class TestResult:
553 """Result of a single test execution."""
554 __slots__ = ('testbase', 'result', 'output', 'skipped_reason', 'duration')
555
556 def __init__(self, testbase, result, output='', skipped_reason='',
557 duration=0.0):
558 self.testbase = testbase
559 self.result = result
560 self.output = output
561 self.skipped_reason = skipped_reason
562 self.duration = duration
563
564
565 def run_one_test(testscript, testbase, scratchdir, base_env, timeout,
566 srcdir, tooldir, setfacl_nodef, always_log):
567 """Run a single test. Returns a TestResult.
568
569 This function is safe to call from multiple threads — it uses only
570 per-test state (unique scratchdir, copy of env).
571 """
572 started = time.monotonic()
573 prep_scratch(scratchdir, srcdir, tooldir, setfacl_nodef)
574
575 env = base_env.copy()
576 env['scratchdir'] = scratchdir
577
578 # Dispatch by extension: shell tests via /bin/sh -e, Python tests via
579 # the same python3 that's running this runner.
580 if testscript.endswith('.py'):
581 cmd = [sys.executable, testscript]
582 else:
583 cmd = ['sh', '-e', testscript]
584
585 logfile = os.path.join(scratchdir, 'test.log')
586 with open(logfile, 'w') as log:
587 # start_new_session: run the test driver as its own session/group leader
588 # so the daemon, clients and flipper it spawns inherit that group. A
589 # timeout then killpg's the whole tree (not just the driver), and the
590 # lock-file sweep can reap a SIGKILLed run's stranded group the same way.
591 proc = subprocess.Popen(
592 cmd,
593 stdout=log, stderr=subprocess.STDOUT,
594 env=env, cwd=env.get('TOOLDIR', '.'),
595 start_new_session=True,
596 )
597 try:
598 result = proc.wait(timeout=timeout)
599 except subprocess.TimeoutExpired:
600 # Reap the whole session group, but only if the driver really is its
601 # own group leader (start_new_session took) and that group isn't ours
602 # -- killpg of our own group would take down the runner.
603 try:
604 pgid = os.getpgid(proc.pid)
605 except OSError:
606 pgid = -1
607 if pgid == proc.pid and pgid != os.getpgrp():
608 try:
609 os.killpg(pgid, signal.SIGKILL)
610 except OSError:
611 proc.kill()
612 else:
613 proc.kill()
614 proc.wait()
615 result = 1
616 log.write(f"\nTIMEOUT: test took over {timeout} seconds\n")
617
618 # Build output text
619 output_parts = []
620
621 show_log = always_log or (result not in (Exit.PASS, Exit.SKIP, Exit.XFAIL))
622 if show_log:
623 output_parts.append(f'----- {testbase} log follows')
624 try:
625 with open(logfile) as f:
626 output_parts.append(f.read().rstrip())
627 except FileNotFoundError:
628 pass
629 output_parts.append(f'----- {testbase} log ends')
630 rsyncd_log = os.path.join(scratchdir, 'rsyncd.log')
631 if os.path.isfile(rsyncd_log):
632 output_parts.append(f'----- {testbase} rsyncd.log follows')
633 with open(rsyncd_log) as f:
634 output_parts.append(f.read().rstrip())
635 output_parts.append(f'----- {testbase} rsyncd.log ends')
636
637 skipped_reason = ''
638 if result == Exit.PASS:
639 output_parts.append(f'PASS {testbase}')
640 elif result == Exit.SKIP:
641 whyfile = os.path.join(scratchdir, 'whyskipped')
642 try:
643 with open(whyfile) as f:
644 skipped_reason = f.read().strip()
645 except FileNotFoundError:
646 pass
647 output_parts.append(f'SKIP {testbase} ({skipped_reason})')
648 elif result == Exit.XFAIL:
649 output_parts.append(f'XFAIL {testbase}')
650 else:
651 output_parts.append(f'FAIL {testbase}')
652
653 return TestResult(testbase, result, '\n'.join(output_parts), skipped_reason,
654 time.monotonic() - started)
655
656
657 # Lock for serializing output in parallel mode
658 _print_lock = threading.Lock()
659
660
661 def main():
662 args = parse_args()
663
664 # Also accept legacy environment variables
665 if args.preserve_scratch or os.environ.get('preserve_scratch') == 'yes':
666 args.preserve_scratch = True
667 if args.log_level == 1:
668 args.log_level = int(os.environ.get('loglevel', '1'))
669 if args.expect_skipped is None:
670 args.expect_skipped = os.environ.get('RSYNC_EXPECT_SKIPPED', 'IGNORE')
671 if args.exclude is None:
672 args.exclude = os.environ.get('RSYNC_EXCLUDE', '')
673 if os.environ.get('whichtests'):
674 args.tests = [os.environ['whichtests']]
675
676 # Determine directories
677 tooldir = args.tooldir or os.environ.get('TOOLDIR') or os.getcwd()
678 script_path = os.path.dirname(os.path.abspath(__file__))
679 srcdir = args.srcdir or script_path
680 if not srcdir or srcdir == '.':
681 srcdir = tooldir
682 rsync_bin = args.rsync_bin or os.environ.get('rsync_bin') or os.path.join(tooldir, 'rsync')
683 # Absolutize: tests run with subprocess(cwd=TOOLDIR) below, so a relative
684 # argv[0] would re-resolve against TOOLDIR rather than the runner's
685 # invocation cwd, breaking --rsync-bin=../foo/rsync forms. abspath()
686 # captures os.getcwd() now, which is what the operator intended.
687 if rsync_bin and not os.path.isabs(rsync_bin):
688 rsync_bin = os.path.abspath(rsync_bin)
689
690 # Optional second ("peer") binary for the daemon / remote-shell side, so a
691 # run can mix two rsync versions. Defaults to rsync_bin -> no mixing.
692 rsync_bin2 = args.rsync_bin2 or os.environ.get('rsync_bin2') or rsync_bin
693 if rsync_bin2 and not os.path.isabs(rsync_bin2):
694 rsync_bin2 = os.path.abspath(rsync_bin2)
695
696 suitedir = os.path.join(srcdir, 'testsuite')
697 # A backport tree excludes what its base cannot run. Those tests never
698 # run, so they must also drop out of the expected-skip set -- otherwise the
699 # oracle demands a skip from a test that was never started.
700 backport_excl = read_backport_exclude(tooldir, suitedir)
701 if backport_excl:
702 args.exclude = ','.join(x for x in (args.exclude,
703 ','.join(sorted(backport_excl))) if x)
704 if args.expect_skipped != 'IGNORE':
705 args.expect_skipped = expand_skip_spec(args.expect_skipped, srcdir, suitedir)
706 if backport_excl:
707 args.expect_skipped = ','.join(n for n in args.expect_skipped.split(',')
708 if n and n not in backport_excl)
709 scratchbase = os.path.join(os.environ.get('scratchbase', tooldir), 'testtmp')
710 os.makedirs(scratchbase, exist_ok=True)
711
712 shconfig = read_shconfig(os.path.join(tooldir, 'shconfig'))
713 tls_args = get_tls_args(os.path.join(tooldir, 'config.h'))
714 setfacl_nodef = find_setfacl_nodef(scratchbase)
715 rsync_cmd = build_rsync_cmd(rsync_bin, args, scratchbase)
716 rsync_peer_cmd = build_rsync_cmd(rsync_bin2, args, scratchbase)
717
718 if not os.path.isfile(rsync_bin):
719 sys.stderr.write(f"rsync_bin {rsync_bin} is not a file\n")
720 sys.exit(Exit.ERROR)
721 if not os.path.isfile(rsync_bin2):
722 sys.stderr.write(f"rsync_bin2 {rsync_bin2} is not a file\n")
723 sys.exit(Exit.ERROR)
724 if not os.path.isdir(srcdir):
725 sys.stderr.write(f"srcdir {srcdir} is not a directory\n")
726 sys.exit(Exit.ERROR)
727
728 # Helper programs the test scripts invoke directly. Missing any of these
729 # would cause many tests to fail with confusing "not found" errors, so
730 # check up front and point the user at the make target that builds them.
731 required_helpers = ['tls', 'trimslash', 't_unsafe', 't_chmod_secure',
732 't_secure_relpath',
733 'wildtest', 'getgroups', 'getfsdev']
734 missing = [h for h in required_helpers
735 if not os.path.isfile(os.path.join(tooldir, h))]
736 if missing:
737 sys.stderr.write(
738 f"runtests.py: missing test helper program(s) in {tooldir}: "
739 f"{', '.join(missing)}\n"
740 f"Build them with: make {' '.join(missing)}\n"
741 f"or run the full test target: make check\n"
742 )
743 sys.exit(Exit.ERROR)
744
745 testuser = get_testuser()
746
747 # Print header
748 print('=' * 60)
749 print(f'{sys.argv[0]} running in {tooldir}')
750 print(f' rsync_bin={rsync_cmd}')
751 if rsync_peer_cmd != rsync_cmd:
752 print(f' rsync_peer={rsync_peer_cmd}')
753 print(f' srcdir={srcdir}')
754 print(f' TLS_ARGS={tls_args}')
755 print(f' testuser={testuser}')
756 print(f' os={subprocess.check_output(["uname", "-a"], text=True).strip()}')
757 print(f' preserve_scratch={"yes" if args.preserve_scratch else "no"}')
758 if args.valgrind:
759 print(f' valgrind=enabled (logs in valgrind-logs/valgrind.*.log)')
760 if args.parallel > 1:
761 print(f' parallel={args.parallel}')
762 print(f' daemon_transport={"tcp (loopback)" if args.use_tcp else "pipe (secure default)"}')
763 print(f' scratchbase={scratchbase}')
764
765 # Build base environment for test scripts
766 path = os.environ.get('PATH', '')
767 if os.path.isdir('/usr/xpg4/bin'):
768 path = '/usr/xpg4/bin:' + path
769
770 # Make the testsuite/ directory importable so Python tests can `import rsyncfns`.
771 pythonpath = suitedir
772 if os.environ.get('PYTHONPATH'):
773 pythonpath = suitedir + os.pathsep + os.environ['PYTHONPATH']
774
775 base_env = os.environ.copy()
776 base_env.update({
777 'PATH': path,
778 'POSIXLY_CORRECT': '1',
779 'TOOLDIR': tooldir,
780 'srcdir': srcdir,
781 'RSYNC': rsync_cmd,
782 'RSYNC_PEER': rsync_peer_cmd,
783 'TLS_ARGS': tls_args,
784 'RUNSHFLAGS': '-e',
785 'scratchbase': scratchbase,
786 'suitedir': suitedir,
787 'TESTRUN_TIMEOUT': str(args.timeout),
788 'HOME': scratchbase,
789 'PYTHONPATH': pythonpath,
790 })
791 if args.use_tcp:
792 # Opt-in: daemon tests start a real rsyncd on a claimed loopback port.
793 # Default (unset) keeps the secure stdio-pipe transport.
794 base_env['RSYNC_TEST_USE_TCP'] = '1'
795 if args.race_timeout is not None:
796 # Only exported when the operator actually passed --race-timeout: its
797 # mere presence is what tells a race test to override its own default.
798 base_env['race_timeout'] = str(args.race_timeout)
799 else:
800 # A stale value inherited from the environment would silently override
801 # every test's default; the flag is the only way to set this.
802 base_env.pop('race_timeout', None)
803 for k, v in shconfig.items():
804 if v:
805 base_env[k] = v
806 if setfacl_nodef:
807 base_env['setfacl_nodef'] = ' '.join(setfacl_nodef)
808 else:
809 base_env['setfacl_nodef'] = 'true'
810 if args.log_level > 8:
811 base_env['RUNSHFLAGS'] = '-e -x'
812
813 # Collect tests
814 tests = collect_tests(suitedir, args.tests)
815 full_run = len(args.tests) == 0
816
817 # Drop excluded tests entirely (matched by basename against name/glob).
818 excl = [e.strip() for e in args.exclude.split(',') if e.strip()]
819 if excl:
820 before = len(tests)
821 tests = [t for t in tests
822 if not any(fnmatch.fnmatch(_testbase(t), pat) for pat in excl)]
823 if before != len(tests):
824 print(f"Excluding {before - len(tests)} test(s) matching: "
825 f"{', '.join(excl)}")
826
827 # Narrow to the daemon-transport tests. The dropped count is always printed:
828 # a pass that silently ran a third of the suite would read in the report as
829 # if it had run all of it.
830 if args.daemon_tests_only:
831 tests, dropped = select_daemon_tests(tests)
832 print(f"Daemon-transport tests only: running {len(tests)}, skipping "
833 f"{len(dropped)} test(s) that cannot observe the transport")
834 # The expected-skip list describes a full run, so it cannot be enforced
835 # against a subset -- same rule as naming tests explicitly.
836 full_run = False
837
838 # An expected-result manifest defines BOTH the run set (its keys) and the
839 # expected per-test outcome (its values). Used for version-mixing runs.
840 expect = parse_expect_result(args.expect_result) if args.expect_result else None
841 if expect is not None:
842 have = {_testbase(t) for t in tests}
843 unknown = sorted(k for k in expect if k not in have)
844 if unknown:
845 sys.stderr.write(
846 "runtests.py: --expect-result lists test(s) with no matching "
847 f"test file (ignored): {', '.join(unknown)}\n"
848 )
849 tests = [t for t in tests if _testbase(t) in expect]
850 full_run = False
851
852 def _cls(outcome):
853 """Equivalence class for outcome comparison: fail and xfail both just
854 mean 'broke', so a manifest 'fail' matches an actual fail OR xfail."""
855 return 'broken' if outcome in ('fail', 'xfail') else outcome
856
857 def mismatch(testbase, actual):
858 """True if actual outcome disagrees with the manifest expectation."""
859 return expect is not None and _cls(expect[testbase]) != _cls(actual)
860
861 # Record test order for consistent skipped-list output
862 test_order = {_testbase(t): i for i, t in enumerate(tests)}
863
864 passed = 0
865 failed = 0
866 skipped = 0
867 xfailed = 0
868 skipped_list = []
869 outcomes = {} # testbase -> actual outcome string ('pass'/'skip'/'fail'/'xfail')
870 durations = {} # testbase -> wall-clock seconds (for --timing)
871
872 def process_result(tr):
873 """Process a TestResult and update counters. Returns True if the test
874 should count as a failure for --stop-on-fail purposes."""
875 nonlocal passed, failed, skipped, xfailed
876 with _print_lock:
877 if tr.output:
878 print(tr.output)
879 scratchdir = os.path.join(scratchbase, tr.testbase)
880 oc = outcome_of(tr.result)
881 outcomes[tr.testbase] = oc
882 durations[tr.testbase] = tr.duration
883 if tr.result == Exit.PASS:
884 passed += 1
885 elif tr.result == Exit.SKIP:
886 skipped_list.append(tr.testbase)
887 skipped += 1
888 elif tr.result == Exit.XFAIL:
889 # XFAIL: an expected failure (a known, documented residual the test
890 # asserts against). Reported distinctly but does NOT fail the suite;
891 # when the underlying issue is fixed the test returns 0 instead.
892 xfailed += 1
893 else:
894 failed += 1
895 if tr.result in (Exit.PASS, Exit.SKIP, Exit.XFAIL) and not args.preserve_scratch \
896 and os.path.isdir(scratchdir):
897 subprocess.run(['rm', '-rf', scratchdir], capture_output=True)
898 # With a manifest, only a mismatch is a "failure" (an expected fail is
899 # fine); without one, any non-pass/non-skip/non-xfail result is a failure.
900 if expect is not None:
901 return mismatch(tr.testbase, oc)
902 return tr.result not in (Exit.PASS, Exit.SKIP, Exit.XFAIL)
903
904 run_started = time.monotonic()
905
906 if args.parallel > 1:
907 # Parallel execution
908 with concurrent.futures.ThreadPoolExecutor(max_workers=args.parallel) as executor:
909 futures = {}
910 for testscript in tests:
911 testbase = _testbase(testscript)
912 scratchdir = os.path.join(scratchbase, testbase)
913 timeout = 600 if ('hardlinks' in testbase or testbase == 'variety') else args.timeout
914 f = executor.submit(
915 run_one_test, testscript, testbase, scratchdir,
916 base_env, timeout, srcdir, tooldir, setfacl_nodef,
917 args.always_log
918 )
919 futures[f] = testbase
920
921 for f in concurrent.futures.as_completed(futures):
922 tr = f.result()
923 is_fail = process_result(tr)
924 if is_fail and args.stop_on_fail:
925 # Cancel pending futures
926 for pending in futures:
927 pending.cancel()
928 break
929 else:
930 # Sequential execution
931 for testscript in tests:
932 testbase = _testbase(testscript)
933 scratchdir = os.path.join(scratchbase, testbase)
934 timeout = 600 if ('hardlinks' in testbase or testbase == 'variety') else args.timeout
935 tr = run_one_test(
936 testscript, testbase, scratchdir,
937 base_env, timeout, srcdir, tooldir, setfacl_nodef,
938 args.always_log
939 )
940 is_fail = process_result(tr)
941 if is_fail and args.stop_on_fail:
942 break
943
944 run_wall = time.monotonic() - run_started
945
946 # Check valgrind logs for errors
947 vg_errors = 0
948 if args.valgrind:
949 for vlog in sorted(glob.glob(os.path.join(scratchbase, 'valgrind-logs', 'valgrind.*.log'))):
950 try:
951 with open(vlog) as f:
952 content = f.read()
953 for line in content.splitlines():
954 if 'ERROR SUMMARY:' in line and 'ERROR SUMMARY: 0 errors' not in line:
955 vg_errors += 1
956 print(f'----- valgrind errors in {os.path.basename(vlog)}:')
957 print(content)
958 break
959 except FileNotFoundError:
960 pass
961
962 # Summary
963 print('-' * 60)
964 print('----- overall results:')
965 print(f' {passed} passed')
966 if failed > 0:
967 print(f' {failed} failed')
968 if xfailed > 0:
969 print(f' {xfailed} xfailed (expected)')
970 if skipped > 0:
971 print(f' {skipped} skipped')
972 if vg_errors > 0:
973 print(f' {vg_errors} valgrind error(s) found (see logs in {os.path.join(scratchbase, "valgrind-logs")})')
974
975 if args.timing:
976 print_timing_report(durations, outcomes, run_wall, args.parallel)
977
978 if expect is not None:
979 # Version-mixing mode: the run is judged purely on whether each test's
980 # actual outcome matched its manifest expectation. An expected 'fail'
981 # is fine; an UNEXPECTED pass (xpass) or any other divergence is not.
982 mismatches = []
983 for tb in sorted(expect, key=lambda x: test_order.get(x, 1 << 30)):
984 actual = outcomes.get(tb, 'notrun')
985 if actual == 'notrun' or mismatch(tb, actual):
986 mismatches.append((tb, expect[tb], actual))
987 if mismatches:
988 print('----- expected-result mismatches:')
989 for tb, want, got in mismatches:
990 tag = ' (xpass)' if _cls(want) == 'broken' and got == 'pass' else ''
991 print(f' {tb}: expected {want}, got {got}{tag}')
992 print('-' * 60)
993 exit_code = len(mismatches) + vg_errors
994 print(f'overall result is {exit_code}')
995 sys.exit(exit_code)
996
997 skipped_str = ','.join(sorted(skipped_list, key=lambda x: test_order.get(x, 0)))
998 if full_run and args.expect_skipped != 'IGNORE':
999 print('----- skipped results:')
1000 print(f' expected: {args.expect_skipped}')
1001 print(f' got: {skipped_str}')
1002 else:
1003 skipped_str = ''
1004 args.expect_skipped = ''
1005
1006 print('-' * 60)
1007
1008 exit_code = failed + vg_errors
1009 if exit_code == 0:
1010 # Compare the skipped set order-insensitively: which tests skipped is
1011 # what matters, not the order runtests happened to collect them in
1012 # (that order is just sorted filenames -- an easy thing to get subtly
1013 # wrong when maintaining the per-platform expected lists).
1014 got = set(s for s in skipped_str.split(',') if s)
1015 want = set(s for s in args.expect_skipped.split(',') if s)
1016 if got != want:
1017 exit_code = 1
1018
1019 print(f'overall result is {exit_code}')
1020 sys.exit(exit_code)
1021
1022
1023 if __name__ == '__main__':
1024 main()