Zig Testing
You’ve written a function and it seems to work. A test is a small piece of code that proves it works, and keeps proving it every time you change something. Zig has testing built into the language: there’s a test keyword, a zig test command and a std.testing module full of checks. No framework to install, no config file. You write tests in the same file as the code they test, and they never end up in your real program.
Your first test
Section titled “Your first test”Here’s a function and two tests for it:
const std = @import("std");
fn isLeapYear(year: u32) bool { if (year % 400 == 0) return true; if (year % 100 == 0) return false; return year % 4 == 0;}
test "2024 is a leap year" { try std.testing.expect(isLeapYear(2024));}
test "1900 is not a leap year" { try std.testing.expect(!isLeapYear(1900));}Save it as main.zig and run:
zig test main.zigOutput:
1/2 main.test.2024 is a leap year...OK2/2 main.test.1900 is not a leap year...OKAll 2 tests passed.Here’s what’s going on:
test "2024 is a leap year" { ... }declares a test. The text in quotes is its name; it can be any sentence you like, so make it say what you’re checking.std.testing.expect(ok)checks thatokistrue. If it isn’t, it returns an error.trypasses that error up, which ends the test and marks it as failed. Forget thetryand Zig won’t compile it, because you’d be ignoring an error.zig testbuilds a special program that runs every test it finds, then prints a summary.
Each line shows the test’s number, its full name (file name, then test, then your name) and the result.
The file has no main function, and that’s fine: zig test doesn’t need one. The other way around works too. When you build or zig run a program, every test block is left out completely, so tests cost your real program nothing. The language reference on Zig Test has the official rules.
The checks you’ll use most
Section titled “The checks you’ll use most”expect works for anything you can write as a bool, but when it fails, all it can tell you is “it was false”. The other checks in std.testing know what you were comparing, so their failure messages show both values. Here are the everyday ones:
const std = @import("std");
fn greet(buf: []u8, name: []const u8) ![]u8 { return std.mem.print(buf, "Hello, {s}!", .{name});}
fn parseAge(text: []const u8) !u8 { return std.fmt.parseInt(u8, text, 10);}
test "numbers" { try std.testing.expectEqual(42, try parseAge("42"));}
test "strings" { var buf: [32]u8 = undefined; try std.testing.expectEqualStrings("Hello, Ada!", try greet(&buf, "Ada"));}
test "slices" { const evens = [_]u8{ 2, 4, 6 }; try std.testing.expectEqualSlices(u8, &.{ 2, 4, 6 }, &evens);}
test "errors" { try std.testing.expectError(error.InvalidCharacter, parseAge("forty")); try std.testing.expectError(error.Overflow, parseAge("300"));}
test "floats" { const a: f64 = 0.1; const b: f64 = 0.2; try std.testing.expectApproxEqAbs(0.3, a + b, 0.0001);}Output:
1/5 main.test.numbers...OK2/5 main.test.strings...OK3/5 main.test.slices...OK4/5 main.test.errors...OK5/5 main.test.floats...OKAll 5 tests passed.Pick the check that matches what you’re testing:
| Check | Use it for |
|---|---|
expect(ok) |
Any condition that should be true. |
expectEqual(expected, actual) |
Numbers, bools, enums, optionals, simple structs. |
expectEqualStrings(expected, actual) |
Text. Shows exactly where the two strings differ. |
expectEqualSlices(T, expected, actual) |
Slices and arrays of T, item by item. |
expectError(error.X, result) |
A function that should fail with a specific error. |
expectApproxEqAbs(expected, actual, tolerance) |
Floats, which are rarely exactly equal (see Zig Floats). |
Two details trip people up:
- The expected value comes first.
expectEqual(42, result), notexpectEqual(result, 42). Swap them and the test still passes or fails the same way, but the message reads backwards: ifresultis 41, you’d see “expected 41, found 42”, which sends you hunting in the wrong place. - Don’t use
expectEqualon strings. Strings are slices, and for slicesexpectEqualcompares the address and length, not the text. Two equal strings in different places in memory would fail. UseexpectEqualStrings.
The float test gives a and b a type on purpose: with plain literals, 0.1 + 0.2 would be worked out while compiling as a comptime_float, and expectApproxEqAbs refuses those. Inside a test, try parseAge("42") is fine: if it fails, the error ends the test, which is exactly what you want.
When a test fails
Section titled “When a test fails”Here’s a function with a classic bug. It finds the largest number by starting from zero:
const std = @import("std");
fn largest(nums: []const i32) i32 { var best: i32 = 0; for (nums) |n| { if (n > best) best = n; } return best;}
test "largest of positive numbers" { try std.testing.expectEqual(9, largest(&.{ 3, 9, 4 }));}
test "largest of negative numbers" { try std.testing.expectEqual(-2, largest(&.{ -5, -2, -7 }));}You’ll see something like this (paths shortened, and the addresses and seed change on every run):
1/2 main.test.largest of positive numbers...OK2/2 main.test.largest of negative numbers...expected -2, found 0FAIL (TestExpectedEqual).../lib/std/testing.zig:93:17: 0x124ee64 in expectEqualInner__func_962 (std.zig) return error.TestExpectedEqual; ^.../lib/std/testing.zig:57:5: 0x124eeef in expectEqual (main.zig) return expectEqualInner(T, expected, actual); ^main.zig:16:5: 0x124ef36 in test.largest of negative numbers (main.zig) try std.testing.expectEqual(-2, largest(&.{ -5, -2, -7 })); ^1 passed; 0 skipped; 1 failed.error: the following test command failed with exit code 1:/root/.cache/zig/o/3c8b944da52f18f863305133a3231aa6/test --seed=0x9a9fec4cIt looks like a lot, but you only need three parts:
expected -2, found 0: what went wrong. The function returned 0 for a list with no zero in it.FAIL (TestExpectedEqual): which check failed.expectfails withTestUnexpectedResult,expectEqualwithTestExpectedEqual.- The last
main.zigline of the trace (main.zig:16:5): the line in your code. The lines above it are insidestd.testingand you can skip them.
The first test passed, and that’s the lesson here: it only used positive numbers, so the bug hid. Good tests try the awkward cases too: empty input, negative numbers, zero, the biggest value. The fix is to start from the first item, var best = nums[0];, and then decide what an empty list should do.
zig test also exits with code 1 when anything fails, so scripts and CI systems notice. Tests keep running after a failure, so one run shows you every broken test, not just the first.
Tests in other files
Section titled “Tests in other files”Bigger programs are split into files (see Zig Modules), and each file keeps its own tests. Say temperature.zig has a function and a test:
pub fn toFahrenheit(celsius: f64) f64 { return celsius * 9.0 / 5.0 + 32.0;}
test toFahrenheit { const std = @import("std"); try std.testing.expectEqual(212.0, toFahrenheit(100.0));}That test is named after the function, test toFahrenheit without quotes. It’s called a doctest: it also shows up as an example in the generated docs. Zig Testing Extras covers it.
And main.zig uses it:
const std = @import("std");const temperature = @import("temperature.zig");
pub fn main() void { std.debug.print("{d}\n", .{temperature.toFahrenheit(21.0)});}
test "main has a test too" { try std.testing.expect(true);}Run zig test main.zig and you’ll see:
1/1 main.test.main has a test too...OKAll 1 tests passed.Only one test. Where did the test in temperature.zig go? Zig is lazy: it only looks at code that’s actually used. In a test build, main isn’t used, so nothing touches temperature.zig, so its tests are never found. (If a test in main.zig had called temperature.toFahrenheit, they would run. That kind of “sometimes” is worse than “never”.)
The fix is a test block with no name that mentions the file:
test { _ = temperature;}Add that to main.zig, and now you’ll see:
1/3 main.test.main has a test too...OK2/3 main.test_0...OK3/3 temperature.decltest.toFahrenheit...OKAll 3 tests passed._ = temperature; uses the file without doing anything with it, which is enough to make Zig look inside and collect its tests. The unnamed test shows up as test_0 and always passes. Put one of these at the bottom of main.zig (or root.zig) listing every file you import, and all your tests run from one command.
zig build test in a project
Section titled “zig build test in a project”In a project made with zig init (see Zig Build System), you don’t call zig test by hand. The generated build.zig already has a test step:
zig build testWhen every test passes, it prints nothing at all. That’s normal: no news is good news. To see what ran, ask for a summary:
zig build test --summary allYou’ll see something like:
Build Summary: 5/5 steps succeeded; 3/3 tests passedtest success+- run test 1 pass (1 total) 4ms MaxRSS:4M| +- compile test debug native success 591ms MaxRSS:170M+- run test 2 pass (2 total) 6ms MaxRSS:4M +- compile test debug native success 619ms MaxRSS:169MThere are two test programs because the template tests two modules: the library in src/root.zig and the app in src/main.zig. The part of build.zig that sets this up looks like this:
const mod_tests = b.addTest(.{ .root_module = mod });const run_mod_tests = b.addRunArtifact(mod_tests);
const test_step = b.step("test", "Run tests");test_step.dependOn(&run_mod_tests.step);addTest does what zig test does: compile one module’s tests into a program. addRunArtifact runs it, and the test step is what zig build test asks for. The test { _ = ...; } rule from the last section still applies inside each module.
When a test fails, zig build test shows the failing test’s name, the message and the trace, then a summary like 2/3 tests passed (1 failed). Tests that already passed and whose code didn’t change are cached and not run again, which is why a second run is so quick.
Practice
Section titled “Practice”1. Test a word counter
Section titled “1. Test a word counter”Write fn countWords(text: []const u8) usize that counts words separated by single spaces, and three tests: a normal sentence, an empty string, and a single word.
Hint: count the starts of words: a letter that’s either first or comes right after a space.
Show solution
const std = @import("std");
fn countWords(text: []const u8) usize { var count: usize = 0; for (text, 0..) |c, i| { if (c != ' ' and (i == 0 or text[i - 1] == ' ')) count += 1; } return count;}
test "a normal sentence" { try std.testing.expectEqual(4, countWords("tests are built in"));}
test "an empty string" { try std.testing.expectEqual(0, countWords(""));}
test "a single word" { try std.testing.expectEqual(1, countWords("hello"));}Output:
1/3 main.test.a normal sentence...OK2/3 main.test.an empty string...OK3/3 main.test.a single word...OKAll 3 tests passed.The empty string is the test that catches most word counters: a version that starts count at 1 passes the other two tests but fails this one.
2. Test the error, not just the answer
Section titled “2. Test the error, not just the answer”Write fn safeDivide(a: i32, b: i32) !i32 that returns error.DivisionByZero when b is 0 and @divTrunc(a, b) otherwise. Test one normal division and the error case.
Hint: expectError takes the error you expect first and the call’s result second.
Show solution
const std = @import("std");
fn safeDivide(a: i32, b: i32) !i32 { if (b == 0) return error.DivisionByZero; return @divTrunc(a, b);}
test "divides normally" { try std.testing.expectEqual(-3, try safeDivide(-7, 2));}
test "refuses to divide by zero" { try std.testing.expectError(error.DivisionByZero, safeDivide(1, 0));}Output:
1/2 main.test.divides normally...OK2/2 main.test.refuses to divide by zero...OKAll 2 tests passed.@divTrunc(-7, 2) rounds toward zero, so it’s -3. Testing the error path matters as much as testing the answer: callers rely on getting exactly error.DivisionByZero, not a crash.
3. Find the bug with a test
Section titled “3. Find the bug with a test”This function should return the last item of a slice, or null if it’s empty. Write a test for a three-item slice and one for an empty slice, find the bug, and fix it.
fn lastItem(items: []const u8) ?u8 { if (items.len == 0) return null; return items[items.len - 2];}Hint: expectEqual works with optionals: expectEqual(null, lastItem("")).
Show solution
const std = @import("std");
fn lastItem(items: []const u8) ?u8 { if (items.len == 0) return null; return items[items.len - 1];}
test "last of three" { try std.testing.expectEqual('c', lastItem("abc"));}
test "last of nothing" { try std.testing.expectEqual(null, lastItem(""));}Output:
1/2 main.test.last of three...OK2/2 main.test.last of nothing...OKAll 2 tests passed.With len - 2, the first test fails with expected 99, found 98: expectEqual prints characters as numbers, and 99 is 'c' while 98 is 'b'. The last item is at len - 1.
- A
test "name" { ... }block holds a test. It lives next to the code it tests and is left out of normal builds. zig test file.zigruns every test it finds. Piped output shows one line per test; a terminal shows just the summary.- Use
expectEqual(expected, actual)with the expected value first,expectEqualStringsfor text andexpectErrorfor failures you expect. - A failure prints the values, the error name and a trace: look for the line in your own file.
- Tests in imported files only run if something uses the file, so add
test { _ = other; }. - In a project, run
zig build test. Silence means success; add--summary allto see what ran.
Next up: Zig Testing Allocator, which turns every test into a memory leak detector.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Zig Test: test declarations, failures, skipping and the default test runner.
- Zig language reference: The Testing Namespace: where the
std.testingchecks are listed. - Zig Build System guide: how
zig buildsteps, includingtest, fit together. - Zig 0.16.0 release notes: unit test timeouts: the
--test-timeoutflag forzig build test.