brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python -m pytest -k picks tests by name with and, or and not

Python
~/tips/tip-python-pytest-k-select

python3 -m pytest -k "login and not bad" -v

Run only the tests whose names match a keyword expression.

When you work on one feature, waiting for the whole test suite is a waste, I think. pytest -k lets you run only the tests whose names match.

python3 -m pytest -k login
python3 -m pytest -k "login and not bad" -v

-k takes an expression that’s matched against the test names, case insensitive and as a substring. So -k login picks test_login_ok and test_login_bad, and "login and not bad" narrows it down to just the first. You can use and, or, not and parentheses. The summary line tells you how many were deselected, which is a good sanity check that you didn’t filter everything away.

It also matches the file and class names, so -k TestCache runs a whole class and -k api catches everything in test_api.py.

The substring matching is both the nice and the annoying part. -k log also picks up test_logout and test_catalog. For one exact test, pass its node id instead, like python3 -m pytest tests/test_auth.py::test_login_ok. And for groups you select often, a marker with -m is more reliable than a name pattern.

Further reading: pytest: selecting tests

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link