Files
helder/Tests/HelderServicesTests/Process/ProcessRunnerTests.swift
T

66 lines
2.6 KiB
Swift

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 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")
}
}