reporters.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. # -*- coding: utf-8 -*-
  2. """!@package grass.gunittest.reporters
  3. @brief GRASS Python testing framework module for report generation
  4. Copyright (C) 2014 by the GRASS Development Team
  5. This program is free software under the GNU General Public
  6. License (>=v2). Read the file COPYING that comes with GRASS GIS
  7. for details.
  8. @author Vaclav Petras
  9. """
  10. import os
  11. import datetime
  12. import xml.sax.saxutils as saxutils
  13. import xml.etree.ElementTree as et
  14. import subprocess
  15. from .utils import ensure_dir
  16. def get_source_url(path, revision, line=None):
  17. """
  18. :param path: directory or file path relative to remote repository root
  19. :param revision: SVN revision (should be a number)
  20. :param line: line in the file (should be None for directories)
  21. """
  22. tracurl = 'http://trac.osgeo.org/grass/browser/'
  23. if line:
  24. return '{tracurl}{path}?rev={revision}#L{line}'.format(**locals())
  25. else:
  26. return '{tracurl}{path}?rev={revision}'.format(**locals())
  27. def html_escape(text):
  28. """Escape ``'&'``, ``'<'``, and ``'>'`` in a string of data."""
  29. return saxutils.escape(text)
  30. def html_unescape(text):
  31. """Unescape ``'&amp;'``, ``'&lt;'``, and ``'&gt;'`` in a string of data."""
  32. return saxutils.unescape(text)
  33. def color_error_line(line):
  34. if line.startswith('ERROR: '):
  35. # TODO: use CSS class
  36. # ignoring the issue with \n at the end, HTML don't mind
  37. line = '<span style="color: red">' + line + "</span>"
  38. if line.startswith('FAIL: '):
  39. # TODO: use CSS class
  40. # ignoring the issue with \n at the end, HTML don't mind
  41. line = '<span style="color: red">' + line + "</span>"
  42. if line.startswith('WARNING: '):
  43. # TODO: use CSS class
  44. # ignoring the issue with \n at the end, HTML don't mind
  45. line = '<span style="color: blue">' + line + "</span>"
  46. #if line.startswith('Traceback ('):
  47. # line = '<span style="color: red">' + line + "</span>"
  48. return line
  49. def get_svn_revision():
  50. """Get SVN revision number
  51. :returns: SVN revision number as string or None if it is
  52. not possible to get
  53. """
  54. # TODO: here should be starting directory
  55. # but now we are using current as starting
  56. p = subprocess.Popen(['svnversion', '.'],
  57. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  58. stdout, stderr = p.communicate()
  59. rc = p.poll()
  60. if not rc:
  61. stdout = stdout.strip()
  62. if stdout.endswith('M'):
  63. stdout = stdout[:-1]
  64. if ':' in stdout:
  65. # the first one is the one of source code
  66. stdout = stdout.split(':')[0]
  67. return stdout
  68. else:
  69. return None
  70. def get_svn_info():
  71. """Get important information from ``svn info``
  72. :returns: SVN info as dictionary or None
  73. if it is not possible to obtain it
  74. """
  75. try:
  76. # TODO: introduce directory, not only current
  77. p = subprocess.Popen(['svn', 'info', '.', '--xml'],
  78. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  79. stdout, stderr = p.communicate()
  80. rc = p.poll()
  81. info = {}
  82. if not rc:
  83. root = et.fromstring(stdout)
  84. # TODO: get also date if this make sense
  85. # expecting only one <entry> element
  86. entry = root.find('entry')
  87. info['revision'] = entry.get('revision')
  88. info['url'] = entry.find('url').text
  89. relurl = entry.find('relative-url')
  90. # element which is not found is None
  91. # empty element would be bool(el) == False
  92. if relurl is not None:
  93. relurl = relurl.text
  94. # relative path has ^ at the beginning in SVN version 1.8.8
  95. if relurl.startswith('^'):
  96. relurl = relurl[1:]
  97. else:
  98. # SVN version 1.8.8 supports relative-url but older do not
  99. # so, get relative part from absolute URL
  100. const_url_part = 'https://svn.osgeo.org/grass/'
  101. relurl = info['url'][len(const_url_part):]
  102. info['relative-url'] = relurl
  103. return info
  104. # TODO: add this to svnversion function
  105. except OSError as e:
  106. import errno
  107. # ignore No such file or directory
  108. if e.errno != errno.ENOENT:
  109. raise
  110. return None
  111. class GrassTestFilesMultiReporter(object):
  112. def __init__(self, reporters, forgiving=False):
  113. self.reporters = reporters
  114. self.forgiving = forgiving
  115. def start(self, results_dir):
  116. # TODO: no directory cleaning (self.clean_before)? now cleaned by caller
  117. # TODO: perhaps only those whoe need it should do it (even multiple times)
  118. # and there is also the delet problem
  119. ensure_dir(os.path.abspath(results_dir))
  120. for reporter in self.reporters:
  121. try:
  122. reporter.start(results_dir)
  123. except AttributeError:
  124. if self.forgiving:
  125. pass
  126. else:
  127. raise
  128. def finish(self):
  129. for reporter in self.reporters:
  130. try:
  131. reporter.finish()
  132. except AttributeError:
  133. if self.forgiving:
  134. pass
  135. else:
  136. raise
  137. def start_file_test(self, module):
  138. for reporter in self.reporters:
  139. try:
  140. reporter.start_file_test(module)
  141. except AttributeError:
  142. if self.forgiving:
  143. pass
  144. else:
  145. raise
  146. def end_file_test(self, **kwargs):
  147. for reporter in self.reporters:
  148. try:
  149. reporter.end_file_test(**kwargs)
  150. except AttributeError:
  151. if self.forgiving:
  152. pass
  153. else:
  154. raise
  155. class GrassTestFilesCountingReporter(object):
  156. def __init__(self):
  157. self.test_files = None
  158. self.files_fail = None
  159. self.files_pass = None
  160. self.file_pass_per = None
  161. self.file_fail_per = None
  162. self.main_start_time = None
  163. self.main_end_time = None
  164. self.main_time = None
  165. self.file_start_time = None
  166. self.file_end_time = None
  167. self.file_time = None
  168. self._start_file_test_called = False
  169. def start(self, results_dir):
  170. self.test_files = 0
  171. self.files_fail = 0
  172. self.files_pass = 0
  173. # this might be moved to some report start method
  174. self.main_start_time = datetime.datetime.now()
  175. def finish(self):
  176. self.main_end_time = datetime.datetime.now()
  177. self.main_time = self.main_end_time - self.main_start_time
  178. assert self.test_files == self.files_fail + self.files_pass
  179. self.file_pass_per = 100 * float(self.files_pass) / self.test_files
  180. self.file_fail_per = 100 * float(self.files_fail) / self.test_files
  181. def start_file_test(self, module):
  182. self.file_start_time = datetime.datetime.now()
  183. self._start_file_test_called = True
  184. self.test_files += 1
  185. def end_file_test(self, returncode, **kwargs):
  186. assert self._start_file_test_called
  187. self.file_end_time = datetime.datetime.now()
  188. self.file_time = self.file_end_time - self.file_start_time
  189. if returncode:
  190. self.files_fail += 1
  191. else:
  192. self.files_pass += 1
  193. self._start_file_test_called = False
  194. class GrassTestFilesHtmlReporter(GrassTestFilesCountingReporter):
  195. unknown_number = '<span style="font-size: 60%">unknown</span>'
  196. def __init__(self):
  197. super(GrassTestFilesHtmlReporter, self).__init__()
  198. self.main_index = None
  199. def start(self, results_dir):
  200. super(GrassTestFilesHtmlReporter, self).start(results_dir)
  201. # having all variables public although not really part of API
  202. self.main_index = open(os.path.join(results_dir, 'index.html'), 'w')
  203. # TODO: this can be moved to the counter class
  204. self.failures = 0
  205. self.errors = 0
  206. self.skiped = 0
  207. self.successes = 0
  208. self.expected_failures = 0
  209. self.unexpected_success = 0
  210. self.total = 0
  211. # TODO: skiped and unexpected success
  212. svn_info = get_svn_info()
  213. if not svn_info:
  214. svn_text = ('<span style="font-size: 60%">'
  215. 'SVN revision cannot be be obtained'
  216. '</span>')
  217. else:
  218. url = get_source_url(path=svn_info['relative-url'],
  219. revision=svn_info['revision'])
  220. svn_text = ('SVN revision'
  221. ' <a href="{url}">'
  222. '{rev}</a>'
  223. ).format(url=url, rev=svn_info['revision'])
  224. self.main_index.write('<html><body>'
  225. '<h1>Test results</h1>'
  226. '{time:%Y-%m-%d %H:%M:%S}'
  227. ' ({svn})'
  228. '<table>'
  229. '<thead><tr>'
  230. '<th>Tested directory</th>'
  231. '<th>Test file</th>'
  232. '<th>Status</th>'
  233. '<th>Tests</th><th>Successful</td>'
  234. '<th>Failed</th><th>Percent successful</th>'
  235. '</tr></thead><tbody>'.format(
  236. time=self.main_start_time,
  237. svn=svn_text))
  238. def finish(self):
  239. super(GrassTestFilesHtmlReporter, self).finish()
  240. if self.total:
  241. pass_per = 100 * (float(self.successes) / self.total)
  242. pass_per = '{:.2f}%'.format(pass_per)
  243. else:
  244. pass_per = self.unknown_number
  245. tfoot = ('<tfoot>'
  246. '<tr>'
  247. '<td>Summary</td>'
  248. '<td>{nfiles} test files</td>'
  249. '<td>{nsper:.2f}% successful</td>'
  250. '<td>{total}</td><td>{st}</td><td>{ft}</td><td>{pt}</td>'
  251. '</tr>'
  252. '</tfoot>'.format(
  253. nfiles=self.test_files, nsper=self.file_pass_per,
  254. st=self.successes, ft=self.failures + self.errors,
  255. total=self.total, pt=pass_per
  256. ))
  257. summary_sentence = ('Executed {nfiles} test files in {time:}.'
  258. ' From them'
  259. ' {nsfiles} files ({nsper:.2f}%) were successful'
  260. ' and {nffiles} files ({nfper:.2f}%) failed.'
  261. .format(
  262. nfiles=self.test_files,
  263. time=self.main_time,
  264. nsfiles=self.files_pass,
  265. nffiles=self.files_fail,
  266. nsper=self.file_pass_per,
  267. nfper=self.file_fail_per))
  268. self.main_index.write('<tbody>{tfoot}</table>'
  269. '<p>{summary}</p>'
  270. '</body></html>'
  271. .format(
  272. tfoot=tfoot,
  273. summary=summary_sentence))
  274. self.main_index.close()
  275. def start_file_test(self, module):
  276. super(GrassTestFilesHtmlReporter, self).start_file_test(module)
  277. self.main_index.flush() # to get previous lines to the report
  278. def wrap_stdstream_to_html(self, infile, outfile, module, stream):
  279. before = '<html><body><h1>%s</h1><pre>' % (module.name + ' ' + stream)
  280. after = '</pre></body></html>'
  281. html = open(outfile, 'w')
  282. html.write(before)
  283. with open(infile) as text:
  284. for line in text:
  285. html.write(color_error_line(html_escape(line)))
  286. html.write(after)
  287. html.close()
  288. def returncode_to_html_text(self, returncode):
  289. if returncode:
  290. return '<span style="color: red">FAILED</span>'
  291. else:
  292. return '<span style="color: green">succeeded</span>' # SUCCEEDED
  293. def returncode_to_html_sentence(self, returncode):
  294. if returncode:
  295. return ('<span style="color: red">&#x274c;</span>'
  296. ' Test failed (return code %d)' % (returncode))
  297. else:
  298. return ('<span style="color: green">&#x2713;</span>'
  299. ' Test succeeded (return code %d)' % (returncode))
  300. def end_file_test(self, module, cwd, returncode, stdout, stderr,
  301. test_summary):
  302. super(GrassTestFilesHtmlReporter, self).end_file_test(
  303. module=module, cwd=cwd, returncode=returncode,
  304. stdout=stdout, stderr=stderr)
  305. # TODO: considering others accoring to total, OK?
  306. total = test_summary.get('total', None)
  307. failures = test_summary.get('failures', 0)
  308. errors = test_summary.get('errors', 0)
  309. # Python unittest TestResult class is reporting success for no
  310. # errors or failures, so skipped, expected failures and unexpected
  311. # success are ignored
  312. # but successful tests are only total - the others
  313. # TODO: add success counter to GrassTestResult base class
  314. skipped = test_summary.get('skipped', 0)
  315. expected_failures = test_summary.get('expected_failures', 0)
  316. unexpected_success = test_summary.get('unexpected_success', 0)
  317. self.failures += failures
  318. self.errors += errors
  319. self.skiped += skipped
  320. self.expected_failures += expected_failures
  321. self.unexpected_success += unexpected_success
  322. if total is not None:
  323. # success are only the clear ones
  324. # percentage is influenced by all but putting only failures to table
  325. successes = total - failures - errors - skipped - expected_failures - unexpected_success
  326. self.successes += successes
  327. self.total += total
  328. pass_per = 100 * (float(successes) / total)
  329. pass_per = '{:.2f}%'.format(pass_per)
  330. else:
  331. total = successes = pass_per = self.unknown_number
  332. bad_ones = failures + errors
  333. self.main_index.write(
  334. '<tr><td>{d}</td>'
  335. '<td><a href="{d}/{m}/index.html">{m}</a></td><td>{sf}</td>'
  336. '<td>{total}</td><td>{st}</td><td>{ft}</td><td>{pt}</td>'
  337. '<tr>'.format(
  338. d=module.tested_dir, m=module.name,
  339. sf=self.returncode_to_html_text(returncode),
  340. st=successes, ft=bad_ones, total=total, pt=pass_per))
  341. self.wrap_stdstream_to_html(infile=stdout,
  342. outfile=os.path.join(cwd, 'stdout.html'),
  343. module=module, stream='stdout')
  344. self.wrap_stdstream_to_html(infile=stderr,
  345. outfile=os.path.join(cwd, 'stderr.html'),
  346. module=module, stream='stderr')
  347. file_index_path = os.path.join(cwd, 'index.html')
  348. file_index = open(file_index_path, 'w')
  349. file_index.write(
  350. '<html><body>'
  351. '<h1>{m.name}</h1>'
  352. '<h2>{m.tested_dir} &ndash; {m.name}</h2>'
  353. '<p>{status}'
  354. '<p>Test duration: {dur}'
  355. '<ul>'
  356. '<li><a href="stdout.html">standard output (stdout)</a>'
  357. '<li><a href="stderr.html">standard error output (stderr)</a>'
  358. '<li><a href="testcodecoverage/index.html">code coverage</a>'
  359. '</ul>'
  360. '</body></html>'
  361. .format(
  362. dur=self.file_time, m=module,
  363. status=self.returncode_to_html_sentence(returncode)))
  364. file_index.close()
  365. if returncode:
  366. pass
  367. # TODO: here we don't have oportunity to write error file
  368. # to stream (stdout/stderr)
  369. # a stream can be added and if not none, we could write
  370. class GrassTestFilesTextReporter(GrassTestFilesCountingReporter):
  371. def __init__(self, stream):
  372. super(GrassTestFilesTextReporter, self).__init__()
  373. self._stream = stream
  374. def start(self, results_dir):
  375. super(GrassTestFilesTextReporter, self).start(results_dir)
  376. def finish(self):
  377. super(GrassTestFilesTextReporter, self).finish()
  378. summary_sentence = ('\nExecuted {nfiles} test files in {time:}.'
  379. '\nFrom them'
  380. ' {nsfiles} files ({nsper:.2f}%) were successful'
  381. ' and {nffiles} files ({nfper:.2f}%) failed.\n'
  382. .format(
  383. nfiles=self.test_files,
  384. time=self.main_time,
  385. nsfiles=self.files_pass,
  386. nffiles=self.files_fail,
  387. nsper=self.file_pass_per,
  388. nfper=self.file_fail_per))
  389. self._stream.write(summary_sentence)
  390. def start_file_test(self, module):
  391. super(GrassTestFilesTextReporter, self).start_file_test(module)
  392. self._stream.flush() # to get previous lines to the report
  393. def end_file_test(self, module, cwd, returncode, stdout, stderr,
  394. test_summary):
  395. super(GrassTestFilesTextReporter, self).end_file_test(
  396. module=module, cwd=cwd, returncode=returncode,
  397. stdout=stdout, stderr=stderr)
  398. if returncode:
  399. self._stream.write(
  400. '{m} from {d} failed'
  401. .format(
  402. d=module.tested_dir,
  403. m=module.name))
  404. num_failed = test_summary.get('failures', None)
  405. if num_failed:
  406. if num_failed > 1:
  407. text = ' ({f} tests failed)'
  408. else:
  409. text = ' ({f} test failed)'
  410. self._stream.write(text.format(f=num_failed))
  411. self._stream.write('\n')
  412. # TODO: here we lost the possibility to include also file name
  413. # of the appropriate report