Run one pytest file, test, or class

Select tests with paths and node IDs, use keyword expressions for broader matches, and inspect collected IDs before filtering parametrized cases.

Best practices
Illustration of software components, data, and application workflows

Pass a test file to run that file, or append :: components to select a function, class, or method. Use the paths and names pytest actually collects.

python -m pytest tests/test_math.py
python -m pytest tests/test_math.py::test_addition
python -m pytest tests/test_math.py::TestMath
python -m pytest tests/test_math.py::TestMath::test_addition

Paths can be absolute or relative to the current working directory. Running from a consistent project directory is convenient, but pytest can discover applicable parent conftest.py files without being launched precisely at the root.

Filter by a keyword expression

python -m pytest -k login
python -m pytest -k "login and not slow"

-k performs case-insensitive matching against collected names and related keywords, including parent names; it is not just an exact function-name comparison. Use a node ID for precision. Use -m for an intentional marker expression rather than treating keyword matching as a substitute for a marker policy.

Add useful run controls

python -m pytest tests/test_math.py -v
python -m pytest tests/test_math.py -x
python -m pytest tests/test_math.py -s
python -m pytest --lf

-v shows more result detail, -x stops after the first failure, and -s disables standard output/error capture in a normal serial run. --lf uses the local cache of previous failures; when there is no such cache, the default is to run the selected tests normally rather than to discover an imaginary prior failure set.

FAQ

Can I select more than one file?

Yes: python -m pytest tests/test_a.py tests/test_b.py. Additional selectors and filters apply within that selection.

How do I select one parametrized case?

Inspect IDs with python -m pytest --collect-only -q, then quote the complete node ID, for example "tests/test_math.py::test_addition[positive]". Quoting prevents shell interpretation of brackets. The parameter ID must match the collected case.

What should I check in an IDE?

Use the test explorer's single-test action, then verify the selected interpreter, working directory, and pytest configuration. An IDE may add its own runner arguments; a similar-looking test label alone does not guarantee the same environment as a terminal run.

References: Running pytest, pytest cache and previous failures.

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting