Testing with a Custom Environment
Run tests in an isolated context. This guide shows how to set a custom working directory and provide specific environment variables for your Zig CLI.
Sometimes your app’s behavior depends on the environment it runs in, like the
current directory or some environment variables. cmdtest lets you control
these for your tests.
Running in a custom directory
If you need to test file operations, it’s a good idea to run your test in a
temporary directory. You can do this with the cwd option.
Zig
test "run in a temp dir" {
// Create a temporary directory for the test
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
const tmp_path = try tmp.dir.realpathAlloc(testing.allocator, ".");
defer testing.allocator.free(tmp_path);
// Assumes "mycli --create-file" creates a file named "output.txt"
const argv = &[_][]const u8{"mycli", "--create-file"};
var result = try cmdtest.run(.{
.argv = argv,
.cwd = tmp_path, // Run the command in our temp directory
});
defer result.deinit();
// Check that the file was actually created inside the temp directory
_ = try tmp.dir.openFile("output.txt", .{});
}Setting custom environment variables
You can also provide a completely custom set of environment variables with the
env_map option. This is useful if your app reads its configuration from the
environment.
When you use env_map, your app will only see the variables you provide. It
will not inherit any from the parent process.
Zig
test "run with custom env var" {
// Create an environment map
var env = std.process.EnvMap.init(testing.allocator);
defer env.deinit();
// Add a variable
try env.put("MY_APP_MODE", "test");
// Assumes "mycli --print-mode" prints the value of MY_APP_MODE
const argv = &[_][]const u8{"mycli", "--print-mode"};
var result = try cmdtest.run(.{
.argv = argv,
.env_map = &env,
});
defer result.deinit();
try testing.expectEqualStrings("test\n", result.stdout);
}