xmlrunner.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. # -*- coding: utf-8 -*-
  2. """unittest-xml-reporting is a PyUnit-based TestRunner that can export test
  3. results to XML files that can be consumed by a wide range of tools, such as
  4. build systems, IDEs and Continuous Integration servers.
  5. This module provides the XMLTestRunner class, which is heavily based on the
  6. default TextTestRunner. This makes the XMLTestRunner very simple to use.
  7. The script below, adapted from the unittest documentation, shows how to use
  8. XMLTestRunner in a very simple way. In fact, the only difference between this
  9. script and the original one is the last line:
  10. import random
  11. import unittest
  12. import xmlrunner
  13. class TestSequenceFunctions(unittest.TestCase):
  14. def setUp(self):
  15. self.seq = range(10)
  16. def test_shuffle(self):
  17. # make sure the shuffled sequence does not lose any elements
  18. random.shuffle(self.seq)
  19. self.seq.sort()
  20. self.assertEqual(self.seq, range(10))
  21. def test_choice(self):
  22. element = random.choice(self.seq)
  23. self.assertTrue(element in self.seq)
  24. def test_sample(self):
  25. self.assertRaises(ValueError, random.sample, self.seq, 20)
  26. for element in random.sample(self.seq, 5):
  27. self.assertTrue(element in self.seq)
  28. if __name__ == '__main__':
  29. unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))
  30. """
  31. from __future__ import absolute_import
  32. import os
  33. import sys
  34. import time
  35. from unittest import TestResult, TextTestResult, TextTestRunner
  36. import xml.dom.minidom
  37. try:
  38. from StringIO import StringIO
  39. except ImportError:
  40. from io import StringIO # doesn't accept 'str' in Py2
  41. class XMLDocument(xml.dom.minidom.Document):
  42. def createCDATAOrText(self, data):
  43. if ']]>' in data:
  44. return self.createTextNode(data)
  45. return self.createCDATASection(data)
  46. class _TestInfo(object):
  47. """This class is used to keep useful information about the execution of a
  48. test method.
  49. """
  50. # Possible test outcomes
  51. (SUCCESS, FAILURE, ERROR) = range(3)
  52. def __init__(self, test_result, test_method, outcome=SUCCESS, err=None):
  53. "Create a new instance of _TestInfo."
  54. self.test_result = test_result
  55. self.test_method = test_method
  56. self.outcome = outcome
  57. self.err = err
  58. self.stdout = test_result.stdout and test_result.stdout.getvalue().strip() or ''
  59. self.stderr = test_result.stdout and test_result.stderr.getvalue().strip() or ''
  60. def get_elapsed_time(self):
  61. """Return the time that shows how long the test method took to
  62. execute.
  63. """
  64. return self.test_result.stop_time - self.test_result.start_time
  65. def get_description(self):
  66. "Return a text representation of the test method."
  67. return self.test_result.getDescription(self.test_method)
  68. def get_error_info(self):
  69. """Return a text representation of an exception thrown by a test
  70. method.
  71. """
  72. if not self.err:
  73. return ''
  74. return self.test_result._exc_info_to_string(
  75. self.err, self.test_method)
  76. class _XMLTestResult(TextTestResult):
  77. """A test result class that can express test results in a XML report.
  78. Used by XMLTestRunner.
  79. """
  80. def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1,
  81. elapsed_times=True):
  82. "Create a new instance of _XMLTestResult."
  83. TextTestResult.__init__(self, stream, descriptions, verbosity)
  84. self.successes = []
  85. self.callback = None
  86. self.elapsed_times = elapsed_times
  87. self.output_patched = False
  88. def _prepare_callback(self, test_info, target_list, verbose_str,
  89. short_str):
  90. """Append a _TestInfo to the given target list and sets a callback
  91. method to be called by stopTest method.
  92. """
  93. target_list.append(test_info)
  94. def callback():
  95. """This callback prints the test method outcome to the stream,
  96. as well as the elapsed time.
  97. """
  98. # Ignore the elapsed times for a more reliable unit testing
  99. if not self.elapsed_times:
  100. self.start_time = self.stop_time = 0
  101. if self.showAll:
  102. self.stream.writeln('(%.3fs) %s' % \
  103. (test_info.get_elapsed_time(), verbose_str))
  104. elif self.dots:
  105. self.stream.write(short_str)
  106. self.callback = callback
  107. def _patch_standard_output(self):
  108. """Replace the stdout and stderr streams with string-based streams
  109. in order to capture the tests' output.
  110. """
  111. if not self.output_patched:
  112. (self.old_stdout, self.old_stderr) = (sys.stdout, sys.stderr)
  113. self.output_patched = True
  114. (sys.stdout, sys.stderr) = (self.stdout, self.stderr) = \
  115. (StringIO(), StringIO())
  116. def _restore_standard_output(self):
  117. "Restore the stdout and stderr streams."
  118. (sys.stdout, sys.stderr) = (self.old_stdout, self.old_stderr)
  119. self.output_patched = False
  120. def startTest(self, test):
  121. "Called before execute each test method."
  122. self._patch_standard_output()
  123. self.start_time = time.time()
  124. TestResult.startTest(self, test)
  125. if self.showAll:
  126. self.stream.write(' ' + self.getDescription(test))
  127. self.stream.write(" ... ")
  128. def stopTest(self, test):
  129. "Called after execute each test method."
  130. self._restore_standard_output()
  131. TextTestResult.stopTest(self, test)
  132. self.stop_time = time.time()
  133. if self.callback and callable(self.callback):
  134. self.callback()
  135. self.callback = None
  136. def addSuccess(self, test):
  137. "Called when a test executes successfully."
  138. self._prepare_callback(_TestInfo(self, test),
  139. self.successes, 'OK', '.')
  140. def addFailure(self, test, err):
  141. "Called when a test method fails."
  142. self._prepare_callback(_TestInfo(self, test, _TestInfo.FAILURE, err),
  143. self.failures, 'FAIL', 'F')
  144. def addError(self, test, err):
  145. "Called when a test method raises an error."
  146. self._prepare_callback(_TestInfo(self, test, _TestInfo.ERROR, err),
  147. self.errors, 'ERROR', 'E')
  148. def printErrorList(self, flavour, errors):
  149. "Write some information about the FAIL or ERROR to the stream."
  150. for test_info in errors:
  151. if isinstance(test_info, tuple):
  152. test_info, exc_info = test_info
  153. try:
  154. t = test_info.get_elapsed_time()
  155. except AttributeError:
  156. t = 0
  157. try:
  158. descr = test_info.get_description()
  159. except AttributeError:
  160. try:
  161. descr = test_info.getDescription()
  162. except AttributeError:
  163. descr = str(test_info)
  164. try:
  165. err_info = test_info.get_error_info()
  166. except AttributeError:
  167. err_info = str(test_info)
  168. self.stream.writeln(self.separator1)
  169. self.stream.writeln('%s [%.3fs]: %s' % (flavour, t, descr))
  170. self.stream.writeln(self.separator2)
  171. self.stream.writeln('%s' % err_info)
  172. def _get_info_by_testcase(self):
  173. """This method organizes test results by TestCase module. This
  174. information is used during the report generation, where a XML report
  175. will be generated for each TestCase.
  176. """
  177. tests_by_testcase = {}
  178. for tests in (self.successes, self.failures, self.errors):
  179. for test_info in tests:
  180. if not isinstance(test_info, _TestInfo):
  181. print("Unexpected test result type: %r" % (test_info,))
  182. continue
  183. testcase = type(test_info.test_method)
  184. # Ignore module name if it is '__main__'
  185. module = testcase.__module__ + '.'
  186. if module == '__main__.':
  187. module = ''
  188. testcase_name = module + testcase.__name__
  189. if testcase_name not in tests_by_testcase:
  190. tests_by_testcase[testcase_name] = []
  191. tests_by_testcase[testcase_name].append(test_info)
  192. return tests_by_testcase
  193. def _report_testsuite(suite_name, tests, xml_document):
  194. "Appends the testsuite section to the XML document."
  195. testsuite = xml_document.createElement('testsuite')
  196. xml_document.appendChild(testsuite)
  197. testsuite.setAttribute('name', str(suite_name))
  198. testsuite.setAttribute('tests', str(len(tests)))
  199. testsuite.setAttribute('time', '%.3f' %
  200. sum([e.get_elapsed_time() for e in tests]))
  201. failures = len([1 for e in tests if e.outcome == _TestInfo.FAILURE])
  202. testsuite.setAttribute('failures', str(failures))
  203. errors = len([1 for e in tests if e.outcome == _TestInfo.ERROR])
  204. testsuite.setAttribute('errors', str(errors))
  205. return testsuite
  206. _report_testsuite = staticmethod(_report_testsuite)
  207. def _report_testcase(suite_name, test_result, xml_testsuite, xml_document):
  208. "Appends a testcase section to the XML document."
  209. testcase = xml_document.createElement('testcase')
  210. xml_testsuite.appendChild(testcase)
  211. testcase.setAttribute('classname', str(suite_name))
  212. testcase.setAttribute('name', test_result.test_method.shortDescription()
  213. or getattr(test_result.test_method, '_testMethodName',
  214. str(test_result.test_method)))
  215. testcase.setAttribute('time', '%.3f' % test_result.get_elapsed_time())
  216. if (test_result.outcome != _TestInfo.SUCCESS):
  217. elem_name = ('failure', 'error')[test_result.outcome-1]
  218. failure = xml_document.createElement(elem_name)
  219. testcase.appendChild(failure)
  220. failure.setAttribute('type', str(test_result.err[0].__name__))
  221. failure.setAttribute('message', str(test_result.err[1]))
  222. error_info = test_result.get_error_info()
  223. failureText = xml_document.createCDATAOrText(error_info)
  224. failure.appendChild(failureText)
  225. _report_testcase = staticmethod(_report_testcase)
  226. def _report_output(test_runner, xml_testsuite, xml_document, stdout, stderr):
  227. "Appends the system-out and system-err sections to the XML document."
  228. systemout = xml_document.createElement('system-out')
  229. xml_testsuite.appendChild(systemout)
  230. systemout_text = xml_document.createCDATAOrText(stdout)
  231. systemout.appendChild(systemout_text)
  232. systemerr = xml_document.createElement('system-err')
  233. xml_testsuite.appendChild(systemerr)
  234. systemerr_text = xml_document.createCDATAOrText(stderr)
  235. systemerr.appendChild(systemerr_text)
  236. _report_output = staticmethod(_report_output)
  237. def generate_reports(self, test_runner):
  238. "Generates the XML reports to a given XMLTestRunner object."
  239. all_results = self._get_info_by_testcase()
  240. if type(test_runner.output) == str and not \
  241. os.path.exists(test_runner.output):
  242. os.makedirs(test_runner.output)
  243. for suite, tests in all_results.items():
  244. doc = XMLDocument()
  245. # Build the XML file
  246. testsuite = _XMLTestResult._report_testsuite(suite, tests, doc)
  247. stdout, stderr = [], []
  248. for test in tests:
  249. _XMLTestResult._report_testcase(suite, test, testsuite, doc)
  250. if test.stdout:
  251. stdout.extend(['*****************', test.get_description(), test.stdout])
  252. if test.stderr:
  253. stderr.extend(['*****************', test.get_description(), test.stderr])
  254. _XMLTestResult._report_output(test_runner, testsuite, doc,
  255. '\n'.join(stdout), '\n'.join(stderr))
  256. xml_content = doc.toprettyxml(indent='\t')
  257. if type(test_runner.output) is str:
  258. report_file = open('%s%sTEST-%s.xml' % \
  259. (test_runner.output, os.sep, suite), 'w')
  260. try:
  261. report_file.write(xml_content)
  262. finally:
  263. report_file.close()
  264. else:
  265. # Assume that test_runner.output is a stream
  266. test_runner.output.write(xml_content)
  267. class XMLTestRunner(TextTestRunner):
  268. """A test runner class that outputs the results in JUnit like XML files.
  269. """
  270. def __init__(self, output='.', stream=None, descriptions=True, verbose=False, elapsed_times=True):
  271. "Create a new instance of XMLTestRunner."
  272. if stream is None:
  273. stream = sys.stderr
  274. verbosity = (1, 2)[verbose]
  275. TextTestRunner.__init__(self, stream, descriptions, verbosity)
  276. self.output = output
  277. self.elapsed_times = elapsed_times
  278. def _make_result(self):
  279. """Create the TestResult object which will be used to store
  280. information about the executed tests.
  281. """
  282. return _XMLTestResult(self.stream, self.descriptions, \
  283. self.verbosity, self.elapsed_times)
  284. def run(self, test):
  285. "Run the given test case or test suite."
  286. # Prepare the test execution
  287. result = self._make_result()
  288. # Print a nice header
  289. self.stream.writeln()
  290. self.stream.writeln('Running tests...')
  291. self.stream.writeln(result.separator2)
  292. # Execute tests
  293. start_time = time.time()
  294. test(result)
  295. stop_time = time.time()
  296. time_taken = stop_time - start_time
  297. # Generate reports
  298. self.stream.writeln()
  299. self.stream.writeln('Generating XML reports...')
  300. result.generate_reports(self)
  301. # Print results
  302. result.printErrors()
  303. self.stream.writeln(result.separator2)
  304. run = result.testsRun
  305. self.stream.writeln("Ran %d test%s in %.3fs" %
  306. (run, run != 1 and "s" or "", time_taken))
  307. self.stream.writeln()
  308. # Error traces
  309. if not result.wasSuccessful():
  310. self.stream.write("FAILED (")
  311. failed, errored = (len(result.failures), len(result.errors))
  312. if failed:
  313. self.stream.write("failures=%d" % failed)
  314. if errored:
  315. if failed:
  316. self.stream.write(", ")
  317. self.stream.write("errors=%d" % errored)
  318. self.stream.writeln(")")
  319. else:
  320. self.stream.writeln("OK")
  321. return result