reporters.py 45 KB

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