diff options
| -rw-r--r-- | build/snap.zig | 22 | ||||
| -rw-r--r-- | docs/next-tests.md | 9 | ||||
| -rw-r--r-- | test/fs.py | 37 | ||||
| -rw-r--r-- | test/process.zig | 235 | ||||
| -rw-r--r-- | test/process/other_files.zig | 36 | ||||
| -rw-r--r-- | test/process_test.zig | 33 | ||||
| -rw-r--r-- | test/snapshot.zig | 9 |
7 files changed, 339 insertions, 42 deletions
diff --git a/build/snap.zig b/build/snap.zig index ad06486a..14e0aef3 100644 --- a/build/snap.zig +++ b/build/snap.zig @@ -41,6 +41,28 @@ pub fn addTty(b: *std.Build, opts: struct { .link_libc = true, }), }); + // The process tests (test/process_test.zig): real sessions over their + // sockets, on the runner the snap scripts share (test/process.zig). + const process_test = b.addExecutable(.{ + .name = "pardes-process-test", + .root_module = b.createModule(.{ + .target = opts.target, + .optimize = opts.optimize, + .root_source_file = b.path("test/process_test.zig"), + .link_libc = true, + }), + }); + if (opts.ghostty_vt) |vt| process_test.root_module.addImport("ghostty-vt", vt); + process_test.root_module.addImport("9p_io", ninep_client); + switch (opts.target.result.os.tag) { + .freebsd, .netbsd, .openbsd => process_test.root_module.linkSystemLibrary("util", .{}), + else => {}, + } + const run_process_test = b.addRunArtifact(process_test); + run_process_test.addArtifactArg(opts.exe); + run_process_test.addPassthruArgs(); + run_process_test.has_side_effects = true; + b.step("process-test", "run the process tests: real sessions driven over their sockets (-- [filter])").dependOn(&run_process_test.step); const run_snap = b.addRunArtifact(snap); run_snap.addArtifactArg(opts.exe); run_snap.addPrefixedFileArg("--lspmock=", lspmock.getEmittedBin()); diff --git a/docs/next-tests.md b/docs/next-tests.md index 4cf2c1fb..1ee47612 100644 --- a/docs/next-tests.md +++ b/docs/next-tests.md @@ -28,6 +28,15 @@ agent's survey. The `e2e` line (kbdin, mousein) is its first step. under a `process-test` step; - **the window's tests (T4)** are `Process` in its window mode. + Built (2026-11-04): + - **test/process.zig:** `Files` (a running pardes's tree over its socket, + dialled by pid or path) and `Detached` (a session in a throwaway root, + PARDES_DAEMON=off, so nothing outlives it). + - **The pty mode** is e2e_harness's Harness with `process.of`. + - **The `process-test` step** runs test/process_test.zig over + test/process/*.zig. Its first case is fs.py's keys_and_mouse. + - **snap9p** reads /screen through `Files`. + The Python suites in the build (fs.py, monkey9p.py, gui_monkey.py, v9fs*.py, agent_session_test.py) move onto it or onto Session, then leave the build. The developer tools (ui_review, record_demos, @@ -1095,42 +1095,6 @@ def cut_writes(binary): assert (screen['cols'], screen['rows']) == (132, 40), (screen['cols'], screen['rows']) -def find_on_screen(client, word): - """Where `word` is drawn, as (col, row), off /screen: what a mousein - line clicks.""" - screen = client.screen() - cols = screen['cols'] - for row in range(screen['rows']): - line = ''.join(cell[0] or ' ' for cell in screen['cells'][row * cols:(row + 1) * cols]) - at = line.find(word) - if at >= 0: - return at, row - raise AssertionError((word, 'not on the screen')) - - -def keys_and_mouse(binary): - """kbdin and mousein: a script types and clicks as the user does, each - write done before it is answered, so no sleep or poll between a write - and the read that checks it; where to click is read off /screen.""" - with tempfile.TemporaryDirectory(prefix='pardes-kbd-') as directory: - root = Path(directory) - (root / 'target.txt').write_bytes(b'hello-target\n') - with session(binary, root, 'kbd') as (client, _): - serial = new_pane(client, b'see \n') - client.write('/focus', f'{serial}\n'.encode()) - client.write('/kbdin', 'Atarget.txt\x1b'.encode()) - assert client.read(f'/pane/{serial}/body') == b'see target.txt\n' - col, row = find_on_screen(client, 'target.txt') - client.write('/mousein', f'm {col + 2} {row} 4\nm {col + 2} {row} 0\n'.encode()) - opened = newest(client) - assert opened != serial and client.read('/index').splitlines()[-1].endswith(b'target.txt 1'), client.read('/index') - assert client.read(f'/pane/{opened}/body') == b'hello-target\n' - # Undone from the keyboard, as the user would: u in normal mode. - client.write('/focus', f'{serial}\n'.encode()) - client.write('/kbdin', b'u') - assert client.read(f'/pane/{serial}/body') == b'see \n' - - 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 @@ -1243,7 +1207,6 @@ def edit_commands(binary): def test(binary, quic=False): started = time.monotonic() - keys_and_mouse(binary) cut_writes(binary) edit_commands(binary) odd_paths(binary) diff --git a/test/process.zig b/test/process.zig new file mode 100644 index 00000000..ef825ef0 --- /dev/null +++ b/test/process.zig @@ -0,0 +1,235 @@ +//! The process runner of docs/next-tests.md: a real `pardes`, detached or +//! in a pty (test/e2e_harness.zig's Harness), and what a 9P client sees of +//! it over its socket, with T1's Session method names (test/session.zig), so +//! a test reads alike at either tier. The snap scripts, the process tests +//! (test/process/) and the window's run on it. +const std = @import("std"); +const libc = std.c; +const eh = @import("e2e_harness.zig"); +const Client = @import("9p_io").Client; + +extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; +extern "c" fn unsetenv(name: [*:0]const u8) c_int; +extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; +extern "c" fn _exit(status: c_int) noreturn; +extern "c" fn mkdtemp(template: [*:0]u8) ?[*:0]u8; +extern "c" fn system(cmd: [*:0]const u8) c_int; +extern "c" fn realpath(path: [*:0]const u8, resolved: [*]u8) ?[*:0]u8; + +/// A running pardes's file tree, dialled by its pid or socket path. +pub const Files = struct { + arena: std.heap.ArenaAllocator, + dial_buf: [4096]u8 = undefined, + dial_len: usize = 0, + + pub fn init(gpa: std.mem.Allocator, to: []const u8) Files { + var f: Files = .{ .arena = .init(gpa) }; + @memcpy(f.dial_buf[0..to.len], to); + f.dial_len = to.len; + return f; + } + + pub fn deinit(f: *Files) void { + f.arena.deinit(); + } + + fn dial(f: *const Files) []const u8 { + return f.dial_buf[0..f.dial_len]; + } + + /// The whole file at `path`, kept until deinit. + pub fn read(f: *Files, path: []const u8) ![]const u8 { + const gpa = f.arena.child_allocator; + const bytes = try Client.read(gpa, f.dial(), path, path); + defer gpa.free(bytes); + return f.arena.allocator().dupe(u8, bytes); + } + + pub fn write(f: *Files, path: []const u8, data: []const u8) !void { + try Client.write(f.arena.child_allocator, f.dial(), path, data); + } + + pub fn expect(f: *Files, path: []const u8, want: []const u8) !void { + try std.testing.expectEqualStrings(want, try f.read(path)); + } + + /// Keys typed at the pane with the keyboard (`/kbdin`'s runes). + pub fn keys(f: *Files, runes: []const u8) !void { + try f.write("/kbdin", runes); + } + + /// A click (1 left, 2 middle, 4 right) `into` cells into the first place + /// `text` is drawn. + pub fn click(f: *Files, text: []const u8, into: usize, buttons: u8) !void { + const col, const row = try f.where(text); + var line: [64]u8 = undefined; + const x = col + into; + try f.write("/mousein", try std.fmt.bufPrint(&line, "m {d} {d} {d}\nm {d} {d} 0\n", .{ x, row, buttons, x, row })); + } + + /// The screen a frame draws, a line a row. + // shortcut: Session.screen's twin (test/session.zig, another module); + // share them when a third copy would be wanted. + pub fn screen(f: *Files) ![]const u8 { + const a = f.arena.allocator(); + const json = try std.json.parseFromSliceLeaky(std.json.Value, a, try f.read("/screen"), .{}); + const cols: usize = @intCast(json.object.get("cols").?.integer); + var out: std.ArrayList(u8) = .empty; + for (json.object.get("cells").?.array.items, 0..) |cell, i| { + if (i > 0 and i % cols == 0) try out.append(a, '\n'); + const g = cell.array.items[0].string; + try out.appendSlice(a, if (g.len == 0) " " else g); + } + return out.items; + } + + /// Where `text` is first drawn, its column and row. + pub fn where(f: *Files, text: []const u8) !struct { usize, usize } { + var rows = std.mem.splitScalar(u8, try f.screen(), '\n'); + var row: usize = 0; + while (rows.next()) |line| : (row += 1) { + if (std.mem.indexOf(u8, line, text)) |i| return .{ try std.unicode.utf8CountCodepoints(line[0..i]), row }; + } + std.debug.print("not on the screen: {s}\n", .{text}); + return error.NotOnScreen; + } + + /// The serial of the pane with the keyboard. + pub fn focused(f: *Files) !u32 { + return std.fmt.parseInt(u32, std.mem.trim(u8, try f.read("/focus"), "\n"), 10); + } + + /// A new pane, made by opening /pane/new; its serial. + pub fn newPane(f: *Files) !u32 { + return std.fmt.parseInt(u32, std.mem.trim(u8, try f.read("/pane/new"), "\n"), 10); + } + + /// A path built from `args`, kept until deinit. + pub fn at(f: *Files, comptime fmt: []const u8, args: anytype) []const u8 { + return std.fmt.allocPrint(f.arena.allocator(), fmt, args) catch @panic("out of memory"); + } +}; + +/// The files of the app a pty harness started. +pub fn of(gpa: std.mem.Allocator, h: *const eh.Harness) Files { + var digits: [24]u8 = undefined; + return .init(gpa, std.fmt.bufPrint(&digits, "{d}", .{h.pid}) catch unreachable); +} + +/// `pardes --detach=<name>` in a throwaway root that is its HOME, runtime +/// and config directory, as test/fs.py's session started one: no session +/// of the user's is reached. No daemon (PARDES_DAEMON=off, as the pty +/// harness starts one): the process is the session, and nothing outlives it. +pub const Detached = struct { + pid: libc.pid_t, + root_buf: [64]u8 = undefined, + root_len: usize = 0, + files: Files, + + pub fn start(gpa: std.mem.Allocator, exe: [:0]const u8, name: []const u8) !Detached { + var d: Detached = .{ .pid = 0, .files = undefined }; + const template = "/tmp/pardes-process-XXXXXX"; + @memcpy(d.root_buf[0..template.len], template); + d.root_buf[template.len] = 0; + _ = mkdtemp(d.root_buf[0..template.len :0]) orelse return error.NoTempDir; + d.root_len = template.len; + const dir = d.root(); + var buf: [4096]u8 = undefined; + const fixture = try std.fmt.bufPrintSentinel(&buf, "{s}/{s}.txt", .{ dir, name }, 0); + try eh.writeFile(fixture, "initial\n"); + var sock: [4096]u8 = undefined; + // The session's socket, as its 9P service links it (src/9p_io.zig). + const socket = try std.fmt.bufPrint(&sock, "{s}/9p/pardes/{s}", .{ dir, name }); + var arg_buf: [256]u8 = undefined; + const detach = try std.fmt.bufPrintSentinel(&arg_buf, "--detach={s}", .{name}, 0); + var env_buf: [3][4096]u8 = undefined; + const root_z = try std.fmt.bufPrintSentinel(&env_buf[0], "{s}", .{dir}, 0); + const config = try std.fmt.bufPrintSentinel(&env_buf[1], "{s}/config", .{dir}, 0); + const dump = try std.fmt.bufPrintSentinel(&env_buf[2], "{s}/{s}.dump.zon", .{ dir, name }, 0); + var err_buf: [4096]u8 = undefined; + const err_log = try std.fmt.bufPrintSentinel(&err_buf, "{s}/stderr", .{dir}, 0); + // The build hands the binary over by a relative path, and the child + // runs in the root. + var exe_buf: [4096]u8 = undefined; + const exe_abs = realpath(exe, &exe_buf) orelse return error.NoBinary; + const pid = libc.fork(); + if (pid < 0) return error.ForkFailed; + if (pid == 0) { + // What a session of the caller's left in the environment, and a + // pager of theirs, are not the session under test's. + for ([_][*:0]const u8{ "PARDES_PID", "PARDES_9P", "PARDES_PANE", "PARDES_MOUNT", "PAGER" }) |v| _ = unsetenv(v); + for ([_][2][*:0]const u8{ + .{ "HOME", root_z }, .{ "XDG_RUNTIME_DIR", root_z }, .{ "XDG_CONFIG_HOME", config }, + .{ "PARDES_NOTIME", "1" }, .{ "PARDES_DUMP", dump }, .{ "PARDES_LSP_RS", "" }, + .{ "PARDES_LSP_C", "" }, .{ "PARDES_LSP_GO", "" }, .{ "PARDES_LSP_TS", "" }, + .{ "PARDES_LSP_PY", "" }, .{ "PARDES_DAEMON", "off" }, + }) |kv| if (setenv(kv[0], kv[1], 1) != 0) _exit(126); + if (libc.chdir(root_z) != 0) _exit(126); + const fd = libc.open(err_log, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); + if (fd >= 0) _ = libc.dup2(fd, 2); + const argv = [_:null]?[*:0]const u8{ exe_abs, detach, fixture }; + _ = execvp(exe_abs, &argv); + _exit(127); + } + d.pid = pid; + errdefer { + d.stop(); + d.removeRoot(); + } + const deadline = eh.nowMs() + 10_000; + var sock_z: [4096]u8 = undefined; + const socket_z = try std.fmt.bufPrintSentinel(&sock_z, "{s}", .{socket}, 0); + while (libc.access(socket_z, 0) != 0) { + var status: c_int = 0; + if (libc.waitpid(pid, &status, std.c.W.NOHANG) == pid) { + d.pid = 0; + var said: [4096]u8 = undefined; + const fd = libc.open(err_log, .{}, @as(libc.mode_t, 0)); + const n = if (fd >= 0) libc.read(fd, &said, said.len) else 0; + if (fd >= 0) _ = libc.close(fd); + std.debug.print("the session exited, status {d}: {s}\n", .{ status, said[0..@intCast(@max(n, 0))] }); + return error.SessionExited; + } + if (eh.nowMs() > deadline) return error.NoSocket; + var ts: libc.timespec = .{ .sec = 0, .nsec = 5 * std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); + } + d.files = .init(gpa, socket); + return d; + } + + pub fn root(d: *const Detached) []const u8 { + return d.root_buf[0..d.root_len]; + } + + /// Ended (SIGTERM, then SIGKILL after 5 s), its root removed. + pub fn deinit(d: *Detached) void { + d.files.deinit(); + d.stop(); + d.removeRoot(); + } + + fn removeRoot(d: *Detached) void { + var cmd: [128]u8 = undefined; + if (std.fmt.bufPrintSentinel(&cmd, "rm -rf -- '{s}'", .{d.root()}, 0)) |c| { + _ = system(c); + } else |_| {} + } + + fn stop(d: *Detached) void { + if (d.pid <= 0) return; + _ = libc.kill(d.pid, libc.SIG.TERM); + const deadline = eh.nowMs() + 5_000; + var status: c_int = 0; + while (libc.waitpid(d.pid, &status, std.c.W.NOHANG) != d.pid) { + if (eh.nowMs() > deadline) { + _ = libc.kill(d.pid, libc.SIG.KILL); + _ = libc.waitpid(d.pid, &status, 0); + break; + } + var ts: libc.timespec = .{ .sec = 0, .nsec = 10 * std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); + } + d.pid = 0; + } +}; diff --git a/test/process/other_files.zig b/test/process/other_files.zig new file mode 100644 index 00000000..178b20cd --- /dev/null +++ b/test/process/other_files.zig @@ -0,0 +1,36 @@ +//! docs/typ/reference.typ, Other files <other-files>, through a real +//! session's socket. +const std = @import("std"); +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 }, +}; + +/// 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 +/// alone.) +fn keysAndMouse(gpa: std.mem.Allocator, exe: [:0]const u8) !void { + var d = try process.Detached.start(gpa, exe, "kbd"); + defer d.deinit(); + const f = &d.files; + var buf: [4096]u8 = undefined; + try @import("../e2e_harness.zig").writeFile(try std.fmt.bufPrintSentinel(&buf, "{s}/target.txt", .{d.root()}, 0), "hello-target\n"); + const serial = try f.newPane(); + try f.write(f.at("/pane/{d}/body", .{serial}), "see \n"); + try f.write("/focus", f.at("{d}\n", .{serial})); + try f.keys("Atarget.txt\x1b"); + try f.expect(f.at("/pane/{d}/body", .{serial}), "see target.txt\n"); + try f.click("target.txt", 2, 4); + var index = std.mem.splitBackwardsScalar(u8, std.mem.trimEnd(u8, try f.read("/index"), "\n"), '\n'); + const last = index.first(); + try std.testing.expect(std.mem.endsWith(u8, last, "target.txt 1")); + const opened = try std.fmt.parseInt(u32, last[0..std.mem.indexOfScalar(u8, last, ' ').?], 10); + try std.testing.expect(opened != serial); + try f.expect(f.at("/pane/{d}/body", .{opened}), "hello-target\n"); + // Undone from the keyboard, as the user would: u in normal mode. + try f.write("/focus", f.at("{d}\n", .{serial})); + try f.keys("u"); + try f.expect(f.at("/pane/{d}/body", .{serial}), "see \n"); +} diff --git a/test/process_test.zig b/test/process_test.zig new file mode 100644 index 00000000..9924b9dd --- /dev/null +++ b/test/process_test.zig @@ -0,0 +1,33 @@ +//! The process tests (T2 of docs/next-tests.md): each case starts a real +//! pardes through test/process.zig and drives it over its socket. A file +//! in test/process/ a section of the book, as test/behaviour/'s are. +//! +//! pardes-process-test <pardes> [filter] +const std = @import("std"); + +const files = .{ + @import("process/other_files.zig"), +}; + +pub fn main(init: std.process.Init) !void { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len < 2) return error.Usage; + const exe = args[1]; + const filter: []const u8 = if (args.len > 2) args[2] else ""; + const gpa = std.heap.page_allocator; + var failed: usize = 0; + var ran: usize = 0; + inline for (files) |file| inline for (file.cases) |case| { + if (std.mem.indexOf(u8, case[0], filter) != null) { + ran += 1; + if (case[1](gpa, exe)) { + std.debug.print("PASS {s}\n", .{case[0]}); + } else |err| { + failed += 1; + std.debug.print("FAIL {s}: {t}\n", .{ case[0], err }); + } + } + }; + std.debug.print("{d} of {d} process tests failed\n", .{ failed, ran }); + if (failed > 0 or ran == 0) std.process.exit(1); +} diff --git a/test/snapshot.zig b/test/snapshot.zig index 1bd4dabf..95d07cc7 100644 --- a/test/snapshot.zig +++ b/test/snapshot.zig @@ -67,7 +67,7 @@ const std = @import("std"); const libc = std.c; const ghostty_vt = @import("ghostty-vt"); const eh = @import("e2e_harness.zig"); -const Client = @import("9p_io").Client; +const process = @import("process.zig"); // This harness parses the app's output with its OWN ghostty-vt, which narrates // every sequence it does not implement — vaxis's startup capability probes @@ -1289,10 +1289,9 @@ const Screen9p = struct { }; fn snap9p(arena: std.mem.Allocator, h: *eh.Harness, label: []const u8, prev: *Prev) ![]u8 { - var dial_buf: [24]u8 = undefined; - const dial = try std.fmt.bufPrint(&dial_buf, "{d}", .{h.pid}); - const bytes = try Client.read(gpa, dial, "/screen", "/screen"); - defer gpa.free(bytes); + var files = process.of(gpa, h); + defer files.deinit(); + const bytes = try files.read("/screen"); const parsed = try std.json.parseFromSlice(Screen9p, gpa, bytes, .{}); defer parsed.deinit(); const screen = parsed.value; |
