reporters.py 44 KB

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