Testing in zig

Good morning, nice zig community :slight_smile:

The Context: I am trying to organize testing of a zig project so that if the zig build test is run from the root directory then all the tests in all the subprojects are run; but if I execute the zig build test from within a subproject then only the subproject’s tests are run.

Here is the tree of the project:

.
β”œβ”€β”€ build.zig
β”œβ”€β”€ build.zig.zon
β”œβ”€β”€ LICENSE
β”œβ”€β”€ src
β”‚   └── hdr
β”‚       β”œβ”€β”€ build.zig
β”‚       β”œβ”€β”€ build.zig.zon
β”‚       β”œβ”€β”€ hdr.md
β”‚       └── src
β”‚           β”œβ”€β”€ domain
β”‚           β”‚   β”œβ”€β”€ Header.zig
β”‚           β”‚   β”œβ”€β”€ processors
β”‚           β”‚   β”‚   β”œβ”€β”€ errors
β”‚           β”‚   β”‚   β”‚   β”œβ”€β”€ BufferError.zig
β”‚           β”‚   β”‚   β”‚   └── TokenError.zig
β”‚           β”‚   β”‚   β”œβ”€β”€ processFILE.zig
β”‚           β”‚   β”‚   └── ProcessFn.zig
β”‚           β”‚   └── Token.zig
β”‚           β”œβ”€β”€ hdr_parser.zig
β”‚           └── hdr.zig
└── utils
    β”œβ”€β”€ build.zig.zon
    └── test_utils.zig

The utils/test_utils.zig contains a addTests function:

pub fn addTests(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, test_step: *std.Build.Step, src_dir: []const u8) !void {
    var dir = try std.fs.cwd().openDir(src_dir, .{ .iterate = true });
    defer dir.close();

    var walker = try dir.walk(b.allocator);
    defer walker.deinit();

    while (try walker.next()) |entry| {
        if (isTestableZigFile(entry)) {
            //
            const test_artifact = b.addTest(.{
                .root_module = b.createModule(.{
                    .root_source_file = b.path(b.fmt("{s}/{s}", .{ src_dir, entry.path })),
                    .target = target,
                    .optimize = optimize,
                }),
            });
            // const run_test_artifact = b.addRunArtifact(test_artifact);
            test_step.dependOn(&test_artifact.step);
        }
    }
}

I would like to use this function in the src/hdr subproject.

The Problem: if I do this:

const addTests = @import("../../utils/test_utils.zig").addTests;

from the src/hdr/build.zig I will get the following error:

error: import of file outside module path: '../../utils/test_utils.zig'

I am a bit lost figuring out ways of importing the addTests function into the src/hdr/build.zig together with ChatGPT. sorry, doing baby steps in zig, need a source of ideas.

Please show me a direction.

best regards,
Dmitry

Hello @Dmitry-N-Medvedev

When you import a dependency in build.zig you can call public functions from the dependencies build.zig
You can move the addTests function in utils build.zig, add utils as a dependency in the top build.zig.zon (.path = β€œutils”) and use the function from the top build.zig:

const addTests = @import("utils").addTests;

Example: Can I use packages inside build.zig? - #7 by kristoff