0
0
PytestHow-ToBeginner ยท 3 min read

How to Use @pytest.mark.xfail to Mark Expected Failures

Use @pytest.mark.xfail to mark a test that is expected to fail. This tells pytest to not count the failure as a test error but as an expected failure, helping track known issues without breaking the test suite.
๐Ÿ“

Syntax

The @pytest.mark.xfail decorator is placed above a test function to mark it as expected to fail. You can add optional parameters like reason to explain why the test is expected to fail, and strict to control if an unexpected pass should cause a failure.

python
import pytest

@pytest.mark.xfail(reason="Feature not implemented yet", strict=False)
def test_example():
    assert False
๐Ÿ’ป

Example

This example shows a test marked with @pytest.mark.xfail. The test asserts False, so it fails, but pytest reports it as an expected failure, not a test error.

python
import pytest

@pytest.mark.xfail(reason="Bug #123 not fixed")
def test_bug():
    assert False

@pytest.mark.xfail(strict=True, reason="Feature incomplete")
def test_feature():
    assert True  # This will cause pytest to fail because strict=True and test passed
Output
test_example.py::test_bug xfail Bug #123 not fixed test_example.py::test_feature XPASS Feature incomplete =========================== short test summary info =========================== XFAIL test_example.py::test_bug XPASS test_example.py::test_feature ========================= 1 xfailed, 1 xpassed in 0.01s ==========================
โš ๏ธ

Common Pitfalls

  • Not using strict=True when you want to catch unexpected passes can hide problems.
  • Marking tests as xfail without a clear reason makes it hard to track why they are expected to fail.
  • Using @pytest.mark.xfail on tests that should pass can cause confusion in test reports.
python
import pytest

# Wrong: no reason given
@pytest.mark.xfail
def test_wrong():
    assert False

# Right: reason provided
@pytest.mark.xfail(reason="Waiting for bug fix")
def test_right():
    assert False
๐Ÿ“Š

Quick Reference

ParameterDescriptionDefault
reasonExplanation why test is expected to failNone
strictFail test if it unexpectedly passesFalse
runWhether to run the test or skip itTrue
raisesException type expected to cause failureNone
โœ…

Key Takeaways

Use @pytest.mark.xfail to mark tests expected to fail without breaking the test suite.
Always provide a clear reason to track why a test is marked xfail.
Set strict=True to catch unexpected passes as test failures.
xfail tests still run by default unless run=False is set.
Use xfail to manage known bugs or incomplete features during development.