reporters.py 44 KB

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