ZigEmbeddedGroup / microzig

Unified abstraction layer and HAL for several microcontrollers
zlib License
1.26k stars 102 forks source link

Add support for using MicroZig within `test` blocks #230

Open bryanmcelvy opened 3 months ago

bryanmcelvy commented 3 months ago

On a personal project I'm working on, I recently ran into an issue in which either importing MicroZig directly or using something that relies on it inside of a test block causes a compilation error. When running using a test step (e.g. zig build test), the error is no module named 'microzig' available within module root. When running using zig test, the error is no module named 'microzig' available within module test. The fix for this was adding a line to build.zig that imports the MicroZig module within the test step:

const test_run_step = b.step("test", "Run unit tests");

const driver_tests = b.addTest(.{
    .name = "driver_tests",
    .root_source_file = b.path("source/drivers.zig"),
    .target = b.graph.host,
});
driver_tests.root_module.addImport("microzig", firmware.modules.microzig); // adding this line fixed the issue

const driver_test_run = b.addRunArtifact(driver_tests);
test_run_step.dependOn(&driver_test_run.step);

Since this is slightly unintuitive, it'd be nice to have direct support for this from within the MicroZig framework.