Skip to content

Instantly share code, notes, and snippets.

@astraw38
Last active June 18, 2024 17:36
Show Gist options
  • Save astraw38/168b23eed298c36b0411 to your computer and use it in GitHub Desktop.
Save astraw38/168b23eed298c36b0411 to your computer and use it in GitHub Desktop.
Combine multiple pytest runs into one XML.
from _pytest.junitxml import LogXML, Junit
from io import open
import pytest
import sys
import time
class MultiRunXml(LogXML):
"""
This is a wrapper around Pytest's LogXML, which
dumps the pytest run data to XML format.
All this does is keep track of all of the data from any test run, but only dumps
the Test Suite when you SPECIFICALLY call dump.
"""
def pytest_sessionfinish(self):
"""
Do nothing! Overrides the base class, which would
dump the data to XML.
:return:
"""
pass
def dump(self):
"""
Dumps all the test data to the specified XML file.
:return:
"""
with open(self.logfile, 'w', encoding='utf-8') as logfile:
suite_stop_time = time.time()
suite_time_delta = suite_stop_time - self.suite_start_time
numtests = self.passed + self.failed
logfile.write(u'<?xml version="1.0" encoding="utf-8"?>')
logfile.write(Junit.testsuite(
self.tests,
name="pytest",
errors=self.errors,
failures=self.failed,
skips=self.skipped,
tests=numtests,
time="%.3f" % suite_time_delta,
).unicode(indent=0))
if __name__ == '__main__':
arg_list = sys.argv[1:]
junit_output = [arg for arg in arg_list if "--junitxml" in arg]
if junit_output:
junit_logfile = junit_output.pop().split('--junitxml=')[1]
xml_dumper = MultiRunXml(logfile=junit_logfile, prefix=None)
xml_dumper.prefix = "FirstRun"
pytest.main(arg_list, plugins=[xml_dumper])
xml_dumper.prefix = "SecondRun"
pytest.main(arg_list, plugins=[xml_dumper])
xml_dumper.dump()
@drjasonharrison
Copy link

Notes: This runs pytest on the list of input tests twice. It is not a post-pytest merger of the test results.
Usage:

python -m MutliRunXml.py tests/test*.py --junitxml=./test-reports/junit.xml

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment