Open In App

Substring Matching of Test Names in Pytest

Last Updated : 04 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
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.

Python3




# Importing the math library
import math
 
# Creating first test case
def test_check_floor():
   num = 6
   assert num==math.floor(6.34532)
 
# Creating second test case
def test_equal():
   assert 50 == 49
 
# Creating third test case
def test_check_difference():
   assert 99-43==57
 
# Creating 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:

Example 2: In this another example, we have defined a string, then we have created 3 unit test cases on it, for removing substrings G with function name test_remove_G, e with function name test_e and o with function name test_remove_o. Here, two functions have remove as common substring in there names, thus we will execute these test cases.

Python3




# Define a string
string_match="Geeks For Geeks"
 
# Creating first test case
def test_remove_G():
    assert string_match.replace('G','')=="eeks For eeks"
 
# Creating second test case
def test_e():
    assert string_match.replace('e','')=="Gaks For Gaks"
 
# Creating third test case
def test_remove_o():
    assert string_match.replace('o','')=="Geeks For 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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads