reporters.py 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. # -*- coding: utf-8 -*-
  2. """GRASS Python testing framework module for report generation
  3. Copyright (C) 2014 by the GRASS Development Team
  4. This program is free software under the GNU General Public
  5. License (>=v2). Read the file COPYING that comes with GRASS GIS
  6. for details.
  7. :authors: Vaclav Petras
  8. """
  9. import os
  10. import datetime
  11. import xml.sax.saxutils as saxutils
  12. import xml.etree.ElementTree as et
  13. import subprocess
  14. import StringIO
  15. import collections
  16. import types
  17. import re
  18. from .utils import ensure_dir
  19. from .checkers import text_to_keyvalue
  20. # TODO: change text_to_keyvalue to same sep as here
  21. # TODO: create keyvalue file and move it there together with things from checkers
  22. def keyvalue_to_text(keyvalue, sep='=', vsep='\n', isep=',',
  23. last_vertical=None):
  24. if not last_vertical:
  25. last_vertical = vsep == '\n'
  26. items = []
  27. for key, value in keyvalue.iteritems():
  28. # TODO: use isep for iterables other than strings
  29. if (not isinstance(value, types.StringTypes)
  30. and isinstance(value, collections.Iterable)):
  31. # TODO: this does not work for list of non-strings
  32. value = isep.join(value)
  33. items.append('{key}{sep}{value}'.format(
  34. key=key, sep=sep, value=value))
  35. text = vsep.join(items)
  36. if last_vertical:
  37. text = text + vsep
  38. return text
  39. def replace_in_file(file_path, pattern, repl):
  40. """
  41. :param repl: a repl paramter of ``re.sub()`` function
  42. """
  43. # using tmp file to store the replaced content
  44. tmp_file_path = file_path + '.tmp'
  45. old_file = open(file_path, 'r')
  46. new_file = open(tmp_file_path, 'w')
  47. for line in old_file:
  48. new_file.write(re.sub(pattern=pattern, string=line, repl=repl))
  49. new_file.close()
  50. old_file.close()
  51. # remove old file since it must not exist for rename/move
  52. os.remove(file_path)
  53. # replace old file by new file
  54. # TODO: this can fail in some (random) cases on MS Windows
  55. os.rename(tmp_file_path, file_path)
  56. class NoopFileAnonymizer(object):
  57. def anonymize(self, filenames):
  58. pass
  59. # TODO: why not remove GISDBASE by default?
  60. class FileAnonymizer(object):
  61. def __init__(self, paths_to_remove, remove_gisbase=True,
  62. remove_gisdbase=False):
  63. self._paths_to_remove = []
  64. if remove_gisbase:
  65. gisbase = os.environ['GISBASE']
  66. self._paths_to_remove.append(gisbase)
  67. if remove_gisdbase:
  68. # import only when really needed to avoid problems with
  69. # translations when environment is not set properly
  70. import grass.script as gscript
  71. gisdbase = gscript.gisenv()['GISDBASE']
  72. self._paths_to_remove.append(gisdbase)
  73. if paths_to_remove:
  74. self._paths_to_remove.extend(paths_to_remove)
  75. def anonymize(self, filenames):
  76. # besides GISBASE and test recursion start directory (which is
  77. # supposed to be source root directory or similar) we can also try
  78. # to remove user home directory and GISDBASE
  79. # we suppuse that we run in standard grass session
  80. # TODO: provide more effective implementation
  81. for path in self._paths_to_remove:
  82. for filename in filenames:
  83. path_end = r'[\\/]?'
  84. replace_in_file(filename, path + path_end, '')
  85. def get_source_url(path, revision, line=None):
  86. """
  87. :param path: directory or file path relative to remote repository root
  88. :param revision: SVN revision (should be a number)
  89. :param line: line in the file (should be None for directories)
  90. """
  91. tracurl = 'http://trac.osgeo.org/grass/browser/'
  92. if line:
  93. return '{tracurl}{path}?rev={revision}#L{line}'.format(**locals())
  94. else:
  95. return '{tracurl}{path}?rev={revision}'.format(**locals())
  96. def html_escape(text):
  97. """Escape ``'&'``, ``'<'``, and ``'>'`` in a string of data."""
  98. return saxutils.escape(text)
  99. def html_unescape(text):
  100. """Unescape ``'&amp;'``, ``'&lt;'``, and ``'&gt;'`` in a string of data."""
  101. return saxutils.unescape(text)
  102. def color_error_line(line):
  103. if line.startswith('ERROR: '):
  104. # TODO: use CSS class
  105. # ignoring the issue with \n at the end, HTML don't mind
  106. line = '<span style="color: red">' + line + "</span>"
  107. if line.startswith('FAIL: '):
  108. # TODO: use CSS class
  109. # ignoring the issue with \n at the end, HTML don't mind
  110. line = '<span style="color: red">' + line + "</span>"
  111. if line.startswith('WARNING: '):
  112. # TODO: use CSS class
  113. # ignoring the issue with \n at the end, HTML don't mind
  114. line = '<span style="color: blue">' + line + "</span>"
  115. #if line.startswith('Traceback ('):
  116. # line = '<span style="color: red">' + line + "</span>"
  117. return line
  118. def to_web_path(path):
  119. """Replace OS dependent path separator with slash.
  120. Path on MS Windows are not usable in links on web. For MS Windows,
  121. this replaces backslash with (forward) slash.
  122. """
  123. if os.path.sep != '/':
  124. return path.replace(os.path.sep, '/')
  125. else:
  126. return path
  127. def get_svn_revision():
  128. """Get SVN revision number
  129. :returns: SVN revision number as string or None if it is
  130. not possible to get
  131. """
  132. # TODO: here should be starting directory
  133. # but now we are using current as starting
  134. p = subprocess.Popen(['svnversion', '.'],
  135. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  136. stdout, stderr = p.communicate()
  137. rc = p.poll()
  138. if not rc:
  139. stdout = stdout.strip()
  140. if stdout.endswith('M'):
  141. stdout = stdout[:-1]
  142. if ':' in stdout:
  143. # the first one is the one of source code
  144. stdout = stdout.split(':')[0]
  145. return stdout
  146. else:
  147. return None
  148. def get_svn_info():
  149. """Get important information from ``svn info``
  150. :returns: SVN info as dictionary or None
  151. if it is not possible to obtain it
  152. """
  153. try:
  154. # TODO: introduce directory, not only current
  155. p = subprocess.Popen(['svn', 'info', '.', '--xml'],
  156. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  157. stdout, stderr = p.communicate()
  158. rc = p.poll()
  159. info = {}
  160. if not rc:
  161. root = et.fromstring(stdout)
  162. # TODO: get also date if this make sense
  163. # expecting only one <entry> element
  164. entry = root.find('entry')
  165. info['revision'] = entry.get('revision')
  166. info['url'] = entry.find('url').text
  167. relurl = entry.find('relative-url')
  168. # element which is not found is None
  169. # empty element would be bool(el) == False
  170. if relurl is not None:
  171. relurl = relurl.text
  172. # relative path has ^ at the beginning in SVN version 1.8.8
  173. if relurl.startswith('^'):
  174. relurl = relurl[1:]
  175. else:
  176. # SVN version 1.8.8 supports relative-url but older do not
  177. # so, get relative part from absolute URL
  178. const_url_part = 'https://svn.osgeo.org/grass/'
  179. relurl = info['url'][len(const_url_part):]
  180. info['relative-url'] = relurl
  181. return info
  182. # TODO: add this to svnversion function
  183. except OSError as e:
  184. import errno
  185. # ignore No such file or directory
  186. if e.errno != errno.ENOENT:
  187. raise
  188. return None
  189. def years_ago(date, years):
  190. # dateutil relative delte would be better but this is more portable
  191. return date - datetime.timedelta(weeks=years * 52)
  192. # TODO: these functions should be called only if we know that svn is installed
  193. # this will simplify the functions, caller must handle it anyway
  194. def get_svn_path_authors(path, from_date=None):
  195. """
  196. :returns: a set of authors
  197. """
  198. if from_date is None:
  199. # this is the SVN default for local copies
  200. revision_range = 'BASE:1'
  201. else:
  202. revision_range = 'BASE:{%s}' % from_date
  203. try:
  204. # TODO: allow also usage of --limit
  205. p = subprocess.Popen(['svn', 'log', '--xml',
  206. '--revision', revision_range, path],
  207. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  208. stdout, stderr = p.communicate()
  209. rc = p.poll()
  210. if not rc:
  211. root = et.fromstring(stdout)
  212. # TODO: get also date if this make sense
  213. # expecting only one <entry> element
  214. author_nodes = root.iterfind('*/author')
  215. authors = [n.text for n in author_nodes]
  216. return set(authors)
  217. except OSError as e:
  218. import errno
  219. # ignore No such file or directory
  220. if e.errno != errno.ENOENT:
  221. raise
  222. return None
  223. def get_html_test_authors_table(directory, tests_authors):
  224. # SVN gives us authors of code together with authors of tests
  225. # so test code authors list also contains authors of tests only
  226. # TODO: don't do this for the top level directories?
  227. tests_authors = set(tests_authors)
  228. no_svn_text = ('<span style="font-size: 60%">'
  229. 'Test file authors were not obtained.'
  230. '</span>')
  231. if (not tests_authors
  232. or (len(tests_authors) == 1 and list(tests_authors)[0] == '')):
  233. return '<h3>Code and test authors</h3>' + no_svn_text
  234. from_date = years_ago(datetime.date.today(), years=1)
  235. tested_dir_authors = get_svn_path_authors(directory, from_date)
  236. if tested_dir_authors is not None:
  237. not_testing_authors = tested_dir_authors - tests_authors
  238. else:
  239. no_svn_text = ('<span style="font-size: 60%">'
  240. 'Authors cannot be obtained using SVN.'
  241. '</span>')
  242. not_testing_authors = tested_dir_authors = [no_svn_text]
  243. if not not_testing_authors:
  244. not_testing_authors = ['all recent authors contributed tests']
  245. test_authors = (
  246. '<h3>Code and test authors</h3>'
  247. '<p style="font-size: 60%"><em>'
  248. 'Note that determination of authors is approximate and only'
  249. ' recent code authors are considered.'
  250. '</em></p>'
  251. '<table><tbody>'
  252. '<tr><td>Test authors:</td><td>{file_authors}</td></tr>'
  253. '<tr><td>Authors of tested code:</td><td>{code_authors}</td></tr>'
  254. '<tr><td>Authors owing tests:</td><td>{not_testing}</td></tr>'
  255. '</tbody></table>'
  256. .format(
  257. file_authors=', '.join(sorted(tests_authors)),
  258. code_authors=', '.join(sorted(tested_dir_authors)),
  259. not_testing=', '.join(sorted(not_testing_authors))
  260. ))
  261. return test_authors
  262. class GrassTestFilesMultiReporter(object):
  263. def __init__(self, reporters, forgiving=False):
  264. self.reporters = reporters
  265. self.forgiving = forgiving
  266. def start(self, results_dir):
  267. # TODO: no directory cleaning (self.clean_before)? now cleaned by caller
  268. # TODO: perhaps only those whoe need it should do it (even multiple times)
  269. # and there is also the delet problem
  270. ensure_dir(os.path.abspath(results_dir))
  271. for reporter in self.reporters:
  272. try:
  273. reporter.start(results_dir)
  274. except AttributeError:
  275. if self.forgiving:
  276. pass
  277. else:
  278. raise
  279. def finish(self):
  280. for reporter in self.reporters:
  281. try:
  282. reporter.finish()
  283. except AttributeError:
  284. if self.forgiving:
  285. pass
  286. else:
  287. raise
  288. def start_file_test(self, module):
  289. for reporter in self.reporters:
  290. try:
  291. reporter.start_file_test(module)
  292. except AttributeError:
  293. if self.forgiving:
  294. pass
  295. else:
  296. raise
  297. def end_file_test(self, **kwargs):
  298. for reporter in self.reporters:
  299. try:
  300. reporter.end_file_test(**kwargs)
  301. except AttributeError:
  302. if self.forgiving:
  303. pass
  304. else:
  305. raise
  306. class GrassTestFilesCountingReporter(object):
  307. def __init__(self):
  308. self.test_files = None
  309. self.files_fail = None
  310. self.files_pass = None
  311. self.file_pass_per = None
  312. self.file_fail_per = None
  313. self.main_start_time = None
  314. self.main_end_time = None
  315. self.main_time = None
  316. self.file_start_time = None
  317. self.file_end_time = None
  318. self.file_time = None
  319. self._start_file_test_called = False
  320. def start(self, results_dir):
  321. self.test_files = 0
  322. self.files_fail = 0
  323. self.files_pass = 0
  324. # this might be moved to some report start method
  325. self.main_start_time = datetime.datetime.now()
  326. def finish(self):
  327. self.main_end_time = datetime.datetime.now()
  328. self.main_time = self.main_end_time - self.main_start_time
  329. assert self.test_files == self.files_fail + self.files_pass
  330. if self.test_files:
  331. self.file_pass_per = 100 * float(self.files_pass) / self.test_files
  332. self.file_fail_per = 100 * float(self.files_fail) / self.test_files
  333. else:
  334. # if no tests were executed, probably something bad happend
  335. # try to report at least something
  336. self.file_pass_per = None
  337. self.file_fail_per = None
  338. def start_file_test(self, module):
  339. self.file_start_time = datetime.datetime.now()
  340. self._start_file_test_called = True
  341. self.test_files += 1
  342. def end_file_test(self, returncode, **kwargs):
  343. assert self._start_file_test_called
  344. self.file_end_time = datetime.datetime.now()
  345. self.file_time = self.file_end_time - self.file_start_time
  346. if returncode:
  347. self.files_fail += 1
  348. else:
  349. self.files_pass += 1
  350. self._start_file_test_called = False
  351. def percent_to_html(percent):
  352. if percent is None:
  353. return '<span style="color: {color}">unknown percentage</span>'
  354. elif percent > 100 or percent < 0:
  355. return "? {:.2f}% ?".format(percent)
  356. elif percent < 40:
  357. color = 'red'
  358. elif percent < 70:
  359. color = 'orange'
  360. else:
  361. color = 'green'
  362. return '<span style="color: {color}">{percent:.0f}%</span>'.format(
  363. percent=percent, color=color)
  364. def wrap_stdstream_to_html(infile, outfile, module, stream):
  365. before = '<html><body><h1>%s</h1><pre>' % (module.name + ' ' + stream)
  366. after = '</pre></body></html>'
  367. html = open(outfile, 'w')
  368. html.write(before)
  369. with open(infile) as text:
  370. for line in text:
  371. html.write(color_error_line(html_escape(line)))
  372. html.write(after)
  373. html.close()
  374. def html_file_preview(filename):
  375. before = '<pre>'
  376. after = '</pre>'
  377. if not os.path.isfile(filename):
  378. return '<p style="color: red>File %s does not exist<p>' % filename
  379. size = os.path.getsize(filename)
  380. if not size:
  381. return '<p style="color: red>File %s is empty<p>' % filename
  382. max_size = 10000
  383. html = StringIO.StringIO()
  384. html.write(before)
  385. if size < max_size:
  386. with open(filename) as text:
  387. for line in text:
  388. html.write(color_error_line(html_escape(line)))
  389. elif size < 10 * max_size:
  390. def tail(filename, n):
  391. return collections.deque(open(filename), n)
  392. html.write('... (lines omitted)\n')
  393. for line in tail(filename, 50):
  394. html.write(color_error_line(html_escape(line)))
  395. else:
  396. return '<p style="color: red>File %s is too large to show<p>' % filename
  397. html.write(after)
  398. return html.getvalue()
  399. def returncode_to_html_text(returncode):
  400. if returncode:
  401. return '<span style="color: red">FAILED</span>'
  402. else:
  403. # alternatives: SUCCEEDED, passed, OK
  404. return '<span style="color: green">succeeded</span>'
  405. # not used
  406. def returncode_to_html_sentence(returncode):
  407. if returncode:
  408. return ('<span style="color: red">&#x274c;</span>'
  409. ' Test failed (return code %d)' % (returncode))
  410. else:
  411. return ('<span style="color: green">&#x2713;</span>'
  412. ' Test succeeded (return code %d)' % (returncode))
  413. def returncode_to_success_html_par(returncode):
  414. if returncode:
  415. return ('<p> <span style="color: red">&#x274c;</span>'
  416. ' Test failed</p>')
  417. else:
  418. return ('<p> <span style="color: green">&#x2713;</span>'
  419. ' Test succeeded</p>')
  420. def success_to_html_text(total, successes):
  421. if successes < total:
  422. return '<span style="color: red">FAILED</span>'
  423. elif successes == total:
  424. # alternatives: SUCCEEDED, passed, OK
  425. return '<span style="color: green">succeeded</span>'
  426. else:
  427. return ('<span style="color: red; font-size: 60%">'
  428. '? more successes than total ?</span>')
  429. UNKNOWN_NUMBER_HTML = '<span style="font-size: 60%">unknown</span>'
  430. def success_to_html_percent(total, successes):
  431. if total:
  432. pass_per = 100 * (float(successes) / total)
  433. pass_per = percent_to_html(pass_per)
  434. else:
  435. pass_per = UNKNOWN_NUMBER_HTML
  436. return pass_per
  437. class GrassTestFilesHtmlReporter(GrassTestFilesCountingReporter):
  438. unknown_number = UNKNOWN_NUMBER_HTML
  439. def __init__(self, file_anonymizer, main_page_name='index.html'):
  440. super(GrassTestFilesHtmlReporter, self).__init__()
  441. self.main_index = None
  442. self._file_anonymizer = file_anonymizer
  443. self._main_page_name = main_page_name
  444. def start(self, results_dir):
  445. super(GrassTestFilesHtmlReporter, self).start(results_dir)
  446. # having all variables public although not really part of API
  447. main_page_name = os.path.join(results_dir, self._main_page_name)
  448. self.main_index = open(main_page_name, 'w')
  449. # TODO: this can be moved to the counter class
  450. self.failures = 0
  451. self.errors = 0
  452. self.skipped = 0
  453. self.successes = 0
  454. self.expected_failures = 0
  455. self.unexpected_success = 0
  456. self.total = 0
  457. svn_info = get_svn_info()
  458. if not svn_info:
  459. svn_text = ('<span style="font-size: 60%">'
  460. 'SVN revision cannot be obtained'
  461. '</span>')
  462. else:
  463. url = get_source_url(path=svn_info['relative-url'],
  464. revision=svn_info['revision'])
  465. svn_text = ('SVN revision'
  466. ' <a href="{url}">'
  467. '{rev}</a>'
  468. ).format(url=url, rev=svn_info['revision'])
  469. self.main_index.write('<html><body>'
  470. '<h1>Test results</h1>'
  471. '{time:%Y-%m-%d %H:%M:%S}'
  472. ' ({svn})'
  473. '<table>'
  474. '<thead><tr>'
  475. '<th>Tested directory</th>'
  476. '<th>Test file</th>'
  477. '<th>Status</th>'
  478. '<th>Tests</th><th>Successful</td>'
  479. '<th>Failed</th><th>Percent successful</th>'
  480. '</tr></thead><tbody>'.format(
  481. time=self.main_start_time,
  482. svn=svn_text))
  483. def finish(self):
  484. super(GrassTestFilesHtmlReporter, self).finish()
  485. pass_per = success_to_html_percent(total=self.total,
  486. successes=self.successes)
  487. tfoot = ('<tfoot>'
  488. '<tr>'
  489. '<td>Summary</td>'
  490. '<td>{nfiles} test files</td>'
  491. '<td>{nsper}</td>'
  492. '<td>{total}</td><td>{st}</td><td>{ft}</td><td>{pt}</td>'
  493. '</tr>'
  494. '</tfoot>'.format(
  495. nfiles=self.test_files,
  496. nsper=percent_to_html(self.file_pass_per),
  497. st=self.successes, ft=self.failures + self.errors,
  498. total=self.total, pt=pass_per
  499. ))
  500. # this is the second place with this function
  501. # TODO: provide one implementation
  502. def format_percentage(percentage):
  503. if percentage is not None:
  504. return "{nsper:.0f}%".format(nsper=percentage)
  505. else:
  506. return "unknown percentage"
  507. summary_sentence = ('\nExecuted {nfiles} test files in {time:}.'
  508. '\nFrom them'
  509. ' {nsfiles} files ({nsper}) were successful'
  510. ' and {nffiles} files ({nfper}) failed.\n'
  511. .format(
  512. nfiles=self.test_files,
  513. time=self.main_time,
  514. nsfiles=self.files_pass,
  515. nffiles=self.files_fail,
  516. nsper=format_percentage(self.file_pass_per),
  517. nfper=format_percentage(self.file_fail_per)))
  518. self.main_index.write('<tbody>{tfoot}</table>'
  519. '<p>{summary}</p>'
  520. '</body></html>'
  521. .format(
  522. tfoot=tfoot,
  523. summary=summary_sentence))
  524. self.main_index.close()
  525. def start_file_test(self, module):
  526. super(GrassTestFilesHtmlReporter, self).start_file_test(module)
  527. self.main_index.flush() # to get previous lines to the report
  528. def end_file_test(self, module, cwd, returncode, stdout, stderr,
  529. test_summary):
  530. super(GrassTestFilesHtmlReporter, self).end_file_test(
  531. module=module, cwd=cwd, returncode=returncode,
  532. stdout=stdout, stderr=stderr)
  533. # considering others accoring to total is OK when we more or less
  534. # know that input data make sense (total >= errors + failures)
  535. total = test_summary.get('total', None)
  536. failures = test_summary.get('failures', 0)
  537. errors = test_summary.get('errors', 0)
  538. # Python unittest TestResult class is reporting success for no
  539. # errors or failures, so skipped, expected failures and unexpected
  540. # success are ignored
  541. # but successful tests are only total - the others
  542. # TODO: add success counter to GrassTestResult base class
  543. skipped = test_summary.get('skipped', 0)
  544. expected_failures = test_summary.get('expected_failures', 0)
  545. unexpected_successes = test_summary.get('unexpected_successes', 0)
  546. successes = test_summary.get('successes', 0)
  547. self.failures += failures
  548. self.errors += errors
  549. self.skipped += skipped
  550. self.expected_failures += expected_failures
  551. self.unexpected_success += unexpected_successes
  552. # zero would be valid here
  553. if total is not None:
  554. # success are only the clear ones
  555. # percentage is influenced by all
  556. # but putting only failures to table
  557. self.successes += successes
  558. self.total += total
  559. # this will handle zero
  560. pass_per = success_to_html_percent(total=total,
  561. successes=successes)
  562. else:
  563. total = successes = pass_per = self.unknown_number
  564. bad_ones = failures + errors
  565. self.main_index.write(
  566. '<tr><td>{d}</td>'
  567. '<td><a href="{d}/{m}/index.html">{m}</a></td>'
  568. '<td>{status}</td>'
  569. '<td>{ntests}</td><td>{stests}</td>'
  570. '<td>{ftests}</td><td>{ptests}</td>'
  571. '<tr>'.format(
  572. d=to_web_path(module.tested_dir), m=module.name,
  573. status=returncode_to_html_text(returncode),
  574. stests=successes, ftests=bad_ones, ntests=total,
  575. ptests=pass_per))
  576. wrap_stdstream_to_html(infile=stdout,
  577. outfile=os.path.join(cwd, 'stdout.html'),
  578. module=module, stream='stdout')
  579. wrap_stdstream_to_html(infile=stderr,
  580. outfile=os.path.join(cwd, 'stderr.html'),
  581. module=module, stream='stderr')
  582. file_index_path = os.path.join(cwd, 'index.html')
  583. file_index = open(file_index_path, 'w')
  584. file_index.write(
  585. '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>'
  586. '<h1>{m.name}</h1>'
  587. '<h2>{m.tested_dir} &ndash; {m.name}</h2>'
  588. '{status}'
  589. .format(
  590. m=module,
  591. status=returncode_to_success_html_par(returncode),
  592. ))
  593. # TODO: include optionaly hyper link to test suite
  594. # TODO: file_path is reconstucted in a naive way
  595. # file_path should be stored in the module/test file object and just used here
  596. summary_section = (
  597. '<table><tbody>'
  598. '<tr><td>Test</td><td>{m}</td></tr>'
  599. '<tr><td>Testsuite</td><td>{d}</td></tr>'
  600. '<tr><td>Test file</td><td>{file_path}</td></tr>'
  601. '<tr><td>Status</td><td>{status}</td></tr>'
  602. '<tr><td>Return code</td><td>{rc}</td></tr>'
  603. '<tr><td>Number of tests</td><td>{ntests}</td></tr>'
  604. '<tr><td>Successful tests</td><td>{stests}</td></tr>'
  605. '<tr><td>Failed tests</td><td>{ftests}</td></tr>'
  606. '<tr><td>Percent successful</td><td>{ptests}</td></tr>'
  607. '<tr><td>Test duration</td><td>{dur}</td></tr>'
  608. .format(
  609. d=module.tested_dir, m=module.name,
  610. file_path=os.path.join(module.tested_dir, 'testsuite', module.name + '.' + module.file_type),
  611. status=returncode_to_html_text(returncode),
  612. stests=successes, ftests=bad_ones, ntests=total,
  613. ptests=pass_per, rc=returncode,
  614. dur=self.file_time))
  615. file_index.write(summary_section)
  616. modules = test_summary.get('tested_modules', None)
  617. if modules:
  618. # TODO: replace by better handling of potential lists when parsing
  619. # TODO: create link to module if running in grass or in addons
  620. # alternatively a link to module test summary
  621. if type(modules) is not list:
  622. modules = [modules]
  623. file_index.write(
  624. '<tr><td>Tested modules</td><td>{}</td></tr>'.format(
  625. ', '.join(sorted(set(modules)))))
  626. file_index.write('<tbody><table>')
  627. # here we would have also links to coverage, profiling, ...
  628. #'<li><a href="testcodecoverage/index.html">code coverage</a></li>'
  629. files_section = (
  630. '<h3>Supplementary files</h3>'
  631. '<ul>'
  632. '<li><a href="stdout.html">standard output (stdout)</a></li>'
  633. '<li><a href="stderr.html">standard error output (stderr)</a></li>'
  634. )
  635. file_index.write(files_section)
  636. supplementary_files = test_summary.get('supplementary_files', None)
  637. if supplementary_files:
  638. # this is something we might want to do once for all and not
  639. # risk that it will be done twice or rely that somebody else
  640. # will do it for use
  641. # the solution is perhaps do the multi reporter more grass-specific
  642. # and do all common things, so that other can rely on it and
  643. # moreover something can be shared with other explicity
  644. # using constructors as seems advantageous for counting
  645. self._file_anonymizer.anonymize(supplementary_files)
  646. for f in supplementary_files:
  647. file_index.write('<li><a href="{f}">{f}</a></li>'.format(f=f))
  648. file_index.write('</ul>')
  649. if returncode:
  650. file_index.write('<h3>Standard error output (stderr)</h3>')
  651. file_index.write(html_file_preview(stderr))
  652. file_index.write('</body></html>')
  653. file_index.close()
  654. if returncode:
  655. pass
  656. # TODO: here we don't have oportunity to write error file
  657. # to stream (stdout/stderr)
  658. # a stream can be added and if not none, we could write
  659. # TODO: document info: additional information to be stored type: dict
  660. # allows to overwrite what was collected
  661. class GrassTestFilesKeyValueReporter(GrassTestFilesCountingReporter):
  662. def __init__(self, info=None):
  663. super(GrassTestFilesKeyValueReporter, self).__init__()
  664. self.result_dir = None
  665. self._info = info
  666. def start(self, results_dir):
  667. super(GrassTestFilesKeyValueReporter, self).start(results_dir)
  668. # having all variables public although not really part of API
  669. self.result_dir = results_dir
  670. # TODO: this can be moved to the counter class
  671. self.failures = 0
  672. self.errors = 0
  673. self.skipped = 0
  674. self.successes = 0
  675. self.expected_failures = 0
  676. self.unexpected_success = 0
  677. self.total = 0
  678. # TODO: document: tested_dirs is a list and it should fit with names
  679. self.names = []
  680. self.tested_dirs = []
  681. self.files_returncodes = []
  682. # sets (no size specified)
  683. self.modules = set()
  684. self.test_files_authors = set()
  685. def finish(self):
  686. super(GrassTestFilesKeyValueReporter, self).finish()
  687. # this shoul be moved to some additional meta passed in constructor
  688. svn_info = get_svn_info()
  689. if not svn_info:
  690. svn_revision = ''
  691. else:
  692. svn_revision = svn_info['revision']
  693. summary = {}
  694. summary['files_total'] = self.test_files
  695. summary['files_successes'] = self.files_pass
  696. summary['files_failures'] = self.files_fail
  697. summary['names'] = self.names
  698. summary['tested_dirs'] = self.tested_dirs
  699. # TODO: we don't have a general mechanism for storing any type in text
  700. summary['files_returncodes'] = [str(item)
  701. for item in self.files_returncodes]
  702. # let's use seconds as a universal time delta format
  703. # (there is no standard way how to store time delta as string)
  704. summary['time'] = self.main_time.total_seconds()
  705. status = 'failed' if self.files_fail else 'succeeded'
  706. summary['status'] = status
  707. summary['total'] = self.total
  708. summary['successes'] = self.successes
  709. summary['failures'] = self.failures
  710. summary['errors'] = self.errors
  711. summary['skipped'] = self.skipped
  712. summary['expected_failures'] = self.expected_failures
  713. summary['unexpected_successes'] = self.unexpected_success
  714. summary['test_files_authors'] = self.test_files_authors
  715. summary['tested_modules'] = self.modules
  716. summary['svn_revision'] = svn_revision
  717. # ignoring issues with time zones
  718. summary['timestamp'] = self.main_start_time.strftime('%Y-%m-%d %H:%M:%S')
  719. # TODO: add some general metadata here (passed in constructor)
  720. # add additional information
  721. for key, value in self._info.iteritems():
  722. summary[key] = value
  723. summary_filename = os.path.join(self.result_dir,
  724. 'test_keyvalue_result.txt')
  725. with open(summary_filename, 'w') as summary_file:
  726. text = keyvalue_to_text(summary, sep='=', vsep='\n', isep=',')
  727. summary_file.write(text)
  728. def end_file_test(self, module, cwd, returncode, stdout, stderr,
  729. test_summary):
  730. super(GrassTestFilesKeyValueReporter, self).end_file_test(
  731. module=module, cwd=cwd, returncode=returncode,
  732. stdout=stdout, stderr=stderr)
  733. # TODO: considering others accoring to total, OK?
  734. # here we are using 0 for total but HTML reporter is using None
  735. total = test_summary.get('total', 0)
  736. failures = test_summary.get('failures', 0)
  737. errors = test_summary.get('errors', 0)
  738. # Python unittest TestResult class is reporting success for no
  739. # errors or failures, so skipped, expected failures and unexpected
  740. # success are ignored
  741. # but successful tests are only total - the others
  742. skipped = test_summary.get('skipped', 0)
  743. expected_failures = test_summary.get('expected_failures', 0)
  744. unexpected_successes = test_summary.get('unexpected_successes', 0)
  745. successes = test_summary.get('successes', 0)
  746. # TODO: move this to counter class and perhaps use aggregation
  747. # rather then inheritance
  748. self.failures += failures
  749. self.errors += errors
  750. self.skipped += skipped
  751. self.expected_failures += expected_failures
  752. self.unexpected_success += unexpected_successes
  753. # TODO: should we test for zero?
  754. if total is not None:
  755. # success are only the clear ones
  756. # percentage is influenced by all
  757. # but putting only failures to table
  758. self.successes += successes
  759. self.total += total
  760. self.files_returncodes.append(returncode)
  761. self.tested_dirs.append(module.tested_dir)
  762. self.names.append(module.name)
  763. modules = test_summary.get('tested_modules', None)
  764. if modules:
  765. # TODO: replace by better handling of potential lists when parsing
  766. # TODO: create link to module if running in grass or in addons
  767. # alternatively a link to module test summary
  768. if type(modules) not in [list, set]:
  769. modules = [modules]
  770. self.modules.update(modules)
  771. test_file_authors = test_summary['test_file_authors']
  772. if type(test_file_authors) not in [list, set]:
  773. test_file_authors = [test_file_authors]
  774. self.test_files_authors.update(test_file_authors)
  775. class GrassTestFilesTextReporter(GrassTestFilesCountingReporter):
  776. def __init__(self, stream):
  777. super(GrassTestFilesTextReporter, self).__init__()
  778. self._stream = stream
  779. def start(self, results_dir):
  780. super(GrassTestFilesTextReporter, self).start(results_dir)
  781. def finish(self):
  782. super(GrassTestFilesTextReporter, self).finish()
  783. def format_percentage(percentage):
  784. if percentage is not None:
  785. return "{nsper:.0f}%".format(nsper=percentage)
  786. else:
  787. return "unknown percentage"
  788. summary_sentence = ('\nExecuted {nfiles} test files in {time:}.'
  789. '\nFrom them'
  790. ' {nsfiles} files ({nsper}) were successful'
  791. ' and {nffiles} files ({nfper}) failed.\n'
  792. .format(
  793. nfiles=self.test_files,
  794. time=self.main_time,
  795. nsfiles=self.files_pass,
  796. nffiles=self.files_fail,
  797. nsper=format_percentage(self.file_pass_per),
  798. nfper=format_percentage(self.file_fail_per)))
  799. self._stream.write(summary_sentence)
  800. def start_file_test(self, module):
  801. super(GrassTestFilesTextReporter, self).start_file_test(module)
  802. self._stream.flush() # to get previous lines to the report
  803. def end_file_test(self, module, cwd, returncode, stdout, stderr,
  804. test_summary):
  805. super(GrassTestFilesTextReporter, self).end_file_test(
  806. module=module, cwd=cwd, returncode=returncode,
  807. stdout=stdout, stderr=stderr)
  808. if returncode:
  809. self._stream.write(
  810. '{m} from {d} failed'
  811. .format(
  812. d=module.tested_dir,
  813. m=module.name))
  814. num_failed = test_summary.get('failures', 0)
  815. num_failed += test_summary.get('errors', 0)
  816. if num_failed:
  817. if num_failed > 1:
  818. text = ' ({f} tests failed)'
  819. else:
  820. text = ' ({f} test failed)'
  821. self._stream.write(text.format(f=num_failed))
  822. self._stream.write('\n')
  823. # TODO: here we lost the possibility to include also file name
  824. # of the appropriate report
  825. # TODO: there is a quite a lot duplication between this class and html reporter
  826. # TODO: document: do not use it for two reports, it accumulates the results
  827. # TODO: add also keyvalue summary generation?
  828. # wouldn't this conflict with collecting data from report afterwards?
  829. class TestsuiteDirReporter(object):
  830. def __init__(self, main_page_name, testsuite_page_name='index.html',
  831. top_level_testsuite_page_name=None):
  832. self.main_page_name = main_page_name
  833. self.testsuite_page_name = testsuite_page_name
  834. self.top_level_testsuite_page_name = top_level_testsuite_page_name
  835. # TODO: this might be even a object which could add and validate
  836. self.failures = 0
  837. self.errors = 0
  838. self.skipped = 0
  839. self.successes = 0
  840. self.expected_failures = 0
  841. self.unexpected_successes = 0
  842. self.total = 0
  843. self.testsuites = 0
  844. self.testsuites_successes = 0
  845. self.files = 0
  846. self.files_successes = 0
  847. def report_for_dir(self, root, directory, test_files):
  848. # TODO: create object from this, so that it can be passed from
  849. # one function to another
  850. # TODO: put the inside of for loop to another fucntion
  851. dir_failures = 0
  852. dir_errors = 0
  853. dir_skipped = 0
  854. dir_successes = 0
  855. dir_expected_failures = 0
  856. dir_unexpected_success = 0
  857. dir_total = 0
  858. test_files_authors = []
  859. file_total = 0
  860. file_successes = 0
  861. page_name = os.path.join(root, directory, self.testsuite_page_name)
  862. if (self.top_level_testsuite_page_name and
  863. os.path.abspath(os.path.join(root, directory))
  864. == os.path.abspath(root)):
  865. page_name = os.path.join(root, self.top_level_testsuite_page_name)
  866. page = open(page_name, 'w')
  867. # TODO: should we use forward slashes also for the HTML because
  868. # it is simpler are more consistent with the rest on MS Windows?
  869. head = (
  870. '<html><body>'
  871. '<h1>{name} testsuite results</h1>'
  872. .format(name=directory))
  873. tests_table_head = (
  874. '<h3>Test files results</h3>'
  875. '<table>'
  876. '<thead><tr>'
  877. '<th>Test file</th><th>Status</th>'
  878. '<th>Tests</th><th>Successful</td>'
  879. '<th>Failed</th><th>Percent successful</th>'
  880. '</tr></thead><tbody>'
  881. )
  882. page.write(head)
  883. page.write(tests_table_head)
  884. for test_file_name in test_files:
  885. # TODO: put keyvalue fine name to constant
  886. summary_filename = os.path.join(root, directory, test_file_name,
  887. 'test_keyvalue_result.txt')
  888. #if os.path.exists(summary_filename):
  889. with open(summary_filename, 'r') as keyval_file:
  890. summary = text_to_keyvalue(keyval_file.read(), sep='=')
  891. #else:
  892. # TODO: write else here
  893. # summary = None
  894. if 'total' not in summary:
  895. bad_ones = successes = UNKNOWN_NUMBER_HTML
  896. total = None
  897. else:
  898. bad_ones = summary['failures'] + summary['errors']
  899. successes = summary['successes']
  900. total = summary['total']
  901. self.failures += summary['failures']
  902. self.errors += summary['errors']
  903. self.skipped += summary['skipped']
  904. self.successes += summary['successes']
  905. self.expected_failures += summary['expected_failures']
  906. self.unexpected_successes += summary['unexpected_successes']
  907. self.total += summary['total']
  908. dir_failures += summary['failures']
  909. dir_errors += summary['failures']
  910. dir_skipped += summary['skipped']
  911. dir_successes += summary['successes']
  912. dir_expected_failures += summary['expected_failures']
  913. dir_unexpected_success += summary['unexpected_successes']
  914. dir_total += summary['total']
  915. # TODO: keyvalue method should have types for keys function
  916. # perhaps just the current post processing function is enough
  917. test_file_authors = summary['test_file_authors']
  918. if type(test_file_authors) is not list:
  919. test_file_authors = [test_file_authors]
  920. test_files_authors.extend(test_file_authors)
  921. file_total += 1
  922. file_successes += 0 if summary['returncode'] else 1
  923. pass_per = success_to_html_percent(total=total,
  924. successes=successes)
  925. row = (
  926. '<tr>'
  927. '<td><a href="{f}/index.html">{f}</a></td>'
  928. '<td>{status}</td>'
  929. '<td>{ntests}</td><td>{stests}</td>'
  930. '<td>{ftests}</td><td>{ptests}</td>'
  931. '<tr>'
  932. .format(
  933. f=test_file_name,
  934. status=returncode_to_html_text(summary['returncode']),
  935. stests=successes, ftests=bad_ones, ntests=total,
  936. ptests=pass_per))
  937. page.write(row)
  938. self.testsuites += 1
  939. self.testsuites_successes += 1 if file_successes == file_total else 0
  940. self.files += file_total
  941. self.files_successes += file_successes
  942. dir_pass_per = success_to_html_percent(total=dir_total,
  943. successes=dir_successes)
  944. file_pass_per = success_to_html_percent(total=file_total,
  945. successes=file_successes)
  946. tests_table_foot = (
  947. '</tbody><tfoot><tr>'
  948. '<td>Summary</td>'
  949. '<td>{status}</td>'
  950. '<td>{ntests}</td><td>{stests}</td>'
  951. '<td>{ftests}</td><td>{ptests}</td>'
  952. '</tr></tfoot></table>'
  953. .format(
  954. status=file_pass_per,
  955. stests=dir_successes, ftests=dir_failures + dir_errors,
  956. ntests=dir_total, ptests=dir_pass_per))
  957. page.write(tests_table_foot)
  958. test_authors = get_html_test_authors_table(
  959. directory=directory, tests_authors=test_files_authors)
  960. page.write(test_authors)
  961. page.write('</body></html>')
  962. page.close()
  963. status = success_to_html_text(total=file_total, successes=file_successes)
  964. row = (
  965. '<tr>'
  966. '<td><a href="{d}/{page}">{d}</a></td><td>{status}</td>'
  967. '<td>{nfiles}</td><td>{sfiles}</td><td>{pfiles}</td>'
  968. '<td>{ntests}</td><td>{stests}</td>'
  969. '<td>{ftests}</td><td>{ptests}</td>'
  970. '<tr>'
  971. .format(
  972. d=to_web_path(directory), page=self.testsuite_page_name,
  973. status=status,
  974. nfiles=file_total, sfiles=file_successes, pfiles=file_pass_per,
  975. stests=dir_successes, ftests=dir_failures + dir_errors,
  976. ntests=dir_total, ptests=dir_pass_per))
  977. return row
  978. def report_for_dirs(self, root, directories):
  979. # TODO: this will need chanages accoring to potential chnages in absolute/relative paths
  980. page_name = os.path.join(root, self.main_page_name)
  981. page = open(page_name, 'w')
  982. head = (
  983. '<html><body>'
  984. '<h1>Testsuites results</h1>'
  985. )
  986. tests_table_head = (
  987. '<table>'
  988. '<thead><tr>'
  989. '<th>Testsuite</th>'
  990. '<th>Status</th>'
  991. '<th>Test files</th><th>Successful</td>'
  992. '<th>Percent successful</th>'
  993. '<th>Tests</th><th>Successful</td>'
  994. '<th>Failed</th><th>Percent successful</th>'
  995. '</tr></thead><tbody>'
  996. )
  997. page.write(head)
  998. page.write(tests_table_head)
  999. for directory, test_files in directories.iteritems():
  1000. row = self.report_for_dir(root=root, directory=directory,
  1001. test_files=test_files)
  1002. page.write(row)
  1003. pass_per = success_to_html_percent(total=self.total,
  1004. successes=self.successes)
  1005. file_pass_per = success_to_html_percent(total=self.files,
  1006. successes=self.files_successes)
  1007. testsuites_pass_per = success_to_html_percent(
  1008. total=self.testsuites, successes=self.testsuites_successes)
  1009. tests_table_foot = (
  1010. '<tfoot>'
  1011. '<tr>'
  1012. '<td>Summary</td><td>{status}</td>'
  1013. '<td>{nfiles}</td><td>{sfiles}</td><td>{pfiles}</td>'
  1014. '<td>{ntests}</td><td>{stests}</td>'
  1015. '<td>{ftests}</td><td>{ptests}</td>'
  1016. '</tr>'
  1017. '</tfoot>'
  1018. .format(
  1019. status=testsuites_pass_per, nfiles=self.files,
  1020. sfiles=self.files_successes, pfiles=file_pass_per,
  1021. stests=self.successes, ftests=self.failures + self.errors,
  1022. ntests=self.total, ptests=pass_per))
  1023. page.write(tests_table_foot)
  1024. page.write('</body></html>')