Execute pytest file using Substring

When we have multiple test cases then we can execute a set of test cases which has a specific substring matching its test names.

Use below syntax to execute test cases containing a substring name.

Syntax: pytest -v -k substring_name


-k : Represents substring name 
-v : Verbose 

In below class we have 4 tests. Two test cases have a name with the substring as “method” test_methodA() , test_methodB() and two test have different names test_Example1() , test_Example2().

test_Substring.py

def test_methodA():
    print("This is method A")


def test_methodB():
    print("This is method B")


def test_Example1():
    print("This is Example1 method")


def test_Example2():
    print("This is Example2 method")



Run below command which contains substring name “method”.

pytest -v -k method test_Substring.py


OutPut data

Here there are totally 4 test cases in the test file test_Substring.py. When we run the test file test_Substring.py it will execute only 2 test cases which contain substring name “method” and remaining 2 test cases will not be executed; those 2 test cases will be deselected.

admin@admin-MacBook substring % pytest -v -k method test_Substring.py 
============================================================================ test session starts ============================================================================
platform darwin -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /Library/Frameworks/Python.framework/Versions/3.8/bin/python3.8
cachedir: .pytest_cache
rootdir: /Users/admin/Documents/Skill2Lead/Tutorials/pytest/substring
plugins: rerunfailures-9.0, allure-pytest-2.8.16, ordering-0.6
collected 4 items / 2 deselected / 2 selected                                                                                                                               

test_Substring.py::test_methodA PASSED                                                                                                                                [ 50%]
test_Substring.py::test_methodB PASSED                                                                                                                                [100%]

====================================================================== 2 passed, 2 deselected in 0.02s ======================================================================
admin@admin-MacBook substring %