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.
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 :
<code>def test_hell():
print 'hello'
</code> <code>from setuptools import setup
setup(
name="test_tox",
script=['test_hello'],
)
</code>Create a tox.ini file in the project root (same directory as setup.py ) with the following content:
<code># 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.test
</code>The directory structure becomes:
<code>.
├── setup.py
├── test_hello.py
└── tox.ini
0 directories, 3 files
</code>Running 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:
<code>[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}
bottle
</code>After 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.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.