brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: pytest --maxfail=2 stops the run after two failures

Python
~/tips/tip-python-pytest-maxfail-stop-early

pytest --maxfail=2

Stop a pytest run after a set number of failures instead of waiting for the whole suite.

When a change breaks something basic, a suite of a few hundred tests can fail in a few hundred ways, and the first couple of tracebacks are usually enough. --maxfail cuts the run short.

pytest --maxfail=2

The run ends as soon as the second failure is reported. With a small demo file of eight tests it looked like this:

FAILED test_demo.py::test_plain - assert (0.1 + 0.2) == 0.3
FAILED test_demo.py::test_fixed - [XPASS(strict)] 
!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 2 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!
2 failed, 2 passed, 1 xfailed in 0.02s

The short form -x is the same as --maxfail=1. Use -x while fixing one thing and a small number like 3 when you want a sample of the damage.

The caveat: the tests after the stop never run, so their failures stay invisible until you run the whole suite again. Errors during setup count as failures too, so a broken fixture can end the run early.

In a throwaway file with five tests, three of which fail, pytest -q --maxfail=2 prints stopping after 2 failures and ends with 2 failed, 1 passed, so the fifth test never ran. Pair it with --lf (rerun only the tests that failed last time) once you have fixed the first problem.

Further reading: How to invoke pytest

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest from functools import cached_property All Python tips (107) All topics

Link