PyTest - Environment Variables

You need to understand variable preference, how to override them, and how to ensure your tests are isolated from the local runtime environment.

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.

Terminal window
uv add --dev pytest-env

Configuration

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:

pyproject.toml
[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

Pending