Testing Stdin, Stdout, and Stderr
Learn to test the core I/O of your Zig CLI. This guide covers how to send data to stdin and check the output written to both stdout and stderr.
Most CLI tools read from stdin or print to stdout and stderr.` Here are a
few recipes for testing that.
Checking stdout
After you run a command, the RunResult struct contains the output. The
stdout field holds everything your app printed to standard out.
Zig
test "check stdout" {
// This assumes your project builds an exe named "mycli"
const argv = &[_][]const u8{"mycli", "hello"};
var result = try cmdtest.run(.{ .argv = argv });
defer result.deinit();
try testing.expectEqualStrings("hello from mycli\n", result.stdout);
}Checking stderr
It works the same way for standard error. Just check the stderr field.
Zig
test "check stderr" {
const argv = &[_][]const u8{"mycli", "--print-to-stderr"};
var result = try cmdtest.run(.{ .argv = argv });
defer result.deinit();
try testing.expectEqualStrings("this is an error message\n", result.stderr);
try testing.expectEqualStrings("", result.stdout); // stdout should be empty
}Sending data to stdin
If your app reads from stdin, you can provide input using the stdin option.
cmdtest will write your string to the process and then close the pipe, which
signals the end of the input.
A good way to test this is with the cat command.
Zig
test "check stdin" {
const argv = &[_][]const u8{"cat"};
const my_input = "line one\nline two\n";
var result = try cmdtest.run(.{ .argv = argv, .stdin = my_input });
defer result.deinit();
try testing.expectEqualStrings(my_input, result.stdout);
}