import Foundation import HelderServices import Testing @Suite struct ProcessRunnerTests { let runner = ProcessRunner() @Test func capturesStdoutAndExitCode() async throws { let result = try await runner.run("echo", ["hello", "world"]) #expect(result == ProcessResult(exitCode: 0, stdout: "hello world\n", stderr: "")) #expect(result.succeeded) } @Test func nonZeroExitIsAResultNotAnError() async throws { let result = try await runner.run("sh", ["-c", "echo oops >&2; exit 3"]) #expect(result.exitCode == 3) #expect(result.stderr == "oops\n") #expect(!result.succeeded) } @Test func runsInTheGivenDirectory() async throws { let dir = URL(fileURLWithPath: "/usr/lib") let result = try await runner.run("pwd", [], in: dir) #expect(result.stdout == "/usr/lib\n") } @Test func passesTheEnvironment() async throws { let result = try await runner.run("sh", arguments: ["-c", "printf %s \"$HELDER_TEST\""], in: nil, environment: ["HELDER_TEST": "yes", "PATH": "/usr/bin:/bin"]) #expect(result.stdout == "yes") } @Test func stdinIsClosed() async throws { let result = try await runner.run("cat", []) #expect(result == ProcessResult(exitCode: 0, stdout: "", stderr: "")) } @Test func inputReachesStdinAndThenEnds() async throws { let result = try await runner.run("cat", arguments: [], in: nil, environment: nil, input: "héllo\nworld") #expect(result == ProcessResult(exitCode: 0, stdout: "héllo\nworld", stderr: "")) } @Test func largeInputIsWrittenWhole() async throws { let input = String(repeating: "x", count: 1_000_000) let result = try await runner.run("wc", arguments: ["-c"], in: nil, environment: nil, input: input) #expect(result.stdout.trimmingCharacters(in: .whitespacesAndNewlines) == "1000000") } @Test func aChildThatIgnoresItsInputStillFinishes() async throws { let input = String(repeating: "x", count: 1_000_000) let result = try await runner.run("true", arguments: [], in: nil, environment: nil, input: input) #expect(result.exitCode == 0) } @Test func aRunnerWithoutStdinSupportRefusesInput() async throws { let fake = CannedRunner(result: ProcessResult(exitCode: 0, stdout: "", stderr: "")) await #expect(throws: ProcessRunnerError.self) { try await fake.run("x", arguments: [], in: nil, environment: nil, input: "prompt") } } @Test func largeOutputOnBothPipesDoesNotDeadlock() async throws { let script = "i=0; while [ $i -lt 20000 ]; do echo line$i; echo err$i >&2; i=$((i+1)); done" let result = try await runner.run("sh", ["-c", script]) #expect(result.stdout.split(separator: "\n").count == 20000) #expect(result.stderr.split(separator: "\n").count == 20000) } @Test func unknownExecutableThrows() async { await #expect(throws: ProcessRunnerError.executableNotFound("helder-no-such-tool")) { try await runner.run("helder-no-such-tool", []) } } @Test func cancellationTerminatesTheChild() async throws { let started = Date() let task = Task { try await runner.run("sleep", ["10"]) } try await Task.sleep(for: .milliseconds(200)) task.cancel() await #expect(throws: CancellationError.self) { try await task.value } #expect(Date().timeIntervalSince(started) < 5) } @Test func locatorFindsToolsOnThePath() { #expect(ExecutableLocator.standard.locate("sh")?.path.hasSuffix("/sh") == true) #expect(ExecutableLocator(directories: []).locate("sh") == nil) #expect(ExecutableLocator(directories: []).locate("/bin/sh")?.path == "/bin/sh") } } @Suite struct ProcessRunnerStreamTests { let runner = ProcessRunner() @Test func streamsEachLineWithItsStreamAndKeepsTheFullOutput() async throws { let log = LineLog() let result = try await runner.stream("sh", arguments: ["-c", "echo one; echo two >&2; printf 'three'"], in: nil, environment: nil, onLine: log.append) #expect(log.outputs == ["one", "three"]) #expect(log.errors == ["two"]) #expect(result == ProcessResult(exitCode: 0, stdout: "one\nthree", stderr: "two\n")) } @Test func aCarriageReturnEndsALineAndEmptyLinesAreDropped() async throws { let log = LineLog() let script = "printf 'Counting 10%%\\rCounting 100%%\\r\\n\\ndone\\n' >&2" let result = try await runner.stream("sh", arguments: ["-c", script], in: nil, environment: nil, onLine: log.append) #expect(log.errors == ["Counting 10%", "Counting 100%", "done"]) #expect(result.stderr == "Counting 10%\rCounting 100%\r\n\ndone\n") } @Test func linesArriveBeforeTheProcessEnds() async throws { let arrivals = LineLog() let started = Date() _ = try await runner.stream("sh", arguments: ["-c", "echo first; sleep 1; echo second"], in: nil, environment: nil) { line, _ in arrivals.append("\(line) \(Date().timeIntervalSince(started))", false) } let times = arrivals.texts.compactMap { $0.split(separator: " ").last.flatMap { Double($0) } } try #require(times.count == 2) #expect(times[1] - times[0] > 0.5) } @Test func largeStreamedOutputOnBothPipesDoesNotDeadlock() async throws { let log = LineLog() let script = "i=0; while [ $i -lt 5000 ]; do echo line$i; echo err$i >&2; i=$((i+1)); done" let result = try await runner.stream("sh", arguments: ["-c", script], in: nil, environment: nil, onLine: log.append) #expect(log.outputs.count == 5000) #expect(log.errors.count == 5000) #expect(log.outputs.last == "line4999") #expect(result.stdout.split(separator: "\n").count == 5000) } @Test func stdinIsClosedWhileStreaming() async throws { let result = try await runner.stream("cat", arguments: [], in: nil, environment: nil) { _, _ in } #expect(result == ProcessResult(exitCode: 0, stdout: "", stderr: "")) } @Test func cancellationTerminatesAStreamingChild() async throws { let started = Date() let task = Task { try await runner.stream("sleep", arguments: ["10"], in: nil, environment: nil) { _, _ in } } try await Task.sleep(for: .milliseconds(200)) task.cancel() await #expect(throws: CancellationError.self) { try await task.value } #expect(Date().timeIntervalSince(started) < 5) } @Test(.timeLimit(.minutes(1))) func cancellationDoesNotWaitForAGrandchildHoldingAPipe() async throws { let marker = "helder-grandchild-\(UUID().uuidString.prefix(8))" let script = "sleep 30 >&2 & echo $! > /tmp/\(marker); sleep 30" let started = Date() let task = Task { try await runner.stream("sh", arguments: ["-c", script], in: nil, environment: nil) { _, _ in } } try await Task.sleep(for: .milliseconds(300)) task.cancel() await #expect(throws: CancellationError.self) { try await task.value } #expect(Date().timeIntervalSince(started) < 2) let pid = try #require(pid_t(String(contentsOfFile: "/tmp/\(marker)", encoding: .utf8).trimmingCharacters(in: .whitespacesAndNewlines))) try? FileManager.default.removeItem(atPath: "/tmp/\(marker)") try await Task.sleep(for: .milliseconds(200)) #expect(kill(pid, 0) != 0) } @Test func theDefaultStreamEmitsStdoutThenStderrAfterTheRun() async throws { let log = LineLog() let fake = CannedRunner(result: ProcessResult(exitCode: 2, stdout: "a\r\nb\n", stderr: "c\n\nd")) let result = try await fake.stream("x", arguments: [], in: nil, environment: nil, onLine: log.append) #expect(log.lines.map(\.text) == ["a", "b", "c", "d"]) #expect(log.lines.map(\.isError) == [false, false, true, true]) #expect(result.exitCode == 2) } } /// A runner that only implements `run`, so `stream` falls back to the protocol's default. private struct CannedRunner: ProcessRunning { var result: ProcessResult func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult { result } }