0
0
PytestHow-ToBeginner ยท 3 min read

How to Use pyproject.toml for Pytest Configuration

You can configure pytest by adding a [tool.pytest.ini_options] section in your pyproject.toml file. This lets you set pytest options like markers, test paths, and addopts in a clean, centralized way without needing a separate pytest.ini file.
๐Ÿ“

Syntax

The pyproject.toml file uses the [tool.pytest.ini_options] table to specify pytest configuration options. Each pytest setting is written as a key-value pair under this section.

  • addopts: Additional command line options as a string.
  • testpaths: List of directories or files where pytest looks for tests.
  • markers: List of custom markers with descriptions.
  • python_files: Glob patterns for test file names.
toml
[tool.pytest.ini_options]
addopts = "-ra -q"
testpaths = ["tests"]
markers = ["slow: marks tests as slow"]
python_files = ["test_*.py", "*_test.py"]
๐Ÿ’ป

Example

This example shows a pyproject.toml file configuring pytest to run tests quietly, look for tests in the tests folder, and define a custom marker slow.

toml
[tool.pytest.ini_options]
addopts = "-ra -q"
testpaths = ["tests"]
markers = ["slow: marks tests as slow"]
python_files = ["test_*.py", "*_test.py"]
โš ๏ธ

Common Pitfalls

Common mistakes when using pyproject.toml for pytest:

  • Not using the correct section header [tool.pytest.ini_options] causes pytest to ignore the config.
  • Writing options in the wrong format, e.g., using a string instead of a list for testpaths.
  • Forgetting to restart pytest or your IDE after changing pyproject.toml.
  • Using deprecated options that pytest no longer supports.

Example of wrong vs right:

toml
# Wrong: missing [tool.pytest.ini_options] header
[testpaths]
paths = ["tests"]

# Right:
[tool.pytest.ini_options]
testpaths = ["tests"]
๐Ÿ“Š

Quick Reference

OptionDescriptionExample
addoptsExtra command line options"-ra -q"
testpathsDirectories or files to search for tests["tests"]
markersCustom test markers with descriptions["slow: marks tests as slow"]
python_filesGlob patterns for test file names["test_*.py", "*_test.py"]
โœ…

Key Takeaways

Use the [tool.pytest.ini_options] section in pyproject.toml to configure pytest.
Write pytest options as key-value pairs with correct types (strings or lists).
Restart pytest or your IDE after changing pyproject.toml to apply settings.
Avoid deprecated pytest options and always check syntax carefully.
pyproject.toml centralizes config and removes the need for pytest.ini files.