Open In App

Substring Matching of Test Names in Pytest

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A free and open-source Python framework that is used to execute and test codes is known as Pytest. Suppose you have written all the test cases related to code on on test file, but you don't want to execute all test cases at once for testing the code. Then, you can do so, by adding some unique portion of names to test cases that you want to run together. In this article, we will study how we can run such test cases having substring matching of test names in Pytest.

Substring Matching of Test Names in Pytest

Syntax

pytest main.py -k substring_match -v

Here,

  • substring_match: It is the substring to be matched while executing the tests in Pytest.

Example 1: In this example, we have created a program that has four test cases, checking floor as function name test_check_floor, equality as function name test_equal, subtraction as function name test_check_difference, and square root as function name test_square_root. Here, two functions have checked as common substrings in their names, thus we will execute these test cases.

Python
import math

# first test case
def test_check_floor():
   num = 6
   assert num==math.floor(6.34532)

# second test case
def test_equal():
   assert 50 == 49

# third test case
def test_check_difference():
   assert 99-43==57

# fourth test case
def test_square_root():
   val=8
   assert val==math.sqrt(81)

Run the Program

Now, we will run the following command with substring_match as check as follows:

pytest main.py -k check -v

Output

Output

Example 2: In this example, a string is defined and three unit tests are created to remove characters 'G', 'e', and 'o'. Three functions test_substring_match_remove_G and test_substring_match_remove_o and test_substring_match_remove_e which include the word "remove" in their names. Hence, running pytest main.py -k remove -v will execute only those tests, demonstrating substring matching in Pytest.

Python
s = "Geeks For Geeks"

# first test case
def test_substring_match_remove_G():
    assert s.replace('G', '') == "eeks For eeks"

# second test case
def test_substring_match_remove_e():
    assert s.replace('e', '') == "Gks For Gks"

# third test case
def test_substring_match_remove_o():
    assert s.replace('o', '') == "Geeks Fr Geeks"

Run the Program

Now, we will run the following command with substring_match as remove as follows:

pytest main.py -k remove -v

Output

Output




Similar Reads