# Unable to run test that uses import outside current directory?

**URL:** <https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286>\
**Category:** Help\
**Tags:** build-system\
**Created:** [February 17, 2024, 3:15pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286 "2024-02-17T15:15:31Z")\
**Posts on this page:** 19\
**Page:** 1

<div class="post-metadata">

**Author:** ![ricknijhuis](https://ziggit.dev/user_avatar/ziggit.dev/ricknijhuis/32/1402_2.png) [@ricknijhuis](https://ziggit.dev/u/ricknijhuis)\
**Post date:** [February 17, 2024, 3:15pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/1 "2024-02-17T15:15:31Z")

</div>

Let’s say I have the following dir structure:

```zig
src
 |
 +-- root.zig
 |    
 +-- dep
    |  
    +-- dep.zig

```

In dep.zig I import root.zig for a function declared in there.  
If I now run `zig test src/dep/dep.zig` I get the following

> error: import of file outside module path ‘…/root.zig’

This is an oversimplified sample but as far as I can see is that as soon as you have an import outside of the directory of the file you want to test than it will fail.

Is this an issue with my setup or a limitation of the zig test command? And is there a way arround this?

`zig build test` works fine in this case but sometimes it can be nice to be able to test some code eventhough the overal build would fail because of some unrelated code.

---

<div class="post-metadata">

**Author:** ![dee0xeed](https://ziggit.dev/letter_avatar_proxy/v4/letter/d/3ab097/32.png) [@dee0xeed](https://ziggit.dev/u/dee0xeed)\
**Post date:** [February 17, 2024, 3:27pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/2 "2024-02-17T15:27:23Z")

</div>

Maybe upper dir notation (`..`) will fix your problem?

```zig
const root = @import("../root.zig");

```

---

<div class="post-metadata">

**Author:** ![ricknijhuis](https://ziggit.dev/user_avatar/ziggit.dev/ricknijhuis/32/1402_2.png) [@ricknijhuis](https://ziggit.dev/u/ricknijhuis)\
**Post date:** [February 17, 2024, 3:36pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/3 "2024-02-17T15:36:33Z")

</div>

That’s exactly what I’m doing, this is the code in dep.zig:

```zig
const root = @import("../root.zig");

test "test" {
    root.functionToTest();
}

```

---

<div class="post-metadata">

**Author:** ![dee0xeed](https://ziggit.dev/letter_avatar_proxy/v4/letter/d/3ab097/32.png) [@dee0xeed](https://ziggit.dev/u/dee0xeed)\
**Post date:** [February 17, 2024, 3:47pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/4 "2024-02-17T15:47:33Z")

</div>

Ok, then the question - why place a test of a thing below a dir where that thing is located?

---

<div class="post-metadata">

**Author:** ![ricknijhuis](https://ziggit.dev/user_avatar/ziggit.dev/ricknijhuis/32/1402_2.png) [@ricknijhuis](https://ziggit.dev/u/ricknijhuis)\
**Post date:** [February 17, 2024, 4:06pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/5 "2024-02-17T16:06:18Z")

</div>

Its just an oversimplified sample, the same happens with the following code:

```zig
const root = @import("../root.zig");

fn functionToTest() void {
    const i = root.functionToTest();

    // do something with i
    _ = i; // autofix
}

test "test" {
    functionToTest();
}

```

I think this is a somewhat standard usecase right? your code can have dependencies outside the current file, the issue is that as soon as one of those dependencies is outside the same directory it goes wrong.

---

<div class="post-metadata">

**Author:** ![dee0xeed](https://ziggit.dev/letter_avatar_proxy/v4/letter/d/3ab097/32.png) [@dee0xeed](https://ziggit.dev/u/dee0xeed)\
**Post date:** [February 17, 2024, 4:06pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/6 "2024-02-17T16:06:58Z")

</div>

```plaintext
zig-lang/test$ tree
.
├── a
│ └── a.zig
├── b
│ └── b.zig
└── test.zig

2 directories, 3 files

```

test.zig:

```zig
const a = @import("a/a.zig").a;
const b = @import("b/b.zig").b;

test "a and b" {
    a();
    b();
}

```

a/a.zig:

```zig
const std = @import("std");

pub fn a() void {
    std.debug.print("{s}", .{"a"});
}

```

b/b.zig:

```zig
const std = @import("std");

pub fn b() void {
    std.debug.print("{s}", .{"b"});
}

```

```zig
zig-lang/test$ zig test test.zig 
TeAll 1 tests passed.

```

TeAll? What was that? 🙂

---

<div class="post-metadata">

**Author:** ![ricknijhuis](https://ziggit.dev/user_avatar/ziggit.dev/ricknijhuis/32/1402_2.png) [@ricknijhuis](https://ziggit.dev/u/ricknijhuis)\
**Post date:** [February 17, 2024, 4:18pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/7 "2024-02-17T16:18:45Z")

</div>

Haha no idea 😃 , but in your sample the test does not depend on something in a parent dir. lets say you have a test defined in a.zig. and a.zig has a dependency on b.zig. in that case it will fail. And yes you could indeed than define the tests as you did in the parent dir but I prefer to have the tests close to the source otherwise test.zig can become very large. Here a sample using your code:

```zig
.
├── a
│ └── a.zig
├── b
│ └── b.zig
└── test.zig

2 directories, 3 files

```

test.zig

```zig
const std = @import("std");

pub const a = @import("a/a.zig");
pub const b = @import("b/b.zig");

test {
    @import("std").testing.refAllDecls(@This());
}

```

a/a.zig

```zig
const std = @import("std");
const b = @import("../b/b.zig");

pub fn a() void {
    b.b();
}

test "test" {
    a();
}

```

b/b.zig

```zig
const std = @import("std");

pub fn b() void {
    std.debug.print("{s}", .{"b"});
}

```

In this case test.zig is used to execute all tests but I would still like to be able to run the single test in a.zig, unfortunatly that is not possible. But indeed it can be a work around by for example defining tests\_a.zig next to tests.zig that contains the a specific tests. I just had hoped that would not be needed.

---

<div class="post-metadata">

**Author:** ![dee0xeed](https://ziggit.dev/letter_avatar_proxy/v4/letter/d/3ab097/32.png) [@dee0xeed](https://ziggit.dev/u/dee0xeed)\
**Post date:** [February 17, 2024, 4:33pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/8 "2024-02-17T16:33:20Z")

</div>

> [@ricknijhuis](#):
>
> Haha no idea

Off topic:

> **there was an update yesterday (Linux Mint 21.3)**
>
> ```zig
> grep language-pack-en /var/log/dpkg.log
> 2024-02-16 20:51:46 upgrade language-pack-en:all 1:22.04+20230801 1:22.04+20240212
> 2024-02-16 20:51:46 status half-configured language-pack-en:all 1:22.04+20230801
> 2024-02-16 20:51:46 status unpacked language-pack-en:all 1:22.04+20230801
> 2024-02-16 20:51:46 status half-installed language-pack-en:all 1:22.04+20230801
> 2024-02-16 20:51:46 status unpacked language-pack-en:all 1:22.04+20240212
> 2024-02-16 20:51:46 upgrade language-pack-en-base:all 1:22.04+20230801 1:22.04+20240212
> 2024-02-16 20:51:46 status half-configured language-pack-en-base:all 1:22.04+20230801
> 2024-02-16 20:51:47 status unpacked language-pack-en-base:all 1:22.04+20230801
> 2024-02-16 20:51:47 status half-installed language-pack-en-base:all 1:22.04+20230801
> 2024-02-16 20:51:47 status unpacked language-pack-en-base:all 1:22.04+20240212
> 2024-02-16 20:51:48 configure language-pack-en:all 1:22.04+20240212 <none>
> 2024-02-16 20:51:48 status unpacked language-pack-en:all 1:22.04+20240212
> 2024-02-16 20:51:48 status half-configured language-pack-en:all 1:22.04+20240212
> 2024-02-16 20:51:48 status installed language-pack-en:all 1:22.04+20240212
> 2024-02-16 20:51:48 configure language-pack-en-base:all 1:22.04+20240212 <none>
> 2024-02-16 20:51:48 status unpacked language-pack-en-base:all 1:22.04+20240212
> 2024-02-16 20:51:48 status half-configured language-pack-en-base:all 1:22.04+20240212
> 2024-02-16 20:51:49 status installed language-pack-en-base:all 1:22.04+20240212
> 
> ```

Maybe this is the reason for that `TeAll`, one never knows ☹

---

<div class="post-metadata">

**Author:** ![Sze](https://ziggit.dev/user_avatar/ziggit.dev/sze/32/496_2.png) [@Sze](https://ziggit.dev/u/Sze)\
**Post date:** [February 17, 2024, 5:14pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/9 "2024-02-17T17:14:47Z")

</div>

The way I see it, in Zig we are sort of building pyramids, the lowest layer has access to everything above it, next layer up has access to everything above it and so on.

Then you can use modules to refer to the base layer of another pyramid.  
Basically if something needs to be accessed from multiple files, it should have a common parent directory and be at the same level or below the file that refers to it.

In this analogy, this prevents us from building inverted pyramids where layers higher up get bigger and wider, it is a sort of loose ordering on how things can be organized.

Personally it took a bit to get used to, but now I appreciate that I don’t have to follow crazy redirecting relative imports that send me to crazy places all over the place in that folder structure. One of the good things about it is that folders can be seen as sub units in some sense.

---

<div class="post-metadata">

**Author:** ![ricknijhuis](https://ziggit.dev/user_avatar/ziggit.dev/ricknijhuis/32/1402_2.png) [@ricknijhuis](https://ziggit.dev/u/ricknijhuis)\
**Post date:** [February 17, 2024, 8:47pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/10 "2024-02-17T20:47:37Z")

</div>

I like this analogy, thanks! Though I am already running into something that I am not sure how to solve in this particular way.

For example, If I would work on some cross platform code to create windows for example. Using you analogy I would have the following file structure:

```zig
├── linux
│ └── native_window.zig
├── win32
│ └── native_window.zig
└── window.zig

```

Here window.zig would contain the general interface that contains a native\_window as member for example:

window.zig

```zig
const NativeWindow = switch (builtin.os.tag) {
    inline .windows => @import("win32/native_window.zig").NativeWindow,
    inline .linux => @import("linux/native_window.zig").NativeWindow,
    else => {
        @compileError("Platform not supported");
    },
};

pub const Window = struct {
    pub const Mode = enum {
        fullscreen,
        borderless,
        windowed,
    };

    native: NativeWindow,
    mode: Mode,

    pub fn init(mode: Mode) !Window {
        var self = Window{
            .mode = mode
        };
        
        self.native = NativeWindow.init(mode);
    }
};

```

win32/native\_window.zig

```zig
pub const NativeWindow = struct {
    pub fn init(mode: Mode) !NativeWindow {
        return NativeWindow{};
    }
};

```

How would I get access to the enum Mode in my native window? Using your anology I would need to declare Mode in win32/native\_window.zig but that would mean I would need to redeclare it for all platforms.

I could remove the platform specific directory and call it win32\_window.zig or something but I would like to be able to organize it in some way.

---

<div class="post-metadata">

**Author:** ![Sze](https://ziggit.dev/user_avatar/ziggit.dev/sze/32/496_2.png) [@Sze](https://ziggit.dev/u/Sze)\
**Post date:** [February 18, 2024, 1:04am UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/11 "2024-02-18T01:04:28Z")

</div>

I searched my code base and there is one place where I actually use `..` to navigate in a deeper folder structure one level up to refer to a bunch of types that are common to a bunch of different files. I guess there are places where the analogy fails.

I think the problem might be that the `zig test` command doesn’t seem to have support for being used for projects with more complex imports, I think you need to use a custom build step to define your test run similar to this (but for testing instead of docs) [Zig Autodoc : exclude anonymous imports? - #2 by dimdin](https://ziggit.dev/t/zig-autodoc-exclude-anonymous-imports/3276/2)  
Basically I think the `zig test` command is only for simple cases, for more complex ones define a build step that does the testing.

I don’t quite know how the `zig test` command determines the root of the module, you also could try calling it from a parent directory, but I am not sure if that works.  
Have you tried `cd src` and the `zig test dep/dep.zig` so that theoretically the command may have the same root directory?

I just know that I had cases where I gave up trying to use `zig test` and then just used testing via a build system run step.

---

<div class="post-metadata">

**Author:** ![FObersteiner](https://ziggit.dev/user_avatar/ziggit.dev/fobersteiner/32/1177_2.png) [@FObersteiner](https://ziggit.dev/u/FObersteiner)\
**Post date:** [February 18, 2024, 2:09pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/12 "2024-02-18T14:09:39Z")

</div>

> [@ricknijhuis](#):
>
> How would I get access to the enum Mode in my native window? Using your anology I would need to declare Mode in win32/native\_window.zig but that would mean I would need to redeclare it for all platforms.

Why do you want to have platform-specific code in subdirectories? I see it uses non-platform-specific code `Mode`, so the separation seems broken already? Maybe an interface is something you could consider here? Not sure though if that solves the problem you have in mind.

Concerning testing (and since my question on autodoc was mentioned - which is not related to a directory structure btw.), I really like to configure and call specific tests via steps in the build.zig. That way, you can for example use library code in a test just like an application would use it. A nice side effect is that you can put your tests in separate files in a separate directory 😉

---

<div class="post-metadata">

**Author:** ![prashanthsp6498](https://ziggit.dev/user_avatar/ziggit.dev/prashanthsp6498/32/3220_2.png) [@prashanthsp6498](https://ziggit.dev/u/prashanthsp6498)\
**Post date:** [August 22, 2024, 3:59pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/13 "2024-08-22T15:59:23Z")

</div>

Consider directory structure like this

```zig
.
├── logger
│ └── logger.zig
├── main.zig
├── scanner.zig
├── test
│ └── token_test.zig
├── tokens
│ ├── tokens.zig
│ └── token.zig
└── utils
    └── objects.zig

```

Now, if i want to access `tokens.zig` and `token.zig` in `token_test.zig` i will end up with “can’t import outside module path” how to handle this.

I am new to zig and trying to understand how this works.

---

<div class="post-metadata">

**Author:** ![dimdin](https://ziggit.dev/user_avatar/ziggit.dev/dimdin/32/1457_2.png) [@dimdin](https://ziggit.dev/u/dimdin)\
**Post date:** [August 22, 2024, 4:29pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/14 "2024-08-22T16:29:07Z")

</div>

Hello @prashanthsp6498  
Welcome to ziggit 🙂

Possible solutions:

1. Move the test folder into tokens folder and use `@import("../token.zig")`.
2. Move token\_test.zig from test folder to tokens folder and use `@import("token.zig")`.
3. Move your tests inside `token.zig` (no need to import anything).
4. Use [createModule](https://ziglang.org/documentation/master/std/#std.Build.createModule) to create a `token` module with `.root_source_file = "tokens/token.zig"` then you can use `@import("token")`. See: [Importing by module or source file](https://ziggit.dev/t/style-question-importing-by-module-or-source-file/5569/5)

---

<div class="post-metadata">

**Author:** ![taylorh140](https://ziggit.dev/user_avatar/ziggit.dev/taylorh140/32/4007_2.png) [@taylorh140](https://ziggit.dev/u/taylorh140)\
**Post date:** [December 19, 2024, 11:51pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/15 "2024-12-19T23:51:40Z")

</div>

I feel like zig test should take an argument that is the main.zig/root.zig so it can include items in the same way the build would. The suggestions here feel like a bandaid.  
More baindaids, I would use test but that means:

- Moving test cases to the root folder.
- Marking items as public that would not typically be pubilc to support test cases.
- Moving items included from a sibling folder into the same folder, to make some of the test work, or worse making a copy.

I believe that the proper solution would be more akin to zig test accepting a root file:  
`zig test ./token_test.zig --test_root=main.zig`

I’m curious if anyone disagrees.

---

<div class="post-metadata">

**Author:** ![taylorh140](https://ziggit.dev/user_avatar/ziggit.dev/taylorh140/32/4007_2.png) [@taylorh140](https://ziggit.dev/u/taylorh140)\
**Post date:** [December 20, 2024, 4:49pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/16 "2024-12-20T16:49:35Z")

</div>

This program can execute such test as if the file was in the root.  
test.zig:

```zig
const std = @import("std");

fn replaceBackslashes(path: []u8) void {
    for (path) |*c| {
        if (c.* == '\\') c.* = '/';
    }
}

pub fn main() !void {

    // Get allocator
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();
    defer _ = gpa.deinit();

    // Parse args into string array (error union needs 'try')
    const args = try std.process.argsAlloc(allocator);
    defer std.process.argsFree(allocator, args);

    // Generate a temporary filename with a `.zig` extension
    const temp_file = "testTemp_zzqqzzq.zig";

    const file_path = try std.fs.cwd().createFile(temp_file, .{});
    defer {
        std.fs.cwd().deleteFile(temp_file) catch unreachable;
        file_path.close();
    }

    replaceBackslashes(args[1]);

    // Write content to the file
    try file_path.writer().print(
        \\comptime {{
        \\_ = @import("{s}");
        \\}}
    ,
        .{args[1]},
    );

    const argv = [_][]const u8{ "zig", "test", temp_file };
    var child = std.process.Child.init(&argv, std.heap.page_allocator);
    try child.spawn();
    _ = try child.wait();
}

```

It works by generating a temporary file with the item that your interested in testing in a comptime block.

testTemp\_zzqqzzq.zig:

```zig
comptime {
    _ = @import("./test/token_test.zig");
}

```

and then runs

```zig
zig test ./testTemp_zzqqzzq.zig

```

which includes the test of interest

it deletes the file when it’s done. this is more of a proof of concept than a polished thing.

to use it just make an exe from the file above and run in the project root.  
`test.exe ./test/token_test.zig `

---

<div class="post-metadata">

**Author:** ![aidan](https://ziggit.dev/user_avatar/ziggit.dev/aidan/32/4039_2.png) [@aidan](https://ziggit.dev/u/aidan)\
**Post date:** [May 6, 2025, 2:52pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/17 "2025-05-06T14:52:20Z")

</div>

I don’t really see this as a helpful approach in a lot of contexts.

In my own use case I have types defined in my root, then many functions that return/take that type. Because of this I want to organize my functions into nested directories. To build a pyramid like you’re describing would require duplicating the types for each directory.

---

<div class="post-metadata">

**Author:** ![Sze](https://ziggit.dev/user_avatar/ziggit.dev/sze/32/496_2.png) [@Sze](https://ziggit.dev/u/Sze)\
**Post date:** [May 6, 2025, 4:29pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/18 "2025-05-06T16:29:12Z")

</div>

> [@aidan](#):
>
> To build a pyramid like you’re describing would require duplicating the types for each directory.

> [@Sze](#):
>
> I searched my code base and there is one place where I actually use `..` to navigate in a deeper folder structure one level up to refer to a bunch of types that are common to a bunch of different files. I guess there are places where the analogy fails.

Also it was never meant as a hard rule, just to describe the tendency that smaller deeper parts get accumulated into bigger namespaces that are closer towards the root until the root combines it into the thing that can be imported as a module.

Even if the import access patterns can’t be categorized in some strict way, personally I still find it helpful to think of it as pyramids, for example it helps with the “files can only be part of a single module”.

But I guess analogies are always hit and miss to some degree and helpful for some and not helpful for others.

---

<div class="post-metadata">

**Author:** ![aidan](https://ziggit.dev/user_avatar/ziggit.dev/aidan/32/4039_2.png) [@aidan](https://ziggit.dev/u/aidan)\
**Post date:** [May 6, 2025, 5:01pm UTC](https://ziggit.dev/t/unable-to-run-test-that-uses-import-outside-current-directory/3286/19 "2025-05-06T17:01:16Z")

</div>

That’s fair and I agree that can definitely be a good structure to follow! I was just adding this to supplement that there are plenty of legitimate use cases where a `zig test` that allows navigating up would be useful.
