Running PyTest in Jenkins - Build an Automation Script
import os import subprocess import xml.etree.ElementTree as ET import unittest class TestJenkinsPytestRun(unittest.TestCase): def test_pytest_run_and_report(self): # Run pytest with JUnit XML output result = subprocess.run(['pytest', '--junitxml=results.xml'], capture_output=True, text=True) # Assert pytest command ran successfully self.assertEqual(result.returncode, 0, f"Pytest failed: {result.stderr}") # Check if results.xml file exists self.assertTrue(os.path.exists('results.xml'), 'JUnit XML report not found') # Parse the XML report tree = ET.parse('results.xml') root = tree.getroot() # Extract test counts tests = int(root.attrib.get('tests', 0)) failures = int(root.attrib.get('failures', 0)) errors = int(root.attrib.get('errors', 0)) skipped = int(root.attrib.get('skipped', 0)) # Assert there is at least one test run self.assertGreater(tests, 0, 'No tests were run') # Assert no errors in test run self.assertEqual(errors, 0, 'There were errors in the test run') # Optionally assert failures count (can be zero or more) # Print summary print(f"Tests run: {tests}, Failures: {failures}, Skipped: {skipped}") if __name__ == '__main__': unittest.main()
This script automates running PyTest with the --junitxml=results.xml option to generate a JUnit XML report file.
It uses Python's subprocess module to run the PyTest command and captures the output and return code to verify the test run succeeded.
Then it checks if the results.xml file was created, which Jenkins uses to display test results.
The script parses the XML report using xml.etree.ElementTree to extract the total tests, failures, errors, and skipped counts.
Assertions verify that tests were run, no errors occurred, and the report file exists.
This matches what Jenkins expects when configured to run PyTest and publish JUnit reports, ensuring the automation covers the manual test case steps.
Now add data-driven testing with 3 different test input scenarios in PyTest and verify Jenkins runs all scenarios.