reporters.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  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. 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. def start_file_test(self, module):
  324. self.file_start_time = datetime.datetime.now()
  325. self._start_file_test_called = True
  326. self.test_files += 1
  327. def end_file_test(self, returncode, **kwargs):
  328. assert self._start_file_test_called
  329. self.file_end_time = datetime.datetime.now()
  330. self.file_time = self.file_end_time - self.file_start_time
  331. if returncode:
  332. self.files_fail += 1
  333. else:
  334. self.files_pass += 1
  335. self._start_file_test_called = False
  336. def percent_to_html(percent):
  337. if percent > 100 or percent < 0:
  338. return "? {:.2f}% ?".format(percent)
  339. elif percent < 40:
  340. color = 'red'
  341. elif percent < 70:
  342. color = 'orange'
  343. else:
  344. color = 'green'
  345. return '<span style="color: {color}">{percent:.0f}%</span>'.format(
  346. percent=percent, color=color)
  347. def wrap_stdstream_to_html(infile, outfile, module, stream):
  348. before = '<html><body><h1>%s</h1><pre>' % (module.name + ' ' + stream)
  349. after = '</pre></body></html>'
  350. html = open(outfile, 'w')
  351. html.write(before)
  352. with open(infile) as text:
  353. for line in text:
  354. html.write(color_error_line(html_escape(line)))
  355. html.write(after)
  356. html.close()
  357. def html_file_preview(filename):
  358. before = '<pre>'
  359. after = '</pre>'
  360. if not os.path.isfile(filename):
  361. return '<p style="color: red>File %s does not exist<p>' % filename
  362. size = os.path.getsize(filename)
  363. if not size:
  364. return '<p style="color: red>File %s is empty<p>' % filename
  365. max_size = 10000
  366. html = StringIO.StringIO()
  367. html.write(before)
  368. if size < max_size:
  369. with open(filename) as text:
  370. for line in text:
  371. html.write(color_error_line(html_escape(line)))
  372. elif size < 10 * max_size:
  373. def tail(filename, n):
  374. return collections.deque(open(filename), n)
  375. html.write('... (lines omitted)\n')
  376. for line in tail(filename, 50):
  377. html.write(color_error_line(html_escape(line)))
  378. else:
  379. return '<p style="color: red>File %s is too large to show<p>' % filename
  380. html.write(after)
  381. return html.getvalue()
  382. def returncode_to_html_text(returncode):
  383. if returncode:
  384. return '<span style="color: red">FAILED</span>'
  385. else:
  386. # alternatives: SUCCEEDED, passed, OK
  387. return '<span style="color: green">succeeded</span>'
  388. # not used
  389. def returncode_to_html_sentence(returncode):
  390. if returncode:
  391. return ('<span style="color: red">&#x274c;</span>'
  392. ' Test failed (return code %d)' % (returncode))
  393. else:
  394. return ('<span style="color: green">&#x2713;</span>'
  395. ' Test succeeded (return code %d)' % (returncode))
  396. def returncode_to_success_html_par(returncode):
  397. if returncode:
  398. return ('<p> <span style="color: red">&#x274c;</span>'
  399. ' Test failed</p>')
  400. else:
  401. return ('<p> <span style="color: green">&#x2713;</span>'
  402. ' Test succeeded</p>')
  403. def success_to_html_text(total, successes):
  404. if successes < total:
  405. return '<span style="color: red">FAILED</span>'
  406. elif successes == total:
  407. # alternatives: SUCCEEDED, passed, OK
  408. return '<span style="color: green">succeeded</span>'
  409. else:
  410. return ('<span style="color: red; font-size: 60%">'
  411. '? more successes than total ?</span>')
  412. UNKNOWN_NUMBER_HTML = '<span style="font-size: 60%">unknown</span>'
  413. def success_to_html_percent(total, successes):
  414. if total:
  415. pass_per = 100 * (float(successes) / total)
  416. pass_per = percent_to_html(pass_per)
  417. else:
  418. pass_per = UNKNOWN_NUMBER_HTML
  419. return pass_per
  420. class GrassTestFilesHtmlReporter(GrassTestFilesCountingReporter):
  421. unknown_number = UNKNOWN_NUMBER_HTML
  422. def __init__(self, file_anonymizer, main_page_name='index.html'):
  423. super(GrassTestFilesHtmlReporter, self).__init__()
  424. self.main_index = None
  425. self._file_anonymizer = file_anonymizer
  426. self._main_page_name = main_page_name
  427. def start(self, results_dir):
  428. super(GrassTestFilesHtmlReporter, self).start(results_dir)
  429. # having all variables public although not really part of API
  430. main_page_name = os.path.join(results_dir, self._main_page_name)
  431. self.main_index = open(main_page_name, 'w')
  432. # TODO: this can be moved to the counter class
  433. self.failures = 0
  434. self.errors = 0
  435. self.skipped = 0
  436. self.successes = 0
  437. self.expected_failures = 0
  438. self.unexpected_success = 0
  439. self.total = 0
  440. svn_info = get_svn_info()
  441. if not svn_info:
  442. svn_text = ('<span style="font-size: 60%">'
  443. 'SVN revision cannot be obtained'
  444. '</span>')
  445. else:
  446. url = get_source_url(path=svn_info['relative-url'],
  447. revision=svn_info['revision'])
  448. svn_text = ('SVN revision'
  449. ' <a href="{url}">'
  450. '{rev}</a>'
  451. ).format(url=url, rev=svn_info['revision'])
  452. self.main_index.write('<html><body>'
  453. '<h1>Test results</h1>'
  454. '{time:%Y-%m-%d %H:%M:%S}'
  455. ' ({svn})'
  456. '<table>'
  457. '<thead><tr>'
  458. '<th>Tested directory</th>'
  459. '<th>Test file</th>'
  460. '<th>Status</th>'
  461. '<th>Tests</th><th>Successful</td>'
  462. '<th>Failed</th><th>Percent successful</th>'
  463. '</tr></thead><tbody>'.format(
  464. time=self.main_start_time,
  465. svn=svn_text))
  466. def finish(self):
  467. super(GrassTestFilesHtmlReporter, self).finish()
  468. if self.total:
  469. pass_per = 100 * (float(self.successes) / self.total)
  470. pass_per = percent_to_html(pass_per)
  471. else:
  472. pass_per = self.unknown_number
  473. tfoot = ('<tfoot>'
  474. '<tr>'
  475. '<td>Summary</td>'
  476. '<td>{nfiles} test files</td>'
  477. '<td>{nsper}</td>'
  478. '<td>{total}</td><td>{st}</td><td>{ft}</td><td>{pt}</td>'
  479. '</tr>'
  480. '</tfoot>'.format(
  481. nfiles=self.test_files,
  482. nsper=percent_to_html(self.file_pass_per),
  483. st=self.successes, ft=self.failures + self.errors,
  484. total=self.total, pt=pass_per
  485. ))
  486. summary_sentence = ('Executed {nfiles} test files in {time:}.'
  487. ' From them'
  488. ' {nsfiles} files ({nsper:.0f}%) were successful'
  489. ' and {nffiles} files ({nfper:.0f}%) failed.'
  490. .format(
  491. nfiles=self.test_files,
  492. time=self.main_time,
  493. nsfiles=self.files_pass,
  494. nffiles=self.files_fail,
  495. nsper=self.file_pass_per,
  496. nfper=self.file_fail_per))
  497. self.main_index.write('<tbody>{tfoot}</table>'
  498. '<p>{summary}</p>'
  499. '</body></html>'
  500. .format(
  501. tfoot=tfoot,
  502. summary=summary_sentence))
  503. self.main_index.close()
  504. def start_file_test(self, module):
  505. super(GrassTestFilesHtmlReporter, self).start_file_test(module)
  506. self.main_index.flush() # to get previous lines to the report
  507. def end_file_test(self, module, cwd, returncode, stdout, stderr,
  508. test_summary):
  509. super(GrassTestFilesHtmlReporter, self).end_file_test(
  510. module=module, cwd=cwd, returncode=returncode,
  511. stdout=stdout, stderr=stderr)
  512. # TODO: considering others accoring to total, OK?
  513. total = test_summary.get('total', None)
  514. failures = test_summary.get('failures', 0)
  515. errors = test_summary.get('errors', 0)
  516. # Python unittest TestResult class is reporting success for no
  517. # errors or failures, so skipped, expected failures and unexpected
  518. # success are ignored
  519. # but successful tests are only total - the others
  520. # TODO: add success counter to GrassTestResult base class
  521. skipped = test_summary.get('skipped', 0)
  522. expected_failures = test_summary.get('expected_failures', 0)
  523. unexpected_successes = test_summary.get('unexpected_successes', 0)
  524. successes = test_summary.get('successes', 0)
  525. self.failures += failures
  526. self.errors += errors
  527. self.skipped += skipped
  528. self.expected_failures += expected_failures
  529. self.unexpected_success += unexpected_successes
  530. # TODO: should we test for zero?
  531. if total is not None:
  532. # success are only the clear ones
  533. # percentage is influenced by all
  534. # but putting only failures to table
  535. self.successes += successes
  536. self.total += total
  537. pass_per = 100 * (float(successes) / total)
  538. pass_per = percent_to_html(pass_per)
  539. else:
  540. total = successes = pass_per = self.unknown_number
  541. bad_ones = failures + errors
  542. self.main_index.write(
  543. '<tr><td>{d}</td>'
  544. '<td><a href="{d}/{m}/index.html">{m}</a></td>'
  545. '<td>{status}</td>'
  546. '<td>{ntests}</td><td>{stests}</td>'
  547. '<td>{ftests}</td><td>{ptests}</td>'
  548. '<tr>'.format(
  549. d=module.tested_dir, m=module.name,
  550. status=returncode_to_html_text(returncode),
  551. stests=successes, ftests=bad_ones, ntests=total,
  552. ptests=pass_per))
  553. wrap_stdstream_to_html(infile=stdout,
  554. outfile=os.path.join(cwd, 'stdout.html'),
  555. module=module, stream='stdout')
  556. wrap_stdstream_to_html(infile=stderr,
  557. outfile=os.path.join(cwd, 'stderr.html'),
  558. module=module, stream='stderr')
  559. file_index_path = os.path.join(cwd, 'index.html')
  560. file_index = open(file_index_path, 'w')
  561. file_index.write(
  562. '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>'
  563. '<h1>{m.name}</h1>'
  564. '<h2>{m.tested_dir} &ndash; {m.name}</h2>'
  565. '{status}'
  566. .format(
  567. m=module,
  568. status=returncode_to_success_html_par(returncode),
  569. ))
  570. # TODO: include optionaly link to test suite
  571. summary_section = (
  572. '<table><tbody>'
  573. '<tr><td>Test file</td><td>{m}</td></tr>'
  574. '<tr><td>Testsuite</td><td>{d}</td></tr>'
  575. '<tr><td>Status</td><td>{status}</td></tr>'
  576. '<tr><td>Return code</td><td>{rc}</td></tr>'
  577. '<tr><td>Number of tests</td><td>{ntests}</td></tr>'
  578. '<tr><td>Successful tests</td><td>{stests}</td></tr>'
  579. '<tr><td>Failed tests</td><td>{ftests}</td></tr>'
  580. '<tr><td>Percent successful</td><td>{ptests}</td></tr>'
  581. '<tr><td>Test duration</td><td>{dur}</td></tr>'
  582. .format(
  583. d=module.tested_dir, m=module.name,
  584. status=returncode_to_html_text(returncode),
  585. stests=successes, ftests=bad_ones, ntests=total,
  586. ptests=pass_per, rc=returncode,
  587. dur=self.file_time))
  588. file_index.write(summary_section)
  589. modules = test_summary.get('tested_modules', None)
  590. if modules:
  591. # TODO: replace by better handling of potential lists when parsing
  592. # TODO: create link to module if running in grass or in addons
  593. # alternatively a link to module test summary
  594. if type(modules) is not list:
  595. modules = [modules]
  596. file_index.write(
  597. '<tr><td>Tested modules</td><td>{}</td></tr>'.format(
  598. ', '.join(sorted(set(modules)))))
  599. file_index.write('<tbody><table>')
  600. # here we would have also links to coverage, profiling, ...
  601. #'<li><a href="testcodecoverage/index.html">code coverage</a></li>'
  602. files_section = (
  603. '<h3>Supplementary files</h3>'
  604. '<ul>'
  605. '<li><a href="stdout.html">standard output (stdout)</a></li>'
  606. '<li><a href="stderr.html">standard error output (stderr)</a></li>'
  607. )
  608. file_index.write(files_section)
  609. supplementary_files = test_summary.get('supplementary_files', None)
  610. if supplementary_files:
  611. # this is something we might want to do once for all and not
  612. # risk that it will be done twice or rely that somebody else
  613. # will do it for use
  614. # the solution is perhaps do the multi reporter more grass-specific
  615. # and do all common things, so that other can rely on it and
  616. # moreover something can be shared with other explicity
  617. # using constructors as seems advantageous for counting
  618. self._file_anonymizer.anonymize(supplementary_files)
  619. for f in supplementary_files:
  620. file_index.write('<li><a href="{f}">{f}</a></li>'.format(f=f))
  621. file_index.write('</ul>')
  622. if returncode:
  623. file_index.write('<h3>Standard error output (stderr)</h3>')
  624. file_index.write(html_file_preview(stderr))
  625. file_index.write('</body></html>')
  626. file_index.close()
  627. if returncode:
  628. pass
  629. # TODO: here we don't have oportunity to write error file
  630. # to stream (stdout/stderr)
  631. # a stream can be added and if not none, we could write
  632. # TODO: document info: additional information to be stored type: dict
  633. # allows to overwrite what was collected
  634. class GrassTestFilesKeyValueReporter(GrassTestFilesCountingReporter):
  635. def __init__(self, info=None):
  636. super(GrassTestFilesKeyValueReporter, self).__init__()
  637. self.result_dir = None
  638. self._info = info
  639. def start(self, results_dir):
  640. super(GrassTestFilesKeyValueReporter, self).start(results_dir)
  641. # having all variables public although not really part of API
  642. self.result_dir = results_dir
  643. # TODO: this can be moved to the counter class
  644. self.failures = 0
  645. self.errors = 0
  646. self.skipped = 0
  647. self.successes = 0
  648. self.expected_failures = 0
  649. self.unexpected_success = 0
  650. self.total = 0
  651. # TODO: document: tested_dirs is a list and it should fit with names
  652. self.names = []
  653. self.tested_dirs = []
  654. self.files_returncodes = []
  655. # sets (no size specified)
  656. self.modules = set()
  657. self.test_files_authors = set()
  658. def finish(self):
  659. super(GrassTestFilesKeyValueReporter, self).finish()
  660. # this shoul be moved to some additional meta passed in constructor
  661. svn_info = get_svn_info()
  662. if not svn_info:
  663. svn_revision = ''
  664. else:
  665. svn_revision = svn_info['revision']
  666. summary = {}
  667. summary['files_total'] = self.test_files
  668. summary['files_successes'] = self.files_pass
  669. summary['files_failures'] = self.files_fail
  670. summary['names'] = self.names
  671. summary['tested_dirs'] = self.tested_dirs
  672. # TODO: we don't have a general mechanism for storing any type in text
  673. summary['files_returncodes'] = [str(item)
  674. for item in self.files_returncodes]
  675. # let's use seconds as a universal time delta format
  676. # (there is no standard way how to store time delta as string)
  677. summary['time'] = self.main_time.total_seconds()
  678. status = 'failed' if self.files_fail else 'succeeded'
  679. summary['status'] = status
  680. summary['total'] = self.total
  681. summary['successes'] = self.successes
  682. summary['failures'] = self.failures
  683. summary['errors'] = self.errors
  684. summary['skipped'] = self.skipped
  685. summary['expected_failures'] = self.expected_failures
  686. summary['unexpected_successes'] = self.unexpected_success
  687. summary['test_files_authors'] = self.test_files_authors
  688. summary['tested_modules'] = self.modules
  689. summary['svn_revision'] = svn_revision
  690. # ignoring issues with time zones
  691. summary['timestamp'] = self.main_start_time.strftime('%Y-%m-%d %H:%M:%S')
  692. # TODO: add some general metadata here (passed in constructor)
  693. # add additional information
  694. for key, value in self._info.iteritems():
  695. summary[key] = value
  696. summary_filename = os.path.join(self.result_dir,
  697. 'test_keyvalue_result.txt')
  698. with open(summary_filename, 'w') as summary_file:
  699. text = keyvalue_to_text(summary, sep='=', vsep='\n', isep=',')
  700. summary_file.write(text)
  701. def end_file_test(self, module, cwd, returncode, stdout, stderr,
  702. test_summary):
  703. super(GrassTestFilesKeyValueReporter, self).end_file_test(
  704. module=module, cwd=cwd, returncode=returncode,
  705. stdout=stdout, stderr=stderr)
  706. # TODO: considering others accoring to total, OK?
  707. # here we are using 0 for total but HTML reporter is using None
  708. total = test_summary.get('total', 0)
  709. failures = test_summary.get('failures', 0)
  710. errors = test_summary.get('errors', 0)
  711. # Python unittest TestResult class is reporting success for no
  712. # errors or failures, so skipped, expected failures and unexpected
  713. # success are ignored
  714. # but successful tests are only total - the others
  715. skipped = test_summary.get('skipped', 0)
  716. expected_failures = test_summary.get('expected_failures', 0)
  717. unexpected_successes = test_summary.get('unexpected_successes', 0)
  718. successes = test_summary.get('successes', 0)
  719. # TODO: move this to counter class and perhaps use aggregation
  720. # rather then inheritance
  721. self.failures += failures
  722. self.errors += errors
  723. self.skipped += skipped
  724. self.expected_failures += expected_failures
  725. self.unexpected_success += unexpected_successes
  726. # TODO: should we test for zero?
  727. if total is not None:
  728. # success are only the clear ones
  729. # percentage is influenced by all
  730. # but putting only failures to table
  731. self.successes += successes
  732. self.total += total
  733. self.files_returncodes.append(returncode)
  734. self.tested_dirs.append(module.tested_dir)
  735. self.names.append(module.name)
  736. modules = test_summary.get('tested_modules', None)
  737. if modules:
  738. # TODO: replace by better handling of potential lists when parsing
  739. # TODO: create link to module if running in grass or in addons
  740. # alternatively a link to module test summary
  741. if type(modules) not in [list, set]:
  742. modules = [modules]
  743. self.modules.update(modules)
  744. test_file_authors = test_summary['test_file_authors']
  745. if type(test_file_authors) not in [list, set]:
  746. test_file_authors = [test_file_authors]
  747. self.test_files_authors.update(test_file_authors)
  748. class GrassTestFilesTextReporter(GrassTestFilesCountingReporter):
  749. def __init__(self, stream):
  750. super(GrassTestFilesTextReporter, self).__init__()
  751. self._stream = stream
  752. def start(self, results_dir):
  753. super(GrassTestFilesTextReporter, self).start(results_dir)
  754. def finish(self):
  755. super(GrassTestFilesTextReporter, self).finish()
  756. summary_sentence = ('\nExecuted {nfiles} test files in {time:}.'
  757. '\nFrom them'
  758. ' {nsfiles} files ({nsper:.0f}%) were successful'
  759. ' and {nffiles} files ({nfper:.0f}%) failed.\n'
  760. .format(
  761. nfiles=self.test_files,
  762. time=self.main_time,
  763. nsfiles=self.files_pass,
  764. nffiles=self.files_fail,
  765. nsper=self.file_pass_per,
  766. nfper=self.file_fail_per))
  767. self._stream.write(summary_sentence)
  768. def start_file_test(self, module):
  769. super(GrassTestFilesTextReporter, self).start_file_test(module)
  770. self._stream.flush() # to get previous lines to the report
  771. def end_file_test(self, module, cwd, returncode, stdout, stderr,
  772. test_summary):
  773. super(GrassTestFilesTextReporter, self).end_file_test(
  774. module=module, cwd=cwd, returncode=returncode,
  775. stdout=stdout, stderr=stderr)
  776. if returncode:
  777. self._stream.write(
  778. '{m} from {d} failed'
  779. .format(
  780. d=module.tested_dir,
  781. m=module.name))
  782. num_failed = test_summary.get('failures', 0)
  783. num_failed += test_summary.get('errors', 0)
  784. if num_failed:
  785. if num_failed > 1:
  786. text = ' ({f} tests failed)'
  787. else:
  788. text = ' ({f} test failed)'
  789. self._stream.write(text.format(f=num_failed))
  790. self._stream.write('\n')
  791. # TODO: here we lost the possibility to include also file name
  792. # of the appropriate report
  793. # TODO: there is a quite a lot duplication between this class and html reporter
  794. # TODO: document: do not use it for two reports, it accumulates the results
  795. # TODO: add also keyvalue summary generation?
  796. # wouldn't this conflict with collecting data from report afterwards?
  797. class TestsuiteDirReporter(object):
  798. def __init__(self, main_page_name, testsuite_page_name='index.html',
  799. top_level_testsuite_page_name=None):
  800. self.main_page_name = main_page_name
  801. self.testsuite_page_name = testsuite_page_name
  802. self.top_level_testsuite_page_name = top_level_testsuite_page_name
  803. # TODO: this might be even a object which could add and validate
  804. self.failures = 0
  805. self.errors = 0
  806. self.skipped = 0
  807. self.successes = 0
  808. self.expected_failures = 0
  809. self.unexpected_successes = 0
  810. self.total = 0
  811. self.testsuites = 0
  812. self.testsuites_successes = 0
  813. self.files = 0
  814. self.files_successes = 0
  815. def report_for_dir(self, root, directory, test_files):
  816. # TODO: create object from this, so that it can be passed from
  817. # one function to another
  818. # TODO: put the inside of for loop to another fucntion
  819. dir_failures = 0
  820. dir_errors = 0
  821. dir_skipped = 0
  822. dir_successes = 0
  823. dir_expected_failures = 0
  824. dir_unexpected_success = 0
  825. dir_total = 0
  826. test_files_authors = []
  827. file_total = 0
  828. file_successes = 0
  829. page_name = os.path.join(root, directory, self.testsuite_page_name)
  830. if (self.top_level_testsuite_page_name and
  831. os.path.abspath(os.path.join(root, directory))
  832. == os.path.abspath(root)):
  833. page_name = os.path.join(root, self.top_level_testsuite_page_name)
  834. page = open(page_name, 'w')
  835. head = (
  836. '<html><body>'
  837. '<h1>{name} testsuite results</h1>'
  838. .format(name=directory))
  839. tests_table_head = (
  840. '<h3>Test files results</h3>'
  841. '<table>'
  842. '<thead><tr>'
  843. '<th>Test file</th><th>Status</th>'
  844. '<th>Tests</th><th>Successful</td>'
  845. '<th>Failed</th><th>Percent successful</th>'
  846. '</tr></thead><tbody>'
  847. )
  848. page.write(head)
  849. page.write(tests_table_head)
  850. for test_file_name in test_files:
  851. # TODO: put keyvalue fine name to constant
  852. summary_filename = os.path.join(root, directory, test_file_name,
  853. 'test_keyvalue_result.txt')
  854. #if os.path.exists(summary_filename):
  855. with open(summary_filename, 'r') as keyval_file:
  856. summary = text_to_keyvalue(keyval_file.read(), sep='=')
  857. #else:
  858. # TODO: write else here
  859. # summary = None
  860. if 'total' not in summary:
  861. bad_ones = successes = UNKNOWN_NUMBER_HTML
  862. total = None
  863. else:
  864. bad_ones = summary['failures'] + summary['errors']
  865. successes = summary['successes']
  866. total = summary['total']
  867. self.failures += summary['failures']
  868. self.errors += summary['errors']
  869. self.skipped += summary['skipped']
  870. self.successes += summary['successes']
  871. self.expected_failures += summary['expected_failures']
  872. self.unexpected_successes += summary['unexpected_successes']
  873. self.total += summary['total']
  874. dir_failures += summary['failures']
  875. dir_errors += summary['failures']
  876. dir_skipped += summary['skipped']
  877. dir_successes += summary['successes']
  878. dir_expected_failures += summary['expected_failures']
  879. dir_unexpected_success += summary['unexpected_successes']
  880. dir_total += summary['total']
  881. # TODO: keyvalue method should have types for keys function
  882. # perhaps just the current post processing function is enough
  883. test_file_authors = summary['test_file_authors']
  884. if type(test_file_authors) is not list:
  885. test_file_authors = [test_file_authors]
  886. test_files_authors.extend(test_file_authors)
  887. file_total += 1
  888. file_successes += 0 if summary['returncode'] else 1
  889. pass_per = success_to_html_percent(total=total,
  890. successes=successes)
  891. row = (
  892. '<tr>'
  893. '<td><a href="{f}/index.html">{f}</a></td>'
  894. '<td>{status}</td>'
  895. '<td>{ntests}</td><td>{stests}</td>'
  896. '<td>{ftests}</td><td>{ptests}</td>'
  897. '<tr>'
  898. .format(
  899. f=test_file_name,
  900. status=returncode_to_html_text(summary['returncode']),
  901. stests=successes, ftests=bad_ones, ntests=total,
  902. ptests=pass_per))
  903. page.write(row)
  904. self.testsuites += 1
  905. self.testsuites_successes += 1 if file_successes == file_total else 0
  906. self.files += file_total
  907. self.files_successes += file_successes
  908. dir_pass_per = success_to_html_percent(total=dir_total,
  909. successes=dir_successes)
  910. file_pass_per = success_to_html_percent(total=file_total,
  911. successes=file_successes)
  912. tests_table_foot = (
  913. '</tbody><tfoot><tr>'
  914. '<td>Summary</td>'
  915. '<td>{status}</td>'
  916. '<td>{ntests}</td><td>{stests}</td>'
  917. '<td>{ftests}</td><td>{ptests}</td>'
  918. '</tr></tfoot></table>'
  919. .format(
  920. status=file_pass_per,
  921. stests=dir_successes, ftests=dir_failures + dir_errors,
  922. ntests=dir_total, ptests=dir_pass_per))
  923. page.write(tests_table_foot)
  924. test_authors = get_html_test_authors_table(
  925. directory=directory, tests_authors=test_files_authors)
  926. page.write(test_authors)
  927. page.write('</body></html>')
  928. page.close()
  929. status = success_to_html_text(total=file_total, successes=file_successes)
  930. row = (
  931. '<tr>'
  932. '<td><a href="{d}/{page}">{d}</a></td><td>{status}</td>'
  933. '<td>{nfiles}</td><td>{sfiles}</td><td>{pfiles}</td>'
  934. '<td>{ntests}</td><td>{stests}</td>'
  935. '<td>{ftests}</td><td>{ptests}</td>'
  936. '<tr>'
  937. .format(
  938. d=directory, page=self.testsuite_page_name, status=status,
  939. nfiles=file_total, sfiles=file_successes, pfiles=file_pass_per,
  940. stests=dir_successes, ftests=dir_failures + dir_errors,
  941. ntests=dir_total, ptests=dir_pass_per))
  942. return row
  943. def report_for_dirs(self, root, directories):
  944. # TODO: this will need chanages accoring to potential chnages in absolute/relative paths
  945. page_name = os.path.join(root, self.main_page_name)
  946. page = open(page_name, 'w')
  947. head = (
  948. '<html><body>'
  949. '<h1>Testsuites results</h1>'
  950. )
  951. tests_table_head = (
  952. '<table>'
  953. '<thead><tr>'
  954. '<th>Testsuite</th>'
  955. '<th>Status</th>'
  956. '<th>Test files</th><th>Successful</td>'
  957. '<th>Percent successful</th>'
  958. '<th>Tests</th><th>Successful</td>'
  959. '<th>Failed</th><th>Percent successful</th>'
  960. '</tr></thead><tbody>'
  961. )
  962. page.write(head)
  963. page.write(tests_table_head)
  964. for directory, test_files in directories.iteritems():
  965. row = self.report_for_dir(root=root, directory=directory,
  966. test_files=test_files)
  967. page.write(row)
  968. pass_per = success_to_html_percent(total=self.total,
  969. successes=self.successes)
  970. file_pass_per = success_to_html_percent(total=self.files,
  971. successes=self.files_successes)
  972. testsuites_pass_per = success_to_html_percent(
  973. total=self.testsuites, successes=self.testsuites_successes)
  974. tests_table_foot = (
  975. '<tfoot>'
  976. '<tr>'
  977. '<td>Summary</td><td>{status}</td>'
  978. '<td>{nfiles}</td><td>{sfiles}</td><td>{pfiles}</td>'
  979. '<td>{ntests}</td><td>{stests}</td>'
  980. '<td>{ftests}</td><td>{ptests}</td>'
  981. '</tr>'
  982. '</tfoot>'
  983. .format(
  984. status=testsuites_pass_per, nfiles=self.files,
  985. sfiles=self.files_successes, pfiles=file_pass_per,
  986. stests=self.successes, ftests=self.failures + self.errors,
  987. ntests=self.total, ptests=pass_per))
  988. page.write(tests_table_foot)
  989. page.write('</body></html>')