PageRenderTime 600ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/dnaComplete_optimized/pymodules/python2.7/lib/python/nose-1.3.0-py2.7.egg/nose/plugins/xunit.py

https://gitlab.com/pooja043/Globus_Docker_3
Python | 332 lines | 303 code | 10 blank | 19 comment | 6 complexity | 6ada5b5dba6fda7e44b0a8dcd8c7b6a7 MD5 | raw file
  1. """This plugin provides test results in the standard XUnit XML format.
  2. It's designed for the `Jenkins`_ (previously Hudson) continuous build
  3. system, but will probably work for anything else that understands an
  4. XUnit-formatted XML representation of test results.
  5. Add this shell command to your builder ::
  6. nosetests --with-xunit
  7. And by default a file named nosetests.xml will be written to the
  8. working directory.
  9. In a Jenkins builder, tick the box named "Publish JUnit test result report"
  10. under the Post-build Actions and enter this value for Test report XMLs::
  11. **/nosetests.xml
  12. If you need to change the name or location of the file, you can set the
  13. ``--xunit-file`` option.
  14. Here is an abbreviated version of what an XML test report might look like::
  15. <?xml version="1.0" encoding="UTF-8"?>
  16. <testsuite name="nosetests" tests="1" errors="1" failures="0" skip="0">
  17. <testcase classname="path_to_test_suite.TestSomething"
  18. name="test_it" time="0">
  19. <error type="exceptions.TypeError" message="oops, wrong type">
  20. Traceback (most recent call last):
  21. ...
  22. TypeError: oops, wrong type
  23. </error>
  24. </testcase>
  25. </testsuite>
  26. .. _Jenkins: http://jenkins-ci.org/
  27. """
  28. import codecs
  29. import doctest
  30. import os
  31. import sys
  32. import traceback
  33. import re
  34. import inspect
  35. from cStringIO import StringIO
  36. from time import time
  37. from xml.sax import saxutils
  38. from nose.plugins.base import Plugin
  39. from nose.exc import SkipTest
  40. from nose.pyversion import UNICODE_STRINGS
  41. # Invalid XML characters, control characters 0-31 sans \t, \n and \r
  42. CONTROL_CHARACTERS = re.compile(r"[\000-\010\013\014\016-\037]")
  43. TEST_ID = re.compile(r'^(.*?)(\(.*\))$')
  44. def xml_safe(value):
  45. """Replaces invalid XML characters with '?'."""
  46. return CONTROL_CHARACTERS.sub('?', value)
  47. def escape_cdata(cdata):
  48. """Escape a string for an XML CDATA section."""
  49. return xml_safe(cdata).replace(']]>', ']]>]]&gt;<![CDATA[')
  50. def id_split(idval):
  51. m = TEST_ID.match(idval)
  52. if m:
  53. name, fargs = m.groups()
  54. head, tail = name.rsplit(".", 1)
  55. return [head, tail+fargs]
  56. else:
  57. return idval.rsplit(".", 1)
  58. def nice_classname(obj):
  59. """Returns a nice name for class object or class instance.
  60. >>> nice_classname(Exception()) # doctest: +ELLIPSIS
  61. '...Exception'
  62. >>> nice_classname(Exception) # doctest: +ELLIPSIS
  63. '...Exception'
  64. """
  65. if inspect.isclass(obj):
  66. cls_name = obj.__name__
  67. else:
  68. cls_name = obj.__class__.__name__
  69. mod = inspect.getmodule(obj)
  70. if mod:
  71. name = mod.__name__
  72. # jython
  73. if name.startswith('org.python.core.'):
  74. name = name[len('org.python.core.'):]
  75. return "%s.%s" % (name, cls_name)
  76. else:
  77. return cls_name
  78. def exc_message(exc_info):
  79. """Return the exception's message."""
  80. exc = exc_info[1]
  81. if exc is None:
  82. # str exception
  83. result = exc_info[0]
  84. else:
  85. try:
  86. result = str(exc)
  87. except UnicodeEncodeError:
  88. try:
  89. result = unicode(exc)
  90. except UnicodeError:
  91. # Fallback to args as neither str nor
  92. # unicode(Exception(u'\xe6')) work in Python < 2.6
  93. result = exc.args[0]
  94. return xml_safe(result)
  95. def format_exception(exc_info):
  96. ec, ev, tb = exc_info
  97. # formatError() may have turned our exception object into a string, and
  98. # Python 3's traceback.format_exception() doesn't take kindly to that (it
  99. # expects an actual exception object). So we work around it, by doing the
  100. # work ourselves if ev is a string.
  101. if isinstance(ev, basestring):
  102. tb_data = ''.join(traceback.format_tb(tb))
  103. return tb_data + ev
  104. else:
  105. return ''.join(traceback.format_exception(*exc_info))
  106. class Tee(object):
  107. def __init__(self, *args):
  108. self._streams = args
  109. def write(self, *args):
  110. for s in self._streams:
  111. s.write(*args)
  112. def flush(self):
  113. for s in self._streams:
  114. s.flush()
  115. class Xunit(Plugin):
  116. """This plugin provides test results in the standard XUnit XML format."""
  117. name = 'xunit'
  118. score = 1500
  119. encoding = 'UTF-8'
  120. error_report_file = None
  121. def __init__(self):
  122. super(Xunit, self).__init__()
  123. self._capture_stack = []
  124. self._currentStdout = None
  125. self._currentStderr = None
  126. def _timeTaken(self):
  127. if hasattr(self, '_timer'):
  128. taken = time() - self._timer
  129. else:
  130. # test died before it ran (probably error in setup())
  131. # or success/failure added before test started probably
  132. # due to custom TestResult munging
  133. taken = 0.0
  134. return taken
  135. def _quoteattr(self, attr):
  136. """Escape an XML attribute. Value can be unicode."""
  137. attr = xml_safe(attr)
  138. if isinstance(attr, unicode) and not UNICODE_STRINGS:
  139. attr = attr.encode(self.encoding)
  140. return saxutils.quoteattr(attr)
  141. def options(self, parser, env):
  142. """Sets additional command line options."""
  143. Plugin.options(self, parser, env)
  144. parser.add_option(
  145. '--xunit-file', action='store',
  146. dest='xunit_file', metavar="FILE",
  147. default=env.get('NOSE_XUNIT_FILE', 'nosetests.xml'),
  148. help=("Path to xml file to store the xunit report in. "
  149. "Default is nosetests.xml in the working directory "
  150. "[NOSE_XUNIT_FILE]"))
  151. def configure(self, options, config):
  152. """Configures the xunit plugin."""
  153. Plugin.configure(self, options, config)
  154. self.config = config
  155. if self.enabled:
  156. self.stats = {'errors': 0,
  157. 'failures': 0,
  158. 'passes': 0,
  159. 'skipped': 0
  160. }
  161. self.errorlist = []
  162. self.error_report_file = codecs.open(options.xunit_file, 'w',
  163. self.encoding, 'replace')
  164. def report(self, stream):
  165. """Writes an Xunit-formatted XML file
  166. The file includes a report of test errors and failures.
  167. """
  168. self.stats['encoding'] = self.encoding
  169. self.stats['total'] = (self.stats['errors'] + self.stats['failures']
  170. + self.stats['passes'] + self.stats['skipped'])
  171. self.error_report_file.write(
  172. u'<?xml version="1.0" encoding="%(encoding)s"?>'
  173. u'<testsuite name="nosetests" tests="%(total)d" '
  174. u'errors="%(errors)d" failures="%(failures)d" '
  175. u'skip="%(skipped)d">' % self.stats)
  176. self.error_report_file.write(u''.join([self._forceUnicode(e)
  177. for e in self.errorlist]))
  178. self.error_report_file.write(u'</testsuite>')
  179. self.error_report_file.close()
  180. if self.config.verbosity > 1:
  181. stream.writeln("-" * 70)
  182. stream.writeln("XML: %s" % self.error_report_file.name)
  183. def _startCapture(self):
  184. self._capture_stack.append((sys.stdout, sys.stderr))
  185. self._currentStdout = StringIO()
  186. self._currentStderr = StringIO()
  187. sys.stdout = Tee(self._currentStdout, sys.stdout)
  188. sys.stderr = Tee(self._currentStderr, sys.stderr)
  189. def startContext(self, context):
  190. self._startCapture()
  191. def beforeTest(self, test):
  192. """Initializes a timer before starting a test."""
  193. self._timer = time()
  194. self._startCapture()
  195. def _endCapture(self):
  196. if self._capture_stack:
  197. sys.stdout, sys.stderr = self._capture_stack.pop()
  198. def afterTest(self, test):
  199. self._endCapture()
  200. self._currentStdout = None
  201. self._currentStderr = None
  202. def finalize(self, test):
  203. while self._capture_stack:
  204. self._endCapture()
  205. def _getCapturedStdout(self):
  206. if self._currentStdout:
  207. value = self._currentStdout.getvalue()
  208. if value:
  209. return '<system-out><![CDATA[%s]]></system-out>' % escape_cdata(
  210. value)
  211. return ''
  212. def _getCapturedStderr(self):
  213. if self._currentStderr:
  214. value = self._currentStderr.getvalue()
  215. if value:
  216. return '<system-err><![CDATA[%s]]></system-err>' % escape_cdata(
  217. value)
  218. return ''
  219. def addError(self, test, err, capt=None):
  220. """Add error output to Xunit report.
  221. """
  222. taken = self._timeTaken()
  223. if issubclass(err[0], SkipTest):
  224. type = 'skipped'
  225. self.stats['skipped'] += 1
  226. else:
  227. type = 'error'
  228. self.stats['errors'] += 1
  229. tb = format_exception(err)
  230. id = test.id()
  231. self.errorlist.append(
  232. '<testcase classname=%(cls)s name=%(name)s time="%(taken).3f">'
  233. '<%(type)s type=%(errtype)s message=%(message)s><![CDATA[%(tb)s]]>'
  234. '</%(type)s>%(systemout)s%(systemerr)s</testcase>' %
  235. {'cls': self._quoteattr(id_split(id)[0]),
  236. 'name': self._quoteattr(id_split(id)[-1]),
  237. 'taken': taken,
  238. 'type': type,
  239. 'errtype': self._quoteattr(nice_classname(err[0])),
  240. 'message': self._quoteattr(exc_message(err)),
  241. 'tb': escape_cdata(tb),
  242. 'systemout': self._getCapturedStdout(),
  243. 'systemerr': self._getCapturedStderr(),
  244. })
  245. def addFailure(self, test, err, capt=None, tb_info=None):
  246. """Add failure output to Xunit report.
  247. """
  248. taken = self._timeTaken()
  249. tb = format_exception(err)
  250. self.stats['failures'] += 1
  251. id = test.id()
  252. self.errorlist.append(
  253. '<testcase classname=%(cls)s name=%(name)s time="%(taken).3f">'
  254. '<failure type=%(errtype)s message=%(message)s><![CDATA[%(tb)s]]>'
  255. '</failure>%(systemout)s%(systemerr)s</testcase>' %
  256. {'cls': self._quoteattr(id_split(id)[0]),
  257. 'name': self._quoteattr(id_split(id)[-1]),
  258. 'taken': taken,
  259. 'errtype': self._quoteattr(nice_classname(err[0])),
  260. 'message': self._quoteattr(exc_message(err)),
  261. 'tb': escape_cdata(tb),
  262. 'systemout': self._getCapturedStdout(),
  263. 'systemerr': self._getCapturedStderr(),
  264. })
  265. def addSuccess(self, test, capt=None):
  266. """Add success output to Xunit report.
  267. """
  268. taken = self._timeTaken()
  269. self.stats['passes'] += 1
  270. id = test.id()
  271. self.errorlist.append(
  272. '<testcase classname=%(cls)s name=%(name)s '
  273. 'time="%(taken).3f">%(systemout)s%(systemerr)s</testcase>' %
  274. {'cls': self._quoteattr(id_split(id)[0]),
  275. 'name': self._quoteattr(id_split(id)[-1]),
  276. 'taken': taken,
  277. 'systemout': self._getCapturedStdout(),
  278. 'systemerr': self._getCapturedStderr(),
  279. })
  280. def _forceUnicode(self, s):
  281. if not UNICODE_STRINGS:
  282. if isinstance(s, str):
  283. s = s.decode(self.encoding, 'replace')
  284. return s