Skip to content

Zig Testing Extras

You can write tests and catch leaks now. This page collects the extras you’ll reach for once your test suite grows: skipping a test that can’t run on this machine, running just the tests you’re working on, doctests that double as documentation, tests for code that reads files, and fuzzing, where Zig invents inputs to break your code. Each one is small on its own, and together they make testing a lot more pleasant.

Some tests only make sense in some places: a Windows-only feature, a test that needs a tool installed. Instead of deleting them or letting them fail, return error.SkipZigTest:

const std = @import("std");
const builtin = @import("builtin");
test "registry lookup (Windows only)" {
if (builtin.target.os.tag != .windows) return error.SkipZigTest;
try std.testing.expect(true);
}
test "runs everywhere" {
try std.testing.expect(1 + 1 == 2);
}

Run on Linux or macOS, you get this.

Output:

1/2 main.test.registry lookup (Windows only)...SKIP
2/2 main.test.runs everywhere...OK
1 passed; 1 skipped; 0 failed.

@import("builtin") tells you about the build: the target’s operating system, the build mode, and so on. A skipped test doesn’t count as a failure, so the run still succeeds (exit code 0), but the summary changes from All 2 tests passed. to a count that shows the skip. On Windows, you’d see both tests pass.

builtin.is_test is handy here too. It’s true only in test builds, so code can behave a little differently under test (use that sparingly: you want to test the real thing).

When you’re fixing one function, you don’t want to wait for all 200 tests. --test-filter keeps only the tests whose name contains the text you give:

const std = @import("std");
test "parse a number" {
try std.testing.expectEqual(42, try std.fmt.parseInt(u8, "42", 10));
}
test "parse a negative number" {
try std.testing.expectEqual(-7, try std.fmt.parseInt(i8, "-7", 10));
}
test "format a number" {
var buf: [8]u8 = undefined;
try std.testing.expectEqualStrings("42", try std.mem.print(&buf, "{d}", .{42}));
}
test {
std.debug.print("(unnamed test runs too) ", .{});
}
Terminal window
zig test main.zig --test-filter parse

You’ll see:

1/3 main.test.parse a number...OK
2/3 main.test.parse a negative number...OK
3/3 main.test_0...(unnamed test runs too) OK
All 3 tests passed.

Three things to know about filters:

  • The match is case-sensitive and looks for the text anywhere in the name. --test-filter Parse would match nothing here.
  • You can pass several filters, and a test runs if it matches any of them: --test-filter negative --test-filter format.
  • Unnamed tests always run, filter or not. That’s on purpose: they’re usually the test { _ = other; } blocks that pull in other files (see Zig Testing), and without them the filter would have nothing to search.

The filter isn’t only about speed. Filtered-out tests aren’t even compiled, so a test file that’s broken somewhere else can still run the one test you care about.

The build.zig made by zig init doesn’t pass filters on. Add an option for it (once, next to your addTest):

const test_filters = b.option([]const []const u8, "test-filter", "Only run tests whose name contains this text") orelse &.{};
const mod_tests = b.addTest(.{
.root_module = mod,
.filters = test_filters,
});

Now zig build test -Dtest-filter=parse runs only the matching tests. Pass -Dtest-filter=... twice for two filters. See Zig Build System for how b.option works.

A test can be named after a declaration instead of a sentence. That’s a doctest:

const std = @import("std");
/// Clamps `value` into the range `low` to `high`.
pub fn clamp(value: i32, low: i32, high: i32) i32 {
return @max(low, @min(value, high));
}
test clamp {
try std.testing.expectEqual(5, clamp(5, 0, 10));
try std.testing.expectEqual(0, clamp(-3, 0, 10));
try std.testing.expectEqual(10, clamp(99, 0, 10));
}
test "clamp with an empty range" {
try std.testing.expectEqual(7, clamp(3, 7, 7));
}

Output:

1/2 main.decltest.clamp...OK
2/2 main.test.clamp with an empty range...OK
All 2 tests passed.

Notice decltest instead of test in the name. A doctest runs like any other test, but it also appears as the example for clamp in the generated documentation (see Zig Comments for making docs). So write it for a reader: short, clear, showing normal use. Put the weird edge cases in ordinary named tests, like the second one here.

The name has to be a real declaration that’s in scope. A typo is caught right away:

const std = @import("std");
pub fn clamp(value: i32, low: i32, high: i32) i32 {
return @max(low, @min(value, high));
}
test clmap {
try std.testing.expectEqual(5, clamp(5, 0, 10));
}
test "another test" {
try std.testing.expect(true);
}
main.zig:7:6: error: use of undeclared identifier 'clmap'
test clmap {
^~~~~

The language reference on doctests describes them in a few lines; the standard library uses them all over the place.

Since Zig 0.16, anything that touches files, the network or the clock takes an io parameter (see Zig I/O Interface). Tests get a ready-made one: std.testing.io. Pair it with std.testing.tmpDir, a fresh, empty folder for each test that’s deleted afterwards, and you can test real file code without touching your own files:

const std = @import("std");
/// Counts the lines in a file.
fn countLines(io: std.Io, dir: std.Io.Dir, path: []const u8, gpa: std.mem.Allocator) !usize {
const data = try dir.readFileAlloc(io, path, gpa, .limited(1024 * 1024));
defer gpa.free(data);
return std.mem.countScalar(u8, data, '\n');
}
test "countLines counts the lines of a real file" {
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(io, .{ .sub_path = "todo.txt", .data = "milk\neggs\nbread\n" });
try std.testing.expectEqual(3, try countLines(io, tmp.dir, "todo.txt", std.testing.allocator));
}
test "countLines reports a missing file" {
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const result = countLines(std.testing.io, tmp.dir, "nope.txt", std.testing.allocator);
try std.testing.expectError(error.FileNotFound, result);
}

Output:

1/2 main.test.countLines counts the lines of a real file...OK
2/2 main.test.countLines reports a missing file...OK
All 2 tests passed.

The trick that makes this testable: countLines takes the folder (dir) as a parameter instead of always using the current directory. The program passes std.Io.Dir.cwd(), the test passes tmp.dir. The same idea as passing an allocator, applied to files.

tmpDir makes its folders under .zig-cache/tmp/ next to where you ran the test, and tmp.cleanup() deletes the folder and everything in it. Like std.testing.allocator, std.testing.io and tmpDir only exist in test builds.

One surprise: if code under test calls std.log.err, the test fails, even when every check passed:

const std = @import("std");
fn parseAge(text: []const u8) ?u8 {
return std.fmt.parseInt(u8, text, 10) catch {
std.log.err("not an age: {s}", .{text});
return null;
};
}
test "bad age gives null" {
try std.testing.expectEqual(null, parseAge("abc"));
}

You’ll see:

1/1 main.test.bad age gives null...[default] (err): not an age: abc
OK
All 1 tests passed.
1 errors were logged.
error: the following test command failed with exit code 1:

The test runner treats an error log as “something went wrong that nobody handled”. If the message is expected (like here, where bad input is normal), log it as std.log.warn or std.log.info instead, which don’t fail tests. If it’s truly an error, the test runner is right to complain.

A test with an endless loop just sits there. zig build test can put a time limit on each test:

Terminal window
zig build test --test-timeout 2s

A test that runs longer is stopped and reported as timed out, and the run moves on to the next test. The limit is wall-clock time, so pick something comfortably above what your slowest test needs on a busy machine. (This flag belongs to zig build; plain zig test doesn’t have it.)

Every test so far uses inputs you picked. You picked them because you thought of them, which means the bug you didn’t think of slips through. Fuzzing turns this around: a fuzzer feeds your code thousands of generated inputs, watches which code paths each one reaches, and keeps mutating the interesting ones until something crashes or a check fails.

Zig has a fuzzer built in. It’s still young: the 0.17.0 release notes say no changes were made to it in this release and that the team expects to improve it later. Everything below was run on Zig 0.17.1 on Linux x86-64.

Here’s a function with a bug that ordinary tests easily miss. It takes the first letter of each word:

// src/root.zig in a project made with `zig init`
const std = @import("std");
/// Writes the first letter of every word in `name` into `out`.
/// "Ada King Lovelace" gives "AKL".
pub fn initials(name: []const u8, out: []u8) []u8 {
var n: usize = 0;
if (name.len > 0 and name[0] != ' ') {
out[n] = name[0];
n += 1;
}
for (name, 0..) |c, i| {
if (c == ' ' and name[i + 1] != ' ') {
out[n] = name[i + 1];
n += 1;
}
}
return out[0..n];
}
test "initials of a normal name" {
var buf: [8]u8 = undefined;
try std.testing.expectEqualStrings("AKL", initials("Ada King Lovelace", &buf));
}
test "initials never crashes" {
try std.testing.fuzz({}, checkInitials, .{});
}
fn checkInitials(_: void, smith: *std.testing.Smith) !void {
var name_buf: [32]u8 = undefined;
const name = name_buf[0..smith.slice(&name_buf)];
var out: [32]u8 = undefined;
const result = initials(name, &out);
try std.testing.expect(result.len <= name.len);
}

The fuzz test has two parts:

  • std.testing.fuzz(context, checkInitials, .{}) registers a fuzz test. context is anything you want passed along ({} means nothing).
  • checkInitials runs once per generated input. The smith gives you values: smith.slice(&name_buf) fills part of the buffer with generated bytes and returns how many. There’s also smith.value(T) for a value of any type T, smith.bytes(buf) and more. Then you call your code and check what should always be true, here “never more initials than characters”, and above all “doesn’t crash”.

Run the tests normally first:

Terminal window
zig build test --summary all

Both pass. Without fuzzing turned on, a fuzz test runs just once, with empty input (and zig test adds a line 1 fuzz tests found. to its summary). Now turn the fuzzer on, with a limit on the number of runs:

Terminal window
zig build test --fuzz=1M -Doptimize=safe

Within a few seconds of the build finishing, you’ll see something like:

test
+- run test failure
thread 30367 panic: index out of bounds: index 3, len 3
src/root.zig:12:30: 0x10c7bbc in initials (test)
if (c == ' ' and name[i + 1] != ' ') {
^
src/root.zig:33:28: 0x10c7a53 in checkInitials (test)
const result = initials(name, &out);
^
(more lines)
error: test 'root.test.initials never crashes' terminated with signal ABRT; input saved to '.zig-cache/f/crash'

The fuzzer found a 3-byte name ending in a space. At the last character, name[i + 1] reads one past the end. The fix is to check there is a next character: if (c == ' ' and i + 1 < name.len and name[i + 1] != ' '). Then add an ordinary test for the case it found, say initials("Ada ", &buf), so the bug can never come back quietly.

A few honest notes from running it here:

  • Fuzzing only works through zig build. Plain zig test can’t run the fuzzer.
  • Use -Doptimize=safe. In the default debug mode, 0.17.1 stopped here with corrupted coverage file ... pcs_len was zero. With -Doptimize=fast it runs, but safety checks are off, so out-of-bounds bugs like this one aren’t caught (we ran a million inputs in fast and it found nothing). safe gives you speed and the checks.
  • --fuzz=1M stops after about a million runs. --fuzz with no number runs until you stop it and starts a web page showing coverage. In our VM the default address failed with AddressFamilyUnsupported; --fuzz --webui=127.0.0.1 worked.
  • The saved file under .zig-cache/f/ is in the fuzzer’s own format, not plain text. The release notes suggest copying it into your project and replaying it with .corpus = &.{@embedFile("initials-crash.bin")} in the options. We tried that and it reproduced the crash in a normal zig build test. Writing a plain test with the input in it, as above, is usually clearer.

Write a test that reads the HOME environment variable through std.testing.environ and skips itself if it isn’t set. If it is set, check that it isn’t empty.

Hint: std.testing.environ is an std.process.Environ. Turn it into a map with try std.testing.environ.createMap(std.testing.allocator), free it with map.deinit(), and look up map.get("HOME"), which is an optional.

Show solution
const std = @import("std");
test "HOME is not empty" {
var env = try std.testing.environ.createMap(std.testing.allocator);
defer env.deinit();
const home = env.get("HOME") orelse return error.SkipZigTest;
try std.testing.expect(home.len > 0);
}

Output:

1/1 main.test.HOME is not empty...OK
All 1 tests passed.

On a machine without HOME (Windows, usually), the orelse returns error.SkipZigTest and the test shows SKIP. orelse return ... is a neat way to bail out of a test when an optional is null.

Write fn saveScore(io: std.Io, dir: std.Io.Dir, score: u32) !void that writes the score as text into score.txt, and a test that saves 1500 in a tmpDir, reads the file back and checks it says 1500.

Hint: format the number with std.mem.print(&buf, "{d}", .{score}), and read the file in the test with tmp.dir.readFileAlloc(io, "score.txt", std.testing.allocator, .limited(64)).

Show solution
const std = @import("std");
fn saveScore(io: std.Io, dir: std.Io.Dir, score: u32) !void {
var buf: [16]u8 = undefined;
const text = try std.mem.print(&buf, "{d}", .{score});
try dir.writeFile(io, .{ .sub_path = "score.txt", .data = text });
}
test "saveScore writes the number" {
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try saveScore(io, tmp.dir, 1500);
const data = try tmp.dir.readFileAlloc(io, "score.txt", std.testing.allocator, .limited(64));
defer std.testing.allocator.free(data);
try std.testing.expectEqualStrings("1500", data);
}

Output:

1/1 main.test.saveScore writes the number...OK
All 1 tests passed.

Because saveScore takes the folder, the test can point it at a throwaway one. The testing allocator also checks that you freed what readFileAlloc gave you.

  • Return error.SkipZigTest to skip a test that can’t run here; the summary counts skips separately.
  • --test-filter text runs only tests whose name contains text (case-sensitive). Unnamed tests always run. In build.zig, pass .filters to addTest.
  • test someDecl { ... } is a doctest: it runs like a test and shows up as an example in the docs.
  • Use std.testing.io and std.testing.tmpDir for code that touches files, and take the folder as a parameter.
  • std.log.err inside a test makes the run fail. zig build test --test-timeout 2s stops tests that hang.
  • Fuzz tests use std.testing.fuzz and a Smith. Run them with zig build test --fuzz=1M -Doptimize=safe, then turn each crash into a normal test.

Next up: Zig Errors Explained, the messages you’ll see most often and how to fix each one.

Quick check

1. You run zig test main.zig --test-filter parse. Which tests run?
2. What is a doctest?
3. A test passes all its checks, but the code it tests calls std.log.err. What happens?
4. Why run the fuzzer with -Doptimize=safe rather than fast?