Zig Testing
Testing is built into the Zig language. You don't install a framework or learn a separate tool: you write test blocks right next to the code they check, and run them with zig test. Tests are compiled only when testing, so they cost nothing in the final program.
Test blocks
A test block has a name (a string) and a body. It fails if the body returns an error, so tests use try with the checking functions from std.testing:
const std = @import("std");
fn celsiusToFahrenheit(c: f64) f64 {
return c * 9.0 / 5.0 + 32.0;
}
fn isLeapYear(year: u32) bool {
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0;
}
test "freezing and boiling points" {
try std.testing.expectEqual(32.0, celsiusToFahrenheit(0));
try std.testing.expectEqual(212.0, celsiusToFahrenheit(100));
}
test "leap years" {
try std.testing.expect(isLeapYear(2024));
try std.testing.expect(!isLeapYear(1900));
try std.testing.expect(isLeapYear(2000));
}Save this as temps.zig and run:
zig test temps.zigAll 2 tests passed.
When a test fails
Let's add a buggy function and a test that catches it:
fn average(values: []const i32) i32 {
var sum: i32 = 0;
for (values) |v| sum += v;
return @divTrunc(sum, @as(i32, @intCast(values.len)) + 1); // bug: + 1
}
test "average of three numbers" {
try std.testing.expectEqual(20, average(&.{ 10, 20, 30 }));
}zig test temps.zig1/3 temps.test.freezing and boiling points...OK
2/3 temps.test.leap years...OK
3/3 temps.test.average of three numbers...expected 20, found 15
FAIL (TestExpectedEqual)
/home/you/temps.zig:24:5: 0x1048f3c in test.average of three numbers (test)
try std.testing.expectEqual(20, average(&.{ 10, 20, 30 }));
^
2 passed; 0 skipped; 1 failed.
error: the following test command failed with exit code 1:
.zig-cache/o/2f1c…/test --seed=0x8a51c2d7
The message tells you what was expected, what was found, and the exact line. (The addresses and paths will differ on your machine.)
The std.testing toolbox
| Function | Passes when |
|---|---|
expect(cond) |
cond is true |
expectEqual(expected, actual) |
the values are equal |
expectEqualStrings(a, b) |
two strings are equal (shows a diff if not) |
expectEqualSlices(T, a, b) |
two slices have equal elements |
expectError(error.X, expr) |
expr returns exactly that error |
expectApproxEqAbs(a, b, tol) |
floats are within tol of each other |
Put the expected value first. These functions are ordinary code returning errors, so you can even try them outside a test:
const std = @import("std");
fn add(a: i32, b: i32) i32 {
return a + b;
}
pub fn main() void {
std.testing.expectEqual(@as(i32, 5), add(2, 3)) catch unreachable;
std.debug.print("first check passed\n", .{});
std.testing.expectEqual(@as(i32, 6), add(2, 3)) catch |err| {
std.debug.print("second check: {t}\n", .{err});
};
}first check passed
expected 6, found 5
second check: TestExpectedEqual
Testing errors
Use expectError to check that bad input is rejected the way you intended:
fn parsePercent(text: []const u8) !u8 {
const n = try std.fmt.parseInt(u8, text, 10);
if (n > 100) return error.OutOfRange;
return n;
}
test "parsePercent rejects bad input" {
try std.testing.expectEqual(42, try parsePercent("42"));
try std.testing.expectError(error.OutOfRange, parsePercent("150"));
try std.testing.expectError(error.InvalidCharacter, parsePercent("4%"));
}Tests and memory leaks
Inside tests, use std.testing.allocator. It is a debug allocator that fails the test if anything allocated is not freed:
test "list does not leak" {
const allocator = std.testing.allocator;
var list: std.ArrayList(u32) = .empty;
defer list.deinit(allocator); // remove this line and the test fails
try list.append(allocator, 7);
try std.testing.expectEqual(1, list.items.len);
}zig test list.zigAll 1 tests passed.
Test blocks don't affect normal builds
When you zig run or zig build-exe a file, its test blocks are skipped entirely. This program runs normally even though it contains a test that would fail:
const std = @import("std");
fn double(x: i32) i32 {
return x * 2;
}
test "this test is wrong on purpose" {
try std.testing.expectEqual(5, double(2));
}
pub fn main() void {
std.debug.print("double(21) = {d}\n", .{double(21)});
}double(21) = 42
Useful options
| Command | Effect |
|---|---|
zig test file.zig |
run all tests in the file (and files it imports) |
zig test file.zig --test-filter "leap" |
run only tests whose name contains "leap" |
zig build test |
run the test step defined in build.zig |
return error.SkipZigTest; |
mark a test as skipped |
Tip: Write the test first when fixing a bug: reproduce the bug as a failing test, then fix the code until it passes. The test then guards against the bug returning.
Test yourself
How does a Zig test block signal failure?
- By printing FAIL
- By returning an error, usually via
try std.testing.expect… - By calling exit(1)
- By panicking only
Which allocator should you use inside tests to catch leaks?
- std.heap.page_allocator
- std.testing.allocator
- No allocator
- std.heap.c_allocator
What happens to test blocks when you run zig build-exe main.zig?
- They run before main
- They are compiled but not run
- They are ignored entirely
- Compilation fails