JUnit XML Generator
junit-xml is a Python library for creating JUnit XML test result documents. These documents are widely used by continuous integration tools like Jenkins, GitLab CI, and others to display test outcomes. The current version is 1.9, and releases are made on an as-needed basis to add features or fix bugs.
Warnings
- breaking The constructor signature for `TestCase` changed significantly in version 1.0.0. Arguments like `output` and `error` were removed and replaced with `stdout` and `stderr` attributes, and the order of arguments was altered.
- breaking The constructor signature for `TestSuite` was also updated in version 1.0.0. The `testcases` argument became a required positional argument after the suite name, and other keyword arguments were added or modified.
- gotcha The `timestamp` argument for `TestSuite` expects an ISO 8601 formatted string (e.g., 'YYYY-MM-DDTHH:MM:SS'). Providing other formats may lead to invalid XML or parsing issues in consuming tools.
Install
-
pip install junit-xml
Imports
- TestSuite
from junit_xml import TestSuite
- TestCase
from junit_xml import TestCase
Quickstart
from junit_xml import TestSuite, TestCase
import os
# Create some test cases
test_cases = [
TestCase('Test case 1', 'com.example.package', 1.23, stdout='Output for TC1', stderr='Error for TC1'),
TestCase('Test case 2', 'com.example.package', 0.5,
stdout='Another output', stderr='Another error')
]
# A failed test case example
failed_test_case = TestCase('Failed test', 'com.example.package', 0.1)
failed_test_case.add_failure_info('Assertion failed', 'Expected 1, got 0')
test_cases.append(failed_test_case)
# Create a test suite and add test cases
# The timestamp should be in ISO 8601 format
test_suite = TestSuite(
"My example test suite",
test_cases,
hostname="localhost",
id="0",
package="com.example.package",
timestamp="2024-07-08T10:30:00"
)
# Write the test suite to an XML file
output_filename = os.environ.get('JUNIT_XML_OUTPUT_FILE', 'output.xml')
with open(output_filename, 'w', encoding='utf-8') as f:
TestSuite.to_file(f, [test_suite], prettyprint=True)
print(f"JUnit XML written to {output_filename}")