Automate a test that is expected to fail using @pytest.mark.xfail
Preconditions (2)
✅ Expected Result: The test is reported as xfailed (expected failure) by pytest, not as a failure or error
import pytest @pytest.mark.xfail def test_addition_expected_failure(): assert 1 + 1 == 3 if __name__ == "__main__": import sys import pytest sys.exit(pytest.main([__file__]))
The @pytest.mark.xfail decorator marks the test as an expected failure. This means pytest will run the test but will not count it as a failure if it fails. Instead, it will report it as 'xfailed'.
The test function test_addition_expected_failure asserts that 1 + 1 equals 3, which is false, so it will fail normally. But because of the @pytest.mark.xfail, pytest expects this failure.
The if __name__ == "__main__" block allows running the test file directly, which helps beginners run and see the test output easily.
Now add three test functions with different expected failures using @pytest.mark.xfail, each failing for a different reason.
@pytest.mark.xfail in a test?@pytest.mark.xfail with parentheses for parameters.strict=True means pytest will fail the test if it unexpectedly passes.@pytest.mark.xfail(strict=True)
def test_divide():
assert 1 / 0 == 0@pytest.mark.xfail(strict=True)
def test_sum():
assert sum([1, 2, 3]) == 5strict=True is needed.@pytest.mark.xfail(strict=True, reason='Flaky API') clearly documents the expected failure and enforces strict checking.Pass the test and this pattern moves unknown