How to Run Specific Test in pytest: Simple Guide
To run a specific test in
pytest, use the command pytest -k <test_name> where <test_name> matches the test function name or part of it. You can also run a test by specifying its file and function like pytest path/to/test_file.py::test_function.Syntax
There are two main ways to run a specific test in pytest:
- By test name pattern: Use
pytest -k <expression>where<expression>matches test names. - By file and test function: Use
pytest <path>::<test_function>to run a single test function in a file.
This lets you focus on one test without running the entire suite.
bash
pytest -k test_name_part pytest tests/test_example.py::test_specific_function
Example
This example shows how to run a specific test function named test_addition inside test_math.py.
python
def test_addition(): assert 1 + 1 == 2 def test_subtraction(): assert 2 - 1 == 1 # Run this specific test with: # pytest test_math.py::test_addition
Output
============================= test session starts =============================
collected 2 items
test_math.py::test_addition PASSED [100%]
============================== 1 passed in 0.01s ==============================
Common Pitfalls
Common mistakes when running specific tests include:
- Using
-kwith a wrong or partial test name that matches multiple tests unintentionally. - Forgetting to specify the full path and function name with
::, causing pytest to run the whole file. - Not escaping special characters in test names when using
-k.
Always double-check the test name and path to avoid running more tests than intended.
bash
## Wrong way: runs all tests in the file
pytest test_math.py
## Right way: runs only one test function
pytest test_math.py::test_additionQuick Reference
| Command | Description |
|---|---|
| pytest -k test_name_part | Run tests matching the name pattern |
| pytest path/to/file.py::test_function | Run a specific test function in a file |
| pytest -m marker_name | Run tests with a specific marker (advanced) |
Key Takeaways
Use
pytest -k <test_name> to run tests matching a name pattern.Use
pytest <file>::<test_function> to run one test function exactly.Check test names carefully to avoid running unintended tests.
Specify full file path and function name for precise test runs.
Markers can also filter tests but require prior setup.