reporters.py 45 KB

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