How to run one specific pytest test from the command line
Table of Contents
Your test suite has 800 tests, one of them is failing, and you don’t want to run the other 799 while you iterate on the fix. Here are six ways to narrow pytest down.
By File #
pytest tests/test_users.py
By Test Function #
pytest tests/test_users.py::test_user_signup
Two colons separate the file from the identifier inside it. Not one - : is what fingers type first, and it fails silently (pytest collects nothing).
By Class and Method #
pytest tests/test_users.py::TestUserService::test_creates_user
By Parametrised Case #
If your test is @pytest.mark.parametrized, you can select one case by its ID:
pytest 'tests/test_users.py::test_user_signup[admin-True]'
Wrap in quotes because the brackets are shell metacharacters.
Not sure what the IDs look like? List them without running:
pytest tests/test_users.py --collect-only -q
By Keyword (across the whole suite) #
The -k flag matches against the test name as a Python expression, so and, or, and not work:
pytest -k signup
pytest -k 'signup and not admin'
Handy when you don’t remember which file the test is in.
By Marker #
If your tests have @pytest.mark.slow (or your own markers):
pytest -m slow
pytest -m 'not slow'
Just Re-Run What Failed #
pytest --last-failed
# or the shorthand
pytest --lf
Runs only tests that failed in the previous run. The complementary flag is --failed-first (--ff), which runs everything but puts the previously-failed tests first.
The Combo I Use Most #
pytest -x -k signup --lf
-xstops at the first failure-k signupnarrows to the tests you’re iterating on--lfprefers the ones that were already broken
Tight iteration loop.