reporters.py 46 KB

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