Sub topic 11
Selecting and controlling tests with markers
This chapter assumes you can write and run pytest tests, use plain assert, and read a pytest report. It also assumes you have seen pytest.mark.parametrize. Parametrize is itself a marker, so you already use the mechanism described here.
What a marker is
A marker is a label attached to a test function, a class, or a whole module. A marker does nothing until something reads it. pytest reads some markers itself and changes how the test runs. Others are only labels that you use to choose which tests to run.
Built-in markers that change behavior:
skipnever runs the test.skipifskips the test when a condition is true.xfailexpects the test to fail.parametrizeruns the test once per input set.usefixturesrequests fixtures without naming them as arguments.
Any other name, such as slow or network, is a custom marker. pytest attaches it to the test and lets you filter on it.
Skipping tests
Use skip when a test cannot run at all, for example because the feature does not exist yet. Use skipif when it cannot run in some environments. The reason text appears in the report.
# test_markers.py
import sys
import pytest
from cart import total
@pytest.mark.skip(reason="discount codes are not built yet")
def test_discount_code():
assert total([100], tax_rate=0.0) == 90
@pytest.mark.skipif(sys.platform == "win32", reason="relies on POSIX paths")
def test_posix_join():
assert "/".join(["a", "b"]) == "a/b"The skipif condition is evaluated when the module is imported. Keep it cheap and free of side effects.
You can also skip from inside a test body. This is useful when the decision depends on something only known at run time:
import pytest
def test_needs_numpy():
np = pytest.importorskip("numpy")
assert np.array([1, 2]).sum() == 3pytest.importorskip skips the test if the import fails. pytest.skip("reason") does the same unconditionally when called.
Expecting failures with xfail
xfail means "expected to fail". Use it for a known bug you have not fixed yet. The test still runs, but a failure is reported as xfailed and does not turn the run red.
import pytest
from cart import total
@pytest.mark.xfail(reason="float rounding bug, see issue 42", strict=True)
def test_total_is_exact_for_cents():
assert total([0.1, 0.2]) == 0.3Here 0.1 + 0.2 is 0.30000000000000004, so the assertion fails and the test is reported as xfailed.
If an xfail test passes, the result is xpassed. By default an xpassed result does not fail the run, so a fixed bug can go unnoticed. Setting strict=True turns an unexpected pass into a failure. The test then tells you to remove the marker. You can make strict the default for all xfail tests with xfail_strict = true in the configuration.
| Marker | Test body runs? | Typical use | Result when it ends |
|---|---|---|---|
| `skip` | No | Feature not built, test not ready | `skipped` |
| `skipif` | Only if the condition is false | Wrong OS, Python version, or missing library | `skipped` or normal |
| `xfail` | Yes | Known bug you intend to fix | `xfailed`, or `xpassed` (a failure with `strict=True`) |
Choose skip when running the test is pointless or harmful. Choose xfail when running it is still informative, because you will learn when the bug is fixed.
Registering and using custom markers
Custom markers let you group tests by any property you care about. The common ones are slow, integration, and network. Apply one with @pytest.mark.<name>:
import pytest
from cart import total
@pytest.mark.slow
def test_total_of_a_million_items():
assert total([1] * 1_000_000) == 1_000_000Register each marker in the configuration so pytest knows it is intentional:
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra --strict-markers"
markers = [
"slow: marks tests as slow (deselect with -m 'not slow')",
"network: marks tests that need internet access",
]Without registration, a typo such as @pytest.mark.slwo creates a new marker silently. The test then runs in every -m "not slow" run and nobody notices. With --strict-markers, an unregistered marker is an error at collection time. Run pytest --markers to list every built-in, plugin, and registered marker with its description.
Selecting tests with -m
The -m option takes a boolean expression over marker names. You can use and, or, not, and parentheses.
pytest -m slow
pytest -m "not slow"
pytest -m "slow and not network"
pytest -m "(slow or network) and not xfail"Quote the expression so the shell does not split it. -m matches only marker names. It does not look at test names.
The -k option is different. It matches substrings of test names, class names, and module names, and it also accepts and, or, and not. Use -k for quick ad hoc selection while developing. Use -m for categories you want to keep stable, such as the set your continuous integration job runs.
Note that deselected tests are not skipped. They do not appear in the skip summary, and the count line shows them as deselected.
Applying markers to many tests at once
A marker on a class applies to every test method in it:
import pytest
@pytest.mark.slow
class TestBulkImport:
def test_ten_thousand_rows(self):
assert sum(range(10_000)) == 49_995_000
def test_hundred_thousand_rows(self):
assert sum(range(100_000)) == 4_999_950_000To mark every test in a module, assign a module-level variable named pytestmark. It can be a single marker or a list:
import pytest
pytestmark = [pytest.mark.network, pytest.mark.slow]
def test_fetch_homepage():
assert TrueThe name must be exactly pytestmark. A different spelling is an ordinary variable and has no effect.
Markers on single parameter sets
When you use parametrize, one input set may need different treatment from the rest. Wrap that set in pytest.param and pass marks:
import pytest
from cart import total
@pytest.mark.parametrize(
"prices, expected",
[
([1, 2], 3),
pytest.param([0.1, 0.2], 0.3, marks=pytest.mark.xfail(reason="float error")),
pytest.param([1] * 100_000, 100_000, marks=pytest.mark.slow),
],
)
def test_total_cases(prices, expected):
assert total(prices) == expectedEach case is reported separately. The first passes, the second is xfailed, and the third carries the slow label so -m "not slow" leaves it out.
Reading marker results in the report
The -r option controls the short summary at the end of a run. -rs lists skip reasons, -rx lists xfails, and -ra lists everything except passes. The -ra setting in the configuration above means every skip and xfail reason is always visible. This matters because a growing number of skipped tests is a common way for a suite to lose coverage without anyone noticing.
Common errors
- Typo in a marker name. Without
--strict-markers, the typo creates a new marker and the test is never filtered. Register markers and enable strict mode. - Unquoted
-mexpression.pytest -m not slowpassesslowas a path argument. Writepytest -m "not slow". - Marker on a fixture. Markers applied to fixture functions have no effect, and recent pytest versions reject this. Put the marker on the tests.
- Using
skipfor a known bug. You lose the signal that the bug has been fixed. Preferxfail(strict=True). - Stale markers. Review
skipandxfailreasons regularly. A reason that references a closed issue means the marker should be removed.
Exercise
A test is marked @pytest.mark.xfail(reason="bug 17") with no other options. After a teammate fixes bug 17, the run still ends green, and the summary shows one xpassed. What change makes pytest report this situation as a failure, and what should you do once it does?
Show answer
Add strict=True to the marker (or set xfail_strict = true in [tool.pytest.ini_options]). An unexpected pass then fails the run. Once it fails, remove the xfail marker so the test runs as a normal test.
Exercise
Your suite has tests tagged @pytest.mark.network and @pytest.mark.slow. Write the command that runs every test that is slow but does not need the network, and name the setting that makes pytest reject a misspelled marker such as @pytest.mark.netwrok.
Show answer
pytest -m "slow and not network". The setting is the --strict-markers option, usually placed in addopts, together with registering the markers in the markers list.