#!/usr/bin/env python3 import contextlib import fcntl import json import os import shutil from pathlib import Path import subprocess import struct import sys import tempfile import termios import threading import time from ninep import Client @contextlib.contextmanager def session(binary, root, name, *options, socket_name=None, file=None, tty=False, network=None, launch=None, inherited=None, terminal=None): # No pager of the caller's (a session's own PAGER, SYSTEMD_PAGER...): # its shells get the session's defaults, the ones under test. env = {key: value for key, value in os.environ.items() if not key.startswith('PARDES_') and 'PAGER' not in key} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), PARDES_NOTIME='1', PARDES_DUMP=str(root / (name + '.dump.zon'))) env.update(inherited or {}) for language in ['RS', 'C', 'GO', 'TS', 'PY']: env['PARDES_LSP_' + language] = '' fixture = root / (name + '.txt') fixture.write_bytes(b'initial\n') address = root / ('pardes-9p-' + (socket_name or name) + '.sock') child = None master = slave = None reader = None try: args = [binary, '--detach=' + name, *options, str(file or fixture)] preexec = None if tty: master, slave = os.openpty() fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', 24, 80, 0, 0)) env['TERM'] = 'xterm-256color' args = [binary, '--tty', '--9p=' + (socket_name or name), *options, str(file or fixture)] preexec = lambda: fcntl.ioctl(0, termios.TIOCSCTTY, 0) if launch is not None: args = [binary, *launch] existing = set(root.glob('pardes-9p-*.sock')) child = subprocess.Popen(args, cwd=root, env=env, stdin=slave, stdout=slave if tty else subprocess.DEVNULL, stderr=subprocess.PIPE, start_new_session=True, preexec_fn=preexec) if terminal is not None: # Borrowed handles for input-driving probes, valid inside this context. terminal.update(pid=child.pid, input_fd=master) if launch is not None and socket_name is None: # Named by the session's pid: a terminal's session is forked # off the process launched, which stays as its stub. address = None if slave is not None: os.close(slave) slave = None def drain(): try: while os.read(master, 65536): pass except OSError: pass reader = threading.Thread(target=drain, daemon=True) reader.start() deadline = time.monotonic() + 10 while address is None or not address.exists(): if address is None: address = next(iter(set(root.glob('pardes-9p-*.sock')) - existing), None) if address is not None: continue if child.poll() is not None: raise AssertionError((args, child.returncode, child.stderr.read().decode())) if time.monotonic() > deadline: raise TimeoutError('default 9P socket did not appear') time.sleep(.005) with Client(address) as client: if network is not None: for dial in client.read('/listeners').decode().splitlines(): parts = dial.split('!') if parts[0] in ['tcp', 'quic']: assert len(parts) == 3 and 0 < int(parts[2]) < 65536, dial network[parts[0].upper()] = int(parts[2]) assert set(network) == {'TCP', 'QUIC'}, network yield client, address finally: if terminal is not None: terminal.clear() if child is not None: if child.poll() is None: child.terminate() try: child.wait(timeout=5) except subprocess.TimeoutExpired: child.kill() child.wait() child.stderr.close() if slave is not None: os.close(slave) if master is not None: os.close(master) if reader is not None: reader.join(timeout=1) assert not reader.is_alive(), 'terminal reader did not stop' def newest(client): """The newest pane's serial: /index is ordered by serial.""" return int(client.read('/index').splitlines()[-1].split()[0]) def new_pane(client, contents): """An open of /pane/new makes a pane; the read names it.""" serial = int(client.read('/pane/new')) if contents: client.write(f'/pane/{serial}/body', contents) return serial def look(client, path, source=None): """A right click on `path` from a pane (a fresh scratch by default).""" serial = source if source is not None else new_pane(client, b'') client.write(f'/pane/{serial}/look', f'{path}\n'.encode()) results = [int(row) for row in client.read('/look').split()] assert len(results) == 1 and results[0] != serial, (path, results) # The scratch it looked from goes: a column holds only so many panes, # each its tag and two rows. if source is None: client.remove(f'/pane/{serial}') return results[0] def execute(client, serial, command): """A middle click on `command` from a pane.""" client.write(f'/pane/{serial}/exec', f'{command}\n'.encode()) def execute_refused(client, serial, command, words): """A middle click on a builtin that fails: the write fails, saying why.""" try: execute(client, serial, command) except OSError as why: assert words in str(why), (command, why) return raise AssertionError(f'{command!r} was taken') def walk_tree(client, path='/', skip=('/log', '/os', '/screen')): """Stat every entry below `path`, as `find` does, without opening anything.""" seen = [] for name in client.list(path): child = (path.rstrip('/') + '/' + name) info = client.stat(child) seen.append((child, info)) if info['dir'] and child not in skip: seen.extend(walk_tree(client, child, skip)) return seen def discovery(binary, embedded=False): with tempfile.TemporaryDirectory(prefix='pardes-discovery-') as directory: root = Path(directory) with session(binary, root, 'discovery') as (client, address): top = client.list('/') # A set: which files the root holds, not the order a listing gives. assert set(top) - {'src', 'shaders'} == {'README', 'index', 'status', 'focus', 'ctl', 'commands', 'recent', 'look', 'exec', 'pager', 'log', 'screen', 'listeners', 'layout', 'tag', 'tagexec', 'pane', 'col', 'os'}, top assert 'self' not in top and 'cons' not in top and 'new' not in top, top assert ('src' in top) == embedded, (top, embedded) before = client.read('/index') guide = client.read('/README') assert guide.count(b'\n') <= 45 and b'Msg hello' in guide and b'pane/new' in guide, guide assert client.stat('/README')['length'] == len(guide) # ls/stat/find over the whole tree, without opening, creates nothing. seen = walk_tree(client) names = {path for path, _ in seen} assert {'/index', '/status', '/look', '/exec', '/log', '/pane/1', '/pane/1/body', '/pane/1/name', '/pane/1/sel', '/pane/1/ctl', '/pane/1/tag', '/pane/1/event', '/pane/1/dot', '/pane/1/limit', '/pane/1/dirty', '/pane/1/mark', '/pane/1/scroll', '/pane/1/look', '/pane/1/exec'} <= names, sorted(names) assert '/pane/1/pty' not in names, 'the fixture file pane grew a pty/' assert not any(name.startswith('/self') or name.endswith('/rdsel') or name.endswith('/wrsel') for name in names), sorted(names) for path, info in seen: assert info['mode'] in (0o755, 0o644, 0o666, 0o444, 0o222, 0o555), (path, info) assert info['mtime'] > 0, (path, info) assert client.read('/index') == before, 'browsing created a pane' assert client.stat('/index')['length'] == len(before) > 0 index = client.stat('/index') assert index['mode'] == 0o444 and client.stat('/status')['mode'] == 0o444 assert client.stat('/exec')['mode'] == 0o666 assert client.stat('/pane/1/body')['mode'] == 0o666 and client.stat('/pane')['mode'] == 0o755 # A range file reads the pair it takes; a flag file reads 0 or 1. assert client.stat('/pane/1/addr')['length'] == 24 assert client.stat('/pane/1/limit')['length'] == 0 assert client.read('/pane/1/dirty') == b'0\n' assert client.read('/pane/1/scroll') == b'1\n' fixture = int(before.split()[0]) assert before.split()[1:3] == [b'text', b'0'] and before.rsplit(b' ', 1)[0].endswith(b'/discovery.txt'), before # /status reports the editor; /exec has nothing to report yet. status = dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines()) assert int(status['pid']) > 0 and status['version'] and int(status['panes']) >= 1, status assert client.read('/exec') == b'' # An open of /pane/new makes a pane and the read names it; each # open makes another. A stat makes none, which is why new can be # listed at all: ls -l stats every name a listing gave it. # /log answers the recent past and ends; `follow` written to the # same open makes its reads past that wait for new records. log = client.open('/log', 2) frozen = len(client.read_fid(log)) client.rpc(118, struct.pack(') deletes the addressed # range only, so the write after it replaces that range. scratch = new_pane(client, b'hello world\nsecond line\n') client.write(f'/pane/{scratch}/addr', b'#0,#5') client.write(f'/pane/{scratch}/data', b'HOWDY', truncate=True) assert client.read(f'/pane/{scratch}/body') == b'HOWDY world\nsecond line\n' # sam's regexps: ^ at any line; a miss says so and leaves no # address, so the data write after it refuses. client.write(f'/pane/{scratch}/addr', b'/^second/') assert client.read(f'/pane/{scratch}/addr') == b' 12 18 ' for path, data, why in ((f'/pane/{scratch}/addr', b'/nowhere/', 'no match for regexp'), (f'/pane/{scratch}/data', b'LOST', 'no address')): try: client.write(path, data) raise AssertionError(f'{path} took {data!r}') except OSError as refused: assert why in str(refused), refused assert client.read(f'/pane/{scratch}/body') == b'HOWDY world\nsecond line\n' # Through a mount both read as EINVAL; the log says which and why. assert f'err {scratch} addr: no match for regexp\n'.encode() in client.read('/log') client.remove(f'/pane/{scratch}') # Real `diff -u` in a command pane: the terminal turns the tab # before each timestamp into blanks, and a look at a changed line # still opens the new file at it. (root / 'diff-old.txt').write_text('one\ntwo\nthree\n') (root / 'diff-new.txt').write_text('one\nTWO\nthree\n') seen = client.read('/log').decode().count('\nexit ') client.write('/exec', b'diff -u diff-old.txt diff-new.txt\n') deadline = time.monotonic() + 10 while client.read('/log').decode().count('\nexit ') <= seen: assert time.monotonic() < deadline, 'diff -u never ended' time.sleep(.05) # A command's pane is kind cmd, not term: no shell to type into. ran = [row.split()[0] for row in client.read('/index').decode().splitlines() if row.split()[1] == 'cmd'] shown = client.read(f'/pane/{ran[-1]}/body').decode() assert '+++ diff-new.txt' in shown and '\t' not in shown, shown client.write(f'/pane/{ran[-1]}/look', b'+TWO\n') opened = [row for row in client.read('/index').decode().splitlines() if row.split()[3] == f'{root}/diff-new.txt'] assert len(opened) == 1, client.read('/index') client.remove(f'/pane/{opened[0].split()[0]}') client.remove(f'/pane/{ran[-1]}') # A Save makes the directories its file goes in, whatever names # it: the pane's own name or Save's path. # `~` is home (this session's HOME, the test's root) wherever a # path is typed: Save, name, a look, with an address or not. tilde = new_pane(client, b'one\ntwo\nthree\n') client.write(f'/pane/{tilde}/ctl', b'Save ~/tilde-made/sub/x.txt\n') assert (root / 'tilde-made/sub/x.txt').read_bytes() == b'one\ntwo\nthree\n' client.write(f'/pane/{tilde}/name', b'~/tilde-named.txt\n') assert client.read(f'/pane/{tilde}/name') == f'{root}/tilde-named.txt\n'.encode() client.remove(f'/pane/{tilde}') client.write('/look', b'~/tilde-made/sub/x.txt:3\n') looked = [row for row in client.read('/index').decode().splitlines() if row.split()[3] == f'{root}/tilde-made/sub/x.txt'] assert len(looked) == 1, client.read('/index') assert client.read(f'/pane/{looked[0].split()[0]}/addr').startswith(b'8 '), client.read(f'/pane/{looked[0].split()[0]}/addr') client.remove(f'/pane/{looked[0].split()[0]}') made_dirs = new_pane(client, b'deep\n') client.write(f'/pane/{made_dirs}/ctl', f'Save {root}/save-made/a/b/x.txt\n'.encode()) assert (root / 'save-made/a/b/x.txt').read_bytes() == b'deep\n' client.write(f'/pane/{made_dirs}/name', f'{root}/save-named/c/y.txt\n'.encode()) client.write(f'/pane/{made_dirs}/ctl', b'Save\n') assert (root / 'save-named/c/y.txt').read_bytes() == b'deep\n' client.remove(f'/pane/{made_dirs}') # A save the host cannot do (a directory it may not make) fails # the write that asked for it, and the log's err record names # the path and why. unsaved = new_pane(client, b'unsaved\n') try: client.write(f'/pane/{unsaved}/ctl', b'Save /nonexistent-pardes-dir/x.txt\n') raise AssertionError('a Save into a missing directory succeeded') except OSError as refused: assert 'Save /nonexistent-pardes-dir/x.txt: no such directory' in str(refused), refused assert f'err {unsaved} ctl: Save /nonexistent-pardes-dir/x.txt: '.encode() in client.read('/log'), client.read('/log') client.remove(f'/pane/{unsaved}') # Sixteen connections fill the slots; the next is told why. extra = [Client(address) for _ in range(15)] try: try: Client(address).__exit__() raise AssertionError('a seventeenth connection was served') except OSError as refused: assert 'too many connections' in str(refused), refused finally: for other in extra: other.__exit__() deadline = time.monotonic() + 5 while b'err - 9p: too many connections' not in client.read('/log'): assert time.monotonic() < deadline, client.read('/log') time.sleep(.01) print('9P discovery: listing/stat/find are inert; new, remove, look, exec, name, sel, log, ctl lock, focus, the ctl split and commands behave') def run_file(binary): """pty/run: a line in, how it ended out, on the same open.""" def run(c, serial, line): fid = c.open(f'/pane/{serial}/pty/run', 2) try: c.rpc(118, struct.pack(' 0, said # A paging command run through pty/run does not wait in less: the # terminal's PAGER is `pardes -`, and its text is a +Pager pane. if shutil.which('git'): repo = root / 'pagedrepo' repo.mkdir() git = ['git', '-C', str(repo), '-c', 'user.name=p', '-c', 'user.email=p@x'] subprocess.run(git + ['init', '-q'], check=True, env=dict(os.environ, HOME=str(root))) (repo / 'f').write_text('x\n') subprocess.run(git + ['add', 'f'], check=True, env=dict(os.environ, HOME=str(root))) subprocess.run(git + ['commit', '-qm', 'paged-commit-subject'], check=True, env=dict(os.environ, HOME=str(root))) assert run(client, term, b'git -C pagedrepo log\n').startswith(b'exit 0\n') pager = [r.split()[0].decode() for r in client.read('/index').splitlines() if r.split()[3:4] == [f'{repo}/+Pager'.encode()]] # git -C runs it in the repo assert len(pager) == 1, client.read('/index') assert b'paged-commit-subject' in client.read(f'/pane/{pager[0]}/body') assert b'\x1b' not in client.read(f'/pane/{pager[0]}/body') client.remove(f'/pane/{pager[0]}') # systemd's tools page through their own variable: set too, its # secure mode off, the path unquoted where it needs none. Read # by the shell: coreutils 9.12's printenv quotes a value with a # blank on a terminal. systemd_pager = run(client, term, b'printf "%s\\n" "$SYSTEMD_PAGER" "$SYSTEMD_PAGERSECURE"\n') assert systemd_pager.startswith(b'exit 0\n') and systemd_pager.rstrip().endswith(b' -\n0'), systemd_pager if shutil.which('journalctl'): assert run(client, term, b'journalctl -n 3 --no-hostname\n').startswith(b'exit ') for row in client.read('/index').splitlines(): if row.split()[3:4] == [f'{root}/+Pager'.encode()]: client.remove(f'/pane/{row.split()[0].decode()}') # A pty is not given one row (it loses the prompt's input mark, # and the shell would read busy for ever): refused, and said. try: client.write(f'/pane/{term}/pty/ctl', b'winsize 20 1\n') raise AssertionError('winsize 20 1 was taken') except OSError as refused: assert 'at least 2 rows' in str(refused), refused client.write(f'/pane/{term}/pty/ctl', b'winsize 20 2\n') time.sleep(.5) assert run(client, term, b'true\n') == b'exit 0\n' assert client.read(f'/pane/{term}/pty/ctl').split()[2] == b'2', client.read(f'/pane/{term}/pty/ctl') client.write(f'/pane/{term}/pty/ctl', b'winsize 80 24\n') # A shell started again that cannot start (its directory is # there but cannot be entered) fails the write and leaves the # running shell be: runs still work. locked = root / 'locked' locked.mkdir() assert run(client, term, f'cd {locked}\n'.encode()) == b'exit 0\n' deadline = time.monotonic() + 5 while str(locked).encode() not in client.read('/index'): assert time.monotonic() < deadline, client.read('/index') time.sleep(.05) locked.chmod(0o600) try: if os.geteuid() != 0: # root enters any directory client.write(f'/pane/{term}/pty/ctl', b'exec\n') raise AssertionError('pty/ctl exec of a shell that cannot start was taken') except OSError as refused: assert 'shell' in str(refused), refused finally: locked.chmod(0o755) kept = run(client, term, b'true\n') assert kept == b'exit 0\n', (kept, client.read('/log')[-600:]) assert run(client, term, f'cd {root}\n'.encode()) == b'exit 0\n' with Client(address) as other: slow = [] waiter = threading.Thread(target=lambda: slow.append(run(other, term, b'sleep 1\n')), daemon=True) waiter.start() time.sleep(.3) # The job the other client ran holds the tty, and says so. assert run(client, term, b'true\n') == b'busy: sleep is running\n' waiter.join(5) assert slow == [b'exit 0\n'], slow closing = [] waiter = threading.Thread(target=lambda: closing.append(run(other, term, b'sleep 30\n')), daemon=True) waiter.start() time.sleep(.3) client.write(f'/pane/{term}/exec', b'Del\n') waiter.join(5) assert closing == [b'error shell gone\n'], closing def exit_answers(binary): """Exit written to /ctl is answered before the editor quits.""" with tempfile.TemporaryDirectory(prefix='pardes-exit-') as directory: seen = {} with session(binary, Path(directory), 'exit', terminal=seen) as (client, _): client.write('/ctl', b'Exit\n') deadline = time.monotonic() + 5 while time.monotonic() < deadline: try: # a zombie has quit; the session reaps it if Path(f'/proc/{seen["pid"]}/stat').read_text().split(') ')[1][0] == 'Z': break except FileNotFoundError: break time.sleep(.01) else: raise AssertionError("Exit did not quit the editor") def unattended_messages_expire(binary): """With nothing attached, a message leaves after MessageLinger on its own clock: no key, no click, no other request comes to move it along.""" with tempfile.TemporaryDirectory(prefix='pardes-msg-') as directory: with session(binary, Path(directory), 'msg') as (client, _): client.write('/pane/1/ctl', b'Msg lingering-words\n') def shown(): screen = json.loads(client.read('/screen')) return 'lingering-words' in ''.join(cell[0] for cell in screen['cells']) assert shown() # Reading /screen is itself a request, so wait without asking. time.sleep(2.5) assert not shown(), 'an unattended message outlived MessageLinger' def directory_panes(binary): """A look at a directory opens a pane listing it, as acme's directory window: a text pane named with a trailing /, its body the entries (a directory's marked /), ctl's isdir 1, and get reads it again.""" with tempfile.TemporaryDirectory(prefix='pardes-dirpane-') as directory: root = Path(directory).resolve() listed = root / 'listed' (listed / 'sub').mkdir(parents=True) (listed / '.dot').write_bytes(b'') with session(binary, root, 'dirpane') as (client, _): serial = look(client, str(listed)) rows = [row.split() for row in client.read('/index').decode().splitlines()] row = next(r for r in rows if int(r[0]) == serial) assert row[1:4] == ['text', '0', f'{listed}/'], row body = client.read(f'/pane/{serial}/body').decode() assert body.split() == ['.dot', 'sub/'], body assert client.read(f'/pane/{serial}/ctl').split()[3] == b'1' (listed / 'later').write_bytes(b'') client.write(f'/pane/{serial}/ctl', b'get\n') assert client.read(f'/pane/{serial}/body').decode().split() == ['.dot', 'later', 'sub/'] def putall_answers_after_its_saves(binary): """Putall with one pane refused (its file changed on disk under unsaved edits) fails, and is answered only once the other panes' saves have landed.""" with tempfile.TemporaryDirectory(prefix='pardes-putall-') as directory: root = Path(directory).resolve() (root / 'a.txt').write_bytes(b'a\n') (root / 'b.txt').write_bytes(b'b\n') with session(binary, root, 'putall') as (client, _): a = look(client, str(root / 'a.txt')) b = look(client, str(root / 'b.txt')) for serial in (a, b): client.write(f'/pane/{serial}/body', b'edited\n') (root / 'b.txt').write_bytes(b'changed on disk\n') deadline = time.monotonic() + 10 while f'changed {b}' not in client.read('/log').decode(): assert time.monotonic() < deadline, 'the watch never saw b.txt change' time.sleep(.05) try: client.write('/ctl', b'Putall\n') except OSError as why: assert 'modified on disk' in str(why), why else: raise AssertionError('Putall over a file changed on disk was taken') assert (root / 'a.txt').read_bytes() == b'a\nedited\n', (root / 'a.txt').read_bytes() assert (root / 'b.txt').read_bytes() == b'changed on disk\n' def new_terminals_named_once(binary): """A terminal started outside the session's directory is named by that directory from its `new` on: no rename to the session's and back.""" with tempfile.TemporaryDirectory(prefix='pardes-names-') as directory: root = Path(directory) (root / 'sub').mkdir() with session(binary, root, 'names') as (client, _): # A look at a directory starts a terminal there (DirLook # terminal); DirLook pane, the default, lists it in a pane. client.write('/ctl', b'DirLook terminal\n') made = [look(client, str(root / 'sub'))] before = {int(row.split()[0]) for row in client.read('/index').splitlines()} client.write('/pane/1/ctl', b'Tty\n') if shutil.which('fish'): client.write('/pane/1/ctl', b'Tty fish\n') made += [s for s in (int(row.split()[0]) for row in client.read('/index').splitlines()) if s not in before] time.sleep(1.5) # their shells start and say where they are # A shell started again by pty/ctl exec: named as it was. client.write(f'/pane/{made[0]}/pty/ctl', b'exec\n') time.sleep(1.5) log = client.read('/log').decode() for serial in made: assert f'\nrename {serial} ' not in '\n' + log, (serial, log) assert f'\nnew {serial} {root}' in '\n' + log, (serial, log) # A shell that cannot start (its interpreter is not there): Tty # fails the write with why and leaves no pane; pty/ctl exec # fails with why and keeps its terminal. bad = root / 'badsh' bad.write_bytes(b'#!/nonexistent/interp\n') bad.chmod(0o755) panes = client.read('/index') for where, line in (('/pane/1/ctl', f'Tty {bad}\n'), ('/ctl', f'Shell {bad}\n')): try: client.write(where, line.encode()) raise AssertionError(f'{line} of a shell that cannot start was taken') except OSError as refused: assert 'interpreter /nonexistent/interp not found' in str(refused), refused time.sleep(.3) assert client.read('/index').count(b'\n') == panes.count(b'\n'), client.read('/index') assert b'shell: shell not found' not in client.read('/log'), client.read('/log') assert str(made[0]).encode() in b' '.join(r.split()[0] for r in client.read('/index').splitlines()) def recent_survives_restart(binary): """A file opened and closed is in /recent closed, and still is in the next session: the list is kept under $XDG_STATE_HOME (here HOME's .local/state) across restarts.""" with tempfile.TemporaryDirectory(prefix='pardes-recent-') as directory: root = Path(directory) kept = root / 'kept.txt' kept.write_bytes(b'one\ntwo\n') with session(binary, root, 'recent1') as (client, _): serial = look(client, f'{kept}:2') assert f'open {kept}\n' in client.read('/recent').decode() client.write(f'/pane/{serial}/ctl', b'Del\n') assert f'closed {kept}\n' in client.read('/recent').decode(), client.read('/recent') assert (root / '.local' / 'state' / 'pardes' / 'store').exists() with session(binary, root, 'recent2') as (client, _): listed = client.read('/recent').decode() assert f'closed {kept}\n' in listed, listed # Recent fills a query pane with it, its row relative to the # pane's directory, and a look at the row opens it again. client.write('/pane/1/exec', b'Recent\n') rows = int(client.read('/pane/1/exec').split()[-1]) body = client.read(f'/pane/{rows}/body').decode() assert body.startswith('Recent '), body row = next(r for r in body.splitlines() if r.startswith('kept.txt:')) client.write(f'/pane/{rows}/look', (row.split(' ')[0] + '\n').encode()) assert f'open {kept}\n' in client.read('/recent').decode() def del_twice(client, serial): """Del, and again when the first refused over unsaved text.""" try: client.write(f'/pane/{serial}/ctl', b'Del\n') except OSError: client.write(f'/pane/{serial}/ctl', b'Del\n') def store_shared_between_windows(binary): """Two windows share one store (Store.zig): a file opened in one is in the other's /recent at its next read, with no restart; a pane Del'd in one comes back where it was from a look at its @p serial there, its text with it, and only there.""" with tempfile.TemporaryDirectory(prefix='pardes-store-') as directory: root = Path(directory) shared = root / 'shared.txt' shared.write_bytes(b'one\ntwo\nthree\n') with session(binary, root, 'store1') as (one, _), session(binary, root, 'store2') as (two, _): serial = look(one, f'{shared}:3') assert f'open {shared}\n' in one.read('/recent').decode() assert f'closed {shared}\n' in two.read('/recent').decode(), two.read('/recent') one.write(f'/pane/{serial}/ctl', b'Del\n') assert f'closed {shared}\n' in one.read('/recent').decode() scratch = new_pane(one, b'kept across a Del\n') del_twice(one, scratch) assert str(scratch) not in [row.split()[0] for row in one.read('/index').decode().splitlines()] back = look(one, f'@p{scratch}') assert one.read(f'/pane/{back}/body') == b'kept across a Del\n' # The other window's session closed no such pane. source = new_pane(two, b'') try: two.write(f'/pane/{source}/look', f'@p{scratch}\n'.encode()) except OSError: pass assert b'kept across a Del' not in b''.join(two.read(f'/pane/{row.split()[0]}/body') for row in two.read('/index').decode().splitlines()) assert (root / '.local' / 'state' / 'pardes' / 'store').exists() def odd_paths(binary): """Long and odd paths written where a path goes -- name, look, DumpDir, Dump, Save -- are refused or said, never a crash: a part over 255 bytes (ENAMETOOLONG), a loop of links (ELOOP), a file taken for a directory (ENOTDIR), one not ours (EACCES).""" with tempfile.TemporaryDirectory(prefix='pardes-odd-') as directory: root = Path(directory) (root / 'loop').symlink_to(root / 'loop') (root / 'plain').write_bytes(b'x\n') odd = ['/tmp/' + 'x' * 300 + '/f.txt', str(root / ('y' * 300)), str(root / 'loop' / 'f'), str(root / 'plain' / 'f'), '/root/nope/f', str(root / 'a' / '..' / 'b.txt')] with session(binary, root, 'odd') as (client, _): serial = new_pane(client, b'text\n') for path in odd: for where, line in ((f'/pane/{serial}/name', path), ('/look', path), ('/ctl', f'DumpDir {path}'), ('/ctl', 'Dump'), (f'/pane/{serial}/ctl', 'Save')): try: client.write(where, (line + '\n').encode()) except OSError: pass assert client.read('/index'), (where, line) client.write('/ctl', b'DumpDir\n') # A theme file that is not there, or no theme, fails the write. (root / 'bad.zon').write_bytes(b'.{ .nonsense = 1 }') for line, why in ((f'ThemeFile {root}/missing.zon', 'theme file'), (f'ThemeFile {root}/bad.zon', 'theme file'), ('ThemeFile notes.txt', 'a theme file is a .zon')): try: client.write('/ctl', (line + '\n').encode()) raise AssertionError(f'{line} was taken') except OSError as refused: assert why in str(refused), (line, refused) def delcol_last_keeps_window(binary): """Delcol on the last column leaves the window, empty but for the workspace tag, as acme does; Newcol and New start again from there.""" with tempfile.TemporaryDirectory(prefix='pardes-delcol-') as directory: with session(binary, Path(directory), 'delcol') as (client, _): def columns(): return [l for l in client.read('/layout').decode().splitlines() if l and not l.startswith('active')] while columns(): client.write(f'/col/{columns()[0].split()[0]}/ctl', b'Delcol\n') # Still here, empty. assert client.read('/index') == b'', client.read('/index') client.write('/ctl', b'Newcol\n') assert len(columns()) == 1, columns() serial = new_pane(client, b'back\n') assert str(serial).encode() in client.read('/index'), client.read('/index') def cut_writes(binary): """A write bigger than a 9P message comes as several, cut anywhere: each command line runs once, whole, an Edit block once it ends, and a last line with no newline when the open closes. Never a fragment.""" with tempfile.TemporaryDirectory(prefix='pardes-cut-') as directory: with session(binary, Path(directory), 'cut') as (client, _): burst = b''.join(b'Msg burst-%04d\n' % i for i in range(1000)) assert len(burst) > client.msize client.write('/exec', burst) log = client.read('/log').decode() said = [line.split(' ', 2)[2] for line in log.splitlines() if line.startswith('msg ') and 'burst-' in line] assert said == ['burst-%04d' % i for i in range(1000)], said[:3] + said[-3:] assert '\nrun ' not in log and 'exit 127' not in log, log[-400:] client.write('/exec', b'Msg no-newline-at-end') assert 'msg ' in client.read('/log').decode().split('no-newline-at-end')[0][-40:] serial = new_pane(client, b'') block = b'Edit ,a\n' + b''.join(b'line %05d of the block\n' % i for i in range(2500)) + b'.\n' assert len(block) > 50000 client.write(f'/pane/{serial}/ctl', block) body = client.read(f'/pane/{serial}/body').decode().splitlines() assert body == ['line %05d of the block' % i for i in range(2500)], (len(body), body[:2]) # A detached session with no frontend is 160x50 until told. screen = client.screen() assert (screen['cols'], screen['rows']) == (160, 50), (screen['cols'], screen['rows']) client.write('/ctl', b'size 132 40\n') screen = client.screen() assert (screen['cols'], screen['rows']) == (132, 40), (screen['cols'], screen['rows']) def edit_commands(binary): """Edit's `< | >` run off the loop and answer the write that ran them once applied; a failing one changes nothing and fails the write in its words; X edits every open file it matches; w writes. The editor answers other requests while a slow command runs.""" with tempfile.TemporaryDirectory(prefix='pardes-edit-') as directory: root = Path(directory) (root / 'a.txt').write_bytes(b'pear\napple\nfig\n') (root / 'b.txt').write_bytes(b'apple pie\n') with session(binary, root, 'edit') as (client, address): a = look(client, str(root / 'a.txt')) b = look(client, str(root / 'b.txt')) # The write returns with the text sorted, through the session's # shell in the file's directory. client.write(f'/pane/{a}/ctl', b'Edit , | sort\n') assert client.read(f'/pane/{a}/body') == b'apple\nfig\npear\n' client.write(f'/pane/{a}/ctl', b'Edit $ < pwd\n') assert client.read(f'/pane/{a}/body') == f'apple\nfig\npear\n{root}\n'.encode() client.write(f'/pane/{a}/ctl', b'Undo\n') assert client.read(f'/pane/{a}/body') == b'apple\nfig\npear\n' # A per-match command, one undo step. client.write(f'/pane/{a}/ctl', b'Edit ,x/[a-z]+/ | tr a-z A-Z\n') assert client.read(f'/pane/{a}/body') == b'APPLE\nFIG\nPEAR\n' # A failing command: nothing changed, the write fails in words, # its stderr in +Errors. try: client.write(f'/pane/{a}/ctl', b'Edit , | echo nope >&2; exit 4\n') raise AssertionError('a failing Edit command was taken') except OSError as why: assert 'exit status 4' in str(why), why assert client.read(f'/pane/{a}/body') == b'APPLE\nFIG\nPEAR\n' index = client.read('/index').decode() errors = [line.split()[0] for line in index.splitlines() if line.endswith(('+Errors', f'{root}/+Errors')) or '+Errors' in line] assert errors and any(b'nope' in client.read(f'/pane/{e}/body') for e in errors), index # While a slow command runs, the editor answers. done = threading.Event() def slow(): with Client(address) as other: other.write(f'/pane/{b}/ctl', b'Edit , | sleep 1; cat\n') done.set() worker = threading.Thread(target=slow) worker.start() time.sleep(.2) began = time.monotonic() client.read('/index') assert time.monotonic() - began < .5 and not done.is_set(), 'the editor waited on the command' worker.join(timeout=15) assert done.is_set() # On the same connection: the Edit's write is held, and a read sent # after it is answered first; a Tflush of it stops it, changes # nothing, and frees the way for the next Edit. def send(kind, tag, payload): client.socket.sendall(struct.pack(' [--quic | --discovery]') test(str(Path(sys.argv[1]).resolve()), quic=len(sys.argv) == 3)