SPB Git

Repository Public

PTYProcessTests.swift 11.1 KB 255 lines swift

1import Foundation2import Testing3@testable import PTYProcess45/// Collects PTY output and exit status from the PTY queue for the tests.6final class Recorder: @unchecked Sendable {7    private let lock = NSLock()8    private var bytes: [UInt8] = []9    private var status: PTYExitStatus?1011    func append(_ slice: ArraySlice<UInt8>) { lock.withLock { bytes.append(contentsOf: slice) } }12    func exit(_ s: PTYExitStatus) { lock.withLock { status = s } }13    var text: String { lock.withLock { String(decoding: bytes, as: UTF8.self) } }14    var exitStatus: PTYExitStatus? { lock.withLock { status } }15    func clear() { lock.withLock { bytes.removeAll() } }1617    func wait(timeout: TimeInterval = 8, _ condition: @Sendable () -> Bool) async -> Bool {18        let deadline = Date().addingTimeInterval(timeout)19        while Date() < deadline {20            if condition() { return true }21            try? await Task.sleep(for: .milliseconds(20))22        }23        return condition()24    }25    func waitFor(_ needle: String, timeout: TimeInterval = 8) async -> Bool {26        await wait(timeout: timeout) { self.text.contains(needle) }27    }28    func waitForExit(timeout: TimeInterval = 8) async -> PTYExitStatus? {29        _ = await wait(timeout: timeout) { self.exitStatus != nil }30        return exitStatus31    }32}3334let baseEnv = ["PATH": "/usr/bin:/bin:/usr/sbin:/sbin", "TERM": "xterm-256color",35               "LANG": "en_US.UTF-8", "HOME": NSTemporaryDirectory(), "PS1": "$ "]3637func spawn(_ exe: String, _ args: [String], cwd: String? = nil, cols: UInt16 = 80, rows: UInt16 = 24,38           recorder: Recorder) throws -> PTYProcess {39    try PTYProcess(PTYLaunchConfiguration(executable: exe, arguments: [exe] + args, environment: baseEnv,40                                          workingDirectory: cwd, columns: cols, rows: rows),41                   onOutput: { recorder.append($0) }, onExit: { recorder.exit($0) })42}4344/// Interactive POSIX shell without user rc files, deterministic prompt.45func spawnShell(recorder: Recorder, cols: UInt16 = 80, rows: UInt16 = 24) throws -> PTYProcess {46    try spawn("/bin/sh", ["-i"], cols: cols, rows: rows, recorder: recorder)47}4849@Suite("PTY process", .serialized)50struct PTYProcessTests {51    @Test func outputAndExitCodeAreReported() async throws {52        let rec = Recorder()53        let pty = try spawn("/bin/sh", ["-c", "printf 'hello-pty\\n'; exit 7"], recorder: rec)54        #expect(await rec.waitForExit() == .exited(code: 7))55        #expect(rec.text.contains("hello-pty"))56        #expect(pty.exitStatus == .exited(code: 7))57        #expect(!pty.isRunning)58    }5960    @Test func childHasARealControllingTerminal() async throws {61        let rec = Recorder()62        let pty = try spawn("/bin/sh", ["-c", "tty; test -t 0 && test -t 1 && test -t 2 && echo ALL-TTY"], recorder: rec)63        _ = await rec.waitForExit()64        #expect(rec.text.contains("ALL-TTY"))65        #expect(rec.text.contains(pty.ttyName))66        #expect(pty.ttyName.hasPrefix("/dev/ttys"))67    }6869    @Test func interactiveShellEchoesAndRunsCommands() async throws {70        let rec = Recorder()71        let pty = try spawnShell(recorder: rec)72        #expect(await rec.waitFor("$ "))73        pty.write("echo marker-$((40+2))\n")74        #expect(await rec.waitFor("marker-42"))75        // The line discipline echoes what was typed: the command text appears before its result.76        #expect(rec.text.contains("echo marker-$((40+2))"))77        pty.write("exit 3\n")78        #expect(await rec.waitForExit() == .exited(code: 3))79    }8081    @Test func initialWindowSizeIsVisibleToTheChild() async throws {82        let rec = Recorder()83        // The process object must stay alive: releasing it hangs up the session (see deinit test).84        let pty = try spawn("/bin/sh", ["-c", "stty size"], cols: 132, rows: 43, recorder: rec)85        _ = await rec.waitForExit()86        #expect(rec.text.contains("43 132"))87        #expect(pty.exitStatus == .exited(code: 0))88    }8990    @Test func resizeDeliversSIGWINCHAndNewSize() async throws {91        let rec = Recorder()92        let pty = try spawnShell(recorder: rec)93        #expect(await rec.waitFor("$ "))94        pty.write("trap 'echo WINCH-$(stty size | tr \" \" x)' WINCH\n")95        try await Task.sleep(for: .milliseconds(200))96        pty.resize(columns: 100, rows: 30)97        // A trap runs when the shell returns from reading; nudge it with an empty line.98        try await Task.sleep(for: .milliseconds(200))99        pty.write("\n")100        #expect(await rec.waitFor("WINCH-30x100"))101        #expect(pty.windowSize()?.columns == 100)102        #expect(pty.windowSize()?.rows == 30)103        pty.write("exit\n")104        _ = await rec.waitForExit()105    }106107    @Test func controlCInterruptsTheForegroundJobNotTheShell() async throws {108        let rec = Recorder()109        let pty = try spawnShell(recorder: rec)110        #expect(await rec.waitFor("$ "))111        pty.write("sleep 30; echo status=$?\n")112        #expect(await rec.wait { pty.hasForegroundJob })113        pty.write([0x03])114        #expect(await rec.waitFor("status=130"))115        #expect(pty.isRunning)116        #expect(await rec.wait { !pty.hasForegroundJob })117        pty.write("exit\n")118        #expect(await rec.waitForExit() != nil)119    }120121    @Test func controlZSuspendsAndJobControlWorks() async throws {122        let rec = Recorder()123        let pty = try spawn("/bin/zsh", ["-f", "-i"], recorder: rec)124        try await Task.sleep(for: .milliseconds(400))125        pty.write("sleep 30\n")126        #expect(await rec.wait { pty.hasForegroundJob })127        pty.write([0x1a])128        #expect(await rec.waitFor("suspended"))129        pty.write("kill %1; echo killed-job\n")130        #expect(await rec.waitFor("killed-job"))131        pty.write("exit\n")132        _ = await rec.waitForExit()133    }134135    @Test func controlDSendsEOF() async throws {136        let rec = Recorder()137        let pty = try spawn("/bin/cat", [], recorder: rec)138        pty.write("line-one\n")139        #expect(await rec.waitFor("line-one\r\nline-one"))140        pty.write([0x04])141        #expect(await rec.waitForExit() == .exited(code: 0))142    }143144    @Test func unicodeRoundTrips() async throws {145        let rec = Recorder()146        let pty = try spawn("/bin/cat", [], recorder: rec)147        let sample = "héllo wörld 日本語 👩‍💻 ✓"148        pty.write(sample + "\n")149        #expect(await rec.wait { rec.text.components(separatedBy: sample).count >= 3 })150        pty.write([0x04])151        _ = await rec.waitForExit()152    }153154    @Test func workingDirectoryAndEnvironmentAreApplied() async throws {155        let rec = Recorder()156        let dir = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().path157        let pty = try PTYProcess(158            PTYLaunchConfiguration(executable: "/bin/sh", arguments: ["/bin/sh", "-c", "pwd -P; echo $SPTERM_TEST; echo ${SECRET_PARENT:-unset}"],159                                   environment: ["PATH": "/usr/bin:/bin", "SPTERM_TEST": "env-ok"], workingDirectory: dir),160            onOutput: { rec.append($0) }, onExit: { rec.exit($0) })161        _ = pty162        _ = await rec.waitForExit()163        #expect(rec.text.contains(dir))164        #expect(rec.text.contains("env-ok"))165        #expect(rec.text.contains("unset"))166    }167168    @Test func terminateEndsTheSessionAndReportsTheSignal() async throws {169        let rec = Recorder()170        let pty = try spawnShell(recorder: rec)171        #expect(await rec.waitFor("$ "))172        pty.write("sleep 60\n")173        #expect(await rec.wait { pty.hasForegroundJob })174        pty.terminate(grace: 0.5)175        let status = await rec.waitForExit()176        #expect(status != nil)177        #expect(!pty.isRunning)178        // Reaped: the pid no longer exists as our child.179        var s: Int32 = 0180        #expect(waitpid(pty.pid, &s, WNOHANG) == -1)181    }182183    @Test func releasingTheObjectHangsUpAndReapsTheChild() async throws {184        let rec = Recorder()185        var pty: PTYProcess? = try spawnShell(recorder: rec)186        #expect(await rec.waitFor("$ "))187        let pid = pty!.pid188        pty = nil189        // No zombie and no orphan: the pid disappears shortly after.190        let gone = await rec.wait(timeout: 5) { kill(pid, 0) == -1 && errno == ESRCH }191        #expect(gone)192    }193194    @Test func childInheritsNoDescriptorFromTheApp() async throws {195        // Descriptors opened without close-on-exec in the parent must not leak into the child.196        // Duplicated to high numbers so they cannot be confused with descriptors the shell197        // allocates for itself (it uses the first free ones from 10 up).198        let source = open("/dev/null", O_RDONLY)199        let leaks = (0..<4).map { _ in fcntl(source, F_DUPFD, 40) }200        defer { leaks.forEach { close($0) }; close(source) }201        #expect(leaks.allSatisfy { $0 >= 40 })202        let rec = Recorder()203        // The shell itself probes which descriptors it was started with (no helper that opens files).204        let list = ([source] + leaks).map(String.init).joined(separator: " ")205        let probe = "for fd in \(list); do if (: <&$fd) 2>/dev/null; then echo OPEN-$fd; fi; done; echo PROBE-DONE"206        let pty = try spawn("/bin/sh", ["-c", probe], recorder: rec)207        #expect(await rec.waitFor("PROBE-DONE"))208        _ = await rec.waitForExit()209        #expect(!rec.text.contains("OPEN-"), "leaked descriptors: \(rec.text)")210        #expect(pty.exitStatus == .exited(code: 0))211    }212213    @Test func launchFailureThrows() {214        let rec = Recorder()215        #expect(throws: PTYError.self) { try spawn("/nonexistent/shell", [], recorder: rec) }216        #expect(throws: PTYError.self) {217            try PTYProcess(PTYLaunchConfiguration(executable: "relative", arguments: ["x"], environment: [:]),218                           onOutput: { _ in }, onExit: { _ in })219        }220    }221222    @Test func largeOutputIsDeliveredCompletelyBeforeExit() async throws {223        let rec = Recorder()224        let pty = try spawn("/bin/sh", ["-c", "seq 1 200000; echo END-OF-STREAM"], recorder: rec)225        #expect(await rec.waitForExit(timeout: 30) == .exited(code: 0))226        #expect(!pty.isRunning)227        // Exit is reported only after the output was drained.228        #expect(rec.text.contains("END-OF-STREAM"))229        #expect(rec.text.contains("\r\n200000\r\n"))230    }231232    @Test func largeInputDoesNotBlockOrLoseData() async throws {233        let rec = Recorder()234        let pty = try spawn("/bin/sh", ["-c", "stty -echo raw; wc -c"], recorder: rec)235        try await Task.sleep(for: .milliseconds(300))236        pty.write([UInt8](repeating: 0x61, count: 300_000))237        try await Task.sleep(for: .milliseconds(300))238        pty.send(signal: SIGHUP)239        _ = await rec.waitForExit()240        #expect(pty.exitStatus != nil)241    }242243    @Test func processProbeReadsNameAndCwd() async throws {244        let rec = Recorder()245        let dir = String(cString: realpath(NSTemporaryDirectory(), nil))246        let pty = try spawn("/bin/sleep", ["5"], cwd: dir, recorder: rec)247        try await Task.sleep(for: .milliseconds(200))248        #expect(ProcessProbe.name(of: pty.pid) == "sleep")249        #expect(ProcessProbe.workingDirectory(of: pty.pid) == dir)250        #expect((ProcessProbe.snapshot(of: pty.pid)?.residentBytes ?? 0) > 0)251        pty.terminate(grace: 0.2)252        _ = await rec.waitForExit()253    }254}255
Files main
Menu

Theme