PageRenderTime 24ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/third_party/cython/src/Cython/Tests/xmlrunner.py

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