Skip or deselect a test in pytest

Use pytest skip and skipif markers, distinguish expected failures from skipped tests, and temporarily exclude a test by its node ID.

Best practices
Python programming and application logging

Use @pytest.mark.skip(reason="...") to keep a test visible in the suite while skipping execution. Use skipif for a condition, or --deselect when you want to exclude a test for one run without editing it.

Skip a test unconditionally

import pytest

@pytest.mark.skip(reason="Feature is being refactored")
def test_addition():
    assert 2 + 2 == 4

The test remains collected and is counted as skipped. Run python -m pytest -rs to include skip reasons in the short summary.

Skip on a condition

import sys
import pytest

@pytest.mark.skipif(sys.platform == "win32", reason="POSIX-only feature")
def test_posix_feature():
    assert sys.platform != "win32"

Use a condition that expresses the actual missing capability or unsupported environment. A test that exposes a known product bug often belongs under xfail instead.

Mark an expected failure

import pytest

@pytest.mark.xfail(reason="Known defect: issue 123", strict=True)
def test_edge_case():
    assert 2 + 2 == 5

By default, an xfail-marked test still executes. A failure becomes XFAIL; an unexpected success becomes XPASS. strict=True makes that unexpected success fail the suite, prompting removal or revision of the marker. With non-strict behavior, XPASS need not fail the run.

Exclude a test for one invocation

python -m pytest --deselect=test_math.py::test_addition

Deselecting removes that node from the selected test set; it is not reported as a skipped test. Use the exact node ID, including parameter identifiers when targeting a single parameterized case.

FAQ

Why not comment out the test? A skip leaves a visible count and reason. Commented-out tests disappear from collection entirely.

Can I skip a class or module? Apply the same marker to a class. For a module, assign pytestmark = pytest.mark.skip(reason="..."), or call pytest.skip("...", allow_module_level=True) at module scope when you must stop collection there.

Can the decision happen during a test? Yes. pytest.skip("Required service is unavailable") inside a test or fixture skips when execution reaches it. Use this for genuine prerequisites, not to conceal a failure the test should detect.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting