Search code examples
testingcompilationzig

How do I run tests in `ReleaseFast` mode in Zig?


Given that compiling in Debug or ReleaseFast mode may yield different results, I wanted to check if my library code works correctly and catch any bugs by using tests.

However, I couldn't find any option to tell tests to be compiled and run in ReleaseFast mode. I assume they are all running on Debug mode by default.


Solution

  • The options are exactly the same as if you were simply compiling the code.

    Using the build system:

    zig build test -Doptimize=ReleaseFast

    Without the build system:

    zig test ./test.zig -O ReleaseFast

    As a proof of concept, this fails in Debug, but works in ReleaseFast:

    test "should fail in debug" {
        var a = [3]u8{ 1, 2, 3 };
        var b: []u8 = a[0..2];
        var i: usize = 2;
    
        try std.testing.expect(b[i] == 3);
    }
    

    And here is one that fails in ReleaseFast but works in Debug:

    fn getString() []u8 {
        var s: [32]u8 = undefined;
        s[0] = 'h';
        s[1] = 'e';
        s[2] = 'l';
        s[3] = 'o';
        return s[0..4];
    }
    
    test "should fail in release" {
        var s = getString();
    
        try std.testing.expectEqual(s[0], 'h');
        try std.testing.expectEqual(s[1], 'e');
        try std.testing.expectEqual(s[2], 'l');
        try std.testing.expectEqual(s[3], 'o');
    }