Image

Daniel Roy Greenfeld: TIL: Setting environment variables for pytest

When writing tests in pytest, often there's a need to set environment variables for your tests. Instead of modifyingos.environdirectly, which can lead to side effects and make tests harder to manage, here's how to do it with thepytest-envpackage.

First, install the package.

A lot of people usepytest.inito configure pytest, but I prefer usingpyproject.tomlfor a more modern approach. Here's how you can set environment variables inpyproject.toml:

Then run your tests just like you would normally do, and now the environment variable will be picked up by whatever test or code is looking for it. That's correct, you don't need to do any further configuration.

Since a lot of API SDK libraries use environment variables for configuration, this is a great way to ensure your tests run in a controlled environment. Either with mock replies or against a test instance of the service.

https://daniel.feldroy.com/posts/til-2025-09-setting-environment-variables-for-pytest