results.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. """Results of coverage measurement."""
  4. import collections
  5. from coverage.backward import iitems
  6. from coverage.misc import format_lines, SimpleRepr
  7. class Analysis(object):
  8. """The results of analyzing a FileReporter."""
  9. def __init__(self, data, file_reporter):
  10. self.data = data
  11. self.file_reporter = file_reporter
  12. self.filename = self.file_reporter.filename
  13. self.statements = self.file_reporter.lines()
  14. self.excluded = self.file_reporter.excluded_lines()
  15. # Identify missing statements.
  16. executed = self.data.lines(self.filename) or []
  17. executed = self.file_reporter.translate_lines(executed)
  18. self.missing = self.statements - executed
  19. if self.data.has_arcs():
  20. self._arc_possibilities = sorted(self.file_reporter.arcs())
  21. self.exit_counts = self.file_reporter.exit_counts()
  22. self.no_branch = self.file_reporter.no_branch_lines()
  23. n_branches = self.total_branches()
  24. mba = self.missing_branch_arcs()
  25. n_partial_branches = sum(len(v) for k,v in iitems(mba) if k not in self.missing)
  26. n_missing_branches = sum(len(v) for k,v in iitems(mba))
  27. else:
  28. self._arc_possibilities = []
  29. self.exit_counts = {}
  30. self.no_branch = set()
  31. n_branches = n_partial_branches = n_missing_branches = 0
  32. self.numbers = Numbers(
  33. n_files=1,
  34. n_statements=len(self.statements),
  35. n_excluded=len(self.excluded),
  36. n_missing=len(self.missing),
  37. n_branches=n_branches,
  38. n_partial_branches=n_partial_branches,
  39. n_missing_branches=n_missing_branches,
  40. )
  41. def missing_formatted(self):
  42. """The missing line numbers, formatted nicely.
  43. Returns a string like "1-2, 5-11, 13-14".
  44. """
  45. return format_lines(self.statements, self.missing)
  46. def has_arcs(self):
  47. """Were arcs measured in this result?"""
  48. return self.data.has_arcs()
  49. def arc_possibilities(self):
  50. """Returns a sorted list of the arcs in the code."""
  51. return self._arc_possibilities
  52. def arcs_executed(self):
  53. """Returns a sorted list of the arcs actually executed in the code."""
  54. executed = self.data.arcs(self.filename) or []
  55. executed = self.file_reporter.translate_arcs(executed)
  56. return sorted(executed)
  57. def arcs_missing(self):
  58. """Returns a sorted list of the arcs in the code not executed."""
  59. possible = self.arc_possibilities()
  60. executed = self.arcs_executed()
  61. missing = (
  62. p for p in possible
  63. if p not in executed
  64. and p[0] not in self.no_branch
  65. )
  66. return sorted(missing)
  67. def arcs_missing_formatted(self):
  68. """The missing branch arcs, formatted nicely.
  69. Returns a string like "1->2, 1->3, 16->20". Omits any mention of
  70. branches from missing lines, so if line 17 is missing, then 17->18
  71. won't be included.
  72. """
  73. arcs = self.missing_branch_arcs()
  74. missing = self.missing
  75. line_exits = sorted(iitems(arcs))
  76. pairs = []
  77. for line, exits in line_exits:
  78. for ex in sorted(exits):
  79. if line not in missing:
  80. pairs.append("%d->%s" % (line, (ex if ex > 0 else "exit")))
  81. return ', '.join(pairs)
  82. def arcs_unpredicted(self):
  83. """Returns a sorted list of the executed arcs missing from the code."""
  84. possible = self.arc_possibilities()
  85. executed = self.arcs_executed()
  86. # Exclude arcs here which connect a line to itself. They can occur
  87. # in executed data in some cases. This is where they can cause
  88. # trouble, and here is where it's the least burden to remove them.
  89. # Also, generators can somehow cause arcs from "enter" to "exit", so
  90. # make sure we have at least one positive value.
  91. unpredicted = (
  92. e for e in executed
  93. if e not in possible
  94. and e[0] != e[1]
  95. and (e[0] > 0 or e[1] > 0)
  96. )
  97. return sorted(unpredicted)
  98. def branch_lines(self):
  99. """Returns a list of line numbers that have more than one exit."""
  100. return [l1 for l1,count in iitems(self.exit_counts) if count > 1]
  101. def total_branches(self):
  102. """How many total branches are there?"""
  103. return sum(count for count in self.exit_counts.values() if count > 1)
  104. def missing_branch_arcs(self):
  105. """Return arcs that weren't executed from branch lines.
  106. Returns {l1:[l2a,l2b,...], ...}
  107. """
  108. missing = self.arcs_missing()
  109. branch_lines = set(self.branch_lines())
  110. mba = collections.defaultdict(list)
  111. for l1, l2 in missing:
  112. if l1 in branch_lines:
  113. mba[l1].append(l2)
  114. return mba
  115. def branch_stats(self):
  116. """Get stats about branches.
  117. Returns a dict mapping line numbers to a tuple:
  118. (total_exits, taken_exits).
  119. """
  120. missing_arcs = self.missing_branch_arcs()
  121. stats = {}
  122. for lnum in self.branch_lines():
  123. exits = self.exit_counts[lnum]
  124. try:
  125. missing = len(missing_arcs[lnum])
  126. except KeyError:
  127. missing = 0
  128. stats[lnum] = (exits, exits - missing)
  129. return stats
  130. class Numbers(SimpleRepr):
  131. """The numerical results of measuring coverage.
  132. This holds the basic statistics from `Analysis`, and is used to roll
  133. up statistics across files.
  134. """
  135. # A global to determine the precision on coverage percentages, the number
  136. # of decimal places.
  137. _precision = 0
  138. _near0 = 1.0 # These will change when _precision is changed.
  139. _near100 = 99.0
  140. def __init__(self, n_files=0, n_statements=0, n_excluded=0, n_missing=0,
  141. n_branches=0, n_partial_branches=0, n_missing_branches=0
  142. ):
  143. self.n_files = n_files
  144. self.n_statements = n_statements
  145. self.n_excluded = n_excluded
  146. self.n_missing = n_missing
  147. self.n_branches = n_branches
  148. self.n_partial_branches = n_partial_branches
  149. self.n_missing_branches = n_missing_branches
  150. def init_args(self):
  151. """Return a list for __init__(*args) to recreate this object."""
  152. return [
  153. self.n_files, self.n_statements, self.n_excluded, self.n_missing,
  154. self.n_branches, self.n_partial_branches, self.n_missing_branches,
  155. ]
  156. @classmethod
  157. def set_precision(cls, precision):
  158. """Set the number of decimal places used to report percentages."""
  159. assert 0 <= precision < 10
  160. cls._precision = precision
  161. cls._near0 = 1.0 / 10**precision
  162. cls._near100 = 100.0 - cls._near0
  163. @property
  164. def n_executed(self):
  165. """Returns the number of executed statements."""
  166. return self.n_statements - self.n_missing
  167. @property
  168. def n_executed_branches(self):
  169. """Returns the number of executed branches."""
  170. return self.n_branches - self.n_missing_branches
  171. @property
  172. def pc_covered(self):
  173. """Returns a single percentage value for coverage."""
  174. if self.n_statements > 0:
  175. numerator, denominator = self.ratio_covered
  176. pc_cov = (100.0 * numerator) / denominator
  177. else:
  178. pc_cov = 100.0
  179. return pc_cov
  180. @property
  181. def pc_covered_str(self):
  182. """Returns the percent covered, as a string, without a percent sign.
  183. Note that "0" is only returned when the value is truly zero, and "100"
  184. is only returned when the value is truly 100. Rounding can never
  185. result in either "0" or "100".
  186. """
  187. pc = self.pc_covered
  188. if 0 < pc < self._near0:
  189. pc = self._near0
  190. elif self._near100 < pc < 100:
  191. pc = self._near100
  192. else:
  193. pc = round(pc, self._precision)
  194. return "%.*f" % (self._precision, pc)
  195. @classmethod
  196. def pc_str_width(cls):
  197. """How many characters wide can pc_covered_str be?"""
  198. width = 3 # "100"
  199. if cls._precision > 0:
  200. width += 1 + cls._precision
  201. return width
  202. @property
  203. def ratio_covered(self):
  204. """Return a numerator and denominator for the coverage ratio."""
  205. numerator = self.n_executed + self.n_executed_branches
  206. denominator = self.n_statements + self.n_branches
  207. return numerator, denominator
  208. def __add__(self, other):
  209. nums = Numbers()
  210. nums.n_files = self.n_files + other.n_files
  211. nums.n_statements = self.n_statements + other.n_statements
  212. nums.n_excluded = self.n_excluded + other.n_excluded
  213. nums.n_missing = self.n_missing + other.n_missing
  214. nums.n_branches = self.n_branches + other.n_branches
  215. nums.n_partial_branches = (
  216. self.n_partial_branches + other.n_partial_branches
  217. )
  218. nums.n_missing_branches = (
  219. self.n_missing_branches + other.n_missing_branches
  220. )
  221. return nums
  222. def __radd__(self, other):
  223. # Implementing 0+Numbers allows us to sum() a list of Numbers.
  224. if other == 0:
  225. return self
  226. return NotImplemented