Configure pytest pythonpath for Monorepo
Rule
Configure pytest pythonpath in pyproject.toml to include all workspace package source directories when working in a monorepo structure.
Context
Pytest runs in its own execution context and cannot automatically discover workspace packages in a monorepo. Without explicit pythonpath configuration, pytest will fail to import local packages even when they are properly structured.
Detection
- Pytest fails with 'ModuleNotFoundError: No module named "
"' when running tests - Tests attempt to import from workspace packages (e.g., 'from mypkg import ...')
- Project has multiple packages under a packages/ directory structure
- No pythonpath configuration exists in pyproject.toml [tool.pytest.ini_options]
Pattern
Add pythonpath to pyproject.toml (list all workspace package src directories):
[tool.pytest.ini_options]
pythonpath = [
"packages/mypkg1/src",
"packages/mypkg2/src",
# add one entry per workspace package
]
After adding configuration:
# Tests should now find packages
uv run pytest tests/ -v
Outcome
- Tests pass: pytest finds all workspace packages
- Consistent behavior: Same imports work in tests and runtime
- Clear configuration: All paths documented in one place
Related
- Match mypy error codes - Related mypy configuration
- uv sync after workspace changes - Keeping packages installed