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=Truewhen you want to catch unexpected passes can hide problems. - Marking tests as xfail without a clear
reasonmakes it hard to track why they are expected to fail. - Using
@pytest.mark.xfailon 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
| Parameter | Description | Default |
|---|---|---|
| reason | Explanation why test is expected to fail | None |
| strict | Fail test if it unexpectedly passes | False |
| run | Whether to run the test or skip it | True |
| raises | Exception type expected to cause failure | None |
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.