|
| 1 | +import codecs |
| 2 | +import os |
| 3 | +import tempfile |
| 4 | +from xml.dom import minidom |
| 5 | + |
| 6 | +from six import PY2 |
| 7 | + |
| 8 | +from junit_xml import TestSuite as Suite |
| 9 | + |
| 10 | + |
| 11 | +def serialize_and_read(test_suites, to_file=False, prettyprint=False, encoding=None): |
| 12 | + """writes the test suite to an XML string and then re-reads it using minidom, |
| 13 | + returning => (test suite element, list of test case elements)""" |
| 14 | + try: |
| 15 | + iter(test_suites) |
| 16 | + except TypeError: |
| 17 | + test_suites = [test_suites] |
| 18 | + |
| 19 | + if to_file: |
| 20 | + fd, filename = tempfile.mkstemp(text=True) |
| 21 | + os.close(fd) |
| 22 | + with codecs.open(filename, mode='w', encoding=encoding) as f: |
| 23 | + Suite.to_file(f, test_suites, prettyprint=prettyprint, encoding=encoding) |
| 24 | + print("Serialized XML to temp file [%s]" % filename) |
| 25 | + xmldoc = minidom.parse(filename) |
| 26 | + os.remove(filename) |
| 27 | + else: |
| 28 | + xml_string = Suite.to_xml_string( |
| 29 | + test_suites, prettyprint=prettyprint, encoding=encoding) |
| 30 | + if PY2: |
| 31 | + assert isinstance(xml_string, unicode) # NOQA |
| 32 | + print("Serialized XML to string:\n%s" % xml_string) |
| 33 | + if encoding: |
| 34 | + xml_string = xml_string.encode(encoding) |
| 35 | + xmldoc = minidom.parseString(xml_string) |
| 36 | + |
| 37 | + def remove_blanks(node): |
| 38 | + for x in node.childNodes: |
| 39 | + if x.nodeType == minidom.Node.TEXT_NODE: |
| 40 | + if x.nodeValue: |
| 41 | + x.nodeValue = x.nodeValue.strip() |
| 42 | + elif x.nodeType == minidom.Node.ELEMENT_NODE: |
| 43 | + remove_blanks(x) |
| 44 | + |
| 45 | + remove_blanks(xmldoc) |
| 46 | + xmldoc.normalize() |
| 47 | + |
| 48 | + ret = [] |
| 49 | + suites = xmldoc.getElementsByTagName("testsuites")[0] |
| 50 | + for suite in suites.getElementsByTagName("testsuite"): |
| 51 | + cases = suite.getElementsByTagName("testcase") |
| 52 | + ret.append((suite, cases)) |
| 53 | + return ret |
0 commit comments