reporters.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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, module, cwd, returncode, stdout, stderr):
  147. for reporter in self.reporters:
  148. try:
  149. reporter.end_file_test(module, cwd, returncode, stdout, stderr)
  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, module, cwd, returncode, stdout, stderr):
  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. def __init__(self):
  196. super(GrassTestFilesHtmlReporter, self).__init__()
  197. self.main_index = None
  198. def start(self, results_dir):
  199. super(GrassTestFilesHtmlReporter, self).start(results_dir)
  200. # having all variables public although not really part of API
  201. self.main_index = open(os.path.join(results_dir, 'index.html'), 'w')
  202. svn_info = get_svn_info()
  203. if not svn_info:
  204. svn_text = ('<span style="font-size: 60%">'
  205. 'SVN revision cannot be be obtained'
  206. '</span>')
  207. else:
  208. url = get_source_url(path=svn_info['relative-url'],
  209. revision=svn_info['revision'])
  210. svn_text = ('SVN revision'
  211. ' <a href="{url}">'
  212. '{rev}</a>'
  213. ).format(url=url, rev=svn_info['revision'])
  214. self.main_index.write('<html><body>'
  215. '<h1>Test results</h1>'
  216. '{time:%Y-%m-%d %H:%M:%S}'
  217. ' ({svn})'
  218. '<table>'
  219. '<thead><tr>'
  220. '<th>Tested directory</th>'
  221. '<th>Test file</th>'
  222. '<th>Status</th>'
  223. '</tr></thead><tbody>'.format(
  224. time=self.main_start_time,
  225. svn=svn_text))
  226. def finish(self):
  227. super(GrassTestFilesHtmlReporter, self).finish()
  228. tfoot = ('<tfoot>'
  229. '<tr>'
  230. '<td>Summary</td>'
  231. '<td>{nfiles} test files</td>'
  232. '<td>{nsper:.2f}% successful</td>'
  233. '</tr>'
  234. '</tfoot>'.format(nfiles=self.test_files,
  235. nsper=self.file_pass_per))
  236. summary_sentence = ('Executed {nfiles} test files in {time:}.'
  237. ' From them'
  238. ' {nsfiles} files ({nsper:.2f}%) were successful'
  239. ' and {nffiles} files ({nfper:.2f}%) failed.'
  240. .format(
  241. nfiles=self.test_files,
  242. time=self.main_time,
  243. nsfiles=self.files_pass,
  244. nffiles=self.files_fail,
  245. nsper=self.file_pass_per,
  246. nfper=self.file_fail_per))
  247. self.main_index.write('<tbody>{tfoot}</table>'
  248. '<p>{summary}</p>'
  249. '</body></html>'
  250. .format(
  251. tfoot=tfoot,
  252. summary=summary_sentence))
  253. self.main_index.close()
  254. def start_file_test(self, module):
  255. super(GrassTestFilesHtmlReporter, self).start_file_test(module)
  256. self.main_index.flush() # to get previous lines to the report
  257. def wrap_stdstream_to_html(self, infile, outfile, module, stream):
  258. before = '<html><body><h1>%s</h1><pre>' % (module.name + ' ' + stream)
  259. after = '</pre></body></html>'
  260. html = open(outfile, 'w')
  261. html.write(before)
  262. with open(infile) as text:
  263. for line in text:
  264. html.write(color_error_line(html_escape(line)))
  265. html.write(after)
  266. html.close()
  267. def returncode_to_html_text(self, returncode):
  268. if returncode:
  269. return '<span style="color: red">FAILED</span>'
  270. else:
  271. return '<span style="color: green">succeeded</span>' # SUCCEEDED
  272. def returncode_to_html_sentence(self, returncode):
  273. if returncode:
  274. return ('<span style="color: red">&#x274c;</span>'
  275. ' Test failed (return code %d)' % (returncode))
  276. else:
  277. return ('<span style="color: green">&#x2713;</span>'
  278. ' Test succeeded (return code %d)' % (returncode))
  279. def end_file_test(self, module, cwd, returncode, stdout, stderr):
  280. super(GrassTestFilesHtmlReporter, self).end_file_test(
  281. module=module, cwd=cwd, returncode=returncode,
  282. stdout=stdout, stderr=stderr)
  283. self.main_index.write(
  284. '<tr><td>{d}</td>'
  285. '<td><a href="{d}/{m}/index.html">{m}</a></td><td>{sf}</td>'
  286. '<tr>'.format(
  287. d=module.tested_dir, m=module.name,
  288. sf=self.returncode_to_html_text(returncode)))
  289. self.wrap_stdstream_to_html(infile=stdout,
  290. outfile=os.path.join(cwd, 'stdout.html'),
  291. module=module, stream='stdout')
  292. self.wrap_stdstream_to_html(infile=stderr,
  293. outfile=os.path.join(cwd, 'stderr.html'),
  294. module=module, stream='stderr')
  295. file_index_path = os.path.join(cwd, 'index.html')
  296. file_index = open(file_index_path, 'w')
  297. file_index.write(
  298. '<html><body>'
  299. '<h1>{m.name}</h1>'
  300. '<h2>{m.tested_dir} &ndash; {m.name}</h2>'
  301. '<p>{status}'
  302. '<p>Test duration: {dur}'
  303. '<ul>'
  304. '<li><a href="stdout.html">standard output (stdout)</a>'
  305. '<li><a href="stderr.html">standard error output (stderr)</a>'
  306. '<li><a href="testcodecoverage/index.html">code coverage</a>'
  307. '</ul>'
  308. '</body></html>'
  309. .format(
  310. dur=self.file_time, m=module,
  311. status=self.returncode_to_html_sentence(returncode)))
  312. file_index.close()
  313. if returncode:
  314. pass
  315. # TODO: here we don't have oportunity to write error file
  316. # to stream (stdout/stderr)
  317. # a stream can be added and if not none, we could write
  318. class GrassTestFilesTextReporter(GrassTestFilesCountingReporter):
  319. def __init__(self, stream):
  320. super(GrassTestFilesTextReporter, self).__init__()
  321. self._stream = stream
  322. def start(self, results_dir):
  323. super(GrassTestFilesTextReporter, self).start(results_dir)
  324. def finish(self):
  325. super(GrassTestFilesTextReporter, self).finish()
  326. summary_sentence = ('\nExecuted {nfiles} test files in {time:}.'
  327. '\nFrom them'
  328. ' {nsfiles} files ({nsper:.2f}%) were successful'
  329. ' and {nffiles} files ({nfper:.2f}%) failed.\n'
  330. .format(
  331. nfiles=self.test_files,
  332. time=self.main_time,
  333. nsfiles=self.files_pass,
  334. nffiles=self.files_fail,
  335. nsper=self.file_pass_per,
  336. nfper=self.file_fail_per))
  337. self._stream.write(summary_sentence)
  338. def start_file_test(self, module):
  339. super(GrassTestFilesTextReporter, self).start_file_test(module)
  340. self._stream.flush() # to get previous lines to the report
  341. def end_file_test(self, module, cwd, returncode, stdout, stderr):
  342. super(GrassTestFilesTextReporter, self).end_file_test(
  343. module=module, cwd=cwd, returncode=returncode,
  344. stdout=stdout, stderr=stderr)
  345. if returncode:
  346. self._stream.write(
  347. '{m} from {d} failed\n'
  348. .format(
  349. d=module.tested_dir,
  350. m=module.name))
  351. # TODO: here we lost the possibility to include also file name
  352. # of the appropriate report