Skipping and Marking Tests in pytest
In pytest, markers provide a flexible way to categorize, skip, or conditionally execute tests. This capability allows you to focus on specific test cases or exclude certain tests based on context.
Marking Tests with @pytest.mark.<tag>
Markers are labels applied to test functions to group or categorize them. Custom markers can be defined for various use cases.
Example: Custom Marker
import pytest
@pytest.mark.slow
def test_long_running_process():
assert sum(range(1_000_000)) == 499999500000
Here, @pytest.mark.slow
tags the test as slow
. You can later run only the tests with this marker.
Running Tests with Specific Markers
To execute tests with a specific marker, use the -m
option:
pytest -m slow
Skipping Tests with @pytest.mark.skip
Sometimes you may need to skip a test that is not relevant in a certain context.
Example: Skipping a Test
@pytest.mark.skip(reason="This feature is under development.")
def test_unfinished_feature():
assert 1 + 1 == 3
This test will be skipped with the provided reason displayed in the output.
Output for Skipped Tests
Skipped tests are marked with s
in the pytest output:
s test_example.py::test_unfinished_feature - This feature is under development.
Conditional Skipping with @pytest.mark.skipif
You can skip tests conditionally based on certain conditions, such as the Python version or the operating system.
Example: Conditional Skipping
import sys
@pytest.mark.skipif(sys.version_info < (3, 9), reason="Requires Python 3.9 or higher.")
def test_python_version():
assert True
This test will only run if the Python version is 3.9 or higher.
Using Custom Markers
You can create custom markers for organizing tests.
Registering Custom Markers
To avoid warnings, register custom markers in pytest.ini
:
[pytest]
markers =
slow: marks tests as slow (deselect with '-m "not slow"')
database: marks tests that require database access
Example: Using Multiple Markers
@pytest.mark.slow
@pytest.mark.database
def test_complex_query():
assert fetch_data_from_database() == "expected_result"
Summary of Marker Usage
Marker | Description |
---|---|
@pytest.mark.<tag> | Custom marker to categorize tests. |
@pytest.mark.skip | Skip a test unconditionally. |
@pytest.mark.skipif | Skip a test based on a condition. |
pytest -m <marker> | Run tests with a specific marker. |
Markers and skipping enable flexible test management, ensuring your test suite remains organized and efficient.