Skip to content

Instantly share code, notes, and snippets.

@ssteinbach
Last active October 21, 2022 16:27
Show Gist options
  • Save ssteinbach/83e68e82828f0cd6d56bc1171d696833 to your computer and use it in GitHub Desktop.
Save ssteinbach/83e68e82828f0cd6d56bc1171d696833 to your computer and use it in GitHub Desktop.
Testing zig files in packages/subdirectories

Testing Zig Files in Packages/Subdirectories

Given a zig file file_with_test.zig in a subdirectory:

.
├── example_package
│   └── file_with_test.zig
└── outer_thing.zig

That references outer_thing.zig in the parent directory:

const std = @import("std");
const outer = @import("../outer_thing.zig");

fn taco(val: i32) i32 {
    return outer.value + val;
}

test "check outer value" {
    try std.testing.expectEqual(@as(i32, 14), taco(2));
    try std.testing.expectEqual(@as(i32, 12), outer.value);
}

and outer_thing.zig:

pub const value:i32 = 12;

test "all" {
    _ = @import("example_package/file_with_test.zig");
}

If you try and run zig test example_package/file_with_test.zig, you get an error:

❯ zig test example_package/file_with_test.zig
example_package/file_with_test.zig:2:23: error: import of file outside package path: '../outer_thing.zig'
const outer = @import("../outer_thing.zig");
                      ^~~~~~~~~~~~~~~~~~~~
referenced by:
    test.check outer value: example_package/file_with_test.zig:10:47
    remaining reference traces hidden; use '-freference-trace' to see all reference traces

To fix this and allow testing the file in the subdirectory, you need to pass --main-pkg-path:

❯ zig test example_package/file_with_test.zig --main-pkg-path .
All 2 tests passed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment