How to Generate Test results in XML in Python Pytest?

Generate Pytest XML report for pytest execution. The major advantage of the report feature is to get output generated in an incomprehensible manner. These file formats are commonly used to make the task of decoding the output easier.

In Pytest, we can generate test results in XML format. XML can be parsed to get the detailed features of execution for any test.

Below are the prerequisite to work with Pytest

  • Python 3.6+ or pypy3

Generate Test results in XML in Python Pytest

  1. Open IDE (Vs-code or Pycharm)
  2. Execute the following command. It will install pytest in our IDE
    pip install pytest

Create an automation test in Pytest

  1. Create a test file named as  test_2.py
  2. Your testing files should be in this order given below:

Now, let us start with a basic example.

The below test_sum function will give the sum of  items present in the list & assert function helps to compare the output so as to make a test case

def test_sum():
    assert sum([1,2,3,4,5]) == 15

Use the command pytest to execute the test code given above.

pytest test_2.py

Following is the output to show that our test case is run successfully.

Next execute the following command in terminal

pytest test_2.py -v --junitxml="result.xml"

Next, we can see an extra file named as result.xml is generated in our IDE with the following data –

The tag <testsuit> summaries there are a total of 1 test and the total number of failures is 0. The tag <testcase> gives the details of each executed test.<failure> tag gives the details of the failed test code.

Now if we change the asserted result for which the test case will fail and we can see that result.xml will also get changed

Thus, In this tutorial, we have learned how to generate test results in XML format using pytest.