From ef0d017705146a74bf7cc2706b9796f227ea6977 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 4 Nov 2026 16:33:08 -0300 Subject: test: test/fs.py's discovery, run_file, exit_answers, unattended_messages_expire, directory_panes, putall_answers_after_its_saves, new_terminals_named_once, recent_survives_restart, store_shared_between_windows, odd_paths, delcol_last_keeps_window, cut_writes and edit_commands in Zig, the Python deleted (and its now unused newest, walk_tree, del_twice and the --discovery switch): at T2 in new test/process/{tree,terminals,root_ctl,edit}.zig and other_files.zig (the tree's listing, stats, log follow, ctl lock, focus, commands, sel, Save making directories, the 16 slots; a write cut at an 8 KiB msize; pty/run's answers, busy and shell gone; terminals named once; Exit; MessageLinger unattended; Putall; odd paths and ThemeFile; Edit's < | > off the loop, a held write answered after a later read and flushed, X and w; /recent across a restart and a store two sessions share), at T1 a directory pane in test/behaviour/look_and_exec.zig and 9P's new after Delcol of the last column in columns_and_tags.zig; discovery brought up to the tree as documented (sessions, kbdin, mousein at the root, /index stats 0, a sel write stays selected, the unknown-message words, a look's line in dot, a Save under / refused as permission denied), as the Python had gone stale; process.Conn gains replace, writeCut, create, newPane, newest, look, dialRefusal, send and answer, and process.sleep; a failing process test prints its error return trace; each checked to fail against a break (a detached session 161 wide, 17 connection slots, a pty taking one row, Edit's failure said as exit code, ThemeFile's .zon words changed, Exit not quitting, unattended messages never expiring, a directory pane's sub/ without its slash, Putall's modified-on-disk words changed, /recent saying shut for closed, a missing interpreter said as missing) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge --- test/behaviour/columns_and_tags.zig | 3 + test/behaviour/look_and_exec.zig | 42 ++ test/fs.py | 834 +----------------------------------- test/process.zig | 121 ++++++ test/process/edit.zig | 139 ++++++ test/process/other_files.zig | 119 +++++ test/process/root_ctl.zig | 107 +++++ test/process/terminals.zig | 241 +++++++++++ test/process/tree.zig | 484 +++++++++++++++++++++ test/process_test.zig | 5 + 10 files changed, 1262 insertions(+), 833 deletions(-) create mode 100644 test/process/edit.zig create mode 100644 test/process/root_ctl.zig create mode 100644 test/process/terminals.zig create mode 100644 test/process/tree.zig diff --git a/test/behaviour/columns_and_tags.zig b/test/behaviour/columns_and_tags.zig index b9e3b3f5..22f55774 100644 --- a/test/behaviour/columns_and_tags.zig +++ b/test/behaviour/columns_and_tags.zig @@ -133,6 +133,9 @@ test "columns-and-tags: Delcol on the last column leaves the window, drawn and t try s.write("/ctl", "Newcol\n"); try s.write(s.at("/col/{d}/ctl", .{try s.column(0)}), "New\n"); try expectEqualStrings(s.at("{d}:{d}", .{ try s.column(0), try s.focused() }), try s.columns()); + // And 9P's new makes a pane there. + const made = try s.newPane(); + try std.testing.expect(std.mem.indexOf(u8, try s.read("/index"), s.at("\n{d} ", .{made})) != null); } test "columns-and-tags: New is a column tag's word, in no pane's tag nor the workspace's" { diff --git a/test/behaviour/look_and_exec.zig b/test/behaviour/look_and_exec.zig index 0d8056da..c46ca394 100644 --- a/test/behaviour/look_and_exec.zig +++ b/test/behaviour/look_and_exec.zig @@ -713,3 +713,45 @@ test "look-and-exec: a pane's tagexec runs a word as a click in its tag, and rea try std.testing.expect(std.mem.indexOf(u8, try s.read("/log"), "from the tag") != null); try s.expect(tagexec, s.at("{d}\n", .{n})); } + +test "look-and-exec: a look at a directory opens a pane listing it, as acme's directory window: named with a trailing /, its entries, ctl's isdir 1, get reading it again" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(std.testing.io, "listed/sub"); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "listed/.dot", .data = "" }); + var s = try Session.initFile(std.testing.allocator, "x\n"); + defer s.deinit(); + const dir = s.at("{s}/listed", .{try tmpPath(&s, &tmp)}); + const scratch = try s.newPane(); + try s.write(s.at("/pane/{d}/look", .{scratch}), s.at("{s}\n", .{dir})); + const serial = try std.fmt.parseInt(u32, std.mem.trim(u8, try s.read("/look"), "\n"), 10); + try std.testing.expect(serial != scratch); + const words = struct { + fn of(text: []const u8, buf: [][]const u8) []const []const u8 { + var it = std.mem.tokenizeAny(u8, text, " \n"); + var n: usize = 0; + while (it.next()) |w| : (n += 1) buf[n] = w; + return buf[0..n]; + } + }.of; + var buf: [16][]const u8 = undefined; + var rows = std.mem.tokenizeScalar(u8, try s.read("/index"), '\n'); + const row = while (rows.next()) |r| { + if (std.mem.startsWith(u8, r, s.at("{d} ", .{serial}))) break words(r, &buf); + } else return error.NoRow; + try std.testing.expectEqualStrings("text", row[1]); + try std.testing.expectEqualStrings("0", row[2]); + try std.testing.expectEqualStrings(s.at("{s}/", .{dir}), row[3]); + const body = words(try s.read(s.at("/pane/{d}/body", .{serial})), &buf); + try std.testing.expectEqual(@as(usize, 2), body.len); + try std.testing.expectEqualStrings(".dot", body[0]); + try std.testing.expectEqualStrings("sub/", body[1]); + try std.testing.expectEqualStrings("1", words(try s.read(s.at("/pane/{d}/ctl", .{serial})), &buf)[3]); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "listed/later", .data = "" }); + try s.write(s.at("/pane/{d}/ctl", .{serial}), "get\n"); + const again = words(try s.read(s.at("/pane/{d}/body", .{serial})), &buf); + try std.testing.expectEqual(@as(usize, 3), again.len); + try std.testing.expectEqualStrings(".dot", again[0]); + try std.testing.expectEqualStrings("later", again[1]); + try std.testing.expectEqualStrings("sub/", again[2]); +} diff --git a/test/fs.py b/test/fs.py index c5dd6234..ee904226 100644 --- a/test/fs.py +++ b/test/fs.py @@ -113,11 +113,6 @@ def session(binary, root, name, *options, socket_name=None, file=None, tty=False 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')) @@ -154,629 +149,6 @@ def execute_refused(client, serial, command, words): 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 workflow_canary(binary): """One session driven as the dogfood agents drive it, asserting the log and the read-backs at every step: the canary for the main paths (the @@ -1016,210 +388,9 @@ def signal_cleans_up(binary): assert not address.exists(), (sig, list(root.iterdir())) -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]') + raise SystemExit('usage: fs.py [--quic]') test(str(Path(sys.argv[1]).resolve()), quic=len(sys.argv) == 3) diff --git a/test/process.zig b/test/process.zig index f797c063..56fe12ba 100644 --- a/test/process.zig +++ b/test/process.zig @@ -182,6 +182,119 @@ pub const Conn = struct { } return names.toOwnedSlice(gpa); } + + // fsa: + + /// `data` written to `path` opened OTRUNC (a shell's `>`), the open + /// clunked after; a refusal by a write or the clunk is `error.Refused`. + pub fn replace(c: *Conn, path: []const u8, data: []const u8) !void { + try c.writeCut(path, 1 | 16, data, msize - 24); + } + + /// `data` written to `path` (opened `mode`) in writes of at most `cut` + /// bytes, as a client with a smaller msize cuts them. + pub fn writeCut(c: *Conn, path: []const u8, mode: u8, data: []const u8, cut: usize) !void { + const fid = try c.hold(path, mode); + var at: usize = 0; + while (at < data.len) { + const n = c.writeFid(fid, at, data[at..@min(data.len, at + cut)]) catch |err| { + c.clunk(fid); + return err; + }; + if (n == 0) { + c.clunk(fid); + return error.ShortWrite; + } + at += n; + } + _ = try c.call(.{ .clunk = .{ .fid = fid } }); + } + + /// A file or directory (`perm` with c9.dmdir) made in `dir`. + pub fn create(c: *Conn, dir: []const u8, name: []const u8, perm: u32) !void { + const fid = try c.walk(dir); + defer c.clunk(fid); + _ = try c.call(.{ .create = .{ .fid = fid, .name = name, .perm = perm, .mode = 0 } }); + } + + /// A new pane, made by an open of /pane/new; its serial. + pub fn newPane(c: *Conn) !u32 { + const fid = try c.hold("/pane/new", 0); + defer c.clunk(fid); + return std.fmt.parseInt(u32, std.mem.trim(u8, try c.readFid(fid, 0, 64), "\n"), 10); + } + + /// The newest pane's serial: /index is ordered by serial. + pub fn newest(c: *Conn, gpa: std.mem.Allocator) !u32 { + const index = try c.read(gpa, "/index"); + defer gpa.free(index); + var rows = std.mem.splitBackwardsScalar(u8, std.mem.trimEnd(u8, index, "\n"), '\n'); + const last = rows.first(); + return std.fmt.parseInt(u32, last[0 .. std.mem.indexOfScalar(u8, last, ' ') orelse last.len], 10); + } + + /// A right click on `path` from a fresh scratch, which goes after: the + /// one pane /look names, never the scratch. + pub fn look(c: *Conn, gpa: std.mem.Allocator, path: []const u8) !u32 { + const scratch = try c.newPane(); + var buf: [4200]u8 = undefined; + try c.write(try std.fmt.bufPrint(&buf, "/pane/{d}/look", .{scratch}), try std.fmt.bufPrint(buf[64..], "{s}\n", .{path})); + const got = try c.read(gpa, "/look"); + defer gpa.free(got); + var rows = std.mem.tokenizeAny(u8, got, " \n"); + const opened = try std.fmt.parseInt(u32, rows.next() orelse return error.NothingOpened, 10); + if (rows.next() != null or opened == scratch) return error.NotOnePane; + try c.remove(try std.fmt.bufPrint(&buf, "/pane/{d}", .{scratch})); + return opened; + } + + /// The words a server refuses a new connection's Tversion with (its + /// slots all taken), copied into `buf`; error.NotRefused when it took it. + pub fn dialRefusal(gpa: std.mem.Allocator, path: []const u8, buf: []u8) ![]const u8 { + const c = try gpa.create(Conn); + defer gpa.destroy(c); + c.* = .{ .fd = libc.socket(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0), .cl = undefined }; + c.cl = c9.Client.init(.{ .in = &c.in, .out = &c.out }); + if (c.fd < 0) return error.NoSocket; + defer _ = libc.close(c.fd); + var addr: libc.sockaddr.un = .{ .path = @splat(0) }; + if (path.len >= addr.path.len) return error.NameTooLong; + @memcpy(addr.path[0..path.len], path); + if (libc.connect(c.fd, @ptrCast(&addr), @sizeOf(libc.sockaddr.un)) != 0) return error.ConnectFailed; + _ = c.call(.{ .version = .{ .msize = msize } }) catch |err| { + if (err != error.Refused) return err; + const n = @min(buf.len, c.said.len); + @memcpy(buf[0..n], c.said[0..n]); + return buf[0..n]; + }; + return error.NotRefused; + } + + /// A request sent without waiting for its answer (several in flight on + /// one connection); its tag. + pub fn send(c: *Conn, req: c9.Client.Request) !u16 { + const tag = c.cl.submit(req) catch return error.Protocol; + while (c.cl.output().len > 0) { + const out = c.cl.output(); + const n = libc.write(c.fd, out.ptr, out.len); + if (n <= 0) return error.Hangup; + c.cl.wrote(@intCast(n)); + } + return tag; + } + + /// The next answer to come, to whichever request `send` sent; a read's + /// bytes valid until the next call. + pub fn answer(c: *Conn) !c9.Client.Done { + while (true) { + if (c.cl.take()) |done| return done; + var buf: [msize]u8 = undefined; + const n = libc.read(c.fd, &buf, buf.len); + if (n <= 0) return error.Hangup; + var at: usize = 0; + while (at < n) at += c.cl.push(buf[at..@intCast(n)]); + } + } }; /// A running pardes's file tree, dialled by its pid or socket path. @@ -482,3 +595,11 @@ fn sleepMs(ms: u32) void { var ts: libc.timespec = .{ .sec = 0, .nsec = @as(isize, ms) * std.time.ns_per_ms }; _ = libc.nanosleep(&ts, null); } + +// fsa: + +/// A wait of `ms` milliseconds, for what a test gives a session time to do. +pub fn sleep(ms: u32) void { + var ts: libc.timespec = .{ .sec = @intCast(ms / 1000), .nsec = @as(isize, ms % 1000) * std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); +} diff --git a/test/process/edit.zig b/test/process/edit.zig new file mode 100644 index 00000000..8cccfdd1 --- /dev/null +++ b/test/process/edit.zig @@ -0,0 +1,139 @@ +//! docs/typ/reference.typ, Edit , through a real session's socket: +//! its commands run in the session's shell, and its w writes. +const std = @import("std"); +const process = @import("../process.zig"); +const eh = @import("../e2e_harness.zig"); +const expect = std.testing.expect; +const expectEqual = std.testing.expectEqual; +const expectEqualStrings = std.testing.expectEqualStrings; + +pub const cases = .{ + .{ "edit: < | > run off the loop and answer their write once applied, a failing one changing nothing; a held Edit write is flushed; X edits every open file it matches, w writes", editCommands }, +}; + +fn has(hay: []const u8, needle: []const u8) bool { + return std.mem.indexOf(u8, hay, needle) != null; +} + +fn refusedSaying(c: *process.Conn, path: []const u8, data: []const u8, why: []const u8) !void { + try std.testing.expectError(error.Refused, c.write(path, data)); + if (!has(c.said, why)) { + std.debug.print("{s} refused saying {s}, not {s}\n", .{ path, c.said, why }); + return error.WrongWords; + } +} + +/// An Edit written on another connection, in a thread. +const Slow = struct { + conn: *process.Conn, + path: []const u8, + done: std.atomic.Value(bool) = .init(false), + + fn go(s: *Slow) void { + s.conn.write(s.path, "Edit , | sleep 1; cat\n") catch {}; + s.done.store(true, .release); + } +}; + +fn editCommands(gpa: std.mem.Allocator, exe: [:0]const u8) !void { + var d = try process.Detached.start(gpa, exe, "edit", .{}); + defer d.deinit(); + const f = &d.files; + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const ar = arena.allocator(); + const c = try process.Conn.dial(gpa, d.socket()); + defer c.deinit(gpa); + const root = d.root(); + try d.put("a.txt", "pear\napple\nfig\n"); + try d.put("b.txt", "apple pie\n"); + const a = try c.look(ar, f.at("{s}/a.txt", .{root})); + const b = try c.look(ar, f.at("{s}/b.txt", .{root})); + const actl = f.at("/pane/{d}/ctl", .{a}); + const abody = f.at("/pane/{d}/body", .{a}); + // The write returns with the text sorted, through the session's shell + // in the file's directory. + try c.write(actl, "Edit , | sort\n"); + try expectEqualStrings("apple\nfig\npear\n", try c.read(ar, abody)); + try c.write(actl, "Edit $ < pwd\n"); + try expectEqualStrings(f.at("apple\nfig\npear\n{s}\n", .{root}), try c.read(ar, abody)); + try c.write(actl, "Undo\n"); + try expectEqualStrings("apple\nfig\npear\n", try c.read(ar, abody)); + // A per-match command, one undo step. + try c.write(actl, "Edit ,x/[a-z]+/ | tr a-z A-Z\n"); + try expectEqualStrings("APPLE\nFIG\nPEAR\n", try c.read(ar, abody)); + // A failing command: nothing changed, the write fails in words, its + // stderr in +Errors. + try refusedSaying(c, actl, "Edit , | echo nope >&2; exit 4\n", "exit status 4"); + try expectEqualStrings("APPLE\nFIG\nPEAR\n", try c.read(ar, abody)); + var said = false; + var rows = std.mem.tokenizeScalar(u8, try c.read(ar, "/index"), '\n'); + while (rows.next()) |row| { + if (!has(row, "+Errors")) continue; + said = said or has(try c.read(ar, f.at("/pane/{s}/body", .{row[0..std.mem.indexOfScalar(u8, row, ' ').?]})), "nope"); + } + try expect(said); + // While a slow command runs, the editor answers. + { + const other = try process.Conn.dial(gpa, d.socket()); + defer other.deinit(gpa); + var slow: Slow = .{ .conn = other, .path = f.at("/pane/{d}/ctl", .{b}) }; + const worker = try std.Thread.spawn(.{}, Slow.go, .{&slow}); + process.sleep(200); + const began = eh.nowMs(); + _ = try c.read(ar, "/index"); + const quick = eh.nowMs() - began < 500 and !slow.done.load(.acquire); + worker.join(); + try expect(quick); // the editor did not wait on the command + try expect(slow.done.load(.acquire)); + } + // 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. + const ctl = try c.hold(actl, 1); + const status = try c.hold("/status", 0); + const began = eh.nowMs(); + const held = try c.send(.{ .write = .{ .fid = ctl, .offset = 0, .data = "Edit , | sleep 1; cat\n" } }); + const read = try c.send(.{ .read = .{ .fid = status, .offset = 0, .count = 4096 } }); + const first = try c.answer(); + try expect(first.tag == read and first.result == .read and eh.nowMs() - began < 500); + const second = try c.answer(); + try expect(second.tag == held and second.result == .write); + const flushed = try c.send(.{ .write = .{ .fid = ctl, .offset = 0, .data = "Edit , | sleep 5; tr a-z A-Z\n" } }); + process.sleep(300); + const flush = try c.send(.{ .flush = .{ .oldtag = flushed } }); + const one = (try c.answer()).tag; + const two = (try c.answer()).tag; + try expect((one == flushed and two == flush) or (one == flush and two == flushed)); + c.clunk(ctl); + c.clunk(status); + process.sleep(1000); + try c.write(actl, "Edit , | cat\n"); + process.sleep(4500); + try expectEqualStrings("APPLE\nFIG\nPEAR\n", try c.read(ar, abody)); + // X: each open file whose line matches; w writes it. + try c.write(actl, "Edit X/b\\.txt$/ ,s/apple/APPLE/\n"); + try expectEqualStrings("APPLE pie\n", try c.read(ar, f.at("/pane/{d}/body", .{b}))); + try c.write(f.at("/pane/{d}/ctl", .{b}), "Edit w\n"); + try expectEqualStrings("APPLE pie\n", try d.get(ar, "b.txt")); + try c.write(actl, "Edit 1 w first.txt\n"); + try expectEqualStrings("APPLE\n", try d.get(ar, "first.txt")); + // A file changed on disk under unsaved edits: Edit's w refuses once, as + // Save does, and the next w overwrites it. + try d.put("w1.txt", "one\n"); + const w = try c.look(ar, f.at("{s}/w1.txt", .{root})); + const wctl = f.at("/pane/{d}/ctl", .{w}); + try c.write(wctl, "Edit $a/two/\n"); + const changed = f.at("\nchanged {d}", .{w}); + const seen = std.mem.count(u8, try c.read(ar, "/log"), changed); + try eh.appendFile(try std.fmt.allocPrintSentinel(ar, "{s}/w1.txt", .{root}, 0), "external\n"); + const deadline = eh.nowMs() + 10_000; + while (std.mem.count(u8, try c.read(ar, "/log"), changed) == seen) { + if (eh.nowMs() > deadline) return error.NeverHeard; + process.sleep(50); + } + try refusedSaying(c, wctl, "Edit w\n", "modified on disk since read (w again to overwrite)"); + try expectEqualStrings("one\nexternal\n", try d.get(ar, "w1.txt")); + try c.write(wctl, "Edit w\n"); + try expectEqualStrings("one\ntwo", try d.get(ar, "w1.txt")); +} diff --git a/test/process/other_files.zig b/test/process/other_files.zig index d03d6b36..f682bb18 100644 --- a/test/process/other_files.zig +++ b/test/process/other_files.zig @@ -6,8 +6,33 @@ const process = @import("../process.zig"); pub const cases = .{ .{ "other-files: kbdin and mousein drive a detached session as the user would, each write done before it is answered", keysAndMouse }, .{ "other-files: a held connection lists a directory, stats a file, writes and reads, is refused in words and removes a pane", heldConnection }, + .{ "other-files: a file opened and closed is in /recent closed, and still is in the next session; Recent's row opens it again", recentSurvivesRestart }, + .{ "other-files: two sessions share one store: a file opened in one is in the other's /recent, a Del'd pane comes back from @p only where it was", storeShared }, }; +extern "c" fn system(cmd: [*:0]const u8) c_int; + +fn has(hay: []const u8, needle: []const u8) bool { + return std.mem.indexOf(u8, hay, needle) != null; +} + +/// A session's root kept past it, removed at the test's end. +fn keepRoot(d: *process.Detached, buf: *[4096]u8) []const u8 { + d.owns_root = false; + @memcpy(buf[0..d.root().len], d.root()); + return buf[0..d.root().len]; +} + +fn removeRoot(root: []const u8) void { + var cmd: [4200]u8 = undefined; + _ = system(std.fmt.bufPrintSentinel(&cmd, "rm -rf -- '{s}'", .{root}, 0) catch return); +} + +fn storeExists(root: []const u8) bool { + var buf: [4200]u8 = undefined; + return std.c.access(std.fmt.bufPrintSentinel(&buf, "{s}/.local/state/pardes/store", .{root}, 0) catch return false, 0) == 0; +} + /// A script types and clicks as the user does: no sleep or poll between a /// write and the read that checks it; where to click is read off /screen. /// (test/fs.py's keys_and_mouse, the first case written through the files @@ -64,3 +89,97 @@ fn heldConnection(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try c.remove(try std.fmt.bufPrint(&path, "/pane/{d}", .{serial})); try std.testing.expectError(error.NotFound, c.walk(body)); } + +/// The list is kept under $XDG_STATE_HOME (here HOME's .local/state) across +/// restarts. +fn recentSurvivesRestart(gpa: std.mem.Allocator, exe: [:0]const u8) !void { + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + var root_buf: [4096]u8 = undefined; + var one = try process.Detached.start(gpa, exe, "recent1", .{}); + const root = keepRoot(&one, &root_buf); + defer removeRoot(root); + const kept = try std.fmt.allocPrint(a, "{s}/kept.txt", .{root}); + { + defer one.deinit(); + try one.put("kept.txt", "one\ntwo\n"); + const c = try process.Conn.dial(gpa, one.socket()); + defer c.deinit(gpa); + const serial = try c.look(a, try std.fmt.allocPrint(a, "{s}:2", .{kept})); + try std.testing.expect(has(try c.read(a, "/recent"), try std.fmt.allocPrint(a, "open {s}\n", .{kept}))); + try c.write(try std.fmt.allocPrint(a, "/pane/{d}/ctl", .{serial}), "Del\n"); + try std.testing.expect(has(try c.read(a, "/recent"), try std.fmt.allocPrint(a, "closed {s}\n", .{kept}))); + } + try std.testing.expect(storeExists(root)); + var two = try process.Detached.start(gpa, exe, "recent2", .{ .root = root }); + defer two.deinit(); + const c = try process.Conn.dial(gpa, two.socket()); + defer c.deinit(gpa); + try std.testing.expect(has(try c.read(a, "/recent"), try std.fmt.allocPrint(a, "closed {s}\n", .{kept}))); + // Recent fills a query pane with it, its row relative to the pane's + // directory, and a look at the row opens it again. + try c.write("/pane/1/exec", "Recent\n"); + var answer = std.mem.tokenizeAny(u8, try c.read(a, "/pane/1/exec"), " \n"); + var last: []const u8 = ""; + while (answer.next()) |w| last = w; + const rows = try std.fmt.parseInt(u32, last, 10); + const body = try c.read(a, try std.fmt.allocPrint(a, "/pane/{d}/body", .{rows})); + try std.testing.expect(std.mem.startsWith(u8, body, "Recent ")); + var lines = std.mem.tokenizeScalar(u8, body, '\n'); + const row = while (lines.next()) |l| { + if (std.mem.startsWith(u8, l, "kept.txt:")) break l; + } else return error.NoRow; + try c.write(try std.fmt.allocPrint(a, "/pane/{d}/look", .{rows}), try std.fmt.allocPrint(a, "{s}\n", .{row[0 .. std.mem.indexOfScalar(u8, row, ' ') orelse row.len]})); + try std.testing.expect(has(try c.read(a, "/recent"), try std.fmt.allocPrint(a, "open {s}\n", .{kept}))); +} + +/// Del, and again when the first refused over unsaved text. +fn delTwice(c: *process.Conn, ctl: []const u8) !void { + c.write(ctl, "Del\n") catch try c.write(ctl, "Del\n"); +} + +/// The store (Store.zig) shared 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. +fn storeShared(gpa: std.mem.Allocator, exe: [:0]const u8) !void { + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + var root_buf: [4096]u8 = undefined; + var one = try process.Detached.start(gpa, exe, "store1", .{}); + const root = keepRoot(&one, &root_buf); + defer removeRoot(root); + { + defer one.deinit(); + var two = try process.Detached.start(gpa, exe, "store2", .{ .root = root }); + defer two.deinit(); + const c1 = try process.Conn.dial(gpa, one.socket()); + defer c1.deinit(gpa); + const c2 = try process.Conn.dial(gpa, two.socket()); + defer c2.deinit(gpa); + try one.put("shared.txt", "one\ntwo\nthree\n"); + const shared = try std.fmt.allocPrint(a, "{s}/shared.txt", .{root}); + const serial = try c1.look(a, try std.fmt.allocPrint(a, "{s}:3", .{shared})); + try std.testing.expect(has(try c1.read(a, "/recent"), try std.fmt.allocPrint(a, "open {s}\n", .{shared}))); + try std.testing.expect(has(try c2.read(a, "/recent"), try std.fmt.allocPrint(a, "closed {s}\n", .{shared}))); + try c1.write(try std.fmt.allocPrint(a, "/pane/{d}/ctl", .{serial}), "Del\n"); + try std.testing.expect(has(try c1.read(a, "/recent"), try std.fmt.allocPrint(a, "closed {s}\n", .{shared}))); + const scratch = try c1.newPane(); + try c1.write(try std.fmt.allocPrint(a, "/pane/{d}/body", .{scratch}), "kept across a Del\n"); + try delTwice(c1, try std.fmt.allocPrint(a, "/pane/{d}/ctl", .{scratch})); + var rows = std.mem.tokenizeScalar(u8, try c1.read(a, "/index"), '\n'); + while (rows.next()) |r| try std.testing.expect(!std.mem.startsWith(u8, r, try std.fmt.allocPrint(a, "{d} ", .{scratch}))); + const back = try c1.look(a, try std.fmt.allocPrint(a, "@p{d}", .{scratch})); + try std.testing.expectEqualStrings("kept across a Del\n", try c1.read(a, try std.fmt.allocPrint(a, "/pane/{d}/body", .{back}))); + // The other window's session closed no such pane. + const source = try c2.newPane(); + c2.write(try std.fmt.allocPrint(a, "/pane/{d}/look", .{source}), try std.fmt.allocPrint(a, "@p{d}\n", .{scratch})) catch {}; + var others = std.mem.tokenizeScalar(u8, try c2.read(a, "/index"), '\n'); + while (others.next()) |r| { + const body = try c2.read(a, try std.fmt.allocPrint(a, "/pane/{s}/body", .{r[0..std.mem.indexOfScalar(u8, r, ' ').?]})); + try std.testing.expect(!has(body, "kept across a Del")); + } + } + try std.testing.expect(storeExists(root)); +} diff --git a/test/process/root_ctl.zig b/test/process/root_ctl.zig new file mode 100644 index 00000000..6c32d499 --- /dev/null +++ b/test/process/root_ctl.zig @@ -0,0 +1,107 @@ +//! docs/typ/reference.typ, The root ctl , through a real +//! session's socket: it exits, keeps its own clock and saves. +const std = @import("std"); +const libc = std.c; +const process = @import("../process.zig"); +const eh = @import("../e2e_harness.zig"); +const expect = std.testing.expect; +const expectEqualStrings = std.testing.expectEqualStrings; + +pub const cases = .{ + .{ "root-ctl: Exit is answered before the editor quits", exitAnswers }, + .{ "root-ctl: with nothing attached a message leaves after MessageLinger on its own clock", messagesExpire }, + .{ "root-ctl: Putall with one pane's file changed on disk fails, answered once the other panes' saves have landed", putallAfterSaves }, + .{ "root-ctl: long and odd paths where a path goes (name, look, DumpDir, Dump, Save) are refused or said, never a crash; a bad ThemeFile fails the write", oddPaths }, +}; + +fn has(hay: []const u8, needle: []const u8) bool { + return std.mem.indexOf(u8, hay, needle) != null; +} + +fn exitAnswers(gpa: std.mem.Allocator, exe: [:0]const u8) !void { + var d = try process.Detached.start(gpa, exe, "exit", .{}); + defer d.deinit(); + try d.files.write("/ctl", "Exit\n"); + if (d.exited(5_000) == null) return error.StillRunning; +} + +/// Nothing attached, no key, no click, no other request comes to move it along. +fn messagesExpire(gpa: std.mem.Allocator, exe: [:0]const u8) !void { + var d = try process.Detached.start(gpa, exe, "msg", .{}); + defer d.deinit(); + try d.files.write("/pane/1/ctl", "Msg lingering-words\n"); + try expect(has(try d.files.screen(), "lingering-words")); + // Reading /screen is itself a request, so wait without asking. + process.sleep(2500); + try expect(!has(try d.files.screen(), "lingering-words")); +} + +fn putallAfterSaves(gpa: std.mem.Allocator, exe: [:0]const u8) !void { + var d = try process.Detached.start(gpa, exe, "putall", .{}); + defer d.deinit(); + const f = &d.files; + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const ar = arena.allocator(); + const c = try process.Conn.dial(gpa, d.socket()); + defer c.deinit(gpa); + try d.put("a.txt", "a\n"); + try d.put("b.txt", "b\n"); + const a = try c.look(ar, f.at("{s}/a.txt", .{d.root()})); + const b = try c.look(ar, f.at("{s}/b.txt", .{d.root()})); + for ([_]u32{ a, b }) |serial| try c.write(f.at("/pane/{d}/body", .{serial}), "edited\n"); + try d.put("b.txt", "changed on disk\n"); + const deadline = eh.nowMs() + 10_000; + while (!has(try c.read(ar, "/log"), f.at("changed {d}", .{b}))) { + if (eh.nowMs() > deadline) return error.NeverHeard; + process.sleep(50); + } + try std.testing.expectError(error.Refused, c.write("/ctl", "Putall\n")); + try expect(has(c.said, "modified on disk")); + try expectEqualStrings("a\nedited\n", try d.get(ar, "a.txt")); + try expectEqualStrings("changed on disk\n", try d.get(ar, "b.txt")); +} + +/// A part over 255 bytes (ENAMETOOLONG), a loop of links (ELOOP), a file +/// taken for a directory (ENOTDIR), one not ours (EACCES). +fn oddPaths(gpa: std.mem.Allocator, exe: [:0]const u8) !void { + var d = try process.Detached.start(gpa, exe, "odd", .{}); + defer d.deinit(); + const f = &d.files; + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const c = try process.Conn.dial(gpa, d.socket()); + defer c.deinit(gpa); + const root = d.root(); + const loop = try std.fmt.allocPrintSentinel(a, "{s}/loop", .{root}, 0); + try expect(libc.symlink(loop, loop) == 0); + try d.put("plain", "x\n"); + const long: [300]u8 = @splat('x'); + const odd = [_][]const u8{ + f.at("/tmp/{s}/f.txt", .{&long}), f.at("{s}/{s}", .{ root, &long }), f.at("{s}/loop/f", .{root}), + f.at("{s}/plain/f", .{root}), "/root/nope/f", f.at("{s}/a/../b.txt", .{root}), + }; + const serial = try c.newPane(); + try c.write(f.at("/pane/{d}/body", .{serial}), "text\n"); + for (odd) |path| { + for ([_][2][]const u8{ + .{ f.at("/pane/{d}/name", .{serial}), path }, .{ "/look", path }, .{ "/ctl", f.at("DumpDir {s}", .{path}) }, + .{ "/ctl", "Dump" }, .{ f.at("/pane/{d}/ctl", .{serial}), "Save" }, + }) |w| { + c.write(w[0], f.at("{s}\n", .{w[1]})) catch {}; + try expect((try c.read(a, "/index")).len > 0); + } + } + try c.write("/ctl", "DumpDir\n"); + // A theme file that is not there, or no theme, fails the write. + try d.put("bad.zon", ".{ .nonsense = 1 }"); + for ([_][2][]const u8{ + .{ f.at("ThemeFile {s}/missing.zon\n", .{root}), "theme file" }, + .{ f.at("ThemeFile {s}/bad.zon\n", .{root}), "theme file" }, + .{ "ThemeFile notes.txt\n", "a theme file is a .zon" }, + }) |t| { + try std.testing.expectError(error.Refused, c.write("/ctl", t[0])); + try expect(has(c.said, t[1])); + } +} diff --git a/test/process/terminals.zig b/test/process/terminals.zig new file mode 100644 index 00000000..e84b48e9 --- /dev/null +++ b/test/process/terminals.zig @@ -0,0 +1,241 @@ +//! docs/typ/guide.typ, Terminals , through a real session's +//! socket: its shells run. +const std = @import("std"); +const libc = std.c; +const process = @import("../process.zig"); +const eh = @import("../e2e_harness.zig"); +const expect = std.testing.expect; +const expectEqual = std.testing.expectEqual; +const expectEqualStrings = std.testing.expectEqualStrings; + +extern "c" fn system(cmd: [*:0]const u8) c_int; + +pub const cases = .{ + .{ "terminals: pty/run takes a line and answers how it ended, then what it printed, on the same open; busy while a job holds the tty, gone with its shell", runFile }, + .{ "terminals: a terminal started outside the session's directory is named by it from its new on, and a shell that cannot start leaves no pane", namedOnce }, +}; + +fn has(hay: []const u8, needle: []const u8) bool { + return std.mem.indexOf(u8, hay, needle) != null; +} + +fn refusedSaying(c: *process.Conn, path: []const u8, data: []const u8, why: []const u8) !void { + try std.testing.expectError(error.Refused, c.write(path, data)); + if (!has(c.said, why)) { + std.debug.print("{s} refused saying {s}, not {s}\n", .{ path, c.said, why }); + return error.WrongWords; + } +} + +/// A line written to a terminal's pty/run and the answer read on the same open. +fn run(a: std.mem.Allocator, c: *process.Conn, serial: u32, line: []const u8) ![]const u8 { + var buf: [64]u8 = undefined; + const fid = try c.hold(try std.fmt.bufPrint(&buf, "/pane/{d}/pty/run", .{serial}), 2); + defer c.clunk(fid); + _ = try c.writeFid(fid, 0, line); + return a.dupe(u8, try c.readFid(fid, 0, 1 << 16)); +} + +/// The serials of /index's rows whose fourth word, the path, is `path`. +fn panesAt(a: std.mem.Allocator, c: *process.Conn, path: []const u8) ![]const []const u8 { + var out: std.ArrayList([]const u8) = .empty; + var rows = std.mem.tokenizeScalar(u8, try c.read(a, "/index"), '\n'); + while (rows.next()) |row| { + var w = std.mem.tokenizeScalar(u8, row, ' '); + const serial = w.next().?; + _ = w.next(); + _ = w.next(); + if (std.mem.eql(u8, w.next() orelse "", path)) try out.append(a, serial); + } + return out.items; +} + +/// The serials /index lists. +fn serials(a: std.mem.Allocator, c: *process.Conn) ![]const u32 { + var out: std.ArrayList(u32) = .empty; + var rows = std.mem.tokenizeScalar(u8, try c.read(a, "/index"), '\n'); + while (rows.next()) |row| try out.append(a, try std.fmt.parseInt(u32, row[0..std.mem.indexOfScalar(u8, row, ' ').?], 10)); + return out.items; +} + +fn shell(a: std.mem.Allocator, comptime fmt: []const u8, args: anytype) c_int { + return system(std.fmt.allocPrintSentinel(a, fmt, args, 0) catch @panic("out of memory")); +} + +/// A run on another connection, as another client's, in a thread. +const Other = struct { + a: std.mem.Allocator, + conn: *process.Conn, + serial: u32, + line: []const u8, + got: []const u8 = "", + + fn go(o: *Other) void { + o.got = run(o.a, o.conn, o.serial, o.line) catch ""; + } +}; + +fn runFile(gpa: std.mem.Allocator, exe: [:0]const u8) !void { + var d = try process.Detached.start(gpa, exe, "run", .{}); + defer d.deinit(); + const f = &d.files; + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const c = try process.Conn.dial(gpa, d.socket()); + defer c.deinit(gpa); + const root = d.root(); + // From a pane on a peer's path no command or terminal starts: refused + // before any pane is made, no `exit 127` pane left. + const peer = try c.newPane(); + try c.write(f.at("/pane/{d}/name", .{peer}), "/n/nosuchpeer/d/f.txt\n"); + const count = std.mem.count(u8, try c.read(a, "/index"), "\n"); + try refusedSaying(c, f.at("/pane/{d}/exec", .{peer}), "ls\n", "no such directory"); + try refusedSaying(c, f.at("/pane/{d}/exec", .{peer}), "Tty\n", "no such directory"); + try expectEqual(count, std.mem.count(u8, try c.read(a, "/index"), "\n")); + try expect(!has(try c.read(a, "/log"), "exit 127")); + try c.remove(f.at("/pane/{d}", .{peer})); + try c.write("/exec", "Shell bash\n"); + try c.write("/exec", "Tty\n"); + var term: u32 = 0; + var rows = std.mem.tokenizeScalar(u8, try c.read(a, "/index"), '\n'); + while (rows.next()) |r| { + var w = std.mem.tokenizeScalar(u8, r, ' '); + const serial = try std.fmt.parseInt(u32, w.next().?, 10); + if (std.mem.eql(u8, w.next().?, "term")) term = @max(term, serial); + } + const deadline = eh.nowMs() + 10_000; + while (std.mem.eql(u8, try run(a, c, term, "true\n"), "busy\n")) { // until its first prompt + if (eh.nowMs() > deadline) return error.NoPrompt; + process.sleep(50); + } + try expectEqualStrings("exit 1\n", try run(a, c, term, "false\n")); + try expectEqualStrings("exit 0\none\ntwo\n", try run(a, c, term, "printf \"one\\ntwo\\n\"\n")); // then what it printed + try expectEqualStrings("exit 7\n", try run(a, c, term, "sh -c \"exit 7\"\n")); + try expectEqualStrings("error not run\n", try run(a, c, term, "fi\n")); // a syntax error runs nothing + try expectEqualStrings("error not run\n", try run(a, c, term, "echo 'open\n")); // nor does an open quote + try expectEqualStrings("exit 0\n", try run(a, c, term, "true\n")); // ...and the shell is clear after + // With no frontend attached the pty's size is in pixels too, at a + // nominal 8x16 cell: a program sizes its kitty graphics by it. + const said = try run(a, c, term, "python3 -c 'import fcntl,termios,struct;print(*struct.unpack(\"4H\",fcntl.ioctl(0,termios.TIOCGWINSZ,bytes(8))))'\n"); + var lines = std.mem.splitScalar(u8, said, '\n'); + _ = lines.next(); + var size = std.mem.tokenizeScalar(u8, lines.next() orelse "", ' '); + var n: [4]u32 = undefined; + for (&n) |*v| v.* = try std.fmt.parseInt(u32, size.next() orelse return error.NoSize, 10); + try expect(n[2] == n[1] * 8 and n[3] == n[0] * 16 and n[2] > 0); + // 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 (shell(a, "command -v git >/dev/null", .{}) == 0) { + const git = f.at("HOME='{s}' git -C '{s}/pagedrepo' -c user.name=p -c user.email=p@x", .{ root, root }); + try expectEqual(@as(c_int, 0), shell(a, "mkdir '{s}/pagedrepo' && {s} init -q && echo x > '{s}/pagedrepo/f' && {s} add f && {s} commit -qm paged-commit-subject", .{ root, git, root, git, git })); + try expect(std.mem.startsWith(u8, try run(a, c, term, "git -C pagedrepo log\n"), "exit 0\n")); + const pager = try panesAt(a, c, f.at("{s}/pagedrepo/+Pager", .{root})); // git -C runs it in the repo + try expectEqual(@as(usize, 1), pager.len); + const body = try c.read(a, f.at("/pane/{s}/body", .{pager[0]})); + try expect(has(body, "paged-commit-subject") and !has(body, "\x1b")); + try c.remove(f.at("/pane/{s}", .{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. + const systemd = try run(a, c, term, "printf \"%s\\n\" \"$SYSTEMD_PAGER\" \"$SYSTEMD_PAGERSECURE\"\n"); + try expect(std.mem.startsWith(u8, systemd, "exit 0\n") and std.mem.endsWith(u8, std.mem.trimEnd(u8, systemd, " \n"), " -\n0")); + if (shell(a, "command -v journalctl >/dev/null", .{}) == 0) { + try expect(std.mem.startsWith(u8, try run(a, c, term, "journalctl -n 3 --no-hostname\n"), "exit ")); + for (try panesAt(a, c, f.at("{s}/+Pager", .{root}))) |p| try c.remove(f.at("/pane/{s}", .{p})); + } + // 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. + const ptyctl = f.at("/pane/{d}/pty/ctl", .{term}); + try refusedSaying(c, ptyctl, "winsize 20 1\n", "at least 2 rows"); + try c.write(ptyctl, "winsize 20 2\n"); + process.sleep(500); + try expectEqualStrings("exit 0\n", try run(a, c, term, "true\n")); + var words = std.mem.tokenizeAny(u8, try c.read(a, ptyctl), " \n"); + _ = words.next(); + _ = words.next(); + try expectEqualStrings("2", words.next().?); + try c.write(ptyctl, "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. + const locked = try std.fmt.allocPrintSentinel(a, "{s}/locked", .{root}, 0); + try expectEqual(@as(c_int, 0), libc.mkdir(locked, 0o755)); + try expectEqualStrings("exit 0\n", try run(a, c, term, f.at("cd {s}\n", .{locked}))); + const until = eh.nowMs() + 5_000; + while (!has(try c.read(a, "/index"), locked)) { + if (eh.nowMs() > until) return error.NeverMoved; + process.sleep(50); + } + _ = libc.chmod(locked, 0o600); + const refused = if (libc.geteuid() != 0) refusedSaying(c, ptyctl, "exec\n", "shell") else {}; // root enters any directory + _ = libc.chmod(locked, 0o755); + try refused; + try expectEqualStrings("exit 0\n", try run(a, c, term, "true\n")); + try expectEqualStrings("exit 0\n", try run(a, c, term, f.at("cd {s}\n", .{root}))); + const other = try process.Conn.dial(gpa, d.socket()); + defer other.deinit(gpa); + const tv: libc.timeval = .{ .sec = 10, .usec = 0 }; + _ = libc.setsockopt(other.fd, libc.SOL.SOCKET, libc.SO.RCVTIMEO, &tv, @sizeOf(libc.timeval)); + var slow: Other = .{ .a = a, .conn = other, .serial = term, .line = "sleep 1\n" }; + var waiter = try std.Thread.spawn(.{}, Other.go, .{&slow}); + process.sleep(300); + // The job the other client ran holds the tty, and says so. + const busy = run(a, c, term, "true\n"); + waiter.join(); + try expectEqualStrings("busy: sleep is running\n", try busy); + try expectEqualStrings("exit 0\n", slow.got); + var closing: Other = .{ .a = a, .conn = other, .serial = term, .line = "sleep 30\n" }; + waiter = try std.Thread.spawn(.{}, Other.go, .{&closing}); + process.sleep(300); + const del = c.write(f.at("/pane/{d}/exec", .{term}), "Del\n"); + waiter.join(); + try del; + try expectEqualStrings("error shell gone\n", closing.got); +} + +fn namedOnce(gpa: std.mem.Allocator, exe: [:0]const u8) !void { + var d = try process.Detached.start(gpa, exe, "names", .{}); + defer d.deinit(); + const f = &d.files; + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const c = try process.Conn.dial(gpa, d.socket()); + defer c.deinit(gpa); + const root = d.root(); + try expectEqual(@as(c_int, 0), libc.mkdir(try std.fmt.allocPrintSentinel(a, "{s}/sub", .{root}, 0), 0o755)); + // A look at a directory starts a terminal there (DirLook terminal); + // DirLook pane, the default, lists it in a pane. + try c.write("/ctl", "DirLook terminal\n"); + var made: std.ArrayList(u32) = .empty; + try made.append(a, try c.look(a, f.at("{s}/sub", .{root}))); + const before = try serials(a, c); + try c.write("/pane/1/ctl", "Tty\n"); + if (shell(a, "command -v fish >/dev/null", .{}) == 0) try c.write("/pane/1/ctl", "Tty fish\n"); + for (try serials(a, c)) |s| if (std.mem.indexOfScalar(u32, before, s) == null) try made.append(a, s); + try expect(made.items.len >= 2); + process.sleep(1500); // their shells start and say where they are + // A shell started again by pty/ctl exec: named as it was. + try c.write(f.at("/pane/{d}/pty/ctl", .{made.items[0]}), "exec\n"); + process.sleep(1500); + const log = f.at("\n{s}", .{try c.read(a, "/log")}); + for (made.items) |s| { + try expect(!has(log, f.at("\nrename {d} ", .{s}))); + try expect(has(log, f.at("\nnew {d} {s}", .{ s, root }))); + } + // 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. + try d.put("badsh", "#!/nonexistent/interp\n"); + const bad = f.at("{s}/badsh", .{root}); + _ = libc.chmod(try std.fmt.allocPrintSentinel(a, "{s}", .{bad}, 0), 0o755); + const panes = std.mem.count(u8, try c.read(a, "/index"), "\n"); + try refusedSaying(c, "/pane/1/ctl", f.at("Tty {s}\n", .{bad}), "interpreter /nonexistent/interp not found"); + try refusedSaying(c, "/ctl", f.at("Shell {s}\n", .{bad}), "interpreter /nonexistent/interp not found"); + process.sleep(300); + try expectEqual(panes, std.mem.count(u8, try c.read(a, "/index"), "\n")); + try expect(!has(try c.read(a, "/log"), "shell: shell not found")); + try expect(std.mem.indexOfScalar(u32, try serials(a, c), made.items[0]) != null); +} diff --git a/test/process/tree.zig b/test/process/tree.zig new file mode 100644 index 00000000..4d1b2915 --- /dev/null +++ b/test/process/tree.zig @@ -0,0 +1,484 @@ +//! docs/typ/reference.typ, The tree , through a real session's socket. +const std = @import("std"); +const libc = std.c; +const process = @import("../process.zig"); +const c9 = @import("cloud9"); +const eh = @import("../e2e_harness.zig"); +const expect = std.testing.expect; +const expectEqual = std.testing.expectEqual; +const expectEqualStrings = std.testing.expectEqualStrings; + +pub const cases = .{ + .{ "tree: listing, stat and find are inert; new, remove, look, exec, name, sel, log, ctl lock, focus, the ctl split, commands, Save and the slots behave", discovery }, + .{ "tree: a write bigger than a 9P message runs each line once, whole, an Edit block once it ends; a detached session is 160x50 until told", cutWrites }, +}; + +fn has(hay: []const u8, needle: []const u8) bool { + return std.mem.indexOf(u8, hay, needle) != null; +} + +fn contains(names: []const []const u8, name: []const u8) bool { + for (names) |n| if (std.mem.eql(u8, n, name)) return true; + return false; +} + +/// A write refused, its words holding `why`. +fn refusedSaying(c: *process.Conn, path: []const u8, data: []const u8, why: []const u8) !void { + try std.testing.expectError(error.Refused, c.write(path, data)); + if (!has(c.said, why)) { + std.debug.print("{s} refused saying {s}, not {s}\n", .{ path, c.said, why }); + return error.WrongWords; + } +} + +/// A read on `c` given up after `sec` seconds, so a wait that never ends fails. +fn timeout(c: *process.Conn, sec: i64) void { + const tv: libc.timeval = .{ .sec = sec, .usec = 0 }; + _ = libc.setsockopt(c.fd, libc.SOL.SOCKET, libc.SO.RCVTIMEO, &tv, @sizeOf(libc.timeval)); +} + +/// /index's row for `serial`. +fn indexRow(index: []const u8, serial: u32) ![]const u8 { + var rows = std.mem.tokenizeScalar(u8, index, '\n'); + while (rows.next()) |row| { + const sp = std.mem.indexOfScalar(u8, row, ' ') orelse continue; + if ((std.fmt.parseInt(u32, row[0..sp], 10) catch continue) == serial) return row; + } + return error.NoRow; +} + +/// The serials of /index's rows whose fourth word, the path, is `path`. +fn panesAt(a: std.mem.Allocator, c: *process.Conn, path: []const u8) ![]const []const u8 { + var out: std.ArrayList([]const u8) = .empty; + var rows = std.mem.tokenizeScalar(u8, try c.read(a, "/index"), '\n'); + while (rows.next()) |row| { + var w = std.mem.tokenizeScalar(u8, row, ' '); + const serial = w.next().?; + _ = w.next(); + _ = w.next(); + if (std.mem.eql(u8, w.next() orelse "", path)) try out.append(a, serial); + } + return out.items; +} + +const Seen = struct { path: []const u8, mode: u32, mtime: u32 }; + +/// Every entry below `path` stated, as `find` does, without opening one. +fn walkTree(a: std.mem.Allocator, c: *process.Conn, path: []const u8, seen: *std.ArrayList(Seen)) !void { + for (try c.list(a, path)) |name| { + const child = try std.fmt.allocPrint(a, "{s}/{s}", .{ std.mem.trimEnd(u8, path, "/"), name }); + const st = try c.stat(child); + try seen.append(a, .{ .path = child, .mode = st.mode, .mtime = st.mtime }); + if (st.mode & c9.dmdir != 0 and !contains(&.{ "/log", "/os", "/screen" }, child)) try walkTree(a, c, child, seen); + } +} + +/// A follower's read on a held /log, which waits for a new record. +const Follower = struct { + conn: *process.Conn, + fid: u32, + off: u64, + buf: [256]u8 = undefined, + len: usize = 0, + + fn run(w: *Follower) void { + const got = w.conn.readFid(w.fid, w.off, 4096) catch return; + w.len = @min(got.len, w.buf.len); + @memcpy(w.buf[0..w.len], got[0..w.len]); + } +}; + +fn discovery(gpa: std.mem.Allocator, exe: [:0]const u8) !void { + var d = try process.Detached.start(gpa, exe, "discovery", .{}); + defer d.deinit(); + const f = &d.files; + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const c = try process.Conn.dial(gpa, d.socket()); + defer c.deinit(gpa); + const root = d.root(); + + const top = try c.list(a, "/"); + // A set: which files the root holds, not the order a listing gives. + const want = [_][]const u8{ "README", "index", "status", "focus", "ctl", "commands", "recent", "look", "exec", "pager", "log", "screen", "listeners", "sessions", "layout", "tag", "tagexec", "kbdin", "mousein", "pane", "col", "os" }; + var others: usize = 0; + for (top) |n| { + if (contains(&.{ "src", "shaders" }, n)) continue; + others += 1; + try expect(contains(&want, n)); + } + try expectEqual(want.len, others); + for (want) |n| try expect(contains(top, n)); + const embedded = contains(top, "src"); + const before = try c.read(a, "/index"); + const guide = try c.read(a, "/README"); + try expect(std.mem.count(u8, guide, "\n") <= 45 and has(guide, "Msg hello") and has(guide, "pane/new")); + try expectEqual(guide.len, (try c.stat("/README")).length); + // ls/stat/find over the whole tree, without opening, creates nothing. + var seen: std.ArrayList(Seen) = .empty; + try walkTree(a, c, "/", &seen); + var names: std.ArrayList([]const u8) = .empty; + for (seen.items) |s| try names.append(a, s.path); + for ([_][]const u8{ "/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" }) |n| try expect(contains(names.items, n)); + try expect(!contains(names.items, "/pane/1/pty")); // the fixture file pane grew no pty/ + for (seen.items) |s| { + try expect(!std.mem.startsWith(u8, s.path, "/self") and !std.mem.endsWith(u8, s.path, "/rdsel") and !std.mem.endsWith(u8, s.path, "/wrsel")); + const mode = s.mode & 0o777; + try expect(mode == 0o755 or mode == 0o644 or mode == 0o666 or mode == 0o444 or mode == 0o222 or mode == 0o555); + try expect(s.mtime > 0); + } + try expectEqualStrings(before, try c.read(a, "/index")); // browsing created no pane + try expect(before.len > 0); + try expectEqual(@as(u64, 0), (try c.stat("/index")).length); // a view made by each read stats 0 (reference.typ, Stats) + try expectEqual(@as(u32, 0o444), (try c.stat("/index")).mode & 0o777); + try expectEqual(@as(u32, 0o444), (try c.stat("/status")).mode & 0o777); + try expectEqual(@as(u32, 0o666), (try c.stat("/exec")).mode & 0o777); + try expectEqual(@as(u32, 0o666), (try c.stat("/pane/1/body")).mode & 0o777); + try expectEqual(@as(u32, 0o755), (try c.stat("/pane")).mode & 0o777); + // A range file reads the pair it takes; a flag file reads 0 or 1. + try expectEqual(@as(u64, 24), (try c.stat("/pane/1/addr")).length); + try expectEqual(@as(u64, 0), (try c.stat("/pane/1/limit")).length); + try expectEqualStrings("0\n", try c.read(a, "/pane/1/dirty")); + try expectEqualStrings("1\n", try c.read(a, "/pane/1/scroll")); + const fixture = try std.fmt.parseInt(u32, before[0..std.mem.indexOfScalar(u8, before, ' ').?], 10); + try expect(std.mem.startsWith(u8, before, f.at("{d} text 0 ", .{fixture}))); + try expect(std.mem.endsWith(u8, before[0..std.mem.lastIndexOfScalar(u8, std.mem.trimEnd(u8, before, "\n"), ' ').?], "/discovery.txt")); + // /status reports the editor; /exec has nothing to report yet. + var pid: i64 = 0; + var version = false; + var panes: i64 = 0; + var lines = std.mem.tokenizeScalar(u8, try c.read(a, "/status"), '\n'); + while (lines.next()) |line| { + const sp = std.mem.indexOfScalar(u8, line, ' ') orelse continue; + const key, const value = .{ line[0..sp], std.mem.trim(u8, line[sp..], " ") }; + if (std.mem.eql(u8, key, "pid")) pid = try std.fmt.parseInt(i64, value, 10); + if (std.mem.eql(u8, key, "version")) version = value.len > 0; + if (std.mem.eql(u8, key, "panes")) panes = try std.fmt.parseInt(i64, value, 10); + } + try expect(pid > 0 and version and panes >= 1); + try expectEqualStrings("", try c.read(a, "/exec")); + // 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. + const log = try c.hold("/log", 2); + const frozen = (try c.readFid(log, 0, 1 << 16)).len; + _ = try c.writeFid(log, 0, "follow\n"); + const first = try c.newPane(); + try expectEqual(first, try c.newest(a)); + const second = try c.newPane(); + try expect(first != second and first != fixture); + try expect(contains(try c.list(a, "/pane"), "new")); + _ = try c.stat("/pane/new"); + try expectEqual(second, try c.newest(a)); // a stat of new made no pane + // What the editor said is in the stream too. + const paneEvent = struct { + fn next(conn: *process.Conn, al: std.mem.Allocator, fid: u32, off: u64) ![]const u8 { + while (true) { + const record = try conn.readFid(fid, off, 1 << 16); + if (!std.mem.startsWith(u8, record, "msg ") and !std.mem.startsWith(u8, record, "err ")) return al.dupe(u8, record); + } + } + }.next; + try expectEqualStrings(f.at("new {d} {s}/+New\n", .{ first, root }), try paneEvent(c, a, log, frozen)); + try expectEqualStrings(f.at("new {d} {s}/+New\n", .{ second, root }), try paneEvent(c, a, log, frozen)); + // A follower that is waiting wakes when the editor logs, not when some + // unrelated request next happens to wait. + { + const follower = try process.Conn.dial(gpa, d.socket()); + defer follower.deinit(gpa); + timeout(follower, 5); + const waiting = try follower.hold("/log", 2); + const start = (try follower.readFid(waiting, 0, 1 << 16)).len; + _ = try follower.writeFid(waiting, 0, "follow\n"); + var w: Follower = .{ .conn = follower, .fid = waiting, .off = start }; + const reader = try std.Thread.spawn(.{}, Follower.run, .{&w}); + process.sleep(200); + try c.write("/exec", "Msg woken\n"); + reader.join(); + try expect(std.mem.endsWith(u8, w.buf[0..w.len], " woken\n")); + } + // A pane's ctl takes acme's lock: a second open's lock fails at once + // with "file in use" until the holder unlocks, and nothing else waits + // on it meanwhile. + { + const other = try process.Conn.dial(gpa, d.socket()); + defer other.deinit(gpa); + const ctl = f.at("/pane/{d}/ctl", .{first}); + const mine = try c.hold(ctl, 2); + _ = try c.writeFid(mine, 0, "lock\n"); + const theirs = try other.hold(ctl, 1); + try std.testing.expectError(error.Refused, other.writeFid(theirs, 0, "lock\n")); + try expect(has(other.said, "file in use")); + try c.write(f.at("/pane/{d}/addr", .{first}), "#0"); + _ = try c.writeFid(mine, 0, "unlock\n"); + _ = try other.writeFid(theirs, 0, "lock\n"); + c.clunk(mine); + other.clunk(theirs); + } + // /focus names the pane with the keyboard and moves it, as rio's wctl + // `current` does; a pane's ctl line ends saying which it is. + try c.write("/focus", f.at("{d}\n", .{first})); + try expectEqualStrings(f.at("{d}\n", .{first}), try c.read(a, "/focus")); + try expect(has(try c.read(a, f.at("/pane/{d}/ctl", .{first})), " current ")); + try expect(has(try c.read(a, f.at("/pane/{d}/ctl", .{second})), " notcurrent ")); + try refusedSaying(c, "/focus", "99999\n", "no such pane"); + // /ctl reads the settings as a write takes them and takes the session's + // builtins; a pane's ctl takes the pane's. + const settings = try c.read(a, "/ctl"); + try expect(has(settings, "Verbose ") and !has(settings, "Platform")); + try c.write("/ctl", settings); + try expectEqualStrings(settings, try c.read(a, "/ctl")); + try c.write("/ctl", "Verbose off\n"); + try expect(has(try c.read(a, "/ctl"), "Verbose off\n")); + try refusedSaying(c, "/ctl", "Del\n", "not a session control message \"Del\""); + try refusedSaying(c, "/ctl", "Nope 3\n", "unknown control message \"Nope\""); + try refusedSaying(c, f.at("/pane/{d}/ctl", .{first}), "Newcol\n", "not a window control message \"Newcol\""); + const commands = try c.read(a, "/commands"); + const row = struct { + fn row(text: []const u8, start: []const u8) bool { + var rows = std.mem.tokenizeScalar(u8, text, '\n'); + while (rows.next()) |r| if (std.mem.eql(u8, r, start) or (std.mem.startsWith(u8, r, start) and r.len > start.len and r[start.len] == ' ')) return true; + return false; + } + }.row; + try expect(row(commands, "Newcol root") and row(commands, "Save arg pane") and row(commands, "Edit arg both")); + // word, `arg` if it takes one, its ctl, a setting's values, then `-- ` what it does + var crows = std.mem.tokenizeScalar(u8, commands, '\n'); + while (crows.next()) |r| { + var w = std.mem.tokenizeScalar(u8, r, ' '); + _ = w.next(); + var which = w.next().?; + if (std.mem.eql(u8, which, "arg")) which = w.next().?; + try expect(contains(&.{ "root", "pane", "both" }, which)); + } + try expect(row(commands, "Placement arg root acme,pardes")); + try expect(std.mem.endsWith(u8, commands, "\n")); + try expectEqual(commands.len, (try c.stat("/commands")).length); + try c.write(f.at("/pane/{d}/ctl", .{first}), "Msg said through ctl\n"); + try expect(has(try f.screen(), "said through ctl")); + const listed = try c.list(a, "/pane"); + try expectEqual(@as(usize, 4), listed.len); + for ([_]u32{ fixture, first, second }) |n| try expect(contains(listed, f.at("{d}", .{n}))); + try expect(contains(listed, "new")); + try c.replace(f.at("/pane/{d}/body", .{first}), "first pane"); + try expectEqualStrings("first pane", try c.read(a, f.at("/pane/{d}/body", .{first}))); + try expectEqualStrings("", try c.read(a, f.at("/pane/{d}/body", .{second}))); + try expectEqual(@as(u64, "first pane".len), (try c.stat(f.at("/pane/{d}/body", .{first}))).length); + const index = try c.read(a, "/index"); + try expect(std.mem.startsWith(u8, try indexRow(index, first), f.at("{d} text 1 ", .{first}))); + try expect(std.mem.startsWith(u8, try indexRow(index, second), f.at("{d} text 0 ", .{second}))); + // name: read the file name, write to rename; sel: the selection. + const name = f.at("/pane/{d}/name", .{first}); + try expectEqualStrings(f.at("{s}/+New\n", .{root}), try c.read(a, name)); + try c.write(name, "notes.txt\n"); + try expectEqualStrings(f.at("{s}/notes.txt\n", .{root}), try c.read(a, name)); + try expectEqualStrings(f.at("rename {d} {s}/notes.txt\n", .{ first, root }), try paneEvent(c, a, log, frozen)); + try expectEqual(@as(u64, f.at("{s}/notes.txt\n", .{root}).len), (try c.stat(name)).length); + // Copying addr onto dot selects that range; sel reads and replaces it. + const addr = f.at("/pane/{d}/addr", .{first}); + const dot = f.at("/pane/{d}/dot", .{first}); + const sel = f.at("/pane/{d}/sel", .{first}); + try c.write(addr, "#0,#5"); + try c.write(dot, try c.read(a, addr)); + try expectEqualStrings(try c.read(a, addr), try c.read(a, dot)); + try expectEqualStrings("first", try c.read(a, sel)); + try expectEqual(@as(u64, 5), (try c.stat(sel)).length); + try c.write(sel, "FIRST"); + try expectEqualStrings("FIRST pane", try c.read(a, f.at("/pane/{d}/body", .{first}))); + try expectEqualStrings("FIRST", try c.read(a, sel)); // what a write to sel put there is selected + // exec Msg shows text; exec Save writes the named file; rmdir closes. + try c.write(f.at("/pane/{d}/exec", .{first}), "Msg hello from 9P\n"); + try expect(has(try f.screen(), "hello from 9P")); + try expectEqualStrings("1\n", try c.read(a, f.at("/pane/{d}/dirty", .{first}))); + try c.write(f.at("/pane/{d}/exec", .{first}), "Save\n"); + try expectEqualStrings("FIRST pane", try d.get(a, "notes.txt")); + try expectEqualStrings(f.at("save {d} {s}/notes.txt\n", .{ first, root }), try paneEvent(c, a, log, frozen)); + try expectEqualStrings(f.at("{d}\n", .{first}), try c.read(a, "/exec")); + try expectEqualStrings("0\n", try c.read(a, f.at("/pane/{d}/dirty", .{first}))); + try c.remove(f.at("/pane/{d}", .{second})); + try expectEqualStrings(f.at("del {d} {s}/+New\n", .{ second, root }), try paneEvent(c, a, log, frozen)); + try expect(!contains(try c.list(a, "/pane"), f.at("{d}", .{second}))); + // look opens a file; the serial reads back. + try d.put("opened.txt", "one\ntwo\nthree\n"); + try c.write("/look", f.at("{s}/opened.txt:2\n", .{root})); + const opened = try std.fmt.parseInt(u32, std.mem.trim(u8, try c.read(a, "/look"), "\n"), 10); + try expect(opened != fixture and opened != first and opened != second); + try expectEqualStrings("one\ntwo\nthree\n", try c.read(a, f.at("/pane/{d}/body", .{opened}))); + try expectEqualStrings(f.at("{s}/opened.txt\n", .{root}), try c.read(a, f.at("/pane/{d}/name", .{opened}))); + try expectEqualStrings(f.at("new {d} {s}/opened.txt\n", .{ opened, root }), try paneEvent(c, a, log, frozen)); + try c.write(f.at("/pane/{d}/look", .{first}), f.at("{s}/opened.txt:3\n", .{root})); + try expectEqualStrings(f.at("{d}\n", .{opened}), try c.read(a, "/look")); // a repeated look targets the open pane + for ([_]u32{ fixture, first, opened }) |n| try expect(contains(try c.list(a, "/pane"), f.at("{d}", .{n}))); + // Writing an event record back still performs the action it names. + try c.replace(f.at("/pane/{d}/body", .{first}), "Msg via event"); + try c.write(f.at("/pane/{d}/event", .{first}), "FX0 13\n"); + try expect(has(try f.screen(), "via event")); + // A command line may not carry control characters, and nothing else in + // the tree may be created or removed. + if (c.write("/exec", "Msg a\x00b")) |_| return error.Taken else |_| {} + if (c.write("/status", "anything\n")) |_| return error.Taken else |_| {} + if (c.create("/", "x", c9.dmdir | 0o755)) |_| return error.Taken else |_| {} + if (c.create("/pane", "one", c9.dmdir | 0o755)) |_| return error.Taken else |_| {} + if (c.create("/pane", "plain-file", 0o644)) |_| return error.Taken else |_| {} + if (c.remove("/pane/1/body")) |_| return error.Taken else |_| {} + if (c.remove("/index")) |_| return error.Taken else |_| {} + c.clunk(log); + if (embedded) { + try expect(std.mem.startsWith(u8, try c.read(a, "/src/pardes.zig"), "const std")); + try expectEqual(@as(u32, 0o444), (try c.stat("/src/pardes.zig")).mode & 0o777); + try expect(has(try c.read(a, f.at("/pane/{d}/body", .{try c.look(a, "/virtual/src/pardes.zig")})), "pub const Pardes")); + } + // An open of data with OTRUNC (a shell's >) deletes the addressed range + // only, so the write after it replaces that range. + const scratch = try c.newPane(); + try c.write(f.at("/pane/{d}/body", .{scratch}), "hello world\nsecond line\n"); + try c.write(f.at("/pane/{d}/addr", .{scratch}), "#0,#5"); + try c.replace(f.at("/pane/{d}/data", .{scratch}), "HOWDY"); + try expectEqualStrings("HOWDY world\nsecond line\n", try c.read(a, f.at("/pane/{d}/body", .{scratch}))); + // sam's regexps: ^ at any line; a miss says so and leaves no address, + // so the data write after it refuses. + try c.write(f.at("/pane/{d}/addr", .{scratch}), "/^second/"); + try expectEqualStrings(" 12 18 ", try c.read(a, f.at("/pane/{d}/addr", .{scratch}))); + try refusedSaying(c, f.at("/pane/{d}/addr", .{scratch}), "/nowhere/", "no match for regexp"); + try refusedSaying(c, f.at("/pane/{d}/data", .{scratch}), "LOST", "no address"); + try expectEqualStrings("HOWDY world\nsecond line\n", try c.read(a, f.at("/pane/{d}/body", .{scratch}))); + // Through a mount both read as EINVAL; the log says which and why. + try expect(has(try c.read(a, "/log"), f.at("err {d} addr: no match for regexp\n", .{scratch}))); + try c.remove(f.at("/pane/{d}", .{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. + try d.put("diff-old.txt", "one\ntwo\nthree\n"); + try d.put("diff-new.txt", "one\nTWO\nthree\n"); + const exits = std.mem.count(u8, try c.read(a, "/log"), "\nexit "); + try c.write("/exec", "diff -u diff-old.txt diff-new.txt\n"); + const deadline = eh.nowMs() + 10_000; + while (std.mem.count(u8, try c.read(a, "/log"), "\nexit ") <= exits) { + if (eh.nowMs() > deadline) return error.DiffNeverEnded; + process.sleep(50); + } + // A command's pane is kind cmd, not term: no shell to type into. + var ran: u32 = 0; + var irows = std.mem.tokenizeScalar(u8, try c.read(a, "/index"), '\n'); + while (irows.next()) |r| { + var w = std.mem.tokenizeScalar(u8, r, ' '); + const serial = w.next().?; + if (std.mem.eql(u8, w.next() orelse "", "cmd")) ran = try std.fmt.parseInt(u32, serial, 10); + } + const shown = try c.read(a, f.at("/pane/{d}/body", .{ran})); + try expect(has(shown, "+++ diff-new.txt") and !has(shown, "\t")); + try c.write(f.at("/pane/{d}/look", .{ran}), "+TWO\n"); + const diffed = try panesAt(a, c, f.at("{s}/diff-new.txt", .{root})); + try expectEqual(@as(usize, 1), diffed.len); + try c.remove(f.at("/pane/{s}", .{diffed[0]})); + try c.remove(f.at("/pane/{d}", .{ran})); + // 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. + const tilde = try c.newPane(); + try c.write(f.at("/pane/{d}/body", .{tilde}), "one\ntwo\nthree\n"); + try c.write(f.at("/pane/{d}/ctl", .{tilde}), "Save ~/tilde-made/sub/x.txt\n"); + try expectEqualStrings("one\ntwo\nthree\n", try d.get(a, "tilde-made/sub/x.txt")); + try c.write(f.at("/pane/{d}/name", .{tilde}), "~/tilde-named.txt\n"); + try expectEqualStrings(f.at("{s}/tilde-named.txt\n", .{root}), try c.read(a, f.at("/pane/{d}/name", .{tilde}))); + try c.remove(f.at("/pane/{d}", .{tilde})); + try c.write("/look", "~/tilde-made/sub/x.txt:3\n"); + const looked = try panesAt(a, c, f.at("{s}/tilde-made/sub/x.txt", .{root})); + try expectEqual(@as(usize, 1), looked.len); + // At line 3: dot, offset 8, where the look put it (addr is a 9P client's own register). + try expect(std.mem.startsWith(u8, std.mem.trimStart(u8, try c.read(a, f.at("/pane/{s}/dot", .{looked[0]})), " "), "8 ")); + try c.remove(f.at("/pane/{s}", .{looked[0]})); + const made_dirs = try c.newPane(); + try c.write(f.at("/pane/{d}/body", .{made_dirs}), "deep\n"); + try c.write(f.at("/pane/{d}/ctl", .{made_dirs}), f.at("Save {s}/save-made/a/b/x.txt\n", .{root})); + try expectEqualStrings("deep\n", try d.get(a, "save-made/a/b/x.txt")); + try c.write(f.at("/pane/{d}/name", .{made_dirs}), f.at("{s}/save-named/c/y.txt\n", .{root})); + try c.write(f.at("/pane/{d}/ctl", .{made_dirs}), "Save\n"); + try expectEqualStrings("deep\n", try d.get(a, "save-named/c/y.txt")); + try c.remove(f.at("/pane/{d}", .{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. + const unsaved = try c.newPane(); + try c.write(f.at("/pane/{d}/body", .{unsaved}), "unsaved\n"); + try refusedSaying(c, f.at("/pane/{d}/ctl", .{unsaved}), "Save /nonexistent-pardes-dir/x.txt\n", "Save /nonexistent-pardes-dir/x.txt: permission denied"); // a directory it may not make + try expect(has(try c.read(a, "/log"), f.at("err {d} ctl: Save /nonexistent-pardes-dir/x.txt: ", .{unsaved}))); + try c.remove(f.at("/pane/{d}", .{unsaved})); + // Sixteen connections fill the slots; the next is told why. + { + var extra: [15]*process.Conn = undefined; + var n: usize = 0; + defer for (extra[0..n]) |e| e.deinit(gpa); + while (n < extra.len) : (n += 1) extra[n] = try process.Conn.dial(gpa, d.socket()); + var words: [256]u8 = undefined; + try expect(has(try process.Conn.dialRefusal(gpa, d.socket(), &words), "too many connections")); + } + const until = eh.nowMs() + 5_000; + while (!has(try c.read(a, "/log"), "err - 9p: too many connections")) { + if (eh.nowMs() > until) return error.NotLogged; + process.sleep(10); + } +} + +fn screenSize(f: *process.Files) !struct { i64, i64 } { + const json = try std.json.parseFromSliceLeaky(std.json.Value, f.arena.allocator(), try f.read("/screen"), .{}); + return .{ json.object.get("cols").?.integer, json.object.get("rows").?.integer }; +} + +/// 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. +fn cutWrites(gpa: std.mem.Allocator, exe: [:0]const u8) !void { + var d = try process.Detached.start(gpa, exe, "cut", .{}); + defer d.deinit(); + const f = &d.files; + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const c = try process.Conn.dial(gpa, d.socket()); + defer c.deinit(gpa); + // As test/fs.py's client cut them: an 8192-byte msize's writes. + const cut = 8192 - 23; + var burst: std.ArrayList(u8) = .empty; + for (0..1000) |i| try burst.print(a, "Msg burst-{d:0>4}\n", .{i}); + try expect(burst.items.len > 8192); + try c.writeCut("/exec", 1, burst.items, cut); + const log = try c.read(a, "/log"); + var i: usize = 0; + var lines = std.mem.tokenizeScalar(u8, log, '\n'); + while (lines.next()) |line| { + if (!std.mem.startsWith(u8, line, "msg ") or !has(line, "burst-")) continue; + var w = std.mem.splitScalar(u8, line, ' '); + _ = w.next(); + _ = w.next(); + try expectEqualStrings(f.at("burst-{d:0>4}", .{i}), w.rest()); + i += 1; + } + try expectEqual(@as(usize, 1000), i); + try expect(!has(log, "\nrun ") and !has(log, "exit 127")); + try c.write("/exec", "Msg no-newline-at-end"); + const said = try c.read(a, "/log"); + const upto = said[0..std.mem.indexOf(u8, said, "no-newline-at-end").?]; + try expect(has(upto[upto.len -| 40..], "msg ")); + const serial = try c.newPane(); + var block: std.ArrayList(u8) = .empty; + try block.appendSlice(a, "Edit ,a\n"); + for (0..2500) |k| try block.print(a, "line {d:0>5} of the block\n", .{k}); + try block.appendSlice(a, ".\n"); + try expect(block.items.len > 50000); + try c.writeCut(f.at("/pane/{d}/ctl", .{serial}), 1, block.items, cut); + var body = std.mem.splitScalar(u8, std.mem.trimEnd(u8, try c.read(a, f.at("/pane/{d}/body", .{serial})), "\n"), '\n'); + var k: usize = 0; + while (body.next()) |line| : (k += 1) try expectEqualStrings(f.at("line {d:0>5} of the block", .{k}), line); + try expectEqual(@as(usize, 2500), k); + // A detached session with no frontend is 160x50 until told. + const cols, const rows = try screenSize(f); + try expect(cols == 160 and rows == 50); + try c.write("/ctl", "size 132 40\n"); + const cols2, const rows2 = try screenSize(f); + try expect(cols2 == 132 and rows2 == 40); +} diff --git a/test/process_test.zig b/test/process_test.zig index 9924b9dd..9ae6bb58 100644 --- a/test/process_test.zig +++ b/test/process_test.zig @@ -7,6 +7,10 @@ const std = @import("std"); const files = .{ @import("process/other_files.zig"), + @import("process/tree.zig"), + @import("process/terminals.zig"), + @import("process/root_ctl.zig"), + @import("process/edit.zig"), }; pub fn main(init: std.process.Init) !void { @@ -24,6 +28,7 @@ pub fn main(init: std.process.Init) !void { std.debug.print("PASS {s}\n", .{case[0]}); } else |err| { failed += 1; + if (@errorReturnTrace()) |t| std.debug.dumpErrorReturnTrace(t); std.debug.print("FAIL {s}: {t}\n", .{ case[0], err }); } } -- cgit v1.3