Pytest substring matching of test names
Substring Matching in Pytest Test Names
To execute a test whose name contains a string, we can use the following syntax –
pytest -k <substring> -v
-k <substring>
represents the substring to search for in the test name.
Now, run the following command –
pytest -k great -v
This will execute all tests with the word ‘great’ in their names. In this case, they are test_greater() and test_greater_equal() . See the results below.
test_compare.py::test_greater FAILED
test_compare.py::test_greater_equal PASSED
============================================== FAILURES
==============================================
______________________________________________ test_greater
____________________________________________
def test_greater():
num = 100
> assert num > 100
E assert 100 > 100
test_compare.py:3: AssertionError
========================== 1 failed, 1 passed, 3 deselected in 0.07 seconds
=============================
In the results here, we can see that 3 tests were deselected. This is because these test names do not contain the word great.
Note – The test function name should still begin with “test”.