html.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
  2. # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
  3. """HTML reporting for coverage.py."""
  4. import datetime
  5. import json
  6. import os
  7. import shutil
  8. import coverage
  9. from coverage import env
  10. from coverage.backward import iitems
  11. from coverage.files import flat_rootname
  12. from coverage.misc import CoverageException, Hasher, isolate_module
  13. from coverage.report import Reporter
  14. from coverage.results import Numbers
  15. from coverage.templite import Templite
  16. os = isolate_module(os)
  17. # Static files are looked for in a list of places.
  18. STATIC_PATH = [
  19. # The place Debian puts system Javascript libraries.
  20. "/usr/share/javascript",
  21. # Our htmlfiles directory.
  22. os.path.join(os.path.dirname(__file__), "htmlfiles"),
  23. ]
  24. def data_filename(fname, pkgdir=""):
  25. """Return the path to a data file of ours.
  26. The file is searched for on `STATIC_PATH`, and the first place it's found,
  27. is returned.
  28. Each directory in `STATIC_PATH` is searched as-is, and also, if `pkgdir`
  29. is provided, at that sub-directory.
  30. """
  31. tried = []
  32. for static_dir in STATIC_PATH:
  33. static_filename = os.path.join(static_dir, fname)
  34. if os.path.exists(static_filename):
  35. return static_filename
  36. else:
  37. tried.append(static_filename)
  38. if pkgdir:
  39. static_filename = os.path.join(static_dir, pkgdir, fname)
  40. if os.path.exists(static_filename):
  41. return static_filename
  42. else:
  43. tried.append(static_filename)
  44. raise CoverageException(
  45. "Couldn't find static file %r from %r, tried: %r" % (fname, os.getcwd(), tried)
  46. )
  47. def read_data(fname):
  48. """Return the contents of a data file of ours."""
  49. with open(data_filename(fname)) as data_file:
  50. return data_file.read()
  51. def write_html(fname, html):
  52. """Write `html` to `fname`, properly encoded."""
  53. with open(fname, "wb") as fout:
  54. fout.write(html.encode('ascii', 'xmlcharrefreplace'))
  55. class HtmlReporter(Reporter):
  56. """HTML reporting."""
  57. # These files will be copied from the htmlfiles directory to the output
  58. # directory.
  59. STATIC_FILES = [
  60. ("style.css", ""),
  61. ("jquery.min.js", "jquery"),
  62. ("jquery.debounce.min.js", "jquery-debounce"),
  63. ("jquery.hotkeys.js", "jquery-hotkeys"),
  64. ("jquery.isonscreen.js", "jquery-isonscreen"),
  65. ("jquery.tablesorter.min.js", "jquery-tablesorter"),
  66. ("coverage_html.js", ""),
  67. ("keybd_closed.png", ""),
  68. ("keybd_open.png", ""),
  69. ]
  70. def __init__(self, cov, config):
  71. super(HtmlReporter, self).__init__(cov, config)
  72. self.directory = None
  73. title = self.config.html_title
  74. if env.PY2:
  75. title = title.decode("utf8")
  76. self.template_globals = {
  77. 'escape': escape,
  78. 'pair': pair,
  79. 'title': title,
  80. '__url__': coverage.__url__,
  81. '__version__': coverage.__version__,
  82. }
  83. self.source_tmpl = Templite(read_data("pyfile.html"), self.template_globals)
  84. self.coverage = cov
  85. self.files = []
  86. self.has_arcs = self.coverage.data.has_arcs()
  87. self.status = HtmlStatus()
  88. self.extra_css = None
  89. self.totals = Numbers()
  90. self.time_stamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
  91. def report(self, morfs):
  92. """Generate an HTML report for `morfs`.
  93. `morfs` is a list of modules or file names.
  94. """
  95. assert self.config.html_dir, "must give a directory for html reporting"
  96. # Read the status data.
  97. self.status.read(self.config.html_dir)
  98. # Check that this run used the same settings as the last run.
  99. m = Hasher()
  100. m.update(self.config)
  101. these_settings = m.hexdigest()
  102. if self.status.settings_hash() != these_settings:
  103. self.status.reset()
  104. self.status.set_settings_hash(these_settings)
  105. # The user may have extra CSS they want copied.
  106. if self.config.extra_css:
  107. self.extra_css = os.path.basename(self.config.extra_css)
  108. # Process all the files.
  109. self.report_files(self.html_file, morfs, self.config.html_dir)
  110. if not self.files:
  111. raise CoverageException("No data to report.")
  112. # Write the index file.
  113. self.index_file()
  114. self.make_local_static_report_files()
  115. return self.totals.n_statements and self.totals.pc_covered
  116. def make_local_static_report_files(self):
  117. """Make local instances of static files for HTML report."""
  118. # The files we provide must always be copied.
  119. for static, pkgdir in self.STATIC_FILES:
  120. shutil.copyfile(
  121. data_filename(static, pkgdir),
  122. os.path.join(self.directory, static)
  123. )
  124. # The user may have extra CSS they want copied.
  125. if self.extra_css:
  126. shutil.copyfile(
  127. self.config.extra_css,
  128. os.path.join(self.directory, self.extra_css)
  129. )
  130. def file_hash(self, source, fr):
  131. """Compute a hash that changes if the file needs to be re-reported."""
  132. m = Hasher()
  133. m.update(source)
  134. self.coverage.data.add_to_hash(fr.filename, m)
  135. return m.hexdigest()
  136. def html_file(self, fr, analysis):
  137. """Generate an HTML file for one source file."""
  138. source = fr.source()
  139. # Find out if the file on disk is already correct.
  140. rootname = flat_rootname(fr.relative_filename())
  141. this_hash = self.file_hash(source.encode('utf-8'), fr)
  142. that_hash = self.status.file_hash(rootname)
  143. if this_hash == that_hash:
  144. # Nothing has changed to require the file to be reported again.
  145. self.files.append(self.status.index_info(rootname))
  146. return
  147. self.status.set_file_hash(rootname, this_hash)
  148. # Get the numbers for this file.
  149. nums = analysis.numbers
  150. if self.has_arcs:
  151. missing_branch_arcs = analysis.missing_branch_arcs()
  152. arcs_executed = analysis.arcs_executed()
  153. # These classes determine which lines are highlighted by default.
  154. c_run = "run hide_run"
  155. c_exc = "exc"
  156. c_mis = "mis"
  157. c_par = "par " + c_run
  158. lines = []
  159. for lineno, line in enumerate(fr.source_token_lines(), start=1):
  160. # Figure out how to mark this line.
  161. line_class = []
  162. annotate_html = ""
  163. annotate_long = ""
  164. if lineno in analysis.statements:
  165. line_class.append("stm")
  166. if lineno in analysis.excluded:
  167. line_class.append(c_exc)
  168. elif lineno in analysis.missing:
  169. line_class.append(c_mis)
  170. elif self.has_arcs and lineno in missing_branch_arcs:
  171. line_class.append(c_par)
  172. shorts = []
  173. longs = []
  174. for b in missing_branch_arcs[lineno]:
  175. if b < 0:
  176. shorts.append("exit")
  177. else:
  178. shorts.append(b)
  179. longs.append(fr.missing_arc_description(lineno, b, arcs_executed))
  180. # 202F is NARROW NO-BREAK SPACE.
  181. # 219B is RIGHTWARDS ARROW WITH STROKE.
  182. short_fmt = "%s&#x202F;&#x219B;&#x202F;%s"
  183. annotate_html = ",&nbsp;&nbsp; ".join(short_fmt % (lineno, d) for d in shorts)
  184. if len(longs) == 1:
  185. annotate_long = longs[0]
  186. else:
  187. annotate_long = "%d missed branches: %s" % (
  188. len(longs),
  189. ", ".join("%d) %s" % (num, ann_long)
  190. for num, ann_long in enumerate(longs, start=1)),
  191. )
  192. elif lineno in analysis.statements:
  193. line_class.append(c_run)
  194. # Build the HTML for the line.
  195. html = []
  196. for tok_type, tok_text in line:
  197. if tok_type == "ws":
  198. html.append(escape(tok_text))
  199. else:
  200. tok_html = escape(tok_text) or '&nbsp;'
  201. html.append(
  202. '<span class="%s">%s</span>' % (tok_type, tok_html)
  203. )
  204. lines.append({
  205. 'html': ''.join(html),
  206. 'number': lineno,
  207. 'class': ' '.join(line_class) or "pln",
  208. 'annotate': annotate_html,
  209. 'annotate_long': annotate_long,
  210. })
  211. # Write the HTML page for this file.
  212. html = self.source_tmpl.render({
  213. 'c_exc': c_exc,
  214. 'c_mis': c_mis,
  215. 'c_par': c_par,
  216. 'c_run': c_run,
  217. 'has_arcs': self.has_arcs,
  218. 'extra_css': self.extra_css,
  219. 'fr': fr,
  220. 'nums': nums,
  221. 'lines': lines,
  222. 'time_stamp': self.time_stamp,
  223. })
  224. html_filename = rootname + ".html"
  225. html_path = os.path.join(self.directory, html_filename)
  226. write_html(html_path, html)
  227. # Save this file's information for the index file.
  228. index_info = {
  229. 'nums': nums,
  230. 'html_filename': html_filename,
  231. 'relative_filename': fr.relative_filename(),
  232. }
  233. self.files.append(index_info)
  234. self.status.set_index_info(rootname, index_info)
  235. def index_file(self):
  236. """Write the index.html file for this report."""
  237. index_tmpl = Templite(read_data("index.html"), self.template_globals)
  238. self.totals = sum(f['nums'] for f in self.files)
  239. html = index_tmpl.render({
  240. 'has_arcs': self.has_arcs,
  241. 'extra_css': self.extra_css,
  242. 'files': self.files,
  243. 'totals': self.totals,
  244. 'time_stamp': self.time_stamp,
  245. })
  246. write_html(os.path.join(self.directory, "index.html"), html)
  247. # Write the latest hashes for next time.
  248. self.status.write(self.directory)
  249. class HtmlStatus(object):
  250. """The status information we keep to support incremental reporting."""
  251. STATUS_FILE = "status.json"
  252. STATUS_FORMAT = 1
  253. # pylint: disable=wrong-spelling-in-comment,useless-suppression
  254. # The data looks like:
  255. #
  256. # {
  257. # 'format': 1,
  258. # 'settings': '540ee119c15d52a68a53fe6f0897346d',
  259. # 'version': '4.0a1',
  260. # 'files': {
  261. # 'cogapp___init__': {
  262. # 'hash': 'e45581a5b48f879f301c0f30bf77a50c',
  263. # 'index': {
  264. # 'html_filename': 'cogapp___init__.html',
  265. # 'name': 'cogapp/__init__',
  266. # 'nums': <coverage.results.Numbers object at 0x10ab7ed0>,
  267. # }
  268. # },
  269. # ...
  270. # 'cogapp_whiteutils': {
  271. # 'hash': '8504bb427fc488c4176809ded0277d51',
  272. # 'index': {
  273. # 'html_filename': 'cogapp_whiteutils.html',
  274. # 'name': 'cogapp/whiteutils',
  275. # 'nums': <coverage.results.Numbers object at 0x10ab7d90>,
  276. # }
  277. # },
  278. # },
  279. # }
  280. def __init__(self):
  281. self.reset()
  282. def reset(self):
  283. """Initialize to empty."""
  284. self.settings = ''
  285. self.files = {}
  286. def read(self, directory):
  287. """Read the last status in `directory`."""
  288. usable = False
  289. try:
  290. status_file = os.path.join(directory, self.STATUS_FILE)
  291. with open(status_file, "r") as fstatus:
  292. status = json.load(fstatus)
  293. except (IOError, ValueError):
  294. usable = False
  295. else:
  296. usable = True
  297. if status['format'] != self.STATUS_FORMAT:
  298. usable = False
  299. elif status['version'] != coverage.__version__:
  300. usable = False
  301. if usable:
  302. self.files = {}
  303. for filename, fileinfo in iitems(status['files']):
  304. fileinfo['index']['nums'] = Numbers(*fileinfo['index']['nums'])
  305. self.files[filename] = fileinfo
  306. self.settings = status['settings']
  307. else:
  308. self.reset()
  309. def write(self, directory):
  310. """Write the current status to `directory`."""
  311. status_file = os.path.join(directory, self.STATUS_FILE)
  312. files = {}
  313. for filename, fileinfo in iitems(self.files):
  314. fileinfo['index']['nums'] = fileinfo['index']['nums'].init_args()
  315. files[filename] = fileinfo
  316. status = {
  317. 'format': self.STATUS_FORMAT,
  318. 'version': coverage.__version__,
  319. 'settings': self.settings,
  320. 'files': files,
  321. }
  322. with open(status_file, "w") as fout:
  323. json.dump(status, fout)
  324. # Older versions of ShiningPanda look for the old name, status.dat.
  325. # Accomodate them if we are running under Jenkins.
  326. # https://issues.jenkins-ci.org/browse/JENKINS-28428
  327. if "JENKINS_URL" in os.environ:
  328. with open(os.path.join(directory, "status.dat"), "w") as dat:
  329. dat.write("https://issues.jenkins-ci.org/browse/JENKINS-28428\n")
  330. def settings_hash(self):
  331. """Get the hash of the coverage.py settings."""
  332. return self.settings
  333. def set_settings_hash(self, settings):
  334. """Set the hash of the coverage.py settings."""
  335. self.settings = settings
  336. def file_hash(self, fname):
  337. """Get the hash of `fname`'s contents."""
  338. return self.files.get(fname, {}).get('hash', '')
  339. def set_file_hash(self, fname, val):
  340. """Set the hash of `fname`'s contents."""
  341. self.files.setdefault(fname, {})['hash'] = val
  342. def index_info(self, fname):
  343. """Get the information for index.html for `fname`."""
  344. return self.files.get(fname, {}).get('index', {})
  345. def set_index_info(self, fname, info):
  346. """Set the information for index.html for `fname`."""
  347. self.files.setdefault(fname, {})['index'] = info
  348. # Helpers for templates and generating HTML
  349. def escape(t):
  350. """HTML-escape the text in `t`.
  351. This is only suitable for HTML text, not attributes.
  352. """
  353. # Convert HTML special chars into HTML entities.
  354. return t.replace("&", "&amp;").replace("<", "&lt;")
  355. def pair(ratio):
  356. """Format a pair of numbers so JavaScript can read them in an attribute."""
  357. return "%s %s" % ratio