Sub topic 12
Testing the built package in a clean environment
This chapter assumes you can build an sdist and a wheel with python -m build, that you know how to create a virtual environment, and that you have read the earlier chapters on the src layout and pyproject.toml. Here you verify that the files in dist/ install and run on their own.
Why a clean install is a separate test
Your test suite passing does not prove the package works for users. Three problems commonly hide behind a green test run:
- Missing files. A data file or a subpackage exists in your working tree but was not included in the wheel.
- Missing dependencies. Your development environment has a library installed that you forgot to list in
dependencies. - Wrong entry points. The console script points to a function that does not exist, or the module path is misspelled.
An editable install (pip install -e .) or a run from the project directory reads your source tree. It can hide all three. A clean install reads only the built artifact, which is what your users get.
The src layout helps here. Because greeter lives under src/, running python from the project root does not put the package on sys.path. An import greeter succeeds only if the package is installed.
The verification loop
Always delete dist/ and rebuild after a fix. Otherwise old files stay next to the new ones, and you may test an old artifact without noticing.
Testing the wheel
The wheel is what most users install, so test it first. Use a new environment outside the project directory. These commands use the greeter example and Linux or macOS paths:
rm -rf dist/
python -m build
python -m venv /tmp/verify-wheel
/tmp/verify-wheel/bin/pip install dist/greeter-0.1.0-py3-none-any.whl
/tmp/verify-wheel/bin/greeter AdaThe expected output is Hello, Ada!. On Windows the interpreter and scripts live in Scripts\ instead of bin/, for example C:\temp\verify-wheel\Scripts\greeter.exe.
Running the script proves that pip installed the console script and that greeter.cli:main resolves. It does not prove that the library imports cleanly, so add an import check. Run it from a different directory so the current directory cannot supply the package:
cd /tmp
/tmp/verify-wheel/bin/python -c "import greeter; print(greeter.__version__, greeter.greet('Ada'))"The expected output is 0.1.0 Hello, Ada!. The version comes from importlib.metadata, so this line also confirms that the installed metadata matches pyproject.toml.
Testing the sdist
The sdist is a separate artifact. Installing it makes pip build a wheel from the archive, which exercises your build backend and the file list inside the sdist. This catches files that are in the wheel configuration but missing from the archive.
python -m venv /tmp/verify-sdist
/tmp/verify-sdist/bin/pip install dist/greeter-0.1.0.tar.gz
/tmp/verify-sdist/bin/greeter AdaPip builds in an isolated environment by default. It downloads the packages listed in build-system.requires, so this step needs network access, and it fails if requires is wrong or incomplete. That failure is useful: it is the same failure a user without a prebuilt wheel would see.
Running your tests against the installed package
A smoke test is good for a first check. A stronger check runs your real test suite against the installed wheel. Install the test extra from the wheel, and run pytest from a location where the source tree cannot be imported.
/tmp/verify-wheel/bin/pip install "greeter[test] @ file://$PWD/dist/greeter-0.1.0-py3-none-any.whl"
/tmp/verify-wheel/bin/python -m pytest tests/This also tests the extra: if [project.optional-dependencies] is misspelled, pip warns that the extra does not exist. Because of the src layout, pytest imports greeter from the environment. If the import fails, the package is not importable from the wheel, and that is a real bug.
Looking at what was installed
When a check fails, inspect the environment directly:
/tmp/verify-wheel/bin/pip show -f greeterThe -f flag lists every installed file. Compare it to what you expect. You should see greeter/__init__.py, greeter/cli.py, greeter/py.typed, the dist-info metadata directory, and the greeter script. Missing py.typed or a data file means the wheel configuration needs fixing.
Common failures and what they mean
| Symptom | Likely cause | Fix |
|---|---|---|
| `ModuleNotFoundError` for a third-party library | The library is missing from `dependencies` | Add it to `[project].dependencies` |
| `ModuleNotFoundError: greeter` after install | Wrong package discovery, or an empty wheel | Check the layout and the backend's package configuration |
| `greeter: command not found` | The venv's `bin/` is not on `PATH`, or `[project.scripts]` is missing | Call the script by full path, or fix the table |
| `ImportError` from the script | The entry point names a module or function that does not exist | Correct the `module:function` value |
| `PackageNotFoundError` on `__version__` | The package is imported from the source tree, not installed | Test from another directory in a clean venv |
| sdist install fails, wheel install works | A file is missing from the sdist, or `build-system.requires` is incomplete | Inspect the archive and fix the backend configuration |
Automating the check
Typing these commands for every release is error-prone. A short script makes the check repeatable. This version uses only the standard library and works on Linux and macOS:
# verify_dist.py
import subprocess
import sys
import tempfile
from pathlib import Path
def run(*cmd: str) -> str:
result = subprocess.run(cmd, check=True, capture_output=True, text=True)
return result.stdout.strip()
def verify(artifact: Path) -> None:
with tempfile.TemporaryDirectory() as tmp:
venv = Path(tmp) / "venv"
run(sys.executable, "-m", "venv", str(venv))
python = str(venv / "bin" / "python")
run(python, "-m", "pip", "install", str(artifact))
output = run(str(venv / "bin" / "greeter"), "Ada")
assert output == "Hello, Ada!", output
print(f"OK: {artifact.name}")
if __name__ == "__main__":
for path in sorted(Path("dist").glob("*")):
if path.suffix == ".whl" or path.name.endswith(".tar.gz"):
verify(path)Run it with python verify_dist.py from the project root. Each artifact gets its own fresh environment, and the environment is deleted afterwards. The same logic can run in continuous integration, which also lets you test on several Python versions and operating systems.
Limits of this check
A clean install on your own machine covers a lot, but not everything:
- It uses one Python version and one platform. A package that declares
requires-python = ">=3.9"should be tested on its oldest supported version at least once. - It resolves dependencies at today's versions. Your code may break with a new release of a dependency that you did not pin.
- It cannot show how PyPI renders your README. That is the job of
twine checkand the TestPyPI rehearsal in the next chapter.
Exercise
Your tests pass with pip install -e ., but a user reports ModuleNotFoundError: No module named 'requests' after installing your wheel. Why did your own checks miss it, and what do you change?
Show answer
Your development environment already had requests installed, and an editable install does not check the declared dependencies against a clean environment. Add requests to [project].dependencies in pyproject.toml, delete dist/, rebuild, and install the new wheel into a fresh virtual environment to confirm the import works.
Exercise
Why should the import check in the verification loop be run from a directory other than the project root, even with a src layout?
Show answer
A different working directory ensures the current directory cannot supply the package or its source files, so the import can succeed only if the package was really installed from the wheel. This guards against false passes caused by tools or configuration that add the project directory to sys.path.
Exercise
The wheel installs and runs, but installing the sdist fails during the build step. Name two causes to check.
Show answer
The build-system.requires list may be incomplete, so pip's isolated build environment lacks something the backend needs. A file needed for the build may also be missing from the sdist archive, which you can find by listing the .tar.gz contents.