// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Every test here runs a real child -- `/bin/sh`, and the ordinary tools a //! script calls -- because what is under test is the talking to one. const std = @import("std"); const builtin = @import("builtin"); const testing = std.testing; const Io = std.Io; const expect = @import("root.zig"); const Regex = expect.zregex.Regex; const Session = expect.Session; const Transport = expect.Transport; const gpa = testing.allocator; const io = testing.io; const both: []const Transport = &.{ .pty, .pipe }; /// A shell running `script`, and what it needs to stay alive for. const Fixture = struct { env: std.process.Environ.Map, session: Session, fn init(f: *Fixture, buffer: []u8, script: []const u8, options: struct { transport: Transport = .pty, window: expect.Winsize = .{}, echo: bool = false, cwd: ?[]const u8 = null, }) !void { f.env = try testing.environ.createMap(gpa); errdefer f.env.deinit(); f.session = try Session.spawn(io, gpa, buffer, .{ .argv = &.{ "/bin/sh", "-c", script }, .environ_map = &f.env, .transport = options.transport, .window = options.window, .echo = options.echo, .cwd = options.cwd, }); } fn deinit(f: *Fixture) void { f.session.deinit(); f.env.deinit(); } /// Waits for `pattern` and returns capture group `group`, copied into /// `out` so that it outlives the result. fn capture(f: *Fixture, pattern: []const u8, group: usize, out: []u8) ![]u8 { var re = try Regex.compile(gpa, pattern); defer re.deinit(); var result = try f.session.expect(void, &.{.{ .tag = {}, .regex = &re }}, expect.within(.fromSeconds(5))); defer result.deinit(gpa); const text = result.group(group).?; @memcpy(out[0..text.len], text); return out[0..text.len]; } fn see(f: *Fixture, pattern: []const u8) !void { var re = try Regex.compile(gpa, pattern); defer re.deinit(); var result = try f.session.expect(void, &.{.{ .tag = {}, .regex = &re }}, expect.within(.fromSeconds(5))); result.deinit(gpa); } fn expectError(f: *Fixture, pattern: []const u8, timeout: Io.Timeout, wanted: anyerror) !void { var re = try Regex.compile(gpa, pattern); defer re.deinit(); if (f.session.expect(void, &.{.{ .tag = {}, .regex = &re }}, timeout)) |r| { var result = r; result.deinit(gpa); return error.TestUnexpectedMatch; } else |err| try testing.expectEqual(wanted, err); } }; test "a prompt is found and its capture read" { for (both) |transport| { var buffer: [256]u8 = undefined; var f: Fixture = undefined; try f.init(&buffer, "printf 'user jeff login: '", .{ .transport = transport }); defer f.deinit(); var re = try Regex.compile(gpa, "user (\\w+) login: "); defer re.deinit(); const Tag = enum { login }; var result = try f.session.expect(Tag, &.{.{ .tag = .login, .regex = &re }}, expect.within(.fromSeconds(5))); defer result.deinit(gpa); try testing.expectEqual(Tag.login, result.tag); try testing.expectEqualStrings("jeff", result.group(1).?); try testing.expectEqualStrings("user jeff login: ", result.group(0).?); try testing.expectEqualStrings("", result.before()); } } test "the first pattern in the list wins, not the earliest match" { var buffer: [256]u8 = undefined; var f: Fixture = undefined; try f.init(&buffer, "echo 'alpha beta'; sleep 5", .{}); defer f.deinit(); var alpha = try Regex.compile(gpa, "alpha"); defer alpha.deinit(); var beta = try Regex.compile(gpa, "beta"); defer beta.deinit(); const Tag = enum { alpha, beta }; var result = try f.session.expect(Tag, &.{ .{ .tag = .beta, .regex = &beta }, .{ .tag = .alpha, .regex = &alpha }, }, expect.within(.fromSeconds(5))); defer result.deinit(gpa); try testing.expectEqual(Tag.beta, result.tag); try testing.expectEqualStrings("alpha ", result.before()); } test "what follows a match is kept for the next call" { for (both) |transport| { var buffer: [256]u8 = undefined; var f: Fixture = undefined; try f.init(&buffer, "printf 'one two three'; sleep 5", .{ .transport = transport }); defer f.deinit(); // All three arrive in one write, and so in one read. try f.see("three"); try f.expectError("one|two", expect.within(.fromMilliseconds(100)), error.Timeout); var g: Fixture = undefined; try g.init(&buffer, "printf 'one two three'; sleep 5", .{ .transport = transport }); defer g.deinit(); var out: [16]u8 = undefined; try testing.expectEqualStrings("one", try g.capture("(o\\w+)", 1, &out)); try testing.expectEqualStrings("two", try g.capture("(t\\w+)", 1, &out)); try testing.expectEqualStrings("three", try g.capture("(t\\w+)", 1, &out)); } } test "input sent is read back through cat" { for (both) |transport| { var buffer: [256]u8 = undefined; var f: Fixture = undefined; try f.init(&buffer, "exec cat", .{ .transport = transport }); defer f.deinit(); try f.session.sendLine("hello there"); var out: [32]u8 = undefined; try testing.expectEqualStrings("hello there", try f.capture("(hello \\w+)\\r?\\n", 1, &out)); try f.session.send("partial"); try f.session.sendLine(" line"); try testing.expectEqualStrings("partial line", try f.capture("(\\w+ \\w+)\\r?\\n", 1, &out)); } } test "a quiet child times out" { for (both) |transport| { var buffer: [256]u8 = undefined; var f: Fixture = undefined; try f.init(&buffer, "sleep 5", .{ .transport = transport }); defer f.deinit(); const began = Io.Clock.awake.now(io); try f.expectError("anything", expect.within(.fromMilliseconds(100)), error.Timeout); const took = began.durationTo(Io.Clock.awake.now(io)); try testing.expect(took.toMilliseconds() >= 100); try testing.expect(took.toMilliseconds() < 2000); } } test "output nobody is waiting for does not extend the deadline" { var buffer: [4096]u8 = undefined; var f: Fixture = undefined; try f.init(&buffer, "while :; do echo tick; sleep 0.05; done", .{}); defer f.deinit(); const began = Io.Clock.awake.now(io); // Anything that reaches the buffer limit first would mask the timeout, // but at twenty lines a second 4096 bytes is minutes away. try f.expectError("tock", expect.within(.fromMilliseconds(300)), error.Timeout); const took = began.durationTo(Io.Clock.awake.now(io)); try testing.expect(took.toMilliseconds() < 2000); } test "a child that ends without a match is the end of the stream" { for (both) |transport| { var buffer: [256]u8 = undefined; var f: Fixture = undefined; try f.init(&buffer, "echo hi; exit 3", .{ .transport = transport }); defer f.deinit(); try f.expectError("nope", .none, error.EndOfStream); try testing.expectEqualStrings("hi", std.mem.trimEnd(u8, f.session.pending(), "\r\n")); try testing.expectEqual(std.process.Child.Term{ .exited = 3 }, try f.session.wait()); try testing.expect(!f.session.isRunning()); } } test "what a child said before it exited can still be matched" { for (both) |transport| { var buffer: [256]u8 = undefined; var f: Fixture = undefined; try f.init(&buffer, "printf 'last words'", .{ .transport = transport }); defer f.deinit(); try testing.expectEqual(std.process.Child.Term{ .exited = 0 }, try f.session.wait()); // On a pipe `wait` has closed the stream, and what was not read by then // is gone; on a terminal it is still waiting in the master. if (transport == .pty) try f.see("last words"); } } test "a full buffer is reported, and discarding makes room" { for (both) |transport| { var buffer: [16]u8 = undefined; var f: Fixture = undefined; try f.init(&buffer, "printf '0123456789abcdefXYZ'; sleep 5", .{ .transport = transport }); defer f.deinit(); // The pipe transport reads standard output into half the free space // and standard error into the other half, so a first read can stop // short of sixteen bytes; keep going until the buffer is full. try f.expectError("XYZ", expect.within(.fromSeconds(5)), error.BufferFull); try testing.expectEqualStrings("0123456789abcdef", f.session.pending()); f.session.discard(10); try testing.expectEqualStrings("abcdef", f.session.pending()); var out: [16]u8 = undefined; try testing.expectEqualStrings("abcdefXYZ", try f.capture("(\\w+XYZ)", 1, &out)); } } test "a long stream passes through a small buffer" { for (both) |transport| { var buffer: [16]u8 = undefined; var f: Fixture = undefined; try f.init(&buffer, "i=1; while [ $i -le 300 ]; do echo $i; i=$((i+1)); done", .{ .transport = transport }); defer f.deinit(); var re = try Regex.compile(gpa, "(\\d+)\\r?\\n"); defer re.deinit(); var wanted: usize = 1; while (wanted <= 300) : (wanted += 1) { var result = try f.session.expect(void, &.{.{ .tag = {}, .regex = &re }}, expect.within(.fromSeconds(5))); defer result.deinit(gpa); try testing.expectEqual(wanted, try std.fmt.parseInt(usize, result.group(1).?, 10)); } try f.expectError("\\d", expect.within(.fromSeconds(5)), error.EndOfStream); } } test "standard error is searched on a pipe" { var buffer: [256]u8 = undefined; var f: Fixture = undefined; try f.init(&buffer, "echo 'on stderr' >&2; sleep 5", .{ .transport = .pipe }); defer f.deinit(); try f.see("on stderr"); } test "a terminal child has a controlling terminal" { var buffer: [256]u8 = undefined; var f: Fixture = undefined; // Writing to /dev/tty fails outright without one, which is the whole // reason for going to the trouble of a terminal. try f.init(&buffer, "tty; [ -t 0 ] && echo stdin-is-a-tty; echo via-dev-tty > /dev/tty", .{}); defer f.deinit(); var out: [64]u8 = undefined; try testing.expect(std.mem.startsWith(u8, try f.capture("(/dev/\\S+)", 1, &out), "/dev/")); try f.see("stdin-is-a-tty"); try f.see("via-dev-tty"); } test "the terminal has the size asked for, and can be resized" { var buffer: [256]u8 = undefined; var f: Fixture = undefined; try f.init(&buffer, "stty size; read x; stty size", .{ .window = .{ .rows = 40, .cols = 100 } }); defer f.deinit(); try f.see("40 100"); try f.session.setWindowSize(.{ .rows = 50, .cols = 132 }); try f.session.sendLine(""); try f.see("50 132"); } test "echo leaves what was sent in the output" { var buffer: [256]u8 = undefined; var f: Fixture = undefined; try f.init(&buffer, "read x; echo got-$x", .{ .echo = true }); defer f.deinit(); try f.session.sendLine("typed"); var out: [16]u8 = undefined; // The terminal echoes the line before `read` has even returned. try testing.expectEqualStrings("typed", try f.capture("^(\\w+)\\r\\n", 1, &out)); try f.see("got-typed"); } test "the end-of-file character ends cat" { for (both) |transport| { var buffer: [256]u8 = undefined; var f: Fixture = undefined; try f.init(&buffer, "exec cat", .{ .transport = transport }); defer f.deinit(); try f.session.sendEof(); try f.expectError("anything", expect.within(.fromSeconds(5)), error.EndOfStream); try testing.expectEqual(std.process.Child.Term{ .exited = 0 }, try f.session.wait()); } } test "a signal reaches the child" { var buffer: [256]u8 = undefined; var f: Fixture = undefined; try f.init(&buffer, "trap 'echo caught; exit 0' INT; echo ready; while :; do sleep 0.05; done", .{}); defer f.deinit(); try f.see("ready"); try f.session.sendSignal(.INT); try f.see("caught"); } test "kill does not wait on a child that ignores SIGTERM" { var buffer: [256]u8 = undefined; var f: Fixture = undefined; try f.init(&buffer, "trap '' TERM; echo ready; while :; do sleep 0.05; done", .{}); defer f.deinit(); try f.see("ready"); f.session.kill(); try testing.expect(!f.session.isRunning()); try testing.expectError(error.NotRunning, f.session.sendSignal(.INT)); } test "the working directory and environment are the child's" { for (both) |transport| { var buffer: [256]u8 = undefined; var f: Fixture = undefined; f.env = try testing.environ.createMap(gpa); try f.env.put("EXPECT_TEST_VALUE", "from-the-map"); f.session = Session.spawn(io, gpa, &buffer, .{ .argv = &.{ "/bin/sh", "-c", "pwd; echo $EXPECT_TEST_VALUE" }, .environ_map = &f.env, .transport = transport, .cwd = "/", }) catch |err| { f.env.deinit(); return err; }; defer f.deinit(); try f.see("^/\\r?\\n"); try f.see("from-the-map"); } } test "a program that does not exist fails to spawn" { for (both) |transport| { var env = try testing.environ.createMap(gpa); defer env.deinit(); var buffer: [16]u8 = undefined; try testing.expectError(error.FileNotFound, Session.spawn(io, gpa, &buffer, .{ .argv = &.{"zig-expect-no-such-program"}, .environ_map = &env, .transport = transport, })); } } test "PATH is searched in the given environment" { for (both) |transport| { var env = try testing.environ.createMap(gpa); defer env.deinit(); var buffer: [64]u8 = undefined; var session = try Session.spawn(io, gpa, &buffer, .{ .argv = &.{ "sh", "-c", "echo found" }, .environ_map = &env, .transport = transport, }); defer session.deinit(); var re = try Regex.compile(gpa, "found"); defer re.deinit(); var result = try session.expect(void, &.{.{ .tag = {}, .regex = &re }}, expect.within(.fromSeconds(5))); result.deinit(gpa); } }