# Tests of starting programs: running them, capturing what they write, talking to # them through pipes, their environment, directory, and streams, and waiting for # them where they close. They run programs every Linux system has: `sh`, `cat`, # `true`, `false`, `pwd`, `sort`, and `printf`, and on Windows, those every # Windows system has: `cmd.exe`, `findstr`, `ping`, and `sort`. import std::io; import std::process; import system; import std::testing; # A directory of a test's own, removed with all it holds where the test returns. struct sandbox : fixture, owning { var at: path; } # Makes a directory no other run has, by making it only where nothing is. def sandbox::setup(t: &mut tester): sandbox { # Windows keeps its temporary files where `TEMP` says. when os == windows { for n in 0..10000 { val named := path::parse($"{temporary()}\\sakura-process-{n}") else (_) { break; }; var at := io::absolute(&named) else (_) { break; }; if io::create_directory(&at) is error(_) { continue; } return sandbox { at = move(at) }; } } for n in 0..10000 { var at := path::parse($"/tmp/sakura-process-{n}") else (_) { break; }; if io::create_directory(&at) is error(_) { continue; } return sandbox { at = move(at) }; } system::abort(); return sandbox {}; } def sandbox::close(&mut this): void { when os == windows { var tree := process::command::new("cmd"); tree.arguments(["/d", "/c", "rmdir", "/s", "/q", this.at.view()]); _ = tree.run(); return; } var remove := process::command::new("rm"); remove.arguments(["-rf", this.at.view()]); _ = remove.run(); } # Writes a file in a directory, with permissions, giving its path. def written(dir: &path, name: strview, text: strview, mode: permissions): path { val at := dir.join(name); _ = io::write_file(&at, text); _ = io::set_permissions(&at, mode); return at; } # Whether something failed, and why. def fails(got: result, why: io_error): bool { if got is error(was) { return was == why; } return false; } # Whether a status is an exit with a code. def exited(s: process::status, code: i32): bool { if s is exited(got) { return got == code; } return false; } when os == linux { # What `sh -c` gives for a script, captured. def shell(script: strview): process::captured { var sh := process::command::new("sh"); sh.arguments(["-c", script]); return sh.capture() else (_) { return process::captured { status = process::status { exited = -1 } }; }; } @test def statuses_say_how_children_stopped(t: &mut tester): void { var yes := process::command::new("true"); val ran := yes.run() else (_) { t.expects(false); return; }; t.expects(ran.succeeded && exited(ran, 0)); var no := process::command::new("false"); val failed := no.run() else (_) { t.expects(false); return; }; t.expects(!failed.succeeded && exited(failed, 1)); t.expects(exited(shell("exit 3").status, 3)); t.expects(shell("kill -9 $$").status == process::status { signaled = 9 }); # A child stopped from here, then waited for; waiting again gives the same. var sleeper := process::command::new("sh"); sleeper.arguments(["-c", "sleep 30"]); var started := sleeper.spawn() else (_) { t.expects(false); return; }; t.expects(started.id > 0); t.expects(started.kill() is value); val stopped := started.wait() else (_) { t.expects(false); return; }; t.expects(stopped == process::status { signaled = 9 }); val again := started.wait() else (_) { t.expects(false); return; }; t.expects(again == stopped && started.kill() is value); } @test def failing_to_start_is_an_error(t: &mut tester, s: sandbox): void { # A name on no directory of the `PATH` is found missing before anything starts. var missing := process::command::new("sakura-no-such-program"); t.expects(fails(missing.run(), io_error::not_found)); var status: system::process_status; t.expects(system::wait(-1, &mut status) < 0); val plain := written(&s.at, "plain", "not a program\n", 0o644); var denied := process::command::new(plain.view()); t.expects(fails(denied.run(), io_error::permission_denied)); var zero := process::command::new("true"); zero.argument("a\0b"); t.expects(fails(zero.run(), io_error::invalid)); var named := process::command::new("true"); named.set_variable("A=B", "c"); t.expects(fails(named.run(), io_error::invalid)); } @test def capture_keeps_both_outputs(t: &mut tester): void { # Each output is more than a pipe holds, so reading one to its end before the # other would wait for good. val first := shell("head -c 100000 /dev/zero | tr '\\0' a; head -c 70000 /dev/zero | tr '\\0' b >&2"); t.expects(first.status.succeeded && first.output.length == 100000 && first.error.length == 70000); t.expects(first.output.view().starts_with("aaa") && first.error.view().ends_with("bbb")); val second := shell("head -c 70000 /dev/zero | tr '\\0' b >&2; head -c 100000 /dev/zero | tr '\\0' a"); t.expects(second.output.length == 100000 && second.error.length == 70000); # A child that fails is still captured, and is given nothing to read. val failed := shell("echo why >&2; cat; exit 2"); t.expects(exited(failed.status, 2) && failed.error.view() == "why\n" && failed.output.length == 0); } @test def children_are_talked_to_through_pipes(t: &mut tester): void { var cat := process::command::new("cat"); cat.input(process::stdio::piped); cat.output(process::stdio::piped); var running := cat.spawn() else (_) { t.expects(false); return; }; { var requests := io::writer_of(&mut running.input()); t.expects(requests.write_line("first") is value && requests.write_line("second") is value); t.expects(requests.flush() is value); } # Closing its input ends what `cat` reads, so it finishes. running.input().close(); var replies := io::reader_of(&mut running.output()); var heard := string::new(nothing{}); for line in replies.lines() { heard.append(line.view()); heard.append("|"); } t.expects(heard.view() == "first|second|"); val stopped := running.wait() else (_) { t.expects(false); return; }; t.expects(stopped.succeeded); } @test def wait_closes_the_input_first(t: &mut tester): void { var cat := process::command::new("cat"); cat.input(process::stdio::piped); cat.output(process::stdio::none); var running := cat.spawn() else (_) { t.expects(false); return; }; t.expects(running.input().write("never read to its end\n") is value); val stopped := running.wait() else (_) { t.expects(false); return; }; t.expects(stopped.succeeded && !running.input().is_open); } @test def children_get_the_programs_variables_with_changes(t: &mut tester, s: sandbox): void { t.expects(process::variable("PATH") is some); t.expects(process::variable("SAKURA_SURELY_UNSET") is none); var sh := process::command::new("sh"); sh.arguments(["-c", "echo \"$GREETING ${HOME-gone}\""]); sh.set_variable("GREETING", "hello"); sh.remove_variable("HOME"); val changed := sh.capture() else (_) { t.expects(false); return; }; t.expects(changed.output.view() == "hello gone\n"); # Cleared, the child gets only what is set after. var env := process::command::new("env"); env.set_variable("BEFORE", "lost"); env.clear_variables(); env.set_variable("ONLY", "this"); val only := env.capture() else (_) { t.expects(false); return; }; t.expects(only.output.view() == "ONLY=this\n"); # A program is found in the directories of the `PATH` the child will have. _ = written(&s.at, "greet", "#!/bin/sh\necho found\n", 0o755); var greet := process::command::new("greet"); t.expects(fails(greet.run(), io_error::not_found)); greet.set_variable("PATH", s.at.view()); val found := greet.capture() else (_) { t.expects(false); return; }; t.expects(found.output.view() == "found\n"); } @test def children_run_in_the_directory_given(t: &mut tester, s: sandbox): void { var pwd := process::command::new("pwd"); pwd.argument("-P"); pwd.directory(&s.at); val ran := pwd.capture() else (_) { t.expects(false); return; }; var wanted := string::from(s.at.view(), nothing{}); wanted.append("\n"); t.expects(ran.output.view() == wanted.view()); # A program named by a relative path is found from there. _ = written(&s.at, "here.sh", "#!/bin/sh\necho here\n", 0o755); var here := process::command::new("./here.sh"); here.directory(&s.at); val said := here.capture() else (_) { t.expects(false); return; }; t.expects(said.output.view() == "here\n"); } @test def files_and_children_are_given_as_streams(t: &mut tester, s: sandbox): void { val log := s.at.join("log.txt"); var echo := process::command::new("printf"); echo.argument("logged\\n"); echo.output_to(io::file::create(&log) else (_) { t.expects(false); return; }); t.expects(echo.run() is value); val logged := io::read_file(&log) else (_) { t.expects(false); return; }; t.expects(logged.view() == "logged\n"); # The file went to the first child, which alone held it. val again := echo.capture() else (_) { t.expects(false); return; }; t.expects(again.output.view() == "logged\n"); val unchanged := io::read_file(&log) else (_) { t.expects(false); return; }; t.expects(unchanged.view() == "logged\n"); var cat := process::command::new("cat"); cat.input_from(io::file::open(&log) else (_) { t.expects(false); return; }); val read := cat.capture() else (_) { t.expects(false); return; }; t.expects(read.output.view() == "logged\n"); # The output of one is the input of another, as a shell's `|` makes it. var list := process::command::new("printf"); list.argument("c\\nb\\na\\n"); list.output(process::stdio::piped); var first := list.spawn() else (_) { t.expects(false); return; }; var sort := process::command::new("sort"); sort.input_from(move(first.output())); val sorted := sort.capture() else (_) { t.expects(false); return; }; t.expects(sorted.output.view() == "a\nb\nc\n" && !first.output().is_open); } @test def children_have_only_their_standard_streams(t: &mut tester): void { var held := io::pipe::open() else (_) { t.expects(false); return; }; val open := shell("ls /proc/$$/fd; true"); t.expects(open.output.view() == "0\n1\n2\n"); t.expects(held.reading.is_open && held.writing.is_open); } @test def children_close_where_their_scope_ends(t: &mut tester): void { { var sleeper := process::command::new("sh"); sleeper.arguments(["-c", "sleep 0"]); var running := sleeper.spawn() else (_) { t.expects(false); return; }; t.expects(running.id > 0); } var status: system::process_status; t.expects(system::wait(-1, &mut status) < 0); # One moved from holds nothing, and closes harmlessly. var yes := process::command::new("true"); var first := yes.spawn() else (_) { t.expects(false); return; }; var taken := move(first); t.expects(first.id == 0 && fails(first.wait(), io_error::invalid)); val stopped := taken.wait() else (_) { t.expects(false); return; }; t.expects(stopped.succeeded); } @test def writing_to_a_child_that_stopped_reading_fails(t: &mut tester): void { var sh := process::command::new("sh"); sh.arguments(["-c", "exec 0<&-; echo closed; sleep 1"]); sh.input(process::stdio::piped); sh.output(process::stdio::piped); var running := sh.spawn() else (_) { t.expects(false); return; }; var said := io::reader_of(&mut running.output()); val line := said.read_line() else { t.expects(false); return; }; t.expects(line.view() == "closed"); t.expects(fails(running.input().write("anyone?\n"), io_error::broken_pipe)); t.expects(running.kill() is value); } @test def children_get_ignored_signals_at_their_defaults(t: &mut tester): void { # What the program ignores, the child does not, so the signal stops it. t.expects(system::ignore(system::signal::user1) == 0); val raised := shell("kill -USR1 $$; echo survived"); t.expects(raised.status == process::status { signaled = 10 } && raised.output.length == 0); # So is `pipe`, which a pipe has the program ignore. var held := io::pipe::open() else (_) { t.expects(false); return; }; val piped := shell("kill -PIPE $$; echo survived"); t.expects(piped.status == process::status { signaled = 13 }); } } when os == windows { # What `cmd /c` gives for a script, captured. `/d` keeps cmd.exe from first # running what the registry asks it to. def batch(script: strview): process::captured { var cmd := process::command::new("cmd"); cmd.arguments(["/d", "/c", script]); return cmd.capture() else (_) { return process::captured { status = process::status { exited = -1 } }; }; } # A line of 98 of a letter, which cmd.exe's `echo` ends in two bytes. def hundred(letter: u8): string { var made := string::new(nothing{}); for _ in 0..98 { made.push(letter); } return made; } @test def statuses_say_how_children_stopped(t: &mut tester): void { val ran := batch("exit 0").status; t.expects(ran.succeeded && exited(ran, 0)); val failed := batch("exit 1").status; t.expects(!failed.succeeded && exited(failed, 1)); t.expects(exited(batch("exit 3").status, 3)); # A child stopped from here, then waited for; waiting again gives the same. var sleeper := process::command::new("ping"); sleeper.arguments(["-n", "30", "127.0.0.1"]); sleeper.output(process::stdio::none); var started := sleeper.spawn() else (_) { t.expects(false); return; }; t.expects(started.id > 0); t.expects(started.kill() is value); val stopped := started.wait() else (_) { t.expects(false); return; }; t.expects(stopped == process::status { signaled = 9 }); val again := started.wait() else (_) { t.expects(false); return; }; t.expects(again == stopped && started.kill() is value); } @test def failing_to_start_is_an_error(t: &mut tester, s: sandbox): void { # A name on no directory of the `PATH` is found missing before anything starts. var missing := process::command::new("sakura-no-such-program"); t.expects(fails(missing.run(), io_error::not_found)); var status: system::process_status; t.expects(system::wait(-1, &mut status) < 0); # A file that is no program may not be run. val plain := written(&s.at, "plain", "not a program\n", 0o644); var denied := process::command::new(plain.view()); t.expects(fails(denied.run(), io_error::permission_denied)); var zero := process::command::new("cmd"); zero.argument("a\0b"); t.expects(fails(zero.run(), io_error::invalid)); var named := process::command::new("cmd"); named.set_variable("A=B", "c"); t.expects(fails(named.run(), io_error::invalid)); # A batch file is given no argument cmd.exe would not pass on as it is. val script := written(&s.at, "said.cmd", "@echo %1\r\n", 0o644); var risky := process::command::new(script.view()); risky.argument("100%"); t.expects(fails(risky.run(), io_error::invalid)); } @test def capture_keeps_both_outputs(t: &mut tester): void { # Each output is more than a pipe holds, so reading one to its end before the # other would wait for good. val a := hundred('a'); val b := hundred('b'); val first := batch($"(for /L %i in (1,1,1000) do @echo {a})& (for /L %i in (1,1,700) do @echo {b})1>&2".view()); t.expects(first.status.succeeded && first.output.length == 100000 && first.error.length == 70000); t.expects(first.output.view().starts_with("aaa") && first.error.view().ends_with("bbb\r\n")); val second := batch($"(for /L %i in (1,1,700) do @echo {b})1>&2& (for /L %i in (1,1,1000) do @echo {a})".view()); t.expects(second.output.length == 100000 && second.error.length == 70000); # A child that fails is still captured, and is given nothing to read. val failed := batch("1>&2 echo why& findstr x& exit 2"); t.expects(exited(failed.status, 2) && failed.error.view() == "why\r\n" && failed.output.length == 0); } @test def children_are_talked_to_through_pipes(t: &mut tester): void { var cat := process::command::new("findstr"); cat.argument("^"); cat.input(process::stdio::piped); cat.output(process::stdio::piped); var running := cat.spawn() else (_) { t.expects(false); return; }; { var requests := io::writer_of(&mut running.input()); t.expects(requests.write_line("first") is value && requests.write_line("second") is value); t.expects(requests.flush() is value); } # Closing its input ends what `findstr` reads, so it finishes. running.input().close(); var replies := io::reader_of(&mut running.output()); var heard := string::new(nothing{}); for line in replies.lines() { heard.append(line.view()); heard.append("|"); } t.expects(heard.view() == "first|second|"); val stopped := running.wait() else (_) { t.expects(false); return; }; t.expects(stopped.succeeded); } @test def wait_closes_the_input_first(t: &mut tester): void { var cat := process::command::new("findstr"); cat.argument("^"); cat.input(process::stdio::piped); cat.output(process::stdio::none); var running := cat.spawn() else (_) { t.expects(false); return; }; t.expects(running.input().write("never read to its end\n") is value); val stopped := running.wait() else (_) { t.expects(false); return; }; t.expects(stopped.succeeded && !running.input().is_open); } @test def children_get_the_programs_variables_with_changes(t: &mut tester, s: sandbox): void { # Names are the same whatever the case of their letters. t.expects(process::variable("PATH") is some && process::variable("path") is some); t.expects(process::variable("SAKURA_SURELY_UNSET") is none); var cmd := process::command::new("cmd"); cmd.arguments(["/d", "/c", "echo %GREETING% %TEMP%"]); cmd.set_variable("greeting", "hello"); cmd.set_variable("GREETING", "hi"); cmd.remove_variable("temp"); val changed := cmd.capture() else (_) { t.expects(false); return; }; t.expects(changed.output.view() == "hi %TEMP%\r\n"); # Cleared, the child gets only what is set after. var env := process::command::new("cmd"); env.arguments(["/d", "/c", "echo %ONLY% %BEFORE% %PATH%"]); env.set_variable("BEFORE", "lost"); env.clear_variables(); env.set_variable("ONLY", "this"); val only := env.capture() else (_) { t.expects(false); return; }; t.expects(only.output.view() == "this %BEFORE% %PATH%\r\n"); # A program is found in the directories of the `PATH` the child will have, # with an ending `PATHEXT` lists. _ = written(&s.at, "greet.cmd", "@echo found\r\n", 0o644); var greet := process::command::new("greet"); t.expects(fails(greet.run(), io_error::not_found)); greet.set_variable("Path", s.at.view()); val found := greet.capture() else (_) { t.expects(false); return; }; t.expects(found.output.view() == "found\r\n"); } @test def children_run_in_the_directory_given(t: &mut tester, s: sandbox): void { var cd := process::command::new("cmd"); cd.arguments(["/d", "/c", "cd"]); cd.directory(&s.at); val ran := cd.capture() else (_) { t.expects(false); return; }; var wanted := string::from(s.at.view(), nothing{}); wanted.append("\r\n"); t.expects(ran.output.view() == wanted.view()); # A program named by a relative path is found from there. _ = written(&s.at, "here.cmd", "@echo here\r\n", 0o644); var here := process::command::new("./here"); here.directory(&s.at); val said := here.capture() else (_) { t.expects(false); return; }; t.expects(said.output.view() == "here\r\n"); } @test def arguments_are_given_as_they_are(t: &mut tester, s: sandbox): void { # `echo` writes the rest of its command line as it is, so it shows how each # argument was quoted for the C runtime to read back. var echo := process::command::new("cmd"); echo.arguments(["/d", "/c", "echo", "plain", "two words", "", "say \"hi\"", "ends\\", "in quotes\\"]); val said := echo.capture() else (_) { t.expects(false); return; }; t.expects(said.output.view() == "plain \"two words\" \"\" \"say \\\"hi\\\"\" ends\\ \"in quotes\\\\\"\r\n"); # A batch file's argument is quoted where cmd.exe would read it otherwise. val script := written(&s.at, "said.cmd", "@echo %1 %2\r\n", 0o644); var batch_file := process::command::new(script.view()); batch_file.arguments(["a&b|c", "plain"]); val quoted := batch_file.capture() else (_) { t.expects(false); return; }; t.expects(quoted.output.view() == "\"a&b|c\" plain\r\n"); } @test def files_and_children_are_given_as_streams(t: &mut tester, s: sandbox): void { val log := s.at.join("log.txt"); var echo := process::command::new("cmd"); echo.arguments(["/d", "/c", "echo logged"]); echo.output_to(io::file::create(&log) else (_) { t.expects(false); return; }); t.expects(echo.run() is value); val logged := io::read_file(&log) else (_) { t.expects(false); return; }; t.expects(logged.view() == "logged\r\n"); # The file went to the first child, which alone held it. val again := echo.capture() else (_) { t.expects(false); return; }; t.expects(again.output.view() == "logged\r\n"); val unchanged := io::read_file(&log) else (_) { t.expects(false); return; }; t.expects(unchanged.view() == "logged\r\n"); var cat := process::command::new("findstr"); cat.argument("^"); cat.input_from(io::file::open(&log) else (_) { t.expects(false); return; }); val read := cat.capture() else (_) { t.expects(false); return; }; t.expects(read.output.view() == "logged\r\n"); # The output of one is the input of another, as a shell's `|` makes it. The # system's own `sort` is named, since another may come first on the `PATH`. var list := process::command::new("cmd"); list.arguments(["/d", "/c", "(echo c& echo b& echo a)"]); list.output(process::stdio::piped); var first := list.spawn() else (_) { t.expects(false); return; }; val root := process::variable("SystemRoot") else { t.expects(false); return; }; var sort := process::command::new($"{root}\\System32\\sort.exe".view()); sort.input_from(move(first.output())); val sorted := sort.capture() else (_) { t.expects(false); return; }; t.expects(sorted.output.view() == "a\r\nb\r\nc\r\n" && !first.output().is_open); } @test def children_have_only_their_standard_streams(t: &mut tester): void { # A child holds no end of a pipe it was not given, so once the program closes # the end it writes, reading the other ends at once, while the child runs on. var held := io::pipe::open() else (_) { t.expects(false); return; }; var sleeper := process::command::new("ping"); sleeper.arguments(["-n", "5", "127.0.0.1"]); sleeper.output(process::stdio::none); var running := sleeper.spawn() else (_) { t.expects(false); return; }; held.writing.close(); var bytes: u8[16]; val began := system::clock(clock_kind::steady); val count := held.reading.read(slice::::over((&mut bytes) as *mut u8, 16)) else (_) { t.expects(false); return; }; t.expects(count == 0 && system::clock(clock_kind::steady) - began < 1000000000); t.expects(running.kill() is value); } @test def children_close_where_their_scope_ends(t: &mut tester): void { { var quick := process::command::new("cmd"); quick.arguments(["/d", "/c", "exit 0"]); var running := quick.spawn() else (_) { t.expects(false); return; }; t.expects(running.id > 0); } var status: system::process_status; t.expects(system::wait(-1, &mut status) < 0); # One moved from holds nothing, and closes harmlessly. var yes := process::command::new("cmd"); yes.arguments(["/d", "/c", "exit 0"]); var first := yes.spawn() else (_) { t.expects(false); return; }; var taken := move(first); t.expects(first.id == 0 && fails(first.wait(), io_error::invalid)); val stopped := taken.wait() else (_) { t.expects(false); return; }; t.expects(stopped.succeeded); } @test def writing_to_a_child_that_stopped_reading_fails(t: &mut tester): void { # The child reads none of its input, and once it stops, nothing does. var cmd := process::command::new("cmd"); cmd.arguments(["/d", "/c", "echo closed"]); cmd.input(process::stdio::piped); cmd.output(process::stdio::piped); var running := cmd.spawn() else (_) { t.expects(false); return; }; var said := io::reader_of(&mut running.output()); val line := said.read_line() else { t.expects(false); return; }; t.expects(line.view() == "closed" && said.read_line() is none); t.expects(fails(running.input().write("anyone?\n"), io_error::broken_pipe)); t.expects(running.kill() is value); } } @test def polling_waits_at_most_as_long_as_asked(t: &mut tester): void { var reading: system::fd = -1; var writing: system::fd = -1; t.expects(system::pipe(&mut reading, &mut writing) == 0); var handles: system::fd[1]; handles[0] = reading; var ready: bool[1]; val watched := span::::over((&handles) as *system::fd, 1); val marks := slice::::over((&mut ready) as *mut bool, 1); # Nothing is written, so the wait runs out, once as long as asked has passed. val before := system::clock(clock_kind::steady); t.expects(system::poll(watched, marks, 20) == 0 && !ready[0]); t.expects(system::clock(clock_kind::steady) - before >= 10000000); t.expects(system::poll(watched, marks, 0) == 0); # Once something is written, it can be read at once, however long is asked. writing.put("x"); t.expects(system::poll(watched, marks, 1000) == 1 && ready[0]); t.expects(system::poll(watched, marks) == 1); reading.close(); writing.close(); }