How to set up a Python project with Poetry and pytest
Set up a Python project with Poetry and pytest: initialize the project, manage dependencies and a virtual environment, write tests, and run them with coverage.
What Poetry and pytest give you
Poetry manages Python dependencies and packaging through a single pyproject.toml, creating an isolated virtual environment automatically so projects do not pollute each other. pytest is the de facto Python testing framework: concise, with powerful fixtures and clear failure output. Together they give a clean, reproducible workflow.
Prerequisites
- Python 3.10 or later
- A terminal
Steps
1. Install and initialize Poetry
Install Poetry, then create a project.
pipx install poetry
poetry new mathlib
cd mathlib
This generates pyproject.toml, a package directory, and a tests directory.
2. Add dependencies
Runtime and development dependencies are tracked separately.
poetry add requests
poetry add --group dev pytest pytest-cov
3. Write code in a package
# mathlib/calc.py
def divide(a: float, b: float) -> float:
if b == 0:
raise ValueError("cannot divide by zero")
return a / b
4. Write pytest tests
pytest discovers files named test_*.py and functions starting with test_.
# tests/test_calc.py
import pytest
from mathlib.calc import divide
def test_divide():
assert divide(10, 2) == 5
def test_divide_by_zero():
with pytest.raises(ValueError):
divide(1, 0)
5. Run tests in the environment
Poetry runs commands inside the project's virtual environment.
poetry run pytest
6. Add coverage and fixtures
Measure coverage and share setup with fixtures.
poetry run pytest --cov=mathlib
Verification
Run poetry run pytest and confirm both tests pass. Break the divide function and confirm pytest reports the failing assertion with the expected and actual values. Run poetry install on a clean checkout to confirm the environment is reproducible.
Next Steps
Add parametrized tests with @pytest.mark.parametrize, configure pytest in pyproject.toml, add type checking with mypy, and run poetry run pytest in continuous integration.
Prerequisites
- Python 3.10+ installed
- Basic command line familiarity
Steps
- 1Install and initialize Poetry
- 2Add dependencies
- 3Write code in a package
- 4Write pytest tests
- 5Run tests in the environment
- 6Add coverage and fixtures