JUnit XML reporting for CI in PyTest - Build an Automation Script
import subprocess import os import xml.etree.ElementTree as ET import unittest class TestPytestJUnitReport(unittest.TestCase): def test_generate_junit_xml_report(self): # Run pytest with JUnit XML output result = subprocess.run(['pytest', '--junitxml=report.xml', 'test_sample.py'], capture_output=True, text=True) # Assert pytest ran successfully self.assertEqual(result.returncode, 0, f"pytest failed with output:\n{result.stdout}\n{result.stderr}") # Assert report.xml file exists self.assertTrue(os.path.exists('report.xml'), 'report.xml file was not created') # Parse XML and check for testsuite and testcase elements tree = ET.parse('report.xml') root = tree.getroot() self.assertEqual(root.tag, 'testsuite', 'Root element is not <testsuite>') testcases = root.findall('testcase') self.assertGreater(len(testcases), 0, 'No <testcase> elements found in report.xml') if __name__ == '__main__': unittest.main()
This script uses Python's unittest framework to automate the manual test case steps.
First, it runs pytest with the --junitxml=report.xml option using subprocess.run. This generates the JUnit XML report file.
Then, it checks the return code to ensure pytest ran successfully.
Next, it verifies that the report.xml file was created in the current directory.
Finally, it parses the XML file using xml.etree.ElementTree to confirm the root element is <testsuite> and that there is at least one <testcase> element inside, ensuring the report is valid and contains test results.
This approach follows best practices by using subprocess for running commands, checking outputs, and parsing XML to validate the report content.
Now add data-driven testing to run pytest with different test files and generate separate JUnit XML reports for each.