You need to understand variable preference, how to override them, and how to ensure your tests are isolated from the local runtime environment.
On this page
Introduction
When writing Python code, you’ve likely used environment variables to pass configuration or other data to your code at runtime.
Specifying environment variables in Python is straightforward, but when it comes to testing, things can get a bit tricky.
So how do you define environment variables in Pytest? Should you use a .env file, fixtures, specify them for each test?
pytest-env
pytest-env is a plugin that allows you to define environment variables in a .env file.
The pytest-env package is a great way to define Environment Variables within your pytest.toml config file.
Let’s look at an example.
First, install the package.
uv add --dev pytest-envConfiguration
Many pytest settings can be set in a configuration file, which by convention resides in the root directory of your repository.
A quick example of the configuration files supported by `pytest:
Use [tool.pytest] to leverage native TOML types:
[tool.pytest]minversion = "9.0"addopts = ["-ra", "-q"]testpaths = [ "tests", "integration",]If you’re not familiar with config files please check out this article for a brief practical overview of the different Pytest config files.
pythonpath
4 Proven Ways To Define Pytest PythonPath and Avoid Module Import Errors