Organizing Tests

Hello all, I am very new to Zig and I was wondering how people are organizing their tests suites. I have looked around in other people’s repos as well as the std lib and I have cribbed this approach of structuring the tests for my toy project.

  • I write my tests in the same code as the respective module files
  • Then I create a test-suite.zig module and import all my .zig files into a test inside this module
  • Add the test-suite in the build so that I can execute zig build test and it will run all my tests

I really like this approach and it is almost as powerful as Rust’s cargo test, with the exception that I might forget to include a module in my test suite. How is everyone else doing it?

If you’re worried about missing something, placing a

comptime {
    std.testing.refAllDecls(@This());
}

block at the end of each of your files and then pointing tests at the entrypoint for the library will guarantee that a) every test in the project is run, because every file will be imported and b) you can catch any type confusion errors that you might not be explicitly testing.

2 Likes

Thank you, that sounds interesting but I need a little more explanation. The comment for refAllDecls in the stdlib says
/// Given a type, reference all the declarations inside, so that the semantic analyzer sees them. What is this all about? :smiley:

Also what do you mean by “pointing the tests at the entrypoint for the library”. Is this what I am doing by creating one test-suite.zig file and importing the other tests?

refAllDecls basically iterates over every declaration in the file and does
_ = name;. This causes the zig compiler to mark it as used and not entirely remove it before running your tests.

By pointing it at the entrypoint I mean whatever file you use when calling addPackage. In your case, the entrypoint is in zigimg/zigimg at zigimg.zig.

That way you can make sure that tests are going to be somewhere near the code that they’re testing.

1 Like