reporters.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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 sys
  12. import datetime
  13. import xml.sax.saxutils as saxutils
  14. import xml.etree.ElementTree as et
  15. import subprocess
  16. from .utils import ensure_dir
  17. def get_source_url(path, revision, line=None):
  18. """
  19. :param path: directory or file path relative to remote repository root
  20. :param revision: SVN revision (should be a number)
  21. :param line: line in the file (should be None for directories)
  22. """
  23. tracurl = 'http://trac.osgeo.org/grass/browser/'
  24. if line:
  25. return '{tracurl}{path}?rev={revision}#L{line}'.format(**locals())
  26. else:
  27. return '{tracurl}{path}?rev={revision}'.format(**locals())
  28. def html_escape(text):
  29. """Escape ``'&'``, ``'<'``, and ``'>'`` in a string of data."""
  30. return saxutils.escape(text)
  31. def html_unescape(text):
  32. """Unescape ``'&amp;'``, ``'&lt;'``, and ``'&gt;'`` in a string of data."""
  33. return saxutils.unescape(text)
  34. def color_error_line(line):
  35. if line.startswith('ERROR: '):
  36. # TODO: use CSS class
  37. # ignoring the issue with \n at the end, HTML don't mind
  38. line = '<span style="color: red">' + line + "</span>"
  39. if line.startswith('FAIL: '):
  40. # TODO: use CSS class
  41. # ignoring the issue with \n at the end, HTML don't mind
  42. line = '<span style="color: red">' + line + "</span>"
  43. if line.startswith('WARNING: '):
  44. # TODO: use CSS class
  45. # ignoring the issue with \n at the end, HTML don't mind
  46. line = '<span style="color: blue">' + line + "</span>"
  47. #if line.startswith('Traceback ('):
  48. # line = '<span style="color: red">' + line + "</span>"
  49. return line
  50. def get_svn_revision():
  51. """Get SVN revision number
  52. :returns: SVN revision number as string or None if it is 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 GrassTestFilesReporter(object):
  112. def __init__(self, results_dir):
  113. # TODO: no directory cleaning (self.clean_before)? now cleaned by caller
  114. ensure_dir(os.path.abspath(results_dir))
  115. # having all variables public although not really part of API
  116. self.main_index = open(os.path.join(results_dir, 'index.html'), 'w')
  117. # this might be moved to some report start method
  118. self.main_start_time = datetime.datetime.now()
  119. svn_info = get_svn_info()
  120. if not svn_info:
  121. svn_text = ('<span style="font-size: 60%">'
  122. 'SVN revision cannot be be obtained'
  123. '</span>')
  124. else:
  125. url = get_source_url(path=svn_info['relative-url'],
  126. revision=svn_info['revision'])
  127. svn_text = ('SVN revision'
  128. ' <a href="{url}">'
  129. '{rev}</a>'
  130. ).format(url=url, rev=svn_info['revision'])
  131. self.main_index.write('<html><body>'
  132. '<h1>Test results</h1>'
  133. '{time:%Y-%m-%d %H:%M:%S}'
  134. ' ({svn})'
  135. '<table>'
  136. '<thead><tr>'
  137. '<th>Tested directory</th>'
  138. '<th>Test file</th>'
  139. '<th>Status</th>'
  140. '</tr></thead><tbody>'.format(
  141. time=self.main_start_time,
  142. svn=svn_text))
  143. self.file_start_time = None
  144. self._start_file_test_called = False
  145. self.test_files = 0
  146. self.files_failed = 0
  147. self.files_succeeded = 0
  148. def finish(self):
  149. main_end_time = datetime.datetime.now()
  150. main_time = main_end_time - self.main_start_time
  151. assert self.test_files == self.files_failed + self.files_succeeded
  152. file_success_per = 100 * float(self.files_succeeded) / self.test_files
  153. file_fail_per = 100 * float(self.files_failed) / self.test_files
  154. tfoot = ('<tfoot>'
  155. '<tr>'
  156. '<td>Summary</td>'
  157. '<td>{nfiles} test files</td>'
  158. '<td>{nsper:.2f}% successful</td>'
  159. '</tr>'
  160. '</tfoot>'.format(nfiles=self.test_files,
  161. nsper=file_success_per))
  162. summary_sentence = ('Executed {nfiles} test files in {time:}.'
  163. ' From them'
  164. ' {nsfiles} files ({nsper:.2f}%) were successful'
  165. ' and {nffiles} files ({nfper:.2f}%) failed.'
  166. .format(
  167. nfiles=self.test_files,
  168. time=main_time,
  169. nsfiles=self.files_succeeded,
  170. nffiles=self.files_failed,
  171. nsper=file_success_per,
  172. nfper=file_fail_per))
  173. self.main_index.write('<tbody>{tfoot}</table>'
  174. '<p>{summary}</p>'
  175. '</body></html>'
  176. .format(
  177. tfoot=tfoot,
  178. summary=summary_sentence))
  179. self.main_index.close()
  180. def start_file_test(self, module):
  181. self.file_start_time = datetime.datetime.now()
  182. self._start_file_test_called = True
  183. self.main_index.flush() # to get previous ones to the report
  184. self.test_files += 1
  185. def wrap_stdstream_to_html(self, infile, outfile, module, stream):
  186. before = '<html><body><h1>%s</h1><pre>' % (module.name + ' ' + stream)
  187. after = '</pre></body></html>'
  188. html = open(outfile, 'w')
  189. html.write(before)
  190. with open(infile) as text:
  191. for line in text:
  192. html.write(color_error_line(html_escape(line)))
  193. html.write(after)
  194. html.close()
  195. def returncode_to_html_text(self, returncode):
  196. if returncode:
  197. return '<span style="color: red">FAILED</span>'
  198. else:
  199. return '<span style="color: green">succeeded</span>' # SUCCEEDED
  200. def returncode_to_html_sentence(self, returncode):
  201. if returncode:
  202. return '<span style="color: red">&#x274c;</span> Test failed (return code %d)' % (returncode)
  203. else:
  204. return '<span style="color: green">&#x2713;</span> Test succeeded (return code %d)' % (returncode)
  205. def end_file_test(self, module, cwd, returncode, stdout, stderr):
  206. assert self._start_file_test_called
  207. file_time = datetime.datetime.now() - self.file_start_time
  208. self.main_index.write(
  209. '<tr><td>{d}</td>'
  210. '<td><a href="{d}/{m}/index.html">{m}</a></td><td>{sf}</td>'
  211. '<tr>'.format(
  212. d=module.tested_dir, m=module.name,
  213. sf=self.returncode_to_html_text(returncode)))
  214. self.wrap_stdstream_to_html(infile=stdout,
  215. outfile=os.path.join(cwd, 'stdout.html'),
  216. module=module, stream='stdout')
  217. self.wrap_stdstream_to_html(infile=stderr,
  218. outfile=os.path.join(cwd, 'stderr.html'),
  219. module=module, stream='stderr')
  220. file_index_path = os.path.join(cwd, 'index.html')
  221. file_index = open(file_index_path, 'w')
  222. file_index.write('<html><body>'
  223. '<h1>{m.name}</h1>'
  224. '<h2>{m.tested_dir} &ndash; {m.name}</h2>'
  225. '<p>{status}'
  226. '<p>Test duration: {dur}'
  227. '<ul>'
  228. '<li><a href="stdout.html">standard output (stdout)</a>'
  229. '<li><a href="stderr.html">standard error output (stderr)</a>'
  230. '<li><a href="testcodecoverage/index.html">code coverage</a>'
  231. '</ul>'
  232. '</body></html>'.format(
  233. dur=file_time, m=module,
  234. status=self.returncode_to_html_sentence(returncode)))
  235. file_index.close()
  236. if returncode:
  237. sys.stderr.write('{d}/{m} failed (see {f})\n'.format(d=module.tested_dir,
  238. m=module.name,
  239. f=file_index_path))
  240. self.files_failed += 1
  241. else:
  242. self.files_succeeded += 1
  243. self._start_file_test_called = False