Using Tox for Python Package Testing and Continuous Integration
This article introduces Tox as a virtualenv manager and command‑line testing tool for Python, explains how to install it, set up a simple project with test and setup files, configure tox.ini, run tests across multiple Python versions, and customize environments for advanced usage.
Reading font
Tox is a standard virtualenv manager and command‑line testing tool for Python that can verify package installation across different Python versions, run test code in isolated environments, and serve as a front‑end for continuous‑integration servers to reduce testing time. pip install tox installs the tool.
Before using Tox, ensure that the required Python interpreters (e.g., 2.7, 2.6, 3.3, 3.4, PyPy) are installed on the system.
Assume a project hello_tox containing test_hello.py and setup.py:
def test_hell():
print 'hello'from setuptools import setup
setup(
name="test_tox",
script=['test_hello'],
)Create a tox.ini file in the project root (same directory as setup.py) with the following content:
# content of: tox.ini , put in same dir as setup.py
[tox]
# Python versions to test
envlist = py27,py34
[testenv]
# Install dependencies
deps = pytest
# Commands to run tests
commands = py.testThe directory structure becomes:
.
├── setup.py
├── test_hello.py
└── tox.ini
0 directories, 3 filesRunning tox executes the tests in both environments, showing a successful run for Python 2.7 and a syntax error for Python 3.4 because the test script uses Python 2 print syntax.
Advanced usage includes defining custom environments such as py26-webpy (Python 2.6 + web.py) and py33-bottle (Python 3.3 + bottle). The tox.ini is extended to declare a base environment and specific testenv sections:
[tox]
envlist = py26-webpy,py33-bottle
[testenv]
commands = py.test
[base]
deps = pytest
[testenv:py26-webpy]
basepython = python2.6
deps =
{[base]deps}
web.py
[testenv:py33-bottle]
basepython = python3.3
deps =
{[base]deps}
bottleAfter updating test_hello.py to import the required libraries, running tox again demonstrates how missing dependencies (e.g., bottle) cause import errors, while successful environments run the tests.
For further details and additional use cases, refer to the official Tox documentation.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.