1. Home
  2. Blog
  3. Test Automation

Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers are labels you attach to tests with @pytest.mark.name. Use them to run only smoke tests, skip tests that cannot run in an environment, mark known bugs as expected failures, and split a big suite into fast and slow groups. Here is each pattern, run on a real suite with pytest 9.2.

9 min read
pytest markers explained with examples

Key takeaways

  • pytest markers label tests; pytest -m smoke then runs only tests marked @pytest.mark.smoke.
  • Register custom markers in pyproject.toml and add --strict-markers: our typo @pytest.mark.smok stopped the run instead of silently doing nothing.
  • -m "not slow" skipped a 1.1-second test and finished in 0.16 s instead of 1.49 s.
  • Use xfail(strict=True) for known bugs, so a fix is noticed the moment it lands.

As a test suite grows, running everything on every change stops being practical. You want quick smoke checks on each commit, the full suite before release, and a clean way to park tests that cannot run on a given machine. pytest markers give you all of that with one decorator. We built a small suite and ran every command below with pytest 9.2.0 on Python 3.13.6. New to pytest? Start with our pytest tutorial.

What are pytest markers?

A marker is metadata attached to a test function, class or module. pytest ships with built-in markers that change behaviour, such as skip, skipif, xfail, parametrize and usefixtures. You can also invent your own, such as smoke, slow or api, which do nothing by themselves but let you select or exclude groups of tests from the command line.

Register your custom markers

# pyproject.toml
[tool.pytest.ini_options]
markers = [
  "smoke: fast checks run on every commit",
  "slow: tests that take more than a second",
  "api: tests that call the HTTP API",
]
addopts = "--strict-markers"

Registering does two jobs. It documents what each label means, and it lets pytest catch typos. The same list can live in pytest.ini under [pytest] or in setup.cfg. Running pytest --markers printed our three descriptions alongside the built-in markers:

@pytest.mark.smoke: fast checks run on every commit
@pytest.mark.slow: tests that take more than a second
@pytest.mark.api: tests that call the HTTP API

Our example suite

import sys, time, pytest

@pytest.mark.smoke
def test_login_page_loads(): assert True

@pytest.mark.smoke
@pytest.mark.api
def test_health_endpoint(): assert True

@pytest.mark.slow
def test_full_report():
    time.sleep(1.1); assert True

@pytest.mark.api
def test_create_order(): assert True

@pytest.mark.skip(reason="feature flag off in this environment")
def test_new_checkout(): assert False

@pytest.mark.skipif(sys.platform == "win32", reason="uses POSIX permissions")
def test_file_permissions(): assert True

@pytest.mark.xfail(reason="BUG-204 rounding", strict=True)
def test_rounding(): assert round(2.675, 2) == 2.68

@pytest.mark.parametrize("n", [1, 2, pytest.param(3, marks=pytest.mark.slow)])
def test_numbers(n): assert n > 0

def test_runtime_skip():
    pytest.importorskip("not_installed_lib")

A test can carry several markers, as test_health_endpoint does. The full run, with -rsx to explain skips and expected failures, looked like this:

....ssx...s                                   [100%]
SKIPPED [1] test_mk.py:17: feature flag off in this environment
SKIPPED [1] test_mk.py:20: uses POSIX permissions
SKIPPED [1] test_mk.py:30: could not import 'not_installed_lib': No module named 'not_installed_lib'
XFAIL test_mk.py::test_rounding - BUG-204 rounding
7 passed, 3 skipped, 1 xfailed in 1.49s

Selecting tests with -m

Command Result in our run
pytest -m smoke 2 passed, 9 deselected in 0.11 s
pytest -m "not slow" 5 passed, 3 skipped, 2 deselected, 1 xfailed in 0.16 s
pytest -m "smoke and api" 1 passed, 10 deselected
pytest (everything) 7 passed, 3 skipped, 1 xfailed in 1.49 s

The -m option takes a boolean expression using and, or, not and parentheses, such as -m "(smoke or api) and not slow". Excluding slow cut the run time by about 90%, which is exactly why teams tag slow tests. Note that -m matches marker names, while -k matches test names and parametrize ids; they can be combined.

Tip: use pytest --durations=5 to find candidates for the slow marker. In our run it listed 1.10s call test_mk.py::test_full_report at the top.

Catching marker typos with –strict-markers

We added a file with a misspelled marker, @pytest.mark.smok, and ran the suite:

ERROR test_typo.py - Failed: 'smok' not found in `markers` configuration option
1 error in 0.25s

Without --strict-markers, pytest only prints a warning for an unknown marker, and the test silently drops out of your smoke selection. With it, the typo fails the run at collection time. Turn it on in every project that uses custom markers.

skip: never run this test here

@pytest.mark.skip(reason=...) always skips the test and shows an s in the progress line. Always give a reason; “skipped” with no explanation is how tests get forgotten for years. Typical uses are features behind a disabled flag or a test that depends on a service that does not exist yet.

skipif: skip only under a condition

@pytest.mark.skipif(sys.platform == "win32", reason="uses POSIX permissions")

Our machine runs Windows, so this test was skipped with its reason; on Linux it would run. Common conditions are the operating system, the Python version (sys.version_info < (3, 12)), a missing environment variable or a missing optional tool. Store a condition in a variable when several tests share it, for example windows_only = pytest.mark.skipif(...), then decorate with @windows_only.

Skipping at runtime

Sometimes you only know inside the test that it cannot run. pytest.importorskip("not_installed_lib") skipped our test because the module did not exist, and reported exactly why. You can also call pytest.skip("reason") anywhere in a test or fixture, for example when an external API returns “service unavailable” during a nightly run.

xfail: an expected failure

@pytest.mark.xfail(reason="BUG-204 rounding", strict=True)
def test_rounding():
    assert round(2.675, 2) == 2.68

This test documents a real surprise: in Python, round(2.675, 2) returned 2.67 in our run, because 2.675 cannot be stored exactly as a binary float. The test fails as expected and is reported as x, so it does not break the build. xfail is different from skip: the test still runs, so you see when the behaviour changes.

The strict=True flag matters. Without it, an xfail test that suddenly passes is reported as XPASS and ignored. With it, an unexpected pass fails the run, which tells you to remove the marker and close the ticket. Put the ticket number in the reason so anyone can find it.

Marking a single parametrized case

@pytest.mark.parametrize("n", [1, 2, pytest.param(3, marks=pytest.mark.slow)])

pytest.param attaches markers to one case only. Here only n=3 was treated as slow, which is why -m "not slow" deselected two tests: test_full_report and this one case. The same works with skip and xfail for individual inputs. More patterns are in our pytest parametrize guide.

Marking a whole class or file

@pytest.mark.api
class TestOrders:
    def test_create(self): ...
    def test_cancel(self): ...

# at the top of a module: mark every test in the file
pytestmark = [pytest.mark.api, pytest.mark.slow]

A marker on a class applies to every test method in it. The special module-level variable pytestmark applies markers to every test in the file, which suits a whole file of API or database tests. Fixtures can be attached the same way with @pytest.mark.usefixtures("db"); see our pytest fixtures guide.

Using markers in CI pipelines

Markers shine when different pipeline stages run different groups:

  • Every commit: pytest -m smoke for feedback in seconds.
  • Every pull request: pytest -m "not slow".
  • Nightly: the full suite, including slow and external API tests.
  • Before release: everything, with -rsx so skipped and expected-failure tests are reviewed.

This mirrors the smoke-then-full strategy in our smoke vs sanity testing guide, and fits straight into a GitHub Actions workflow.

Common mistakes

  • Unregistered markers: typos silently drop tests from selections. Register and use --strict-markers.
  • Skips without reasons: nobody knows if they can be removed.
  • Using skip for flaky tests: it hides the problem. Fix it or quarantine it with a tracked marker; see our flaky tests guide.
  • Non-strict xfail: fixed bugs go unnoticed.
  • Too many labels: five meaningful markers beat thirty that nobody remembers.

pytest markers cheat sheet

Goal Code or command
Label a test @pytest.mark.smoke
Run a group pytest -m smoke
Exclude a group pytest -m "not slow"
Combine pytest -m "smoke and api"
Always skip @pytest.mark.skip(reason="...")
Skip on a condition @pytest.mark.skipif(cond, reason="...")
Known bug @pytest.mark.xfail(reason="BUG-1", strict=True)
Mark one case pytest.param(x, marks=pytest.mark.slow)
Mark a whole file pytestmark = pytest.mark.api
List markers pytest --markers
Explain skips pytest -rsx

Final thoughts

pytest markers turn one large suite into many useful ones. Register a handful of meaningful custom markers, enforce them with --strict-markers, select groups with -m, and use skip, skipif and strict xfail with clear reasons. In our run that meant a smoke check in a tenth of a second and a full suite whenever we wanted it, from the same code.

Frequently asked questions

What are markers in pytest?

Markers are labels added with @pytest.mark.name to tests, classes or modules. Built-in markers change behaviour, such as skip and xfail, while custom markers let you select groups of tests with -m.

How do I run only tests with a specific marker?

Use the -m option, for example pytest -m smoke. Combine markers with and, or and not, such as pytest -m “smoke and not slow”.

How do I register custom markers in pytest?

List them under markers in pyproject.toml, pytest.ini or setup.cfg, each with a short description, and add –strict-markers so typos cause an error.

What is the difference between skip and xfail?

skip does not run the test at all. xfail runs it and expects it to fail, so you notice when the behaviour changes, especially with strict=True.

Why do I get an unknown pytest mark warning?

The marker is not registered. Add it to the markers list in your pytest configuration, or fix the spelling if it was a typo.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
Software Development

HTTP Methods Explained: GET, POST, PUT, PATCH, DELETE, Tested on a Live Server

HTTP methods explained with a small server we ran: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, safe vs idempotent,…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Software Development

JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5

How to sort an array in JavaScript correctly: numbers with a compare function, objects by one or more fields, strings…

Read article →
Software Development

Python String Methods: Cheat Sheet, Real Examples and the strip() Trap

Python string methods with tested examples: split, join, strip, replace, find, startswith, is-methods, casefold, partition and translate, plus the strip()…

Read article →
Software Development

Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps

Python zip() pairs items from several lists in one loop. Tested examples for dicts, unzipping with *, strict=True, zip_longest, sliding…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
Software Development

UTF-8 Encoding Explained: How Text Becomes Bytes and How to Fix Garbled Text

UTF-8 encoding explained with byte-level examples we ran in Python: how characters become 1 to 4 bytes, why café turns…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Databases & SQL

Delete Duplicate Rows in SQL: 5 Safe Methods, Tested Step by Step

How to delete duplicate rows in SQL safely: find them, preview them, then remove them with ROW_NUMBER, MIN(id), EXISTS, rowid…

Read article →
Databases & SQL

SQL RANK vs DENSE_RANK vs ROW_NUMBER: Differences with Tested Examples

SQL RANK vs DENSE_RANK vs ROW_NUMBER in one table: how each handles ties, top-N per group, the second-highest salary trap…

Read article →
Software Development

JavaScript Optional Chaining (?.) Explained: 8 Examples, ?? Defaults and Traps

JavaScript optional chaining stops “Cannot read properties of undefined” errors. 8 tested examples for properties, arrays and methods, ?? vs…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Databases & SQL

SQL COALESCE Explained: Defaults, NULLIF, IFNULL vs ISNULL and Traps, Tested

SQL COALESCE explained with queries we ran in SQLite 3.50: first non-null values, empty strings, NULL in maths, NULLIF for…

Read article →
Databases & SQL

SQL Self Join Explained: Employee-Manager, Pairs and Row Comparisons, Tested

SQL self join explained with queries we ran in SQLite 3.50: employee and manager, earning more than the manager, unique…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →
Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →