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