#How to properly organize tests in Zig?

1 messages · Page 1 of 1 (latest)

tough adder
#

I'm trying Zig for the first time, and I don't really understand how to conveniently organize tests with the build system. Right now, all my tests are in the same files as the function implementations, after which I collect all the files into one test block like this (tests.zig):

test {
    _ = @import("main.zig");
    _ = @import("day1.zig");
    _ = @import("day2.zig");
    _ = @import("tools.zig");
}

And in build.zig I run them using

    const exe_tests = b.addTest(.{
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/tests.zig"),
            .target = target,
            .optimize = optimize,
        }),
    });

    const run_exe_tests = b.addRunArtifact(exe_tests);

    const test_step = b.step("test", "Run all tests");
    test_step.dependOn(&run_exe_tests.step);

But this looks very cursed. If in any of the files tested in tests.zig I do an import by module name instead of by file name, the tests won't start. Example:

#
❯ zig build test -freference-trace=4
test
└─ run test
   └─ compile test Debug native 1 errors
src/day2.zig:2:23: error: no module named 'tools' available within module 'root'
const tools = @import("tools");
                      ^~~~~~~
referenced by:
    next: src/day2.zig:25:27
    second: src/day2.zig:94:21
    decltest.second: src/day2.zig:106:51
    test_0: src/tests.zig:4:17
error: the following command failed with 1 compilation errors:
/usr/bin/zig test -freference-trace=4 -ODebug -Mroot=/home/rantoo/prog/zig/aoc/src/tests.zig --cache-dir .zig-cache --global-cache-dir /home/rantoo/.cache/zig --name test --zig-lib-dir /usr/lib/zig/ --listen=-

Build Summary: 0/3 steps succeeded; 1 failed
test transitive failure
└─ run test transitive failure
   └─ compile test Debug native 1 errors

error: the following build command failed with exit code 1:
.zig-cache/o/4f5b763ea4d5e488659b70286bb907c8/build /usr/bin/zig /usr/lib/zig /home/rantoo/prog/zig/aoc .zig-cache /home/rantoo/.cache/zig --seed 0x89d117ee -Z61ccd7abce4628cc test -freference-trace=4
#

Adding each file to a module and doing addTest() like this:

    const file1 = b.addModule("file1", .{
        .root_source_file = b.path("src/file1.zig"),
        .target = target,
    });
    const file1_tests = b.addTest(.{
        .root_module = mod,
    });
    const run_file1_tests = b.addRunArtifact(file1_tests);

    ...

    const test_step = b.step("test", "Run tests");
    test_step.dependOn(&run_file1_tests.step);
    test_step.dependOn(&run_file2_tests.step);

looks very verbose and overcomplicated.

That's why I'm almost certain that I'm doing this completely wrong

wise badger
#

tests dont run accross module boundries, each module needs to be tested on its own.
for sub files of modules, they need to be referenced. there is std.testing.refAllDecls[Recursive]() to help with that.