Pytest - Substring Matching of Test Names



To execute the tests containing a string in its name we can use the following syntax −

pytest -k <substring> -v

-k <substring> represents the substring to search for in the test names.

Now, run the following command −

pytest -k great -v

This will execute all the test names having the word great in its name. In this case, they are test_greater() and test_greater_equal(). See the result below.

============================ test session starts ================================
platform win32 -- Python 3.14.2, pytest-9.0.2, pluggy-1.6.0 
-- C:\Users\mahes\AppData\Local\Programs\Python\Python314\python.exe
cachedir: .pytest_cache
rootdir: D:\Projects\python\myenv\automation
collected 5 items / 3 deselected / 2 selected

test_compare.py::test_greater FAILED                                       [ 50%]
test_compare.py::test_greater_equal PASSED                                 [100%]

============================ FAILURES ===========================================
____________________________ test_greater _______________________________________

    def test_greater():
       num = 100
>   assert num > 100
E      assert 100 > 100

test_compare.py:3: AssertionError
============================ short test summary info ============================
FAILED test_compare.py::test_greater - assert 100 > 100
============================ 1 failed, 1 passed, 3 deselected in 0.06s ==========

Here in the result, we can see 3 tests deselected. This is because those test names do not contain the word great in them.

Note − The name of the test function should still start with test.

Advertisements