A pytest marker is a label on a test, which you use to choose the tests to run or to change how pytest runs them. You add one with a decorator such as @pytest.mark.slow, or to every test in a file with a variable named pytestmark. See How to mark test functions with attributes. The commands here were run with pytest 9.2.0 and Python 3.13.

What problem do they solve?

You're working on my-app/, which has one function, total in prices.py, tested in tests/test_prices.py. Most of the tests finish in milliseconds. One checks total on a million random carts and takes about a second, and more tests like it will follow. You want to run the fast tests every time you save a file, and all of them before you push.

You could move the slow tests to another file and choose files on the command line. But then the tests of total are split by how long they take, not by what they test. A marker puts the label on the test itself, wherever it lives, and pytest -m selects tests by their labels.

How do I mark a test?

Here is prices.py:

def total(prices, discount=0.0):
    return round(sum(prices) * (1 - discount), 2)

Put @pytest.mark.slow on the slow test in tests/test_prices.py:

import random

import pytest

from prices import total


def test_total_adds_prices():
    assert total([2.50, 1.25]) == 3.75


def test_total_applies_discount():
    assert total([10.00], discount=0.1) == 9.00


@pytest.mark.slow
def test_total_is_never_negative():
    rng = random.Random(0)
    for _ in range(1_000_000):
        prices = [rng.uniform(0, 100) for _ in range(5)]
        assert total(prices, discount=rng.random()) >= 0

pytest.mark accepts any name, so slow works without being defined anywhere. But pytest can't tell a name you meant from a typo, so it warns: PytestUnknownMarkWarning: Unknown pytest.mark.slow - is this a typo?. Register each marker in pyproject.toml, with a description:

[tool.pytest]
pythonpath = ["."]
strict = true
markers = [
    "slow: takes more than a second",
]

pythonpath lets the tests import prices.py from the project root. strict = true makes an unregistered marker an error rather than a warning, along with other checks covered below. The [tool.pytest] table needs pytest 9.0 or later. Older versions read [tool.pytest.ini_options] instead, where you add --strict-markers to addopts. See the pyproject.toml formats.

Now leave the slow test out:

pytest -m "not slow"
collected 3 items / 1 deselected / 2 selected

tests/test_prices.py ..                                                  [100%]

======================= 2 passed, 1 deselected in 0.02s ========================

pytest -m slow runs only the slow test, and pytest on its own runs all three. A -m expression combines marker names with and, or, not, and parentheses. pytest --markers lists the markers you registered, followed by the ones that come with pytest.

How do I mark every test in a file?

Assign the marker to a variable named pytestmark at the top level of the file. Suppose you want to label each test file with the kind of tests it holds, and the tests of total check one function on its own. Register "unit: tests one function on its own" next to slow, then add one line under the imports:

from prices import total

pytestmark = pytest.mark.unit

Every test in the file now has the unit mark as well as its own marks. test_total_is_never_negative has both unit and slow, so pytest -m "unit and not slow" runs the other two. For more than one mark, use a list: pytestmark = [pytest.mark.unit, pytest.mark.filterwarnings("error")].

Marks can also go on a group of tests. A decorator on a test class marks every test method in it, and pytest.param(1_000_000, marks=pytest.mark.slow) marks one case of a parametrized test. See Marking whole classes or modules.

Which markers come with pytest?

Your own markers do nothing by themselves. They matter only when -m selects by them. The built-in markers change how a test runs, and they're registered already:

Marker What it does
skip(reason=...) Doesn't run the test, and reports it as skipped
skipif(condition, reason=...) Skips the test when the condition is true, such as sys.platform == "win32"
xfail(reason=...) Runs the test and expects it to fail
parametrize(names, values) Runs the test once for each set of values
usefixtures(*names) Sets up fixtures that the test doesn't take as arguments
filterwarnings(filter) Changes how warnings are handled in the test, such as turning one into an error

See the marks reference for the details of each.

For example, total([0.125]) returns 0.12, because round rounds a value that is exactly halfway to the even digit. You want 0.13, but you won't fix it today. Add a test that records the bug, and mark it xfail:

@pytest.mark.xfail(reason="round() rounds halves to even")
def test_total_rounds_half_up():
    assert total([0.125]) == 0.13

Running pytest -m "not slow" again shows the new test as x, for xfailed: it failed as expected, and the run still succeeds.

collected 4 items / 1 deselected / 3 selected

tests/test_prices.py ..x                                                 [100%]

================== 2 passed, 1 deselected, 1 xfailed in 0.02s ==================

Figure 1 shows what happened to each test.

Four tests from tests/test_prices.py pass through three stages. Collect: every test has the unit mark from pytestmark, test_total_rounds_half_up also has xfail, and test_total_is_never_negative also has slow. Select with -m "not slow": three tests are selected and test_total_is_never_negative is deselected. Run: two tests pass, test_total_rounds_half_up is xfailed, and the deselected test never runs.
Figure 1. -m reads the marks before any test runs, so the slow test is left out without being started. The xfail mark has no effect until its test runs and fails.

What should I watch out for?

  • Without strict mode, a misspelled marker is only a warning. A test marked @pytest.mark.slwo has no slow mark, so pytest -m "not slow" runs it, and the warning is easy to miss in a long output. With strict = true, the file fails to collect with 'slwo' not found in `markers` configuration option. Since pytest 9.2.0, strict mode also rejects an unknown name in -m, such as pytest -m slwo.
  • A misspelled pytestmark does nothing, and nothing warns. pytest_mark = pytest.mark.unit is an ordinary variable, so pytest -m unit deselects every test in the file. To see which tests a selection picks, run pytest -m unit --collect-only -q.
  • Only the last -m counts. If addopts in your config contains -m "not slow", running pytest -m unit replaces it instead of adding to it, and the slow test runs too. Write the whole expression, pytest -m "unit and not slow", or use pytest -m "" to run everything.
  • Deselected tests aren't reported as skipped. The summary only counts them. If CI always runs pytest -m "not slow", the slow tests never run anywhere. Add a CI job that runs pytest -m slow, on a schedule or before a release.
  • An xfail test that passes doesn't fail the run by default. It's reported as XPASS, so you might not notice that the bug was fixed. strict = true turns on strict_xfail, which makes such a test fail. For one test, use @pytest.mark.xfail(strict=True).
  • Strict mode grows with pytest. In 9.2.0, strict = true turns on strict_config, strict_markers, strict_xfail, and strict_parametrization_ids, and checks added in later versions will be turned on too. The strict option is meant for projects that pin the pytest version, so an upgrade happens on purpose. You can turn off one check, such as strict_xfail = false, and keep the others.

When are they worth it?

  • Tests that need something you don't always have, such as time, the network, a GPU, or an API key. Mark them, and choose where each group runs: on every save, in CI, or before a release.
  • Several kinds of tests in the same folders. One pytestmark line per file labels them all.
  • Known bugs and platform-specific tests. xfail and skipif keep the test in the suite and record the reason next to it.

If your tests are already split by folder, such as tests/unit/ and tests/integration/, pytest tests/unit selects them without markers. Otherwise, start with one marker for the tests you most often want to leave out, usually slow. Register it, and turn on strict mode with a pinned pytest version, so a typo stops the run instead of printing a warning.


Reading Time

~6 min read

Published

Category

Tags

Stay in Touch