ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
33.83k stars 2.47k forks source link

Allow b.addTest to accept an existing module #21470

Open pfgithub opened 7 hours ago

pfgithub commented 7 hours ago

A common thing I'm doing is adding a module to export from a package and adding a test for it. Right now, that requires duplicating the imports setup and anything else done to the module:

const my_mod = b.addModule("my_mod", .{
    .root_source_file = b.path("src/my.zig");
    .target = target,
    .optimize = optimize,
});
my_mod.addImport("foo", foo_dep.module("foo"));
my_mod.addImport("bar", foo_dep.module("bar"));
my_mod.addImport("baz", foo_dep.module("baz"));

const my_mod_test = b.addTest(.{
    .root_source_file = b.path("src/my.zig");
    .target = target,
    .optimize = optimize,
});
my_mod_test.root_module.addImport("foo", foo_dep.module("foo"));
my_mod_test.root_module.addImport("bar", foo_dep.module("bar"));
my_mod_test.root_module.addImport("baz", foo_dep.module("baz"));

b.installArtifact(my_mod_test);

It would be nice to be able to pass the module directly as the root module for the test, eg:

const my_mod = b.addModule("my_mod", .{
    .root_source_file = b.path("src/my.zig");
    .target = target,
    .optimize = optimize,
});
my_mod.addImport("foo", foo_dep.module("foo"));
my_mod.addImport("bar" foo_dep.module("bar"));
my_mod.addImport("baz" foo_dep.module("baz"));

const my_mod_test = b.addTest(.{ .module = my_mod });
b.installArtifact(my_mod_test);

This would be weird with the functions on Step.Compile that update root_module directly. These would all mutate the passed in module which would be unexpected: