pytest-variables
pytest-variables is a plugin for pytest that provides a mechanism to supply external variables to tests and fixtures. It allows defining variables in various file formats (JSON, YAML, TOML, HJSON) and making them accessible as a dictionary fixture within your pytest test suite. The current version is 3.1.0, and it follows a regular release cadence with major versions indicating breaking changes.
Warnings
- breaking Version 3.1.0 dropped support for Python 3.7. Ensure your project uses Python 3.8 or newer.
- breaking Version 3.0.0 switched internal variable storage from `_variables` to `pytest.stash`. While not a public API, direct access to `_variables` will break.
- gotcha When multiple `--variables` files are specified, later files in the command line override values from earlier files if duplicate keys are encountered (for non-dictionary values). For dictionaries, they are merged.
- gotcha If using YAML files, the `yaml_loader` can be configured in `pytest.ini`. The loader name (e.g., `BaseLoader`, `SafeLoader`, `FullLoader`, `UnsafeLoader`) is case-sensitive. The default is `FullLoader`.
Install
-
pip install pytest-variables -
pip install pytest-variables[hjson] -
pip install pytest-variables[yaml] -
pip install pytest-variables[toml]
Imports
- variables
def test_example(variables):
Quickstart
# content of variables.json
{
"base_url": "https://api.example.com",
"api_key": "${API_KEY:default_key}"
}
# content of test_api.py
def test_api_endpoint(variables):
assert variables['base_url'] == 'https://api.example.com'
assert variables['api_key'] is not None
# Example of accessing an environment variable fallback:
import os
expected_api_key = os.environ.get('API_KEY', 'default_key')
assert variables['api_key'] == expected_api_key
# To run: pytest --variables variables.json
# You can also pass multiple files: pytest --variables file1.json --variables file2.yaml