reporters.py 46 KB

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