Zig test with build tag

In my build.zig I have added a debug build option

    ...
    const debug_options = b.addOptions();
    debug_options.addOption(bool, "trace-execution", b.option(bool, "trace-execution", "Stack Trace Execution") orelse false);

    exe_mod.addOptions("debug", debug_options);
    ...

And use it like so

// compiler.zig
const TRACE_EXECUTION = @import("debug").@"trace-execution";

Sometimes as I iterate through creating a new function, I would add a test right under the function to verify its behavior. But with zig test src/compiler.zig the Zig compiler will complain to me error: no module named 'debug' available within module test. Is there any way to make the build options available to module test?

Thanks!!

This happens because b.addOptions() is a build system concept; it will not be available when you run zig test, which does not go through the build system.

You’d need to add a step in your build script and invoke that (typically as zig build test).

Thanks for answering. I am aware of zig build test, but it cannot arbitrarily target a file at the time of invoking, the path of the target test file is defined in build.zig.

Say the path of the root module of the test step is src/main.zig. Imagine working on a new .zig module that hasn’t been imported by main.zig yet. I could just import the new file there for it to be included when running zig build test, but then I have to remove it later.

You can take a build option for a test name, b.addTest lets you filter which tests are run via .filter or .filters. Ofc that only works if the test is accessible via the module being tested.

Don’t forget, build.zig is just code, you can implement whatever build functionality you want.

You can take an option for a file name, then you’d have to find the file, make the module and test for it.

2 Likes