JUnit XML Generator

1.9 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to create `TestCase` objects, add them to a `TestSuite`, and then write the complete JUnit XML structure to a file. It includes examples of successful and failed tests, and uses `stdout` and `stderr` for additional messaging.

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}")

view raw JSON →