Open In App

Test Execution Results in XML in Pytest

Last Updated : 08 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The testing framework in Python which is used to write and execute test codes is called Pytest. There occur some circumstances in Pytest when we need to store the test execution results in an XML file apart from just displaying them in the terminal. In this article, we will discuss how to store the test execution results of Pytest in an XML file.

Test Execution Results in XML in Pytest

Syntax: pytest python_file.py -v –junitxml=”xml_file.xml”

Here,

  • python_file: It is the name of the Python test file which you want to execute tests.
  • xml_file: It is the name of the XML file in which you want to store test execution results.

Example 1

In this example, we have created a Python file, gfg2.py, which has four test cases, checking floor, equality, subtraction, and square root. We will store the test execution results in gfg.xml file.

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_check_equal():
   assert 50 == 49
 
# Creating third test case
def test_check_difference():
   assert 99-43==57
 
# Creating fourth test case
def test_check_square_root():
   val=9
   assert val==math.sqrt(81)


Output

Now, we will run the following command in terminal:

pytest gfg2.py -v --junitxml="gfg.xml"

Video

Example 2

In this another example, we have created a Python file, gfg3.py defined a string, then we have created 3 unit test cases on it, for removing substrings G, e and o. We will store the test execution results in gfg1.xml file.

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_remove_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"


Output

Now, we will run the following command in terminal:

pytest gfg3.py -v --junitxml="gfg1.xml"

Video



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

Similar Reads