danielfm/unittest-xml-reporting — pull request #38 by chrisklaiber (2013-09-18 06:54:45+00:00)
Title: Remove invalid unicode characters from XML output

Prior to this patch invalid XML documents were generated when the
captured stdout/stderr contained unicode characters that are invalid in
XML 1.0. See http://www.w3.org/TR/2006/REC-xml-20060816/#charsets

This assumes that the encoding of bytes written to stdout/stderr is
utf-8 which seems reasonable and was the assumption prior to when commit
5f1cfab7 introduced Python 3 support.

I also fixed a minor typo ("fornat" -> "format") when writing the count
of unexpectedSuccesses.

I tested on Python 2.5, 2.7, and 3.3 with the following code. The one
gotcha was that Python 3's stdout doesn't accept byte strings. Without
the patch, the call to minidom.parse() raises:

xml.parsers.expat.ExpatError: not well-formed (invalid token): line 5, column 22

import sys
try:
import unittest
except ImportError:
import unittest2 as unittest
from xml.dom import minidom
import xmlrunner
is_py3 = sys.version_info[0] == 3

class UnicodeTest(unittest.TestCase):
def test_invalid_xml_unicode(self):
s = u'invalid xml: \x01\x0B\uFFFE'
if is_py3:
print(s)
else:
print(s.encode('utf-8'))

if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(UnicodeTest)
xmlrunner.XMLTestRunner(outsuffix='x').run(suite)
# This will error pre-patch on invalid XML characters.
minidom.parse('TEST-UnicodeTest-x.xml')