如何配置tox工具以生成wheel包并基于该包开展测试?
Alright, let's tackle this. Tox's default behavior of using python setup.py sdist works for basic scenarios, but switching to wheel packages makes your tests align better with how real users will install and use your code. Here's a step-by-step breakdown to set this up properly:
Step 1: Disable Tox's Default Source Distribution Generation
First, we need to turn off Tox's automatic source package creation. Add this to your tox.ini under the [tox] section:
[tox] envlist = py38, py39, py310 # Adjust to your target Python versions skipsdist = true
The skipsdist = true flag tells Tox not to run its default sdist command, so we can replace it with our wheel-building workflow.
Step 2: Configure Wheel Generation and Test Installation
Next, update the [testenv] section to define how to build the wheel and install it for testing. We'll use the command you referenced (python setup.py bdist_wheel --universal) and ensure Tox tests against the installed wheel instead of a development copy:
[testenv] # Install dependencies needed to build wheels and run tests deps = wheel pytest # Replace with your test runner (e.g., unittest, nose) # Command to build a universal wheel (compatible with py2/py3) package_command = python setup.py bdist_wheel --universal # Tell Tox to install the generated wheel instead of source code install_command = pip install {envtmpdir}/dist/*.whl {opts} {packages} # Your test execution command here commands = pytest tests/ # Adjust to your test directory/command
Key Details:
wheelis added todepsto ensure thebdist_wheelcommand is available (it’s part of the official wheel package).- Omit the
--universalflag if you only target modern Python 3 versions—this creates a Python-version-specific wheel instead. - The
{envtmpdir}variable points to Tox's temporary environment directory, so each test environment gets a fresh, isolated install of your wheel.
Modern Alternative (PEP 517/518 Compliant)
If you're using pyproject.toml (the modern standard for Python packaging) instead of relying solely on setup.py, use the official build module for more standardized wheel creation. Update the package_command and deps like this:
[testenv] deps = build pytest package_command = python -m build --wheel # ... keep the rest of your testenv config the same
Verify the Setup
Run tox as usual—you’ll see Tox build the wheel first, install it into each test environment, then run your tests against that installed wheel. This ensures your tests reflect exactly how end-users will interact with your package.
内容的提问来源于stack exchange,提问作者Pablo

