Skip to content

What it is

tox is a Python tool for automated testing in multiple environments. It allows developers to run tests across different Python versions and dependency configurations, ensuring compatibility and reliability.

tox automates creating virtual environments, installing dependencies, running tests, and reporting results. It reads configuration from a `tox.ini` file where you define environments, dependencies, and test commands.

Installation

pip install tox

Getting started

The smallest useful thing you can do with it, and what each part means.

Creating a basic tox.ini
[tox]
envlist = py38, py39

[testenv]
deps = pytest
commands = pytest
Defines two environments (Python 3.8 and 3.9) that install pytest and run the test suite.
Running tox
# In terminal:
tox
Creates virtual environments for each Python version defined in `envlist` and runs the specified test commands.

Advanced usage

Where the library earns its place over a simpler alternative.

Specifying different dependencies per environment
[testenv:py38]
deps = pytest==6.2.5

[testenv:py39]
deps = pytest==7.0.0
Demonstrates how to install specific versions of dependencies for different Python versions.
Passing environment variables
[testenv]
setenv = DJANGO_SETTINGS_MODULE=myproject.settings
commands = pytest
Sets environment variables within the virtual environment before running tests.
Running multiple commands
[testenv]
deps = flake8
commands = flake8 src tests
           pytest
Runs linting with flake8 followed by pytest in the same environment.

Errors and fixes

The failures you are most likely to hit, and what actually resolves them.

InterpreterNotFound
Ensure the specified Python versions are installed and accessible in your PATH.
Dependency installation failed
Verify that dependencies are correctly specified and available on PyPI or other indexes.
Command failed
Check the command syntax and ensure all necessary dependencies are installed in the environment.

Best practices

  • Use tox to test your code against all supported Python versions.
  • Keep your `tox.ini` file simple and modular to avoid complexity.
  • Combine linting, testing, and coverage in tox environments.
  • Use `skip_missing_interpreters = true` to avoid failures if a Python version isn’t installed.
  • Integrate tox with CI/CD pipelines for automated testing.

Background

Why it exists, and what it was reacting to.

tox was created to standardize testing in Python projects and simplify the management of virtual environments for testing purposes. It is widely used in open-source projects to ensure that code runs correctly on multiple Python versions and environments.