Sometimes tests should not run or are expected to fail. Built-in markers help control this easily.
0
0
Built-in markers (skip, skipif, xfail) in PyTest
Introduction
Skip a test that needs a feature not yet implemented.
Skip a test only on certain operating systems or Python versions.
Mark a test as expected to fail because of a known bug.
Temporarily skip tests that depend on external services that are down.
Avoid running slow tests during quick checks by skipping them.
Syntax
PyTest
import pytest @pytest.mark.skip(reason="reason text") def test_example(): assert True @pytest.mark.skipif(condition, reason="reason text") def test_conditional(): assert True @pytest.mark.xfail(condition=None, reason="reason text", strict=False) def test_expected_fail(): assert False
skip always skips the test with a reason.
skipif skips the test only if the condition is True.
xfail marks a test as expected to fail; it won't fail the test suite if it does.
Examples
This test will always be skipped with the reason 'Not ready yet'.
PyTest
import pytest @pytest.mark.skip(reason="Not ready yet") def test_skip(): assert 1 == 1
This test runs only if the platform is not Windows.
PyTest
import sys import pytest @pytest.mark.skipif(sys.platform == "win32", reason="Does not run on Windows") def test_skipif(): assert True
This test is expected to fail because of a known bug.
PyTest
import pytest @pytest.mark.xfail(reason="Bug #123") def test_xfail(): assert False
This test is expected to fail, but if it passes, pytest will mark it as an error because strict=True.
PyTest
import pytest @pytest.mark.xfail(strict=True, reason="Fix soon") def test_xfail_strict(): assert True
Sample Program
This script shows all three markers:
test_always_skipis always skipped.test_skipif_versionruns only if Python version is 3.8 or higher.test_expected_failureis expected to fail and won't break the test suite.test_xfail_strictis expected to fail but passes, so pytest will report an error because of strict=True.
PyTest
import sys import pytest @pytest.mark.skip(reason="Skipping this test always") def test_always_skip(): assert False @pytest.mark.skipif(sys.version_info < (3, 8), reason="Needs Python 3.8+") def test_skipif_version(): assert True @pytest.mark.xfail(reason="Known bug in feature") def test_expected_failure(): assert False @pytest.mark.xfail(strict=True, reason="Should fix soon") def test_xfail_strict(): assert True
OutputSuccess
Important Notes
Always provide a clear reason to explain why a test is skipped or expected to fail.
Use skipif for conditions like OS, Python version, or missing dependencies.
With xfail(strict=True), a passing test will cause pytest to fail, helping track bug fixes.
Summary
Built-in markers help control test execution flow simply.
skip always skips, skipif skips conditionally, xfail marks expected failures.
Use them to manage tests during development and known issues.