summaryrefslogtreecommitdiff
path: root/test/daemon.py
diff options
context:
space:
mode:
Diffstat (limited to 'test/daemon.py')
-rw-r--r--test/daemon.py121
1 files changed, 120 insertions, 1 deletions
diff --git a/test/daemon.py b/test/daemon.py
index c497bb19..051297a8 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -24,13 +24,17 @@ private HOME and runtime directory:
python3 -B test/daemon.py --clients <pardes>
the replica clients alone
python3 -B test/daemon.py --far <pardes>
- the far clients and their blob cache alone
+ the far clients and their blob cache alone, and a file by its hash
+ python3 -B test/daemon.py --games <pardes> <lib> [seconds]
+ the games in the clients that show them, from zig build
+ addon-test's <prefix>/lib (libsnake, liblife, libliar)
python3 -B test/daemon.py --window-clients <pardes> <pardes-gui>
window replica clients (hidden, offscreen) of a terminal's session,
at 0/30/80/207 ms, and a window's session serving replicas
"""
import fcntl
import os
+import random
import re
import select
import shutil
@@ -1178,6 +1182,119 @@ def by_hash(binary):
shutil.rmtree(root, ignore_errors=True)
+def games(binary, libs, secs=10):
+ """The games (PA_PLAIN kinds: snake, life) run in the clients that show
+ them, from `libs` (zig build addon-test's <prefix>/lib): a client's keys
+ into one apply at once (none stopped), the snake steps under a client's
+ focus, and snake and life focused in two clients while a third types
+ text agree with the session throughout, rollbacks and all. Then a kind
+ that breaks its promise (test/liar.zig, its tick reads the clock): its
+ client finds it, joins again once, says why, and agrees from then on."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rg-', dir=scratch))
+ 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_DATA_HOME=str(root / 'data'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ (root / 'data' / 'pardes' / 'addons').mkdir(parents=True)
+ for name in ('snake', 'life', 'liar'):
+ shutil.copy(Path(libs) / f'lib{name}.so', root / 'data' / 'pardes' / 'addons' / f'{name}.so')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
+ started, terms = [], []
+
+ def client(name):
+ t = Term(30, 100)
+ terms.append(t)
+ c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:files'],
+ dict(env, PARDES_REPLICA_CHECK=str(root / f'{name}.check'), PARDES_REPLICA_STATS=str(root / f'{name}.stats')))
+ started.append(c.pid)
+ # Its frame: the notes, or what the third client typed into them.
+ wait_for(f'client {name}\'s first frame', lambda: b'of the notes' in t.text() or b'typed by c' in t.text(), timeout=30)
+ time.sleep(.3)
+ return t, c
+
+ def kind_pane(word):
+ return next((int(r.split()[0]) for r in nine.read('/index').splitlines() if r.split()[1] == word), None)
+
+ def steps(pane):
+ return int(re.search(rb'steps (\d+)', nine.read(f'/pane/{pane}/body')).group(1))
+
+ def opened(t, word):
+ # In this client's view: its key the last input, the session's
+ # live view is its own when the word runs.
+ os.write(t.master, b'j')
+ time.sleep(.5)
+ nine.write(f'/pane/{text}/exec', word.capitalize() + b'\n')
+ return wait_for(f'a {word} pane', lambda: kind_pane(word))
+
+ def leave(name, t, c):
+ c.send_signal(signal.SIGHUP)
+ c.wait(timeout=20)
+ line = (root / f'{name}.stats').read_text().split()
+ got = {line[i]: line[i + 1] for i in range(0, len(line) - 1, 2)}
+ assert not [l for l in checks(root / f'{name}.check') if l.startswith('differ')], name
+ return got
+ try:
+ sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
+ started.append(sess.pid)
+ wait_for('the replica socket', (root / 'pardes-replica.sock').exists)
+ wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists)
+ nine = Client(root / 'pardes-9p-files.sock')
+ text = kind_pane(b'text')
+ (tc, c), (ta, a) = client('c'), client('a')
+ snake = opened(ta, b'snake')
+ tb, b = client('b')
+ life = opened(tb, b'life')
+ os.write(ta.master, b'r')
+ time.sleep(.3)
+ s0 = steps(snake)
+ time.sleep(.6)
+ assert steps(snake) > s0, 'the snake steps under a client\'s focus'
+ rnd = random.Random(7)
+ end, n = time.monotonic() + secs, 0
+ while time.monotonic() < end:
+ os.write(ta.master, bytes([rnd.choice(b'hjkl')]) if n % 40 else b'r')
+ os.write(tb.master, bytes([rnd.choice(b'hjkl ')]))
+ os.write(tc.master, b'Atyped by c %d\x1b' % n)
+ n += 1
+ time.sleep(rnd.uniform(.02, .12))
+ for name in 'abc':
+ wait_for(f'client {name} agrees once quiet', lambda: agreed(root / f'{name}.check', 0), timeout=30)
+ assert not any(b'joined again' in t.text() for t in (ta, tb, tc))
+ got = {name: leave(name, t, cl) for name, t, cl in (('a', ta, a), ('b', tb, b), ('c', tc, c))}
+ for name in 'ab':
+ assert got[name]['stopped'] == '0' and got[name]['mispredicted'] == '0', (name, got[name])
+ # The liar: caught at a tick, its client joined again once, and agrees.
+ td, d = client('d')
+ opened(td, b'liar')
+ wait_for('client D caught the liar', lambda: b'joined again' in td.text(), timeout=30)
+ assert b'liar: its state after tick' in td.text(), td.text()[-600:]
+ seen = len(checks(root / 'd.check'))
+ os.write(td.master, b'j')
+ wait_for('client D agrees after it', lambda: agreed(root / 'd.check', seen), timeout=30)
+ assert td.text().count(b'joined again') == 1 and d.poll() is None
+ print(f'daemon: games in clients, {secs:.0f} s: snake and life focused in two clients, keys stopped {got["a"]["stopped"]} and '
+ f'{got["b"]["stopped"]} of {got["a"]["inputs"]} and {got["b"]["inputs"]}, rollbacks {got["a"]["foreign"]}, {got["b"]["foreign"]}, '
+ f'{got["c"]["foreign"]} (the third typing text), every digest agreed; a kind whose tick reads the clock was caught and its '
+ f'client joined again once')
+ exit_session(nine, text)
+ sess.wait(timeout=10)
+ nine.socket.close()
+ finally:
+ for t in terms:
+ t.close()
+ for pid in started + processes(root):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
def far_joins(sock, session, binary, n):
"""`n` far joins of one session in a row, each read whole (its blobs
asked for by none, its zstd frames unpacked) and answering a ping, then
@@ -1944,6 +2061,8 @@ if __name__ == '__main__':
clients(sys.argv[2])
elif sys.argv[1:2] == ['--manage']:
manage(sys.argv[2])
+ elif sys.argv[1:2] == ['--games']:
+ games(sys.argv[2], sys.argv[3], float(sys.argv[4]) if len(sys.argv) > 4 else 10)
elif sys.argv[1:2] == ['--far']:
far(sys.argv[2])
by_hash(sys.argv[2])