pytest -k: Select Tests by Name Command Reference
Run only the tests whose names match an expression.
pytest -k filters collected tests by a Python-like expression matched against test names and their path. It is the quickest way to run a focused subset in CI.
Common flags / usage
- -k "auth" -- run tests whose name contains auth
- -k "auth and not slow" -- combine with and/or/not
- -k "login or signup" -- match either substring
- pair with --collect-only -- preview what the expression selects
Example
shell
# Fast smoke subset on every push:
- run: python -m pytest -k "smoke and not integration" -qIn CI
Use -k to split a slow suite into fast feedback (a name-matched smoke subset on each push) and a full run on a schedule. The expression matches the test name and the module path, so name conventions make selection predictable.
Key takeaways
- pytest -k selects tests by a name expression with and/or/not.
- It matches against test names and their module path.
- Use it to carve a fast smoke subset out of a larger suite.
Related guides
pytest: Run Tests Command Reference for CIReference for pytest in CI: running the suite, useful flags, why python -m pytest fixes import errors, and a…
pytest -m: Select Tests by Marker Command ReferenceReference for pytest -m in CI: selecting tests by registered markers, deselecting slow tests, registering mar…
pytest -x and --maxfail: Fail-Fast Command ReferenceReference for pytest fail-fast flags in CI: -x to stop on the first failure and --maxfail=N to stop after N,…