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's xfail marker records a known bug without breaking the run

Python
~/tips/tip-python-pytest-xfail-strict-known-bugs

import pytest

Mark a failing test as xfail so it is reported but does not fail the suite.

Sometimes a test is right and the code is wrong, and the fix has to wait. Deleting the test hides the bug, and leaving it red hides everything else. @pytest.mark.xfail sits in between.

import pytest

@pytest.mark.xfail(reason="known bug #12")
def test_known_bug():
    assert 1 == 2

@pytest.mark.xfail(strict=True)
def test_fixed():
    assert True

Run with -rx to list the expected failures with their reasons:

XFAIL test_demo.py::test_known_bug - known bug #12
1 failed, 6 deselected, 1 xfailed in 0.02s

That run used -k to pick just these two tests. The first is counted as xfailed and does not fail the suite. The second would pass, and because of strict=True an unexpected pass is turned into a failure ([XPASS(strict)] in the output). That is what reminds you to remove the marker once the bug is fixed.

The caveat: without strict, an unexpected pass is reported as xpassed and the suite stays green, which is easy to miss. There is an xfail_strict ini option if you want strict everywhere.

You can narrow what counts as an expected failure with raises. With @pytest.mark.xfail(raises=ZeroDivisionError), a test that fails with a different exception, such as a plain AssertionError, is reported as a normal failure instead of xfailed. That keeps a marker from hiding a new, unrelated bug in the same test.

Further reading: Skip and xfail

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link