PageRenderTime 50ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/python/coverage/control.py

https://github.com/andymckay/zamboni-lib
Python | 345 lines | 271 code | 18 blank | 56 comment | 12 complexity | 827f8786412ed402d335392e3e2d7d57 MD5 | raw file
  1. """Core control stuff for Coverage."""
  2. import atexit, os, socket
  3. from coverage.annotate import AnnotateReporter
  4. from coverage.backward import string_class # pylint: disable-msg=W0622
  5. from coverage.codeunit import code_unit_factory, CodeUnit
  6. from coverage.collector import Collector
  7. from coverage.data import CoverageData
  8. from coverage.files import FileLocator
  9. from coverage.html import HtmlReporter
  10. from coverage.results import Analysis
  11. from coverage.summary import SummaryReporter
  12. from coverage.xmlreport import XmlReporter
  13. class coverage(object):
  14. """Programmatic access to Coverage.
  15. To use::
  16. from coverage import coverage
  17. cov = coverage()
  18. cov.start()
  19. #.. blah blah (run your code) blah blah ..
  20. cov.stop()
  21. cov.html_report(directory='covhtml')
  22. """
  23. def __init__(self, data_file=None, data_suffix=False, cover_pylib=False,
  24. auto_data=False, timid=False, branch=False):
  25. """
  26. `data_file` is the base name of the data file to use, defaulting to
  27. ".coverage". `data_suffix` is appended to `data_file` to create the
  28. final file name. If `data_suffix` is simply True, then a suffix is
  29. created with the machine and process identity included.
  30. `cover_pylib` is a boolean determining whether Python code installed
  31. with the Python interpreter is measured. This includes the Python
  32. standard library and any packages installed with the interpreter.
  33. If `auto_data` is true, then any existing data file will be read when
  34. coverage measurement starts, and data will be saved automatically when
  35. measurement stops.
  36. If `timid` is true, then a slower and simpler trace function will be
  37. used. This is important for some environments where manipulation of
  38. tracing functions breaks the faster trace function.
  39. If `branch` is true, then branch coverage will be measured in addition
  40. to the usual statement coverage.
  41. """
  42. from coverage import __version__
  43. self.cover_pylib = cover_pylib
  44. self.auto_data = auto_data
  45. self.atexit_registered = False
  46. self.exclude_re = ""
  47. self.exclude_list = []
  48. self.file_locator = FileLocator()
  49. # Timidity: for nose users, read an environment variable. This is a
  50. # cheap hack, since the rest of the command line arguments aren't
  51. # recognized, but it solves some users' problems.
  52. timid = timid or ('--timid' in os.environ.get('COVERAGE_OPTIONS', ''))
  53. self.collector = Collector(
  54. self._should_trace, timid=timid, branch=branch
  55. )
  56. # Create the data file.
  57. if data_suffix:
  58. if not isinstance(data_suffix, string_class):
  59. # if data_suffix=True, use .machinename.pid
  60. data_suffix = ".%s.%s" % (socket.gethostname(), os.getpid())
  61. else:
  62. data_suffix = None
  63. self.data = CoverageData(
  64. basename=data_file, suffix=data_suffix,
  65. collector="coverage v%s" % __version__
  66. )
  67. # The default exclude pattern.
  68. self.exclude('# *pragma[: ]*[nN][oO] *[cC][oO][vV][eE][rR]')
  69. # The prefix for files considered "installed with the interpreter".
  70. if not self.cover_pylib:
  71. # Look at where the "os" module is located. That's the indication
  72. # for "installed with the interpreter".
  73. os_file = self.file_locator.canonical_filename(os.__file__)
  74. self.pylib_prefix = os.path.split(os_file)[0]
  75. # To avoid tracing the coverage code itself, we skip anything located
  76. # where we are.
  77. here = self.file_locator.canonical_filename(__file__)
  78. self.cover_prefix = os.path.split(here)[0]
  79. def _should_trace(self, filename, frame):
  80. """Decide whether to trace execution in `filename`
  81. This function is called from the trace function. As each new file name
  82. is encountered, this function determines whether it is traced or not.
  83. Returns a canonicalized filename if it should be traced, False if it
  84. should not.
  85. """
  86. if filename == '<string>':
  87. # There's no point in ever tracing string executions, we can't do
  88. # anything with the data later anyway.
  89. return False
  90. # Compiled Python files have two filenames: frame.f_code.co_filename is
  91. # the filename at the time the .pyc was compiled. The second name
  92. # is __file__, which is where the .pyc was actually loaded from. Since
  93. # .pyc files can be moved after compilation (for example, by being
  94. # installed), we look for __file__ in the frame and prefer it to the
  95. # co_filename value.
  96. dunder_file = frame.f_globals.get('__file__')
  97. if dunder_file:
  98. if not dunder_file.endswith(".py"):
  99. if dunder_file[-4:-1] == ".py":
  100. dunder_file = dunder_file[:-1]
  101. filename = dunder_file
  102. canonical = self.file_locator.canonical_filename(filename)
  103. # If we aren't supposed to trace installed code, then check if this is
  104. # near the Python standard library and skip it if so.
  105. if not self.cover_pylib:
  106. if canonical.startswith(self.pylib_prefix):
  107. return False
  108. # We exclude the coverage code itself, since a little of it will be
  109. # measured otherwise.
  110. if canonical.startswith(self.cover_prefix):
  111. return False
  112. return canonical
  113. # To log what should_trace returns, change this to "if 1:"
  114. if 0:
  115. _real_should_trace = _should_trace
  116. def _should_trace(self, filename, frame): # pylint: disable-msg=E0102
  117. """A logging decorator around the real _should_trace function."""
  118. ret = self._real_should_trace(filename, frame)
  119. print("should_trace: %r -> %r" % (filename, ret))
  120. return ret
  121. def use_cache(self, usecache):
  122. """Control the use of a data file (incorrectly called a cache).
  123. `usecache` is true or false, whether to read and write data on disk.
  124. """
  125. self.data.usefile(usecache)
  126. def load(self):
  127. """Load previously-collected coverage data from the data file."""
  128. self.collector.reset()
  129. self.data.read()
  130. def start(self):
  131. """Start measuring code coverage."""
  132. if self.auto_data:
  133. self.load()
  134. # Save coverage data when Python exits.
  135. if not self.atexit_registered:
  136. atexit.register(self.save)
  137. self.atexit_registered = True
  138. self.collector.start()
  139. def stop(self):
  140. """Stop measuring code coverage."""
  141. self.collector.stop()
  142. self._harvest_data()
  143. def erase(self):
  144. """Erase previously-collected coverage data.
  145. This removes the in-memory data collected in this session as well as
  146. discarding the data file.
  147. """
  148. self.collector.reset()
  149. self.data.erase()
  150. def clear_exclude(self):
  151. """Clear the exclude list."""
  152. self.exclude_list = []
  153. self.exclude_re = ""
  154. def exclude(self, regex):
  155. """Exclude source lines from execution consideration.
  156. `regex` is a regular expression. Lines matching this expression are
  157. not considered executable when reporting code coverage. A list of
  158. regexes is maintained; this function adds a new regex to the list.
  159. Matching any of the regexes excludes a source line.
  160. """
  161. self.exclude_list.append(regex)
  162. self.exclude_re = "(" + ")|(".join(self.exclude_list) + ")"
  163. def get_exclude_list(self):
  164. """Return the list of excluded regex patterns."""
  165. return self.exclude_list
  166. def save(self):
  167. """Save the collected coverage data to the data file."""
  168. self._harvest_data()
  169. self.data.write()
  170. def combine(self):
  171. """Combine together a number of similarly-named coverage data files.
  172. All coverage data files whose name starts with `data_file` (from the
  173. coverage() constructor) will be read, and combined together into the
  174. current measurements.
  175. """
  176. self.data.combine_parallel_data()
  177. def _harvest_data(self):
  178. """Get the collected data and reset the collector."""
  179. self.data.add_line_data(self.collector.get_line_data())
  180. self.data.add_arc_data(self.collector.get_arc_data())
  181. self.collector.reset()
  182. # Backward compatibility with version 1.
  183. def analysis(self, morf):
  184. """Like `analysis2` but doesn't return excluded line numbers."""
  185. f, s, _, m, mf = self.analysis2(morf)
  186. return f, s, m, mf
  187. def analysis2(self, morf):
  188. """Analyze a module.
  189. `morf` is a module or a filename. It will be analyzed to determine
  190. its coverage statistics. The return value is a 5-tuple:
  191. * The filename for the module.
  192. * A list of line numbers of executable statements.
  193. * A list of line numbers of excluded statements.
  194. * A list of line numbers of statements not run (missing from execution).
  195. * A readable formatted string of the missing line numbers.
  196. The analysis uses the source file itself and the current measured
  197. coverage data.
  198. """
  199. analysis = self._analyze(morf)
  200. return (
  201. analysis.filename, analysis.statements, analysis.excluded,
  202. analysis.missing, analysis.missing_formatted()
  203. )
  204. def _analyze(self, it):
  205. """Analyze a single morf or code unit.
  206. Returns an `Analysis` object.
  207. """
  208. if not isinstance(it, CodeUnit):
  209. it = code_unit_factory(it, self.file_locator)[0]
  210. return Analysis(self, it)
  211. def report(self, morfs=None, show_missing=True, ignore_errors=False,
  212. file=None, omit_prefixes=None): # pylint: disable-msg=W0622
  213. """Write a summary report to `file`.
  214. Each module in `morfs` is listed, with counts of statements, executed
  215. statements, missing statements, and a list of lines missed.
  216. """
  217. reporter = SummaryReporter(self, show_missing, ignore_errors)
  218. reporter.report(morfs, outfile=file, omit_prefixes=omit_prefixes)
  219. def annotate(self, morfs=None, directory=None, ignore_errors=False,
  220. omit_prefixes=None):
  221. """Annotate a list of modules.
  222. Each module in `morfs` is annotated. The source is written to a new
  223. file, named with a ",cover" suffix, with each line prefixed with a
  224. marker to indicate the coverage of the line. Covered lines have ">",
  225. excluded lines have "-", and missing lines have "!".
  226. """
  227. reporter = AnnotateReporter(self, ignore_errors)
  228. reporter.report(
  229. morfs, directory=directory, omit_prefixes=omit_prefixes)
  230. def html_report(self, morfs=None, directory=None, ignore_errors=False,
  231. omit_prefixes=None):
  232. """Generate an HTML report.
  233. """
  234. reporter = HtmlReporter(self, ignore_errors)
  235. reporter.report(
  236. morfs, directory=directory, omit_prefixes=omit_prefixes)
  237. def xml_report(self, morfs=None, outfile=None, ignore_errors=False,
  238. omit_prefixes=None):
  239. """Generate an XML report of coverage results.
  240. The report is compatible with Cobertura reports.
  241. """
  242. if outfile:
  243. outfile = open(outfile, "w")
  244. try:
  245. reporter = XmlReporter(self, ignore_errors)
  246. reporter.report(
  247. morfs, omit_prefixes=omit_prefixes, outfile=outfile)
  248. finally:
  249. outfile.close()
  250. def sysinfo(self):
  251. """Return a list of key,value pairs showing internal information."""
  252. import coverage as covmod
  253. import platform, re, sys
  254. info = [
  255. ('version', covmod.__version__),
  256. ('coverage', covmod.__file__),
  257. ('cover_prefix', self.cover_prefix),
  258. ('pylib_prefix', self.pylib_prefix),
  259. ('tracer', self.collector.tracer_name()),
  260. ('data_path', self.data.filename),
  261. ('python', sys.version.replace('\n', '')),
  262. ('platform', platform.platform()),
  263. ('cwd', os.getcwd()),
  264. ('path', sys.path),
  265. ('environment', [
  266. ("%s = %s" % (k, v)) for k, v in os.environ.items()
  267. if re.search("^COV|^PY", k)
  268. ]),
  269. ]
  270. return info