/usr/lib/python2.7/dist-packages/rosunit/xmlrunner.py is in python-rosunit 1.14.2-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 | """
XML Test Runner for PyUnit
"""
# Written by Sebastian Rittau <srittau@jroger.in-berlin.de> and placed in
# the Public Domain. With contributions by Paolo Borelli.
from __future__ import print_function
__revision__ = "$Id$"
import codecs
import os.path
import re
import sys
import time
import traceback
import unittest
try:
from cStringIO import StringIO
python2 = True
except ImportError:
from io import StringIO
python2 = False
from xml.sax.saxutils import escape
import xml.etree.ElementTree as ET
def cdata(cdata_text):
return '<![CDATA[\n{}\n]]>'.format(cdata_text)
class _TestInfo(object):
"""Information about a particular test.
Used by _XMLTestResult.
"""
def __init__(self, test, time):
(self._class, self._method) = test.id().rsplit(".", 1)
self._time = time
self._error = None
self._failure = None
@staticmethod
def create_success(test, time):
"""Create a _TestInfo instance for a successful test."""
return _TestInfo(test, time)
@staticmethod
def create_failure(test, time, failure):
"""Create a _TestInfo instance for a failed test."""
info = _TestInfo(test, time)
info._failure = failure
return info
@staticmethod
def create_error(test, time, error):
"""Create a _TestInfo instance for an erroneous test."""
info = _TestInfo(test, time)
info._error = error
return info
def xml(self):
"""Create an XML tag with information about this test case.
"""
testcase = ET.Element("testcase")
testcase.set('classname', self._class)
testcase.set('name', self._method)
testcase.set('time', '%.4f' % self._time)
if self._failure != None:
self._print_error(testcase, 'failure', self._failure)
if self._error != None:
self._print_error(testcase, 'error', self._error)
return testcase
def print_report(self, stream):
"""Print information about this test case in XML format to the
supplied stream.
"""
stream.write(ET.tostring(self.xml()))
def print_report_text(self, stream):
#stream.write(' <testcase classname="%(class)s" name="%(method)s" time="%(time).4f">' % \
# {
# "class": self._class,
# "method": self._method,
# "time": self._time,
# })
stream.write('[Testcase: ' + self._method + ']')
if self._failure != None:
stream.write(' ... FAILURE!\n')
self._print_error_text(stream, 'failure', self._failure)
if self._error != None:
stream.write(' ... ERROR!\n')
self._print_error_text(stream, 'error', self._error)
if self._failure == None and self._error == None:
stream.write(' ... ok\n')
def _print_error(self, testcase, tagname, error):
"""
Append an XML tag with information from a failure or error to the
supplied testcase.
"""
tag = ET.SubElement(testcase, tagname)
tag.set('type', str(error[0].__name__))
tb_stream = StringIO()
traceback.print_tb(error[2], None, tb_stream)
tag.text ='%s\n%s' % (str(error[1]), tb_stream.getvalue())
def _print_error_text(self, stream, tagname, error):
"""Print information from a failure or error to the supplied stream."""
text = escape(str(error[1]))
stream.write('%s: %s\n' \
% (tagname.upper(), text))
tb_stream = StringIO()
traceback.print_tb(error[2], None, tb_stream)
stream.write(escape(tb_stream.getvalue()))
stream.write('-'*80 + '\n')
class _XMLTestResult(unittest.TestResult):
"""A test result class that stores result as XML.
Used by XMLTestRunner.
"""
def __init__(self, classname):
unittest.TestResult.__init__(self)
self._test_name = classname
self._start_time = None
self._tests = []
self._error = None
self._failure = None
def startTest(self, test):
unittest.TestResult.startTest(self, test)
self._error = None
self._failure = None
self._start_time = time.time()
def stopTest(self, test):
time_taken = time.time() - self._start_time
unittest.TestResult.stopTest(self, test)
if self._error:
info = _TestInfo.create_error(test, time_taken, self._error)
elif self._failure:
info = _TestInfo.create_failure(test, time_taken, self._failure)
else:
info = _TestInfo.create_success(test, time_taken)
self._tests.append(info)
def addError(self, test, err):
unittest.TestResult.addError(self, test, err)
self._error = err
def addFailure(self, test, err):
unittest.TestResult.addFailure(self, test, err)
self._failure = err
def filter_nonprintable_text(self, text):
pattern = r'[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\xFF\u0100-\uD7FF\uE000-\uFDCF\uFDE0-\uFFFD]'
if python2:
pattern = pattern.decode('unicode_escape')
else:
pattern = codecs.decode(pattern, 'unicode_escape')
invalid_chars = re.compile(pattern)
def invalid_char_replacer(m):
return "&#x"+('%04X' % ord(m.group(0)))+";"
return re.sub(invalid_chars, invalid_char_replacer, str(text))
def xml(self, time_taken, out, err):
"""
@return XML tag representing the object
@rtype: xml.etree.ElementTree.Element
"""
test_suite = ET.Element('testsuite')
test_suite.set('errors', str(len(self.errors)))
test_suite.set('failures', str(len(self.failures)))
test_suite.set('name', self._test_name)
test_suite.set('tests', str(self.testsRun))
test_suite.set('time', '%.3f' % time_taken)
for info in self._tests:
test_suite.append(info.xml())
system_out = ET.SubElement(test_suite, 'system-out')
system_out.text = cdata(self.filter_nonprintable_text(out))
system_err = ET.SubElement(test_suite, 'system-err')
system_err.text = cdata(self.filter_nonprintable_text(err))
return ET.ElementTree(test_suite)
def print_report(self, stream, time_taken, out, err):
"""Prints the XML report to the supplied stream.
The time the tests took to perform as well as the captured standard
output and standard error streams must be passed in.a
"""
stream.write(ET.tostring(self.xml(time_taken, out, err).getroot(), encoding='utf-8', method='xml'))
def print_report_text(self, stream, time_taken, out, err):
"""Prints the text report to the supplied stream.
The time the tests took to perform as well as the captured standard
output and standard error streams must be passed in.a
"""
#stream.write('<testsuite errors="%(e)d" failures="%(f)d" ' % \
# { "e": len(self.errors), "f": len(self.failures) })
#stream.write('name="%(n)s" tests="%(t)d" time="%(time).3f">\n' % \
# {
# "n": self._test_name,
# "t": self.testsRun,
# "time": time_taken,
# })
for info in self._tests:
info.print_report_text(stream)
class XMLTestRunner(object):
"""A test runner that stores results in XML format compatible with JUnit.
XMLTestRunner(stream=None) -> XML test runner
The XML file is written to the supplied stream. If stream is None, the
results are stored in a file called TEST-<module>.<class>.xml in the
current working directory (if not overridden with the path property),
where <module> and <class> are the module and class name of the test class.
"""
def __init__(self, stream=None):
self._stream = stream
self._path = "."
def run(self, test):
"""Run the given test case or test suite."""
class_ = test.__class__
classname = class_.__module__ + "." + class_.__name__
if self._stream == None:
filename = "TEST-%s.xml" % classname
stream = file(os.path.join(self._path, filename), "w")
stream.write('<?xml version="1.0" encoding="utf-8"?>\n')
else:
stream = self._stream
result = _XMLTestResult(classname)
start_time = time.time()
# TODO: Python 2.5: Use the with statement
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = StringIO()
sys.stderr = StringIO()
try:
test(result)
try:
out_s = sys.stdout.getvalue()
except AttributeError:
out_s = ""
try:
err_s = sys.stderr.getvalue()
except AttributeError:
err_s = ""
finally:
sys.stdout = old_stdout
sys.stderr = old_stderr
time_taken = time.time() - start_time
result.print_report(stream, time_taken, out_s, err_s)
result.print_report_text(sys.stdout, time_taken, out_s, err_s)
return result
def _set_path(self, path):
self._path = path
path = property(lambda self: self._path, _set_path, None,
"""The path where the XML files are stored.
This property is ignored when the XML file is written to a file
stream.""")
|