summaryrefslogtreecommitdiff
path: root/test/cross_replay.py
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-10-31 06:28:48 -0300
committerGabriel Schneider <[email protected]>2026-10-31 06:28:48 -0300
commita479792a1ab2b593642d7f648194bfa23ce01dba (patch)
tree96ddee7d879a9084daa07db43b0b7910b072a785 /test/cross_replay.py
parente179cc44fe5060c76a5b00c41e53f11209f5acd9 (diff)
parent4c761893e5b3fdae422622cfa02104ab36633045 (diff)
downloadpardes-a479792a1ab2b593642d7f648194bfa23ce01dba.tar.gz
pardes-a479792a1ab2b593642d7f648194bfa23ce01dba.zip
Merge the upstream daemon and replicated client/server refactor
Diffstat (limited to 'test/cross_replay.py')
-rw-r--r--test/cross_replay.py145
1 files changed, 145 insertions, 0 deletions
diff --git a/test/cross_replay.py b/test/cross_replay.py
new file mode 100644
index 00000000..21367ca1
--- /dev/null
+++ b/test/cross_replay.py
@@ -0,0 +1,145 @@
+#!/usr/bin/env python3
+"""A session's tape recorded by one build of pardes and replayed by another
+(docs/next-daemon.md, the remote bugs): a window's build replaying a
+terminal's session, a terminal's build a window's, a Linux build a FreeBSD
+one's. A replica of another build reads its session's units as this replay
+reads the tape, so what the tape carries must mean the same to both.
+
+ python3 -B test/cross_replay.py <recorder> <replayer>...
+ a session of <recorder> recorded here, replayed by it and by each
+ replayer (a pardes-gui records in a hidden window)
+ python3 -B test/cross_replay.py --record <recorder> <dir>
+ the session alone, its tapes left in <dir> (on the box, say)
+ python3 -B test/cross_replay.py --replay <replayer> <tape>...
+ each tape replayed alone
+
+The session meets the host's failures, whose errors cross by name: a Look
+of a fifo (a read the host refuses) and of a directory, a stat and a read
+under /os over 9P, a Save into a file as if it were a directory and a
+Restore of a dump that is not there (errors the host reports, anyerrors).
+It greps and finds, as a script does, which a 9P write runs on the loop:
+its reads are a tape site (a replica of a session a script greps in read
+no file and diverged). And it holds what a digest must name the same in
+every build: a +LocationsConfig, whose origin is a Builtin, a file
+pane renamed (H19: no Linux client could join a FreeBSD session so), and
+a +Help, which lists the build's words (Tty9p was a Linux build's alone).
+"""
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).parent))
+from daemon import Window, alive, processes, wait_for # noqa: E402
+from ninep import Client # noqa: E402
+
+
+def record(binary, out):
+ """One session of `binary`, recording into `out`: its tapes' paths."""
+ out = Path(out).resolve()
+ out.mkdir(parents=True, exist_ok=True)
+ # A short runtime directory: a socket's path holds 108 bytes at most.
+ root = Path(tempfile.mkdtemp(prefix='xr-', dir=os.environ.get('TMPDIR', '/tmp')))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ XDG_STATE_HOME=str(root / 'state'), XDG_CACHE_HOME=str(root / 'cache'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/sh')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'a.txt').write_text('hello\n')
+ (root / 'dir').mkdir()
+ (root / 'dir' / 'b.txt').write_text('in a directory\n')
+ os.mkfifo(root / 'fifo')
+ # As test/daemon.py's sessions are: a detached session's message goes at
+ # once, on the clock (Messages.expireUnattended).
+ (root / 'config' / 'pardes' / 'init').write_text('MessageLinger 0\n')
+ stem = Path(binary).name
+ env['PARDES_RECORD'] = str(out / f'{stem}-')
+ window = 'gui' in stem
+ started = []
+ win = None
+ try:
+ if window:
+ win = Window(root, 'rec', [binary, '--9p=xr', str(root / 'a.txt')], env)
+ started.append(win.pid)
+ else:
+ started.append(subprocess.Popen([binary, '--detach=xr', str(root / 'a.txt')], env=env, cwd=root,
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL, start_new_session=True).pid)
+ sock = root / 'pardes-9p-xr.sock'
+ wait_for('the session\'s 9P socket', sock.exists, timeout=30)
+ with Client(sock) as c:
+ status = dict(line.split(maxsplit=1) for line in c.read('/status').decode().splitlines())
+ started.append(int(status['pid']))
+ pane = next(int(row.split()[0]) for row in c.read('/index').splitlines() if row.split()[1] == b'text')
+ for line in (f'Look {root / "fifo"}', f'Look {root / "dir"}', f'Save {root / "a.txt" / "x"}',
+ f'Restore {root / "nothing.dump"}', 'Grep hello', 'Find txt', 'LocationsConfig', 'Help'):
+ try:
+ c.write(f'/pane/{pane}/exec', line.encode() + b'\n')
+ except Exception:
+ pass # said as the write's error: a failure is what is wanted
+ time.sleep(.3)
+ # A pane a word made (+LocationsConfig: its origin a Builtin,
+ # which a FreeBSD build numbers otherwise), and a file renamed.
+ c.write(f'/pane/{pane}/ctl', f'name {root / "renamed.txt"}\n'.encode())
+ time.sleep(.3)
+ c.stat(f'/os{root / "a.txt"}')
+ assert c.read(f'/os{root / "a.txt"}') == b'hello\n'
+ for _ in range(2): # the failed Save left the text edited: Exit asks again
+ try:
+ c.write(f'/pane/{pane}/exec', b'Exit\n')
+ except Exception:
+ pass
+ if win:
+ win.close()
+ wait_for('the session\'s end', lambda: not any(alive(p) for p in started), timeout=20)
+ finally:
+ for pid in started + processes(root):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+ tapes = sorted(out.glob(f'{stem}-*.tape'))
+ assert tapes, f'{binary} wrote no tape into {out}'
+ taped = b''.join(t.read_bytes() for t in tapes)
+ for name in (b'NotAFile', b'NotDir', b'FileNotFound'): # the fifo's, the Save's, the Restore's
+ assert name in taped, f'no {name} in the tapes'
+ return tapes
+
+
+def replay(binary, tape):
+ """`binary`'s replay of `tape`: its replicas' digests agree. A replica
+ client never draws its session's frames, and only the replica that
+ draws none (`headless`) must agree with another frontend's tape: the
+ two that draw meet the other build's drawing (a window's, a terminal's)."""
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_')}
+ env['PARDES_REPLAY'] = str(tape)
+ got = subprocess.run([binary], env=env, capture_output=True, timeout=600)
+ said = got.stderr.decode(errors='replace')
+ alike = ('gui' in Path(tape).name) == ('gui' in Path(binary).name)
+ agreed = [line for line in said.splitlines() if line.endswith('digests agree')]
+ assert ('headless replica' in ''.join(agreed)) and (not alike or (got.returncode == 0 and len(agreed) == 3)), \
+ f'{binary} replaying {tape}:\n{said[-3000:]}'
+ print(f'cross_replay: {Path(binary).name} replayed {Path(tape).name}: ' +
+ '; '.join(line.split(': ', 1)[1] for line in said.splitlines() if 'replica' in line))
+
+
+if __name__ == '__main__':
+ if sys.argv[1:2] == ['--record']:
+ for t in record(sys.argv[2], sys.argv[3]):
+ print(t)
+ elif sys.argv[1:2] == ['--replay']:
+ for t in sys.argv[3:]:
+ replay(sys.argv[2], t)
+ else:
+ out = Path(tempfile.mkdtemp(prefix='xr-tapes-', dir=os.environ.get('TMPDIR', '/tmp')))
+ try:
+ for t in record(sys.argv[1], out):
+ for b in sys.argv[1:]:
+ replay(b, t)
+ finally:
+ shutil.rmtree(out, ignore_errors=True)