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.
Skipping a test
Section titled “Skipping a test”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)...SKIP2/2 main.test.runs everywhere...OK1 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).
Running only some tests
Section titled “Running only some tests”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) ", .{});}zig test main.zig --test-filter parseYou’ll see:
1/3 main.test.parse a number...OK2/3 main.test.parse a negative number...OK3/3 main.test_0...(unnamed test runs too) OKAll 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 Parsewould 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.
Filters with zig build test
Section titled “Filters with zig build test”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.
Doctests: tests that document
Section titled “Doctests: tests that document”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...OK2/2 main.test.clamp with an empty range...OKAll 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.
Testing code that needs io
Section titled “Testing code that needs io”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...OK2/2 main.test.countLines reports a missing file...OKAll 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.
Logged errors fail the test
Section titled “Logged errors fail the test”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: abcOKAll 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.
Tests that hang
Section titled “Tests that hang”A test with an endless loop just sits there. zig build test can put a time limit on each test:
zig build test --test-timeout 2sA 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.)
Fuzzing: let Zig find the inputs
Section titled “Fuzzing: let Zig find the inputs”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.contextis anything you want passed along ({}means nothing).checkInitialsruns once per generated input. Thesmithgives you values:smith.slice(&name_buf)fills part of the buffer with generated bytes and returns how many. There’s alsosmith.value(T)for a value of any typeT,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:
zig build test --summary allBoth 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:
zig build test --fuzz=1M -Doptimize=safeWithin a few seconds of the build finishing, you’ll see something like:
test+- run test failurethread 30367 panic: index out of bounds: index 3, len 3src/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. Plainzig testcan’t run the fuzzer. - Use
-Doptimize=safe. In the defaultdebugmode, 0.17.1 stopped here withcorrupted coverage file ... pcs_len was zero. With-Doptimize=fastit runs, but safety checks are off, so out-of-bounds bugs like this one aren’t caught (we ran a million inputs infastand it found nothing).safegives you speed and the checks. --fuzz=1Mstops after about a million runs.--fuzzwith no number runs until you stop it and starts a web page showing coverage. In our VM the default address failed withAddressFamilyUnsupported;--fuzz --webui=127.0.0.1worked.- 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 normalzig build test. Writing a plain test with the input in it, as above, is usually clearer.
Practice
Section titled “Practice”1. Skip when a variable is missing
Section titled “1. Skip when a variable is missing”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...OKAll 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.
2. Save and load, with a temporary folder
Section titled “2. Save and load, with a temporary folder”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...OKAll 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.SkipZigTestto skip a test that can’t run here; the summary counts skips separately. --test-filter textruns only tests whose name containstext(case-sensitive). Unnamed tests always run. Inbuild.zig, pass.filterstoaddTest.test someDecl { ... }is a doctest: it runs like a test and shows up as an example in the docs.- Use
std.testing.ioandstd.testing.tmpDirfor code that touches files, and take the folder as a parameter. std.log.errinside a test makes the run fail.zig build test --test-timeout 2sstops tests that hang.- Fuzz tests use
std.testing.fuzzand aSmith. Run them withzig 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Skip Tests:
error.SkipZigTestand how filters treat unnamed tests. - Zig language reference: Doctests: tests named after declarations.
- Zig 0.16.0 release notes: Fuzzer: the
Smithinterface, multi-core fuzzing and crash files. - Zig 0.16.0 release notes: Unit Test Timeouts: how
--test-timeoutworks. - Zig 0.17.0 release notes: Fuzzer: the current state of the fuzzer.