Sub topic 14
Configuring pytest in pyproject.toml
This chapter assumes you can run pytest from a terminal and write tests with markers (@pytest.mark.slow). It also assumes you have a project with a pyproject.toml file or can create one. The goal is to move the options you type on every run into a file that every developer and every CI job shares.
Why configure pytest
Without configuration, pytest uses defaults. It searches from the current directory, collects any file named test_*.py or *_test.py, and reports only what its default output includes. That works for a small project. In a larger one you end up repeating command-line options, and people run the suite differently from each other.
A configuration file fixes that. It records:
- where tests live,
- which options are always on,
- which custom markers are allowed,
- how warnings are treated,
- which directories are added to the import path.
Where pytest looks for configuration
Pytest supports several file formats. It picks one configuration file (also called the ini-file) and uses its directory as the rootdir. The rootdir is where pytest stores its cache and builds test IDs.
| File | Used when |
|---|---|
| `pytest.ini` | It exists. It wins even if it is empty. |
| `pyproject.toml` | It contains a `[tool.pytest.ini_options]` table. |
| `tox.ini` | It contains a `[pytest]` section. |
| `setup.cfg` | It contains a `[tool:pytest]` section. |
Pytest checks them in that order, starting in the directory of the arguments you pass (or the current directory) and moving up through parent directories. The first match determines the rootdir.
Because a pytest.ini file always wins, a stray one in a parent directory can silently hide your pyproject.toml settings. You can check which file is active in the first lines of the output:
rootdir: /home/ada/shop
configfile: pyproject.toml
testpaths: testsIf configfile shows something you didn't expect, fix that before debugging anything else.
The pyproject.toml table
In pyproject.toml, all pytest settings go under [tool.pytest.ini_options]. The name is literal. A table called [tool.pytest] is not read by older pytest versions, and pytest then ignores it without any message.
[tool.pytest.ini_options]
minversion = "7.0"
testpaths = ["tests"]
addopts = "-ra --strict-markers"
pythonpath = ["src"]
markers = [
"slow: marks tests as slow (deselect with -m 'not slow')",
"integration: needs a real database",
]
filterwarnings = [
"error",
"ignore::DeprecationWarning:some_old_library.*",
]Each option does one job:
minversionmakes pytest stop with a clear error if the installed version is older than the one your tests need.testpathslists the directories pytest searches when you run it with no arguments. It has no effect when you pass paths explicitly, sopytest tests/unitstill runs onlytests/unit.addoptsis added to every command line. Write it as one string, exactly as you would type it.pythonpathadds directories tosys.path. This is useful for thesrc/layout, where the package isn't importable until it is installed.markersregisters custom markers. Each entry isname: description.filterwarningscontrols how warnings are handled during tests. The list uses the same syntax as Python's-Woption.
Choosing addopts
addopts is the most useful option and the easiest to misuse. Everything in it applies to every run, including runs on a colleague's machine and in CI.
Good candidates are options that make output more informative or catch mistakes:
-raprints a short summary of every outcome except passes (skips, expected failures, errors).--strict-markersturns an unregistered marker into an error.--strict-configturns unknown configuration keys into errors.--tb=shortshortens tracebacks.
Poor candidates are options you only want sometimes. Putting -x or --cov in addopts means every run stops at the first failure or pays the coverage cost. Keep those on the command line.
You can override addopts for one run with -o (--override-ini):
pytest -o addopts="" tests/test_cart.py
pytest -o addopts="-ra --tb=long"The first command drops all the configured defaults. The second replaces them. Use this when you want to check whether a default option is causing a problem.
Registering markers
Chapter 11 showed that a mistyped marker such as @pytest.mark.slwo is accepted silently. Pytest warns with PytestUnknownMarkWarning, but the test still runs and your -m "not slow" filter no longer excludes it. Registering markers in the markers list lets pytest recognize them. Adding --strict-markers then turns the typo into an error during collection.
# tests/test_reports.py
import pytest
@pytest.mark.slow
def test_full_report():
assert sum(range(1_000_000)) == 499999500000
def test_small_report():
assert sum(range(10)) == 45With the configuration above, these commands behave as follows:
pytest -m "not slow"
pytest --markersThe first deselects test_full_report. The second lists every registered marker, built-in and custom, with the descriptions from your file. That list also serves as documentation for new contributors.
Warnings as errors
Setting filterwarnings = ["error"] turns every warning raised during a test into a failure. This catches deprecated API use early, before an upgrade breaks it. The trade-off is that a new warning from a third-party library can break the whole suite after a dependency update. The usual approach is to start strict and add narrow ignore entries, each naming the warning category and module. Avoid a blanket ignore.
A single test can also opt in or out:
import warnings
import pytest
@pytest.mark.filterwarnings("ignore:old api:DeprecationWarning")
def test_legacy_call():
warnings.warn("old api", DeprecationWarning)
assert TrueCommon errors
- Settings seem ignored. Check the
configfile:line in the header. Apytest.iniortox.inihigher up, or a misspelled table name such as[tool.pytest], is the usual cause. ModuleNotFoundErrorfor your own package. Either install the project in editable mode (pip install -e .) or setpythonpath = ["src"].addoptswritten as a list. Write it as a string, for example"-ra -q". The list form is for options such astestpathsandmarkers.- Unknown config option warnings. A typo in a key name produces
PytestConfigWarning: Unknown config option. Add--strict-configso this fails the run instead. - Different results in CI. CI may run from another directory. Because pytest resolves the rootdir from the arguments, run it from the project root or pass the path explicitly.
Exercise
Your pyproject.toml has testpaths = ["tests"] and addopts = "-ra --strict-markers". You run pytest tests/unit -m "not slow" and get an error that says 'slow' not found in markers configuration option. What is wrong, and how do you fix it?
Show answer
The slow marker is used in a test but not registered, and --strict-markers turns that into an error. Add an entry to the markers list under [tool.pytest.ini_options], for example "slow: marks tests as slow (deselect with -m 'not slow')". The testpaths setting plays no part here, because explicit paths on the command line override it.
Exercise
Your configuration changes have no effect, and the pytest header shows configfile: pytest.ini, although you only edited pyproject.toml. Why, and what are two ways to resolve it?
Show answer
A pytest.ini file is found first and always takes precedence, even if it is empty, so pyproject.toml is never read. Either delete pytest.ini or move its settings into pyproject.toml, or put your settings in pytest.ini and stop using the pyproject.toml table.