multireport.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. # -*- coding: utf-8 -*-
  2. """Testing framework module for multi report
  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 sys
  10. import os
  11. import argparse
  12. import itertools
  13. import datetime
  14. import operator
  15. from collections import defaultdict, namedtuple
  16. from grass.gunittest.checkers import text_to_keyvalue
  17. from grass.gunittest.utils import ensure_dir
  18. from grass.gunittest.reporters import success_to_html_percent
  19. # TODO: we should be able to work without matplotlib
  20. import matplotlib
  21. matplotlib.use('Agg')
  22. # This counts as code already, so silence "import not at top of file".
  23. # Perhaps in the future, switch_backend() could be used.
  24. import matplotlib.pyplot as plt # noqa: E402
  25. from matplotlib.dates import date2num # noqa: E402
  26. class TestResultSummary(object):
  27. def __init__(self):
  28. self.timestamp = None
  29. self.svn_revision = None
  30. self.location = None
  31. self.location_type = None
  32. self.total = None
  33. self.successes = None
  34. self.failures = None
  35. self.errors = None
  36. self.skipped = []
  37. self.expected_failures = []
  38. self.unexpected_successes = []
  39. self.files_total = None
  40. self.files_successes = None
  41. self.files_failures = None
  42. self.tested_modules = []
  43. self.tested_dirs = []
  44. self.test_files_authors = []
  45. self.tested_dirs = []
  46. self.time = []
  47. self.names = []
  48. self.report = None
  49. def plot_percents(x, xticks, xlabels, successes, failures, filename, style):
  50. fig = plt.figure()
  51. graph = fig.add_subplot(111)
  52. # Plot the data as a red line with round markers
  53. graph.plot(x, successes, color=style.success_color,
  54. linestyle=style.linestyle, linewidth=style.linewidth)
  55. graph.plot(x, failures, color=style.fail_color,
  56. linestyle=style.linestyle, linewidth=style.linewidth)
  57. fig.autofmt_xdate()
  58. graph.set_xticks(xticks)
  59. graph.set_xticklabels(xlabels)
  60. percents = range(0, 110, 10)
  61. graph.set_yticks(percents)
  62. graph.set_yticklabels(['%d%%' % p for p in percents])
  63. fig.savefig(filename)
  64. def plot_percent_successful(x, xticks, xlabels, successes, filename, style):
  65. fig = plt.figure()
  66. graph = fig.add_subplot(111)
  67. def median(values):
  68. n = len(values)
  69. if n == 1:
  70. return values[0]
  71. sorted_values = sorted(values)
  72. if n % 2 == 0:
  73. return (sorted_values[n / 2 - 1] + sorted_values[n / 2]) / 2
  74. else:
  75. return sorted_values[n / 2]
  76. # this is useful for debugging or some other stat
  77. # cmeans = []
  78. # cmedians = []
  79. # csum = 0
  80. # count = 0
  81. # for i, s in enumerate(successes):
  82. # csum += s
  83. # count += 1
  84. # cmeans.append(csum/count)
  85. # cmedians.append(median(successes[:i + 1]))
  86. smedian = median(successes)
  87. smax = max(successes)
  88. if successes[-1] < smedian:
  89. color = 'r'
  90. else:
  91. color = 'g'
  92. # another possibility is to color according to the gradient, ideally
  93. # on the whole curve but that's much more complicated
  94. graph.plot(x, successes, color=color,
  95. linestyle=style.linestyle, linewidth=style.linewidth)
  96. # rotates the xlabels
  97. fig.autofmt_xdate()
  98. graph.set_xticks(xticks)
  99. graph.set_xticklabels(xlabels)
  100. step = 5
  101. ymin = int(min(successes) / step) * step
  102. ymax = int(smax / step) * step
  103. percents = range(ymin, ymax + step + 1, step)
  104. graph.set_yticks(percents)
  105. graph.set_yticklabels(['%d%%' % p for p in percents])
  106. fig.savefig(filename)
  107. def tests_successful_plot(x, xticks, xlabels, results, filename, style):
  108. successes = []
  109. for result in results:
  110. if result.total:
  111. successes.append(float(result.successes) / result.total * 100)
  112. else:
  113. # this is not expected to happen
  114. # but we don't want any exceptions if it happens
  115. successes.append(0)
  116. plot_percent_successful(x=x, xticks=xticks, xlabels=xlabels,
  117. successes=successes,
  118. filename=filename, style=style)
  119. def tests_plot(x, xticks, xlabels, results, filename, style):
  120. total = [result.total for result in results]
  121. successes = [result.successes for result in results]
  122. # TODO: document: counting errors and failures together
  123. failures = [result.failures + result.errors for result in results]
  124. fig = plt.figure()
  125. graph = fig.add_subplot(111)
  126. graph.plot(x, total, color=style.total_color,
  127. linestyle=style.linestyle, linewidth=style.linewidth)
  128. graph.plot(x, successes, color=style.success_color,
  129. linestyle=style.linestyle, linewidth=style.linewidth)
  130. graph.plot(x, failures, color=style.fail_color,
  131. linestyle=style.linestyle, linewidth=style.linewidth)
  132. fig.autofmt_xdate()
  133. graph.set_xticks(xticks)
  134. graph.set_xticklabels(xlabels)
  135. fig.savefig(filename)
  136. def tests_percent_plot(x, xticks, xlabels, results, filename, style):
  137. successes = []
  138. failures = []
  139. for result in results:
  140. if result.total:
  141. successes.append(float(result.successes) / result.total * 100)
  142. # TODO: again undocumented, counting errors and failures together
  143. failures.append(float(result.failures + result.errors) / result.total * 100)
  144. else:
  145. # this is not expected to happen
  146. # but we don't want any exceptions if it happens
  147. successes.append(0)
  148. failures.append(0)
  149. plot_percents(x=x, xticks=xticks, xlabels=xlabels,
  150. successes=successes, failures=failures,
  151. filename=filename, style=style)
  152. def files_successful_plot(x, xticks, xlabels, results, filename, style):
  153. successes = []
  154. for result in results:
  155. if result.total:
  156. successes.append(float(result.files_successes) / result.files_total * 100)
  157. else:
  158. # this is not expected to happen
  159. # but we don't want any exceptions if it happens
  160. successes.append(0)
  161. plot_percent_successful(x=x, xticks=xticks, xlabels=xlabels,
  162. successes=successes,
  163. filename=filename, style=style)
  164. def files_plot(x, xticks, xlabels, results, filename, style):
  165. total = [result.files_total for result in results]
  166. successes = [result.files_successes for result in results]
  167. failures = [result.files_failures for result in results]
  168. fig = plt.figure()
  169. graph = fig.add_subplot(111)
  170. graph.plot(x, total, color=style.total_color,
  171. linestyle=style.linestyle, linewidth=style.linewidth)
  172. graph.plot(x, successes, color=style.success_color,
  173. linestyle=style.linestyle, linewidth=style.linewidth)
  174. graph.plot(x, failures, color=style.fail_color,
  175. linestyle=style.linestyle, linewidth=style.linewidth)
  176. fig.autofmt_xdate()
  177. graph.set_xticks(xticks)
  178. graph.set_xticklabels(xlabels)
  179. fig.savefig(filename)
  180. def files_percent_plot(x, xticks, xlabels, results, filename, style):
  181. successes = []
  182. failures = []
  183. for result in results:
  184. if result.files_total:
  185. successes.append(float(result.files_successes) / result.files_total * 100)
  186. failures.append(float(result.files_failures) / result.files_total * 100)
  187. else:
  188. # this is not expected to happen
  189. # but we don't want any exceptions if it happens
  190. successes.append(0)
  191. failures.append(0)
  192. plot_percents(x=x, xticks=xticks, xlabels=xlabels,
  193. successes=successes, failures=failures,
  194. filename=filename, style=style)
  195. def info_plot(x, xticks, xlabels, results, filename, style):
  196. modules = [len(result.tested_modules) for result in results]
  197. names = [len(result.names) for result in results]
  198. authors = [len(result.test_files_authors) for result in results]
  199. # we want just unique directories
  200. dirs = [len(set(result.tested_dirs)) for result in results]
  201. fig = plt.figure()
  202. graph = fig.add_subplot(111)
  203. graph.plot(x, names, color='b', label="Test files",
  204. linestyle=style.linestyle, linewidth=style.linewidth)
  205. graph.plot(x, modules, color='g', label="Tested modules",
  206. linestyle=style.linestyle, linewidth=style.linewidth)
  207. # dirs == testsuites
  208. graph.plot(x, dirs, color='orange', label="Tested directories",
  209. linestyle=style.linestyle, linewidth=style.linewidth)
  210. graph.plot(x, authors, color='r', label="Test authors",
  211. linestyle=style.linestyle, linewidth=style.linewidth)
  212. graph.legend(loc='best', shadow=False)
  213. fig.autofmt_xdate()
  214. graph.set_xticks(xticks)
  215. graph.set_xticklabels(xlabels)
  216. fig.savefig(filename)
  217. # TODO: solve the directory inconsitencies, implement None
  218. def main_page(results, filename, images, captions, title='Test reports',
  219. directory=None):
  220. filename = os.path.join(directory, filename)
  221. with open(filename, 'w') as page:
  222. page.write(
  223. '<html><body>'
  224. '<h1>{title}</h1>'
  225. '<table>'
  226. '<thead><tr>'
  227. '<th>Date (timestamp)</th><th>SVN revision</th><th>Name</th>'
  228. '<th>Successful files</th><th>Successful tests</th>'
  229. '</tr></thead>'
  230. '<tbody>'
  231. .format(title=title)
  232. )
  233. for result in reversed(results):
  234. # TODO: include name to summary file
  235. # now using location or test report directory as name
  236. if result.location != 'unknown':
  237. name = result.location
  238. else:
  239. name = os.path.basename(result.report)
  240. if not name:
  241. # Python basename returns '' for 'abc/'
  242. for d in reversed(os.path.split(result.report)):
  243. if d:
  244. name = d
  245. break
  246. per_test = success_to_html_percent(
  247. total=result.total, successes=result.successes)
  248. per_file = success_to_html_percent(
  249. total=result.files_total, successes=result.files_successes)
  250. report_path = os.path.relpath(path=result.report, start=directory)
  251. page.write(
  252. '<tr>'
  253. '<td><a href={report_path}/index.html>{result.timestamp}</a></td>'
  254. '<td>{result.svn_revision}</td>'
  255. '<td><a href={report_path}/index.html>{name}</a></td>'
  256. '<td>{pfiles}</td><td>{ptests}</td>'
  257. '</tr>'
  258. .format(result=result, name=name, report_path=report_path,
  259. pfiles=per_file, ptests=per_test))
  260. page.write('</tbody></table>')
  261. for image, caption in itertools.izip(images, captions):
  262. page.write(
  263. '<h3>{caption}<h3>'
  264. '<img src="{image}" alt="{caption}" title="{caption}">'
  265. .format(image=image, caption=caption))
  266. page.write('</body></html>')
  267. def main():
  268. parser = argparse.ArgumentParser(
  269. description='Create overall report from several individual test reports')
  270. parser.add_argument('reports', metavar='report_directory',
  271. type=str, nargs='+',
  272. help='Directories with reports')
  273. parser.add_argument('--output', dest='output', action='store',
  274. default='testreports_summary',
  275. help='Output directory')
  276. parser.add_argument('--timestamps', dest='timestamps', action='store_true',
  277. help='Use file timestamp instead of date in test summary')
  278. args = parser.parse_args()
  279. output = args.output
  280. reports = args.reports
  281. use_timestamps = args.timestamps
  282. ensure_dir(output)
  283. all_results = []
  284. results_in_locations = defaultdict(list)
  285. for report in reports:
  286. try:
  287. summary_file = os.path.join(report, 'test_keyvalue_result.txt')
  288. if not os.path.exists(summary_file):
  289. sys.stderr.write('WARNING: Key-value summary not available in'
  290. ' report <%s>, skipping.\n' % summary_file)
  291. # skipping incomplete reports
  292. # use only results list for further processing
  293. continue
  294. summary = text_to_keyvalue(open(summary_file).read(), sep='=')
  295. if use_timestamps:
  296. test_timestamp = datetime.datetime.fromtimestamp(os.path.getmtime(summary_file))
  297. else:
  298. test_timestamp = datetime.datetime.strptime(summary['timestamp'], "%Y-%m-%d %H:%M:%S")
  299. result = TestResultSummary()
  300. result.timestamp = test_timestamp
  301. result.total = summary['total']
  302. result.successes = summary['successes']
  303. result.failures = summary['failures']
  304. result.errors = summary['errors']
  305. result.files_total = summary['files_total']
  306. result.files_successes = summary['files_successes']
  307. result.files_failures = summary['files_failures']
  308. result.svn_revision = str(summary['svn_revision'])
  309. result.tested_modules = summary['tested_modules']
  310. result.names = summary['names']
  311. result.test_files_authors = summary['test_files_authors']
  312. result.tested_dirs = summary['tested_dirs']
  313. result.report = report
  314. # let's consider no location as valid state and use 'unknown'
  315. result.location = summary.get('location', 'unknown')
  316. result.location_type = summary.get('location_type', 'unknown')
  317. # grouping according to location types
  318. # this can cause that two actual locations tested at the same time
  319. # will end up together, this is not ideal but testing with
  320. # one location type and different actual locations is not standard
  321. # and although it will not break anything it will not give a nice
  322. # report
  323. results_in_locations[result.location_type].append(result)
  324. all_results.append(result)
  325. del result
  326. except KeyError as e:
  327. print('File %s does not have right values (%s)' % (report, e.message))
  328. locations_main_page = open(os.path.join(output, 'index.html'), 'w')
  329. locations_main_page.write(
  330. '<html><body>'
  331. '<h1>Test reports grouped by location type</h1>'
  332. '<table>'
  333. '<thead><tr>'
  334. '<th>Location</th>'
  335. '<th>Successful files</th><th>Successful tests</th>'
  336. '</tr></thead>'
  337. '<tbody>'
  338. )
  339. PlotStyle = namedtuple('PlotStyle',
  340. ['linestyle', 'linewidth',
  341. 'success_color', 'fail_color', 'total_color'])
  342. plot_style = PlotStyle(linestyle='-', linewidth=4.0,
  343. success_color='g', fail_color='r', total_color='b')
  344. for location_type, results in results_in_locations.items():
  345. results = sorted(results, key=operator.attrgetter('timestamp'))
  346. # TODO: document: location type must be a valid dir name
  347. directory = os.path.join(output, location_type)
  348. ensure_dir(directory)
  349. if location_type == 'unknown':
  350. title = 'Test reports'
  351. else:
  352. title = ('Test reports for &lt;{type}&gt; location type'
  353. .format(type=location_type))
  354. x = [date2num(result.timestamp) for result in results]
  355. # the following would be an alternative but it does not work with
  356. # labels and automatic axis limits even after removing another date fun
  357. # x = [result.svn_revision for result in results]
  358. xlabels = [result.timestamp.strftime("%Y-%m-%d") + ' (r' + result.svn_revision + ')' for result in results]
  359. step = len(x) / 10
  360. xticks = x[step::step]
  361. xlabels = xlabels[step::step]
  362. tests_successful_plot(x=x, xticks=xticks, xlabels=xlabels, results=results,
  363. filename=os.path.join(directory, 'tests_successful_plot.png'),
  364. style=plot_style)
  365. files_successful_plot(x=x, xticks=xticks, xlabels=xlabels, results=results,
  366. filename=os.path.join(directory, 'files_successful_plot.png'),
  367. style=plot_style)
  368. tests_plot(x=x, xticks=xticks, xlabels=xlabels, results=results,
  369. filename=os.path.join(directory, 'tests_plot.png'),
  370. style=plot_style)
  371. tests_percent_plot(x=x, xticks=xticks, xlabels=xlabels, results=results,
  372. filename=os.path.join(directory, 'tests_percent_plot.png'),
  373. style=plot_style)
  374. files_plot(x=x, xticks=xticks, xlabels=xlabels, results=results,
  375. filename=os.path.join(directory, 'files_plot.png'),
  376. style=plot_style)
  377. files_percent_plot(x=x, xticks=xticks, xlabels=xlabels, results=results,
  378. filename=os.path.join(directory, 'files_percent_plot.png'),
  379. style=plot_style)
  380. info_plot(x=x, xticks=xticks, xlabels=xlabels, results=results,
  381. filename=os.path.join(directory, 'info_plot.png'),
  382. style=plot_style)
  383. main_page(results=results, filename='index.html',
  384. images=['tests_successful_plot.png',
  385. 'files_successful_plot.png',
  386. 'tests_plot.png',
  387. 'files_plot.png',
  388. 'tests_percent_plot.png',
  389. 'files_percent_plot.png',
  390. 'info_plot.png'],
  391. captions=['Success of individual tests in percents',
  392. 'Success of test files in percents',
  393. 'Successes, failures and number of individual tests',
  394. 'Successes, failures and number of test files',
  395. 'Successes and failures of individual tests in percent',
  396. 'Successes and failures of test files in percents',
  397. 'Additional information'],
  398. directory=directory,
  399. title=title)
  400. files_successes = sum(result.files_successes for result in results)
  401. files_total = sum(result.files_total for result in results)
  402. successes = sum(result.successes for result in results)
  403. total = sum(result.total for result in results)
  404. per_test = success_to_html_percent(
  405. total=total, successes=successes)
  406. per_file = success_to_html_percent(
  407. total=files_total, successes=files_successes)
  408. locations_main_page.write(
  409. '<tr>'
  410. '<td><a href={location}/index.html>{location}</a></td>'
  411. '<td>{pfiles}</td><td>{ptests}</td>'
  412. '</tr>'
  413. .format(location=location_type,
  414. pfiles=per_file, ptests=per_test))
  415. locations_main_page.write('</tbody></table>')
  416. locations_main_page.write('</body></html>')
  417. locations_main_page.close()
  418. return 0
  419. if __name__ == '__main__':
  420. sys.exit(main())