Pub main fn changes and accessing env vars in tests

Good afternoon all, I know that the recent changes on master have introduced a new way of accessing env vars, which I really like the design, but also I am unsure as to where I’m supposed to access env vars now in tests. Where before I could use posix or the windows equivalent in a test I don’t know how I am supposed to access them now.

I understand that checking for an ENV var in a test is not the best usage of tests, but it really simplifies something I am working on at the moment to be able to quickly run tests. Thanks.

this sounds like potentially an X–Y problem to me. Given that it’s unlikely that you’re testing getting env vars, maybe a different solution to your real problem is worth exploring?

2 Likes

In specific I have created an interface that abstract over creating a client to connect to something in this case a Unix Socket, the location of which is read from an env var (Wayland in specific) there are other env vars that in order to test my interface I simply swap out the implementation which resolves specific socket paths or urls, or really any type of connection. The tests originally failed with a specific error that the Var could not be located, and if the client failed for another reason a different but specific error.

In general this just helped me test that each implementation continued to work and if it failed for env var related problem that could be conveyed. Also I just don’t like hard coding in env vars in the tests even though the vars are stable.

it sounds like you’re wanting to do an end-to-end test as opposed to a unit test. that’s great, but you might consider creating a separate b.addTest in your build.zig file from your unit tests. this has the advantage of, for instance, allowing you to explicitly add the environment variables the build runner sees to the environment that the test sees. i’m pretty sure (based on your example) that the normal test runner does not do this.