test_child
import std::test::test_child; · source
Types
TestChild
type struct TestChild {}
Some tests need a real child process: one in its own process group that receives an interrupt, or one whose exit status or output is the thing under test. Mark a function in the test file ![test_child] instead of ![test]. It has a test's shape, () -> Result<(), TestError>, but the runner never runs it as a test and --list does not show it.
A test starts it by its fully-qualified name with TestChild::command, which returns a Command that runs this test binary as that test child; the test configures it and spawns it like any other command. The child runs that one function and exits 0 when it returns Ok, 1 when it returns Err (the error's message on stderr), and through the panic's own exit when it panics. The per-test timeout applies to the child as well. A name no test child has makes the child print an error and exit 2.
import std::fmt;
import std::process::command::{ Command, Output };
import std::test::*;
![test_child]
function prints_ready() -> Result<(), TestError> {
fmt::print("ready");
return Result::Ok(());
}
![test]
function a_test_child_runs_by_name_and_exits_zero() -> Result<(), TestError> {
const command: Command = TestChild::command(Str::new("MyApp::Tests::Math::prints_ready"))?;
const output: Output = command.output()?;
return expect_equal(output.status().exit_code(), Option::Some(0));
}
command fails only when the running executable's path cannot be read.
Static functions
static command(name: Str) -> Result<Command, TestError>;
static command(name: Str) -> Result<Command, TestError>;A command that runs this test binary as the test child name, the child function's fully-qualified name (Tests::Signals::waits_for_break). A name no test child has makes the child print an error and exit 2. Fails only when the running executable's path cannot be read.
type struct Name { ... }
type enum Name { ... }
type trait Name { ... }
type union Name { ... }Begins a type declaration; the keyword that follows says which kind. On its own, type Name = Existing; declares an alias.
type struct Name {
field: Type;
method(&this) -> Ret { ... }
}A value type with named fields and optional methods. Structs live on the stack and are passed by value. Fields are public by default and may carry = default values; methods take their receiver as &this, mut &this, or this.
type struct TestChild {}TestChild: start a ![test_child] function of this test binary as a process of its own.
import a::b;
import a::b::{ X, Y };
import a::b as c;
import a::b::*;Brings a module, or selected items from it, into scope. One path per declaration: use the brace form for several items, as to alias, and * for everything public (prefer the brace form; wildcards invite name collisions).
type struct Command {}A program to run and how to run it: its arguments, environment, working directory and standard streams. Configure it with the chaining setters, then start it with spawn (a running Child), status (wait for the exit), output (wait and capture both streams), or their async spellings run and collect.
type struct Output {}What a finished child left behind, from Command.output or Command.collect: its exit status and every byte it wrote to stdout and to stderr.
function name<T>(param: Type) -> Ret { ... }Declares a function. Parameters are written name: Type and are never inferred; the return type follows -> and defaults to void. Declaration order does not matter: every signature is collected before any body is checked, so functions may call each other freely and recurse.
function prints_ready() -> Result<(), TestError>type enum Result<T, E> with [Eq, Clone, Debug] {
Ok(T);
Err(E);
}The outcome of an operation that can fail: Ok(value) on success, Err(error) on failure.
primitive ()The unit type: a value that carries no information, and the empty tuple. Distinct from void, which is the absence of a value - Result<(), E> succeeds with nothing to return. 0 bytes.
type enum TestError {
Failed(String);
Other(String);
}Why a test failed. The runner prints the variant's message verbatim to stderr from the child process before exiting non-zero, so the parent can show the failing message in the test summary.
std::test::errorfunction print(text: Arguments) -> voidWrite text to stdout: an f-string (print(f"{x}"), its holes formatted through Display/Debug), a literal or a Str; a String is written as its view, print(name.as_str()). Nothing is consumed. There is no format string to interpret here (a % in the text is data, not a directive).
return value;Leaves the current function with the given value. A function whose return type is not void must return one; a bare return; is for void. In an async function it completes the future with the value.
Result::Ok(T)function a_test_child_runs_by_name_and_exits_zero() -> Result<(), TestError>const name: Type = value;An immutable binding: it cannot be reassigned after initialisation. The annotation may be omitted when an initialiser is present - the binding takes the initialiser's concrete type, inferred locally. Mutability is opt-in through mut.
const command: Commandtype struct TestChild {}TestChild: start a ![test_child] function of this test binary as a process of its own.
static TestChild::command(name: Str) -> Result<Command, TestError>A command that runs this test binary as the test child name, the child function's fully-qualified name (Tests::Signals::waits_for_break). A name no test child has makes the child print an error and exit 2. Fails only when the running executable's path cannot be read.
type struct Str {}A read-only view of UTF-8 text owned elsewhere: a string literal, a String, a file's bytes. Copying a Str copies the view, not the text, and it is valid only while what it views is. Str::new("text") views a literal; String.as_str() views a String.
static Str::new(text: string) -> StrConstruct from a NUL-terminated C-style string literal. The caller certifies that text is valid UTF-8 and outlives this view. The NUL terminator is not included in the view.
value?Error propagation. On a Result<T, E> it yields the T of an Ok and otherwise returns the Err(e) from the enclosing function unchanged; on an Option<T> it yields the T of a Some or returns None. It works on any type implementing Try, in a function whose return type implements FromResidual of it; an error of another type converts through From.
const output: Outputconst command: CommandCommand::output(&this) -> Result<Output, IoError>spawn + wait + collect stdout/stderr into arrays. Stdin is left Inherit (or whatever the caller set). Use this for the common "run this and tell me what it printed" case.
function expect_equal<T>(a: T, b: T) -> Result<(), TestError>
where T: Eq + DisplayOk(()) if a.equals(&b), otherwise Err carrying a multi-line "assertion left == right failed" message that Display-formats both values. Allocates the message on the heap; on allocation failure during message building, returns a generic fallback message.
const output: OutputExitStatus::exit_code(&this) -> Option<i32>Some(code) for a normal exit, None if the child was killed by a signal.
type enum Option<T> with [Eq, Clone, Debug] {
Some(T);
None;
}A value of type T that may be absent: Some(value) or None.
Option::Some(T)namespace std::test::test_child;TestChild: start a ![test_child] function of this test binary as a process of its own.
Result::Err(E)static name(param: Type) -> Ret { ... }A method that belongs to the type rather than an instance, called as Type::name(..). For structs, static new(..) returning a struct literal is the idiomatic constructor.
(parameter) name: Str