### Install development version from Git Source: https://github.com/xmlrunner/unittest-xml-reporting/blob/master/README.md Clone the repository and install the package from source. ```bash $ git clone https://github.com/xmlrunner/unittest-xml-reporting.git $ cd unittest-xml-reporting $ sudo python -m pip install . ``` -------------------------------- ### Install development version from tarball Source: https://github.com/xmlrunner/unittest-xml-reporting/blob/master/README.md Download and install the development version using a zip archive. ```bash $ wget https://github.com/xmlrunner/unittest-xml-reporting/archive/master.zip $ unzip master.zip $ cd unittest-xml-reporting $ sudo python -m pip install . ``` -------------------------------- ### Install via Pip Source: https://github.com/xmlrunner/unittest-xml-reporting/blob/master/README.md Install the package using the Python package manager. ```bash $ pip install unittest-xml-reporting ``` -------------------------------- ### Install and Run Tox for Testing Source: https://github.com/xmlrunner/unittest-xml-reporting/blob/master/README.md Use tox to test your changes before submitting a pull request. Install tox using pip and run it for basic sanity tests or all combinations. ```bash pip install tox ``` ```bash tox -e pytest ``` ```bash tox ``` -------------------------------- ### Configure XMLTestRunner Constructor Source: https://context7.com/xmlrunner/unittest-xml-reporting/llms.txt Shows how to instantiate XMLTestRunner with various configuration options. These parameters control output location, file naming, encoding, verbosity, and test execution behavior. ```python import unittest import xmlrunner # Full constructor with all options runner = xmlrunner.XMLTestRunner( output='test-reports', # Directory for XML files (string) or file stream outsuffix=None, # Suffix for filenames (None=timestamp, ''=no suffix) elapsed_times=True, # Include elapsed time in reports encoding='UTF-8', # XML encoding verbosity=2, # Verbosity level (0, 1, or 2) failfast=False, # Stop on first failure buffer=True, # Buffer stdout/stderr during tests ) # Run a test suite suite = unittest.TestLoader().loadTestsFromTestCase(MyTestCase) result = runner.run(suite) # Check results print(f"Tests run: {result.testsRun}") print(f"Failures: {len(result.failures)}") print(f"Errors: {len(result.errors)}") print(f"Skipped: {len(result.skipped)}") ``` -------------------------------- ### Command-Line Interface Usage Source: https://context7.com/xmlrunner/unittest-xml-reporting/llms.txt Illustrates how to execute tests and generate XML reports directly from the command line using the xmlrunner executable. This method supports various options for test discovery and output configuration. ```bash # Example command-line usage (actual command not provided in source, only heading) # python -m xmlrunner discover -o test-reports # python -m xmlrunner path/to/tests -o test-reports --suffix .xml ``` -------------------------------- ### Discover Tests with unittest-xml-reporting Source: https://github.com/xmlrunner/unittest-xml-reporting/blob/master/docs/index.md Use this command to discover and run tests with optional arguments. ```bash python -m xmlrunner discover [options] ``` -------------------------------- ### Run Tests with unittest-xml-reporting Source: https://github.com/xmlrunner/unittest-xml-reporting/blob/master/docs/index.md Use these commands to run tests directly from the command line, specifying the test module, class, or method. ```bash python -m xmlrunner test_module ``` ```bash python -m xmlrunner module.TestClass ``` ```bash python -m xmlrunner module.Class.test_method ``` -------------------------------- ### Run tests via command line Source: https://github.com/xmlrunner/unittest-xml-reporting/blob/master/README.md Execute tests using the xmlrunner module from the command line. ```bash python -m xmlrunner [options] python -m xmlrunner discover [options] # help python -m xmlrunner -h ``` ```bash python -m xmlrunner discover -t ~/mycode/tests -o /tmp/build/junit-reports ``` -------------------------------- ### Run tests via command line Source: https://context7.com/xmlrunner/unittest-xml-reporting/llms.txt Execute tests using the xmlrunner module with various options for targeting modules, classes, methods, and output configuration. ```bash python -m xmlrunner test_module ``` ```bash python -m xmlrunner module.TestClass ``` ```bash python -m xmlrunner module.TestClass.test_method ``` ```bash python -m xmlrunner discover -t ~/mycode/tests -o /tmp/build/junit-reports ``` ```bash python -m xmlrunner discover --output-file results.xml ``` ```bash python -m xmlrunner discover -o reports --outsuffix build123 ``` ```bash python -m xmlrunner -h ``` -------------------------------- ### Run Tests with XMLTestRunner to Directory Source: https://context7.com/xmlrunner/unittest-xml-reporting/llms.txt Demonstrates basic usage of XMLTestRunner to output XML reports to a specified directory. This is the default behavior when running tests via unittest.main. ```python import unittest import xmlrunner class TestMathOperations(unittest.TestCase): def test_addition(self): self.assertEqual(1 + 1, 2) def test_division(self): self.assertEqual(10 / 2, 5) @unittest.skip("demonstrating skipping") def test_skipped(self): self.fail("shouldn't happen") def test_failure(self): self.assertEqual(1, 2) # This will fail if __name__ == '__main__': # Output XML reports to 'test-reports' directory unittest.main( testRunner=xmlrunner.XMLTestRunner(output='test-reports'), failfast=False, buffer=False, catchbreak=False ) # Generated XML file: test-reports/TEST-__main__.TestMathOperations-20240115120000.xml ``` -------------------------------- ### Run doctests with XMLTestRunner Source: https://context7.com/xmlrunner/unittest-xml-reporting/llms.txt Integrate doctests into an XML report by creating a DocTestSuite and running it with XMLTestRunner. ```python import doctest import xmlrunner def twice(n): """ Returns twice the input number. >>> twice(5) 10 >>> twice(0) 0 >>> twice(-3) -6 """ return 2 * n class Multiplicator: def threetimes(self, n): """ Returns three times the input number. >>> Multiplicator().threetimes(5) 15 >>> Multiplicator().threetimes(10) 30 """ return 3 * n if __name__ == "__main__": # Create a test suite from doctests suite = doctest.DocTestSuite() # Run with XMLTestRunner runner = xmlrunner.XMLTestRunner(output='doctest-reports', verbosity=2) runner.run(suite) ``` -------------------------------- ### Configure Django test runner Source: https://context7.com/xmlrunner/unittest-xml-reporting/llms.txt Set up XMLTestRunner in Django projects via settings or programmatic configuration. ```python # settings.py - Django configuration # Set the custom test runner TEST_RUNNER = 'xmlrunner.extra.djangotestrunner.XMLTestRunner' # Optional: Configure XML report settings TEST_OUTPUT_VERBOSE = 2 # Verbosity: 0, 1, or 2 TEST_OUTPUT_DESCRIPTIONS = True # Show docstrings instead of method names TEST_OUTPUT_DIR = 'test-reports' # Output directory for XML files TEST_OUTPUT_FILE_NAME = None # Set to filename for single-file output # Run tests with: python manage.py test ``` ```python # Running Django tests programmatically from django.conf import settings from django.test.utils import get_runner # Configure Django settings settings.configure( DEBUG=True, DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3'}}, INSTALLED_APPS=['django.contrib.contenttypes', 'django.contrib.auth'], TEST_RUNNER='xmlrunner.extra.djangotestrunner.XMLTestRunner', TEST_OUTPUT_DIR='./test-reports', ) import django django.setup() # Get and run the test runner TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(["myapp.tests"]) ``` -------------------------------- ### Support for doctests Source: https://github.com/xmlrunner/unittest-xml-reporting/blob/master/README.md Use XMLTestRunner to execute and report on doctest suites. ```python import doctest import xmlrunner def twice(n): """ >>> twice(5) 10 """ return 2 * n class Multiplicator(object): def threetimes(self, n): """ >>> Multiplicator().threetimes(5) 15 """ return 3 * n if __name__ == "__main__": suite = doctest.DocTestSuite() xmlrunner.XMLTestRunner().run(suite) ``` -------------------------------- ### Generate Single XML File Output Source: https://context7.com/xmlrunner/unittest-xml-reporting/llms.txt Demonstrates how to consolidate all test results into a single XML file by passing a file stream to the XMLTestRunner. This is useful for centralized reporting. ```python import unittest import xmlrunner class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') def test_isupper(self): self.assertTrue('FOO'.isupper()) self.assertFalse('Foo'.isupper()) class TestListMethods(unittest.TestCase): def test_append(self): lst = [1, 2, 3] lst.append(4) self.assertEqual(lst, [1, 2, 3, 4]) if __name__ == '__main__': # Output all results to a single XML file with open('results.xml', 'wb') as output: unittest.main( testRunner=xmlrunner.XMLTestRunner(output=output), failfast=False, buffer=False, catchbreak=False, exit=False ) # Generated file: results.xml (contains all test suites in element) ``` -------------------------------- ### Configure XML Test Runner in tests.py Source: https://github.com/xmlrunner/unittest-xml-reporting/blob/master/docs/index.md Add this block to your tests.py file to run tests and output XML reports to the 'test-reports' directory. This configures the unittest main function to use the XMLTestRunner. ```python # tests.py if __name__ == '__main__': unittest.main( testRunner=xmlrunner.XMLTestRunner(output='test-reports'), # these make sure that some options that are not applicable # remain hidden from the help menu. failfast=False, buffer=False, catchbreak=False) ``` -------------------------------- ### Run Tests and Store Results in Memory Source: https://github.com/xmlrunner/unittest-xml-reporting/blob/master/README.md Use this snippet to run unit tests and capture the XML results in an in-memory buffer. This is useful for programmatic access to test results without writing to a file immediately. ```python import io import unittest import xmlrunner # run the tests storing results in memory out = io.BytesIO() unittest.main( testRunner=xmlrunner.XMLTestRunner(output=out), failfast=False, buffer=False, catchbreak=False, exit=False) ``` -------------------------------- ### Build XML reports with TestXMLBuilder Source: https://context7.com/xmlrunner/unittest-xml-reporting/llms.txt Construct custom XML test reports programmatically using the builder pattern. ```python from xmlrunner.builder import TestXMLBuilder # Create a new XML builder builder = TestXMLBuilder() # Begin the root testsuites context builder.begin_context('testsuites', 'AllTests') # Add a testsuite builder.begin_context('testsuite', 'test_module.TestClass') # Add a passing testcase builder.begin_context('testcase', 'test_success') builder.increment_counter('tests') builder.end_context() # Add a failing testcase builder.begin_context('testcase', 'test_failure') builder.increment_counter('tests') builder.increment_counter('failures') builder.append('failure', 'AssertionError: 1 != 2', type='AssertionError', message='1 != 2') builder.end_context() # Add a testcase with system output builder.begin_context('testcase', 'test_with_output') builder.increment_counter('tests') builder.append_cdata_section('system-out', 'Debug output from test\nMore output') builder.append_cdata_section('system-err', 'Warning messages') builder.end_context() # Close testsuite builder.end_context() # Close testsuites and get the XML xml_output = builder.finish() print(xml_output.decode('utf-8')) ``` -------------------------------- ### Report to a single file Source: https://github.com/xmlrunner/unittest-xml-reporting/blob/master/README.md Configure the runner to output results to a specific file path. ```python if __name__ == '__main__': with open('/path/to/results.xml', 'wb') as output: unittest.main( testRunner=xmlrunner.XMLTestRunner(output=output), failfast=False, buffer=False, catchbreak=False) ``` -------------------------------- ### Handle unittest subtests with XML reporting Source: https://context7.com/xmlrunner/unittest-xml-reporting/llms.txt Demonstrates using self.subTest within a test class. Note that subtest results may have limited granularity in XML due to xUnit schema constraints. ```python import unittest import xmlrunner class TestWithSubTests(unittest.TestCase): def test_even_numbers(self): """Test that numbers are correctly identified as even.""" for num in range(0, 6, 2): with self.subTest(num=num): self.assertEqual(num % 2, 0) def test_number_ranges(self): """Test various number ranges.""" test_cases = [ (0, 10, True), (5, 10, True), (15, 10, False), ] for value, max_val, expected in test_cases: with self.subTest(value=value, max_val=max_val): self.assertEqual(value <= max_val, expected) if __name__ == '__main__': unittest.main( testRunner=xmlrunner.XMLTestRunner(output='subtest-reports', verbosity=2), failfast=False, buffer=False, catchbreak=False ) ``` -------------------------------- ### Configure Django Settings for XMLTestRunner Source: https://github.com/xmlrunner/unittest-xml-reporting/blob/master/README.md Add this line to your Django settings.py to enable XMLTestRunner as the test runner. This setting is essential for generating XML test reports. ```python TEST_RUNNER = 'xmlrunner.extra.djangotestrunner.XMLTestRunner' ``` -------------------------------- ### Use XMLTestRunner in unittest Source: https://github.com/xmlrunner/unittest-xml-reporting/blob/master/README.md Replace the standard unittest runner with XMLTestRunner to generate XML reports. ```python import random import unittest import xmlrunner class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.seq = list(range(10)) @unittest.skip("demonstrating skipping") def test_skipped(self): self.fail("shouldn't happen") def test_shuffle(self): # make sure the shuffled sequence does not lose any elements random.shuffle(self.seq) self.seq.sort() self.assertEqual(self.seq, list(range(10))) # should raise an exception for an immutable sequence self.assertRaises(TypeError, random.shuffle, (1,2,3)) def test_choice(self): element = random.choice(self.seq) self.assertTrue(element in self.seq) def test_sample(self): with self.assertRaises(ValueError): random.sample(self.seq, 20) for element in random.sample(self.seq, 5): self.assertTrue(element in self.seq) if __name__ == '__main__': unittest.main( testRunner=xmlrunner.XMLTestRunner(output='test-reports'), # these make sure that some options that are not applicable # remain hidden from the help menu. failfast=False, buffer=False, catchbreak=False) ``` -------------------------------- ### Generate XML Reports to Memory Source: https://context7.com/xmlrunner/unittest-xml-reporting/llms.txt Shows how to capture XML test report output in memory using an io.BytesIO object. This allows for programmatic manipulation or custom handling of the XML content without writing to disk. ```python import io import unittest import xmlrunner class TestCalculator(unittest.TestCase): def test_multiply(self): self.assertEqual(3 * 4, 12) # Run tests storing results in memory out = io.BytesIO() unittest.main( module='__main__', testRunner=xmlrunner.XMLTestRunner(output=out), failfast=False, buffer=False, catchbreak=False, exit=False ) # Access the XML content xml_content = out.getvalue() print(xml_content.decode('utf-8')) # Output: # # # # # # ``` -------------------------------- ### Extend test result class for custom reporting Source: https://context7.com/xmlrunner/unittest-xml-reporting/llms.txt Shows how to subclass _XMLTestResult and _TestInfo to track custom metrics during test execution. ```python import unittest import xmlrunner from xmlrunner.result import _XMLTestResult, _TestInfo class CustomTestInfo(_TestInfo): """Extended test info with custom attributes.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.custom_data = {} def add_custom_data(self, key, value): self.custom_data[key] = value class CustomXMLTestResult(_XMLTestResult): """Custom result class with additional tracking.""" def __init__(self, *args, **kwargs): kwargs['infoclass'] = CustomTestInfo super().__init__(*args, **kwargs) self.custom_metrics = {'total_assertions': 0} def addSuccess(self, test): super().addSuccess(test) # Add custom tracking self.custom_metrics['total_assertions'] += 1 # Use custom result class with XMLTestRunner runner = xmlrunner.XMLTestRunner( output='custom-reports', resultclass=CustomXMLTestResult, verbosity=2 ) suite = unittest.TestLoader().loadTestsFromTestCase(MyTestCase) result = runner.run(suite) # Access custom metrics print(f"Custom metrics: {result.custom_metrics}") ``` -------------------------------- ### Transform XML for Jenkins xUnit Source: https://context7.com/xmlrunner/unittest-xml-reporting/llms.txt Use the xunit_plugin transform to strip non-compliant attributes from XML reports for Jenkins compatibility. ```python import io import unittest import xmlrunner from xmlrunner.extra.xunit_plugin import transform class TestFeature(unittest.TestCase): def test_something(self): self.assertTrue(True) # Run tests and capture XML in memory out = io.BytesIO() unittest.main( module='__main__', testRunner=xmlrunner.XMLTestRunner(output=out), failfast=False, buffer=False, catchbreak=False, exit=False ) # Transform to remove file, line, timestamp attributes for strict xUnit compliance transformed_xml = transform(out.getvalue()) # Write the transformed XML to a file with open('TEST-report.xml', 'wb') as report: report.write(transformed_xml) # Original XML includes: file="...", line="...", timestamp="..." # Transformed XML has these attributes removed for strict schema compliance ``` -------------------------------- ### Transform and Save XML Test Results Source: https://github.com/xmlrunner/unittest-xml-reporting/blob/master/README.md This code transforms the raw XML output from the test runner, removing extra attributes, and saves it to a file named 'TEST-report.xml'. Ensure the 'transform' function is imported from 'xmlrunner.extra.xunit_plugin'. ```python from xmlrunner.extra.xunit_plugin import transform with open('TEST-report.xml', 'wb') as report: report.write(transform(out.getvalue())) ``` -------------------------------- ### Report expected failures and unexpected successes Source: https://context7.com/xmlrunner/unittest-xml-reporting/llms.txt Uses the @unittest.expectedFailure decorator to manage known bugs and unexpected test outcomes in XML reports. ```python import unittest import xmlrunner class TestExpectedBehaviors(unittest.TestCase): @unittest.expectedFailure def test_known_bug(self): """This test is expected to fail due to a known bug.""" self.assertEqual(1, 2) # Known issue, expected to fail @unittest.expectedFailure def test_unexpected_success(self): """This was expected to fail but passes - flagged as unexpected success.""" self.assertEqual(1, 1) # Unexpectedly passes def test_normal_pass(self): """Regular passing test.""" self.assertTrue(True) if __name__ == '__main__': unittest.main( testRunner=xmlrunner.XMLTestRunner(output='expected-reports', verbosity=2), failfast=False, buffer=False, catchbreak=False ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.