control.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  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. """Core control stuff for coverage.py."""
  4. import atexit
  5. import inspect
  6. import itertools
  7. import os
  8. import platform
  9. import re
  10. import sys
  11. import traceback
  12. from coverage import env
  13. from coverage.annotate import AnnotateReporter
  14. from coverage.backward import string_class, iitems
  15. from coverage.collector import Collector
  16. from coverage.config import read_coverage_config
  17. from coverage.data import CoverageData, CoverageDataFiles
  18. from coverage.debug import DebugControl, write_formatted_info
  19. from coverage.files import TreeMatcher, FnmatchMatcher
  20. from coverage.files import PathAliases, find_python_files, prep_patterns
  21. from coverage.files import canonical_filename, set_relative_directory
  22. from coverage.files import ModuleMatcher, abs_file
  23. from coverage.html import HtmlReporter
  24. from coverage.misc import CoverageException, bool_or_none, join_regex
  25. from coverage.misc import file_be_gone, isolate_module
  26. from coverage.plugin import FileReporter
  27. from coverage.plugin_support import Plugins
  28. from coverage.python import PythonFileReporter, source_for_file
  29. from coverage.results import Analysis, Numbers
  30. from coverage.summary import SummaryReporter
  31. from coverage.xmlreport import XmlReporter
  32. try:
  33. from coverage.multiproc import patch_multiprocessing
  34. except ImportError: # pragma: only jython
  35. # Jython has no multiprocessing module.
  36. patch_multiprocessing = None
  37. os = isolate_module(os)
  38. # Pypy has some unusual stuff in the "stdlib". Consider those locations
  39. # when deciding where the stdlib is. These modules are not used for anything,
  40. # they are modules importable from the pypy lib directories, so that we can
  41. # find those directories.
  42. _structseq = _pypy_irc_topic = None
  43. if env.PYPY:
  44. try:
  45. import _structseq
  46. except ImportError:
  47. pass
  48. try:
  49. import _pypy_irc_topic
  50. except ImportError:
  51. pass
  52. class Coverage(object):
  53. """Programmatic access to coverage.py.
  54. To use::
  55. from coverage import Coverage
  56. cov = Coverage()
  57. cov.start()
  58. #.. call your code ..
  59. cov.stop()
  60. cov.html_report(directory='covhtml')
  61. """
  62. def __init__(
  63. self, data_file=None, data_suffix=None, cover_pylib=None,
  64. auto_data=False, timid=None, branch=None, config_file=True,
  65. source=None, omit=None, include=None, debug=None,
  66. concurrency=None,
  67. ):
  68. """
  69. `data_file` is the base name of the data file to use, defaulting to
  70. ".coverage". `data_suffix` is appended (with a dot) to `data_file` to
  71. create the final file name. If `data_suffix` is simply True, then a
  72. suffix is created with the machine and process identity included.
  73. `cover_pylib` is a boolean determining whether Python code installed
  74. with the Python interpreter is measured. This includes the Python
  75. standard library and any packages installed with the interpreter.
  76. If `auto_data` is true, then any existing data file will be read when
  77. coverage measurement starts, and data will be saved automatically when
  78. measurement stops.
  79. If `timid` is true, then a slower and simpler trace function will be
  80. used. This is important for some environments where manipulation of
  81. tracing functions breaks the faster trace function.
  82. If `branch` is true, then branch coverage will be measured in addition
  83. to the usual statement coverage.
  84. `config_file` determines what configuration file to read:
  85. * If it is ".coveragerc", it is interpreted as if it were True,
  86. for backward compatibility.
  87. * If it is a string, it is the name of the file to read. If the
  88. file can't be read, it is an error.
  89. * If it is True, then a few standard files names are tried
  90. (".coveragerc", "setup.cfg", "tox.ini"). It is not an error for
  91. these files to not be found.
  92. * If it is False, then no configuration file is read.
  93. `source` is a list of file paths or package names. Only code located
  94. in the trees indicated by the file paths or package names will be
  95. measured.
  96. `include` and `omit` are lists of file name patterns. Files that match
  97. `include` will be measured, files that match `omit` will not. Each
  98. will also accept a single string argument.
  99. `debug` is a list of strings indicating what debugging information is
  100. desired.
  101. `concurrency` is a string indicating the concurrency library being used
  102. in the measured code. Without this, coverage.py will get incorrect
  103. results if these libraries are in use. Valid strings are "greenlet",
  104. "eventlet", "gevent", "multiprocessing", or "thread" (the default).
  105. This can also be a list of these strings.
  106. .. versionadded:: 4.0
  107. The `concurrency` parameter.
  108. .. versionadded:: 4.2
  109. The `concurrency` parameter can now be a list of strings.
  110. """
  111. # Build our configuration from a number of sources.
  112. self.config_file, self.config = read_coverage_config(
  113. config_file=config_file,
  114. data_file=data_file, cover_pylib=cover_pylib, timid=timid,
  115. branch=branch, parallel=bool_or_none(data_suffix),
  116. source=source, run_omit=omit, run_include=include, debug=debug,
  117. report_omit=omit, report_include=include,
  118. concurrency=concurrency,
  119. )
  120. # This is injectable by tests.
  121. self._debug_file = None
  122. self._auto_load = self._auto_save = auto_data
  123. self._data_suffix = data_suffix
  124. # The matchers for _should_trace.
  125. self.source_match = None
  126. self.source_pkgs_match = None
  127. self.pylib_match = self.cover_match = None
  128. self.include_match = self.omit_match = None
  129. # Is it ok for no data to be collected?
  130. self._warn_no_data = True
  131. self._warn_unimported_source = True
  132. # A record of all the warnings that have been issued.
  133. self._warnings = []
  134. # Other instance attributes, set later.
  135. self.omit = self.include = self.source = None
  136. self.source_pkgs_unmatched = None
  137. self.source_pkgs = None
  138. self.data = self.data_files = self.collector = None
  139. self.plugins = None
  140. self.pylib_paths = self.cover_paths = None
  141. self.data_suffix = self.run_suffix = None
  142. self._exclude_re = None
  143. self.debug = None
  144. # State machine variables:
  145. # Have we initialized everything?
  146. self._inited = False
  147. # Have we started collecting and not stopped it?
  148. self._started = False
  149. # If we have sub-process measurement happening automatically, then we
  150. # want any explicit creation of a Coverage object to mean, this process
  151. # is already coverage-aware, so don't auto-measure it. By now, the
  152. # auto-creation of a Coverage object has already happened. But we can
  153. # find it and tell it not to save its data.
  154. if not env.METACOV:
  155. _prevent_sub_process_measurement()
  156. def _init(self):
  157. """Set all the initial state.
  158. This is called by the public methods to initialize state. This lets us
  159. construct a :class:`Coverage` object, then tweak its state before this
  160. function is called.
  161. """
  162. if self._inited:
  163. return
  164. self._inited = True
  165. # Create and configure the debugging controller. COVERAGE_DEBUG_FILE
  166. # is an environment variable, the name of a file to append debug logs
  167. # to.
  168. if self._debug_file is None:
  169. debug_file_name = os.environ.get("COVERAGE_DEBUG_FILE")
  170. if debug_file_name:
  171. self._debug_file = open(debug_file_name, "a")
  172. else:
  173. self._debug_file = sys.stderr
  174. self.debug = DebugControl(self.config.debug, self._debug_file)
  175. # Load plugins
  176. self.plugins = Plugins.load_plugins(self.config.plugins, self.config, self.debug)
  177. # _exclude_re is a dict that maps exclusion list names to compiled
  178. # regexes.
  179. self._exclude_re = {}
  180. self._exclude_regex_stale()
  181. set_relative_directory()
  182. # The source argument can be directories or package names.
  183. self.source = []
  184. self.source_pkgs = []
  185. for src in self.config.source or []:
  186. if os.path.isdir(src):
  187. self.source.append(canonical_filename(src))
  188. else:
  189. self.source_pkgs.append(src)
  190. self.source_pkgs_unmatched = self.source_pkgs[:]
  191. self.omit = prep_patterns(self.config.run_omit)
  192. self.include = prep_patterns(self.config.run_include)
  193. concurrency = self.config.concurrency or []
  194. if "multiprocessing" in concurrency:
  195. if not patch_multiprocessing:
  196. raise CoverageException( # pragma: only jython
  197. "multiprocessing is not supported on this Python"
  198. )
  199. patch_multiprocessing(rcfile=self.config_file)
  200. # Multi-processing uses parallel for the subprocesses, so also use
  201. # it for the main process.
  202. self.config.parallel = True
  203. self.collector = Collector(
  204. should_trace=self._should_trace,
  205. check_include=self._check_include_omit_etc,
  206. timid=self.config.timid,
  207. branch=self.config.branch,
  208. warn=self._warn,
  209. concurrency=concurrency,
  210. )
  211. # Early warning if we aren't going to be able to support plugins.
  212. if self.plugins.file_tracers and not self.collector.supports_plugins:
  213. self._warn(
  214. "Plugin file tracers (%s) aren't supported with %s" % (
  215. ", ".join(
  216. plugin._coverage_plugin_name
  217. for plugin in self.plugins.file_tracers
  218. ),
  219. self.collector.tracer_name(),
  220. )
  221. )
  222. for plugin in self.plugins.file_tracers:
  223. plugin._coverage_enabled = False
  224. # Suffixes are a bit tricky. We want to use the data suffix only when
  225. # collecting data, not when combining data. So we save it as
  226. # `self.run_suffix` now, and promote it to `self.data_suffix` if we
  227. # find that we are collecting data later.
  228. if self._data_suffix or self.config.parallel:
  229. if not isinstance(self._data_suffix, string_class):
  230. # if data_suffix=True, use .machinename.pid.random
  231. self._data_suffix = True
  232. else:
  233. self._data_suffix = None
  234. self.data_suffix = None
  235. self.run_suffix = self._data_suffix
  236. # Create the data file. We do this at construction time so that the
  237. # data file will be written into the directory where the process
  238. # started rather than wherever the process eventually chdir'd to.
  239. self.data = CoverageData(debug=self.debug)
  240. self.data_files = CoverageDataFiles(
  241. basename=self.config.data_file, warn=self._warn, debug=self.debug,
  242. )
  243. # The directories for files considered "installed with the interpreter".
  244. self.pylib_paths = set()
  245. if not self.config.cover_pylib:
  246. # Look at where some standard modules are located. That's the
  247. # indication for "installed with the interpreter". In some
  248. # environments (virtualenv, for example), these modules may be
  249. # spread across a few locations. Look at all the candidate modules
  250. # we've imported, and take all the different ones.
  251. for m in (atexit, inspect, os, platform, _pypy_irc_topic, re, _structseq, traceback):
  252. if m is not None and hasattr(m, "__file__"):
  253. self.pylib_paths.add(self._canonical_path(m, directory=True))
  254. if _structseq and not hasattr(_structseq, '__file__'):
  255. # PyPy 2.4 has no __file__ in the builtin modules, but the code
  256. # objects still have the file names. So dig into one to find
  257. # the path to exclude.
  258. structseq_new = _structseq.structseq_new
  259. try:
  260. structseq_file = structseq_new.func_code.co_filename
  261. except AttributeError:
  262. structseq_file = structseq_new.__code__.co_filename
  263. self.pylib_paths.add(self._canonical_path(structseq_file))
  264. # To avoid tracing the coverage.py code itself, we skip anything
  265. # located where we are.
  266. self.cover_paths = [self._canonical_path(__file__, directory=True)]
  267. if env.TESTING:
  268. # Don't include our own test code.
  269. self.cover_paths.append(os.path.join(self.cover_paths[0], "tests"))
  270. # When testing, we use PyContracts, which should be considered
  271. # part of coverage.py, and it uses six. Exclude those directories
  272. # just as we exclude ourselves.
  273. import contracts
  274. import six
  275. for mod in [contracts, six]:
  276. self.cover_paths.append(self._canonical_path(mod))
  277. # Set the reporting precision.
  278. Numbers.set_precision(self.config.precision)
  279. atexit.register(self._atexit)
  280. # Create the matchers we need for _should_trace
  281. if self.source or self.source_pkgs:
  282. self.source_match = TreeMatcher(self.source)
  283. self.source_pkgs_match = ModuleMatcher(self.source_pkgs)
  284. else:
  285. if self.cover_paths:
  286. self.cover_match = TreeMatcher(self.cover_paths)
  287. if self.pylib_paths:
  288. self.pylib_match = TreeMatcher(self.pylib_paths)
  289. if self.include:
  290. self.include_match = FnmatchMatcher(self.include)
  291. if self.omit:
  292. self.omit_match = FnmatchMatcher(self.omit)
  293. # The user may want to debug things, show info if desired.
  294. self._write_startup_debug()
  295. def _write_startup_debug(self):
  296. """Write out debug info at startup if needed."""
  297. wrote_any = False
  298. with self.debug.without_callers():
  299. if self.debug.should('config'):
  300. config_info = sorted(self.config.__dict__.items())
  301. write_formatted_info(self.debug, "config", config_info)
  302. wrote_any = True
  303. if self.debug.should('sys'):
  304. write_formatted_info(self.debug, "sys", self.sys_info())
  305. for plugin in self.plugins:
  306. header = "sys: " + plugin._coverage_plugin_name
  307. info = plugin.sys_info()
  308. write_formatted_info(self.debug, header, info)
  309. wrote_any = True
  310. if wrote_any:
  311. write_formatted_info(self.debug, "end", ())
  312. def _canonical_path(self, morf, directory=False):
  313. """Return the canonical path of the module or file `morf`.
  314. If the module is a package, then return its directory. If it is a
  315. module, then return its file, unless `directory` is True, in which
  316. case return its enclosing directory.
  317. """
  318. morf_path = PythonFileReporter(morf, self).filename
  319. if morf_path.endswith("__init__.py") or directory:
  320. morf_path = os.path.split(morf_path)[0]
  321. return morf_path
  322. def _name_for_module(self, module_globals, filename):
  323. """Get the name of the module for a set of globals and file name.
  324. For configurability's sake, we allow __main__ modules to be matched by
  325. their importable name.
  326. If loaded via runpy (aka -m), we can usually recover the "original"
  327. full dotted module name, otherwise, we resort to interpreting the
  328. file name to get the module's name. In the case that the module name
  329. can't be determined, None is returned.
  330. """
  331. if module_globals is None: # pragma: only ironpython
  332. # IronPython doesn't provide globals: https://github.com/IronLanguages/main/issues/1296
  333. module_globals = {}
  334. dunder_name = module_globals.get('__name__', None)
  335. if isinstance(dunder_name, str) and dunder_name != '__main__':
  336. # This is the usual case: an imported module.
  337. return dunder_name
  338. loader = module_globals.get('__loader__', None)
  339. for attrname in ('fullname', 'name'): # attribute renamed in py3.2
  340. if hasattr(loader, attrname):
  341. fullname = getattr(loader, attrname)
  342. else:
  343. continue
  344. if isinstance(fullname, str) and fullname != '__main__':
  345. # Module loaded via: runpy -m
  346. return fullname
  347. # Script as first argument to Python command line.
  348. inspectedname = inspect.getmodulename(filename)
  349. if inspectedname is not None:
  350. return inspectedname
  351. else:
  352. return dunder_name
  353. def _should_trace_internal(self, filename, frame):
  354. """Decide whether to trace execution in `filename`, with a reason.
  355. This function is called from the trace function. As each new file name
  356. is encountered, this function determines whether it is traced or not.
  357. Returns a FileDisposition object.
  358. """
  359. original_filename = filename
  360. disp = _disposition_init(self.collector.file_disposition_class, filename)
  361. def nope(disp, reason):
  362. """Simple helper to make it easy to return NO."""
  363. disp.trace = False
  364. disp.reason = reason
  365. return disp
  366. # Compiled Python files have two file names: frame.f_code.co_filename is
  367. # the file name at the time the .pyc was compiled. The second name is
  368. # __file__, which is where the .pyc was actually loaded from. Since
  369. # .pyc files can be moved after compilation (for example, by being
  370. # installed), we look for __file__ in the frame and prefer it to the
  371. # co_filename value.
  372. dunder_file = frame.f_globals and frame.f_globals.get('__file__')
  373. if dunder_file:
  374. filename = source_for_file(dunder_file)
  375. if original_filename and not original_filename.startswith('<'):
  376. orig = os.path.basename(original_filename)
  377. if orig != os.path.basename(filename):
  378. # Files shouldn't be renamed when moved. This happens when
  379. # exec'ing code. If it seems like something is wrong with
  380. # the frame's file name, then just use the original.
  381. filename = original_filename
  382. if not filename:
  383. # Empty string is pretty useless.
  384. return nope(disp, "empty string isn't a file name")
  385. if filename.startswith('memory:'):
  386. return nope(disp, "memory isn't traceable")
  387. if filename.startswith('<'):
  388. # Lots of non-file execution is represented with artificial
  389. # file names like "<string>", "<doctest readme.txt[0]>", or
  390. # "<exec_function>". Don't ever trace these executions, since we
  391. # can't do anything with the data later anyway.
  392. return nope(disp, "not a real file name")
  393. # pyexpat does a dumb thing, calling the trace function explicitly from
  394. # C code with a C file name.
  395. if re.search(r"[/\\]Modules[/\\]pyexpat.c", filename):
  396. return nope(disp, "pyexpat lies about itself")
  397. # Jython reports the .class file to the tracer, use the source file.
  398. if filename.endswith("$py.class"):
  399. filename = filename[:-9] + ".py"
  400. canonical = canonical_filename(filename)
  401. disp.canonical_filename = canonical
  402. # Try the plugins, see if they have an opinion about the file.
  403. plugin = None
  404. for plugin in self.plugins.file_tracers:
  405. if not plugin._coverage_enabled:
  406. continue
  407. try:
  408. file_tracer = plugin.file_tracer(canonical)
  409. if file_tracer is not None:
  410. file_tracer._coverage_plugin = plugin
  411. disp.trace = True
  412. disp.file_tracer = file_tracer
  413. if file_tracer.has_dynamic_source_filename():
  414. disp.has_dynamic_filename = True
  415. else:
  416. disp.source_filename = canonical_filename(
  417. file_tracer.source_filename()
  418. )
  419. break
  420. except Exception:
  421. self._warn(
  422. "Disabling plugin %r due to an exception:" % (
  423. plugin._coverage_plugin_name
  424. )
  425. )
  426. traceback.print_exc()
  427. plugin._coverage_enabled = False
  428. continue
  429. else:
  430. # No plugin wanted it: it's Python.
  431. disp.trace = True
  432. disp.source_filename = canonical
  433. if not disp.has_dynamic_filename:
  434. if not disp.source_filename:
  435. raise CoverageException(
  436. "Plugin %r didn't set source_filename for %r" %
  437. (plugin, disp.original_filename)
  438. )
  439. reason = self._check_include_omit_etc_internal(
  440. disp.source_filename, frame,
  441. )
  442. if reason:
  443. nope(disp, reason)
  444. return disp
  445. def _check_include_omit_etc_internal(self, filename, frame):
  446. """Check a file name against the include, omit, etc, rules.
  447. Returns a string or None. String means, don't trace, and is the reason
  448. why. None means no reason found to not trace.
  449. """
  450. modulename = self._name_for_module(frame.f_globals, filename)
  451. # If the user specified source or include, then that's authoritative
  452. # about the outer bound of what to measure and we don't have to apply
  453. # any canned exclusions. If they didn't, then we have to exclude the
  454. # stdlib and coverage.py directories.
  455. if self.source_match:
  456. if self.source_pkgs_match.match(modulename):
  457. if modulename in self.source_pkgs_unmatched:
  458. self.source_pkgs_unmatched.remove(modulename)
  459. return None # There's no reason to skip this file.
  460. if not self.source_match.match(filename):
  461. return "falls outside the --source trees"
  462. elif self.include_match:
  463. if not self.include_match.match(filename):
  464. return "falls outside the --include trees"
  465. else:
  466. # If we aren't supposed to trace installed code, then check if this
  467. # is near the Python standard library and skip it if so.
  468. if self.pylib_match and self.pylib_match.match(filename):
  469. return "is in the stdlib"
  470. # We exclude the coverage.py code itself, since a little of it
  471. # will be measured otherwise.
  472. if self.cover_match and self.cover_match.match(filename):
  473. return "is part of coverage.py"
  474. # Check the file against the omit pattern.
  475. if self.omit_match and self.omit_match.match(filename):
  476. return "is inside an --omit pattern"
  477. # No reason found to skip this file.
  478. return None
  479. def _should_trace(self, filename, frame):
  480. """Decide whether to trace execution in `filename`.
  481. Calls `_should_trace_internal`, and returns the FileDisposition.
  482. """
  483. disp = self._should_trace_internal(filename, frame)
  484. if self.debug.should('trace'):
  485. self.debug.write(_disposition_debug_msg(disp))
  486. return disp
  487. def _check_include_omit_etc(self, filename, frame):
  488. """Check a file name against the include/omit/etc, rules, verbosely.
  489. Returns a boolean: True if the file should be traced, False if not.
  490. """
  491. reason = self._check_include_omit_etc_internal(filename, frame)
  492. if self.debug.should('trace'):
  493. if not reason:
  494. msg = "Including %r" % (filename,)
  495. else:
  496. msg = "Not including %r: %s" % (filename, reason)
  497. self.debug.write(msg)
  498. return not reason
  499. def _warn(self, msg, slug=None):
  500. """Use `msg` as a warning.
  501. For warning suppression, use `slug` as the shorthand.
  502. """
  503. if slug in self.config.disable_warnings:
  504. # Don't issue the warning
  505. return
  506. self._warnings.append(msg)
  507. if slug:
  508. msg = "%s (%s)" % (msg, slug)
  509. if self.debug.should('pid'):
  510. msg = "[%d] %s" % (os.getpid(), msg)
  511. sys.stderr.write("Coverage.py warning: %s\n" % msg)
  512. def get_option(self, option_name):
  513. """Get an option from the configuration.
  514. `option_name` is a colon-separated string indicating the section and
  515. option name. For example, the ``branch`` option in the ``[run]``
  516. section of the config file would be indicated with `"run:branch"`.
  517. Returns the value of the option.
  518. .. versionadded:: 4.0
  519. """
  520. return self.config.get_option(option_name)
  521. def set_option(self, option_name, value):
  522. """Set an option in the configuration.
  523. `option_name` is a colon-separated string indicating the section and
  524. option name. For example, the ``branch`` option in the ``[run]``
  525. section of the config file would be indicated with ``"run:branch"``.
  526. `value` is the new value for the option. This should be a Python
  527. value where appropriate. For example, use True for booleans, not the
  528. string ``"True"``.
  529. As an example, calling::
  530. cov.set_option("run:branch", True)
  531. has the same effect as this configuration file::
  532. [run]
  533. branch = True
  534. .. versionadded:: 4.0
  535. """
  536. self.config.set_option(option_name, value)
  537. def use_cache(self, usecache):
  538. """Obsolete method."""
  539. self._init()
  540. if not usecache:
  541. self._warn("use_cache(False) is no longer supported.")
  542. def load(self):
  543. """Load previously-collected coverage data from the data file."""
  544. self._init()
  545. self.collector.reset()
  546. self.data_files.read(self.data)
  547. def start(self):
  548. """Start measuring code coverage.
  549. Coverage measurement only occurs in functions called after
  550. :meth:`start` is invoked. Statements in the same scope as
  551. :meth:`start` won't be measured.
  552. Once you invoke :meth:`start`, you must also call :meth:`stop`
  553. eventually, or your process might not shut down cleanly.
  554. """
  555. self._init()
  556. if self.include:
  557. if self.source or self.source_pkgs:
  558. self._warn("--include is ignored because --source is set", slug="include-ignored")
  559. if self.run_suffix:
  560. # Calling start() means we're running code, so use the run_suffix
  561. # as the data_suffix when we eventually save the data.
  562. self.data_suffix = self.run_suffix
  563. if self._auto_load:
  564. self.load()
  565. self.collector.start()
  566. self._started = True
  567. def stop(self):
  568. """Stop measuring code coverage."""
  569. if self._started:
  570. self.collector.stop()
  571. self._started = False
  572. def _atexit(self):
  573. """Clean up on process shutdown."""
  574. if self.debug.should("process"):
  575. self.debug.write("atexit: {0!r}".format(self))
  576. if self._started:
  577. self.stop()
  578. if self._auto_save:
  579. self.save()
  580. def erase(self):
  581. """Erase previously-collected coverage data.
  582. This removes the in-memory data collected in this session as well as
  583. discarding the data file.
  584. """
  585. self._init()
  586. self.collector.reset()
  587. self.data.erase()
  588. self.data_files.erase(parallel=self.config.parallel)
  589. def clear_exclude(self, which='exclude'):
  590. """Clear the exclude list."""
  591. self._init()
  592. setattr(self.config, which + "_list", [])
  593. self._exclude_regex_stale()
  594. def exclude(self, regex, which='exclude'):
  595. """Exclude source lines from execution consideration.
  596. A number of lists of regular expressions are maintained. Each list
  597. selects lines that are treated differently during reporting.
  598. `which` determines which list is modified. The "exclude" list selects
  599. lines that are not considered executable at all. The "partial" list
  600. indicates lines with branches that are not taken.
  601. `regex` is a regular expression. The regex is added to the specified
  602. list. If any of the regexes in the list is found in a line, the line
  603. is marked for special treatment during reporting.
  604. """
  605. self._init()
  606. excl_list = getattr(self.config, which + "_list")
  607. excl_list.append(regex)
  608. self._exclude_regex_stale()
  609. def _exclude_regex_stale(self):
  610. """Drop all the compiled exclusion regexes, a list was modified."""
  611. self._exclude_re.clear()
  612. def _exclude_regex(self, which):
  613. """Return a compiled regex for the given exclusion list."""
  614. if which not in self._exclude_re:
  615. excl_list = getattr(self.config, which + "_list")
  616. self._exclude_re[which] = join_regex(excl_list)
  617. return self._exclude_re[which]
  618. def get_exclude_list(self, which='exclude'):
  619. """Return a list of excluded regex patterns.
  620. `which` indicates which list is desired. See :meth:`exclude` for the
  621. lists that are available, and their meaning.
  622. """
  623. self._init()
  624. return getattr(self.config, which + "_list")
  625. def save(self):
  626. """Save the collected coverage data to the data file."""
  627. self._init()
  628. self.get_data()
  629. self.data_files.write(self.data, suffix=self.data_suffix)
  630. def combine(self, data_paths=None, strict=False):
  631. """Combine together a number of similarly-named coverage data files.
  632. All coverage data files whose name starts with `data_file` (from the
  633. coverage() constructor) will be read, and combined together into the
  634. current measurements.
  635. `data_paths` is a list of files or directories from which data should
  636. be combined. If no list is passed, then the data files from the
  637. directory indicated by the current data file (probably the current
  638. directory) will be combined.
  639. If `strict` is true, then it is an error to attempt to combine when
  640. there are no data files to combine.
  641. .. versionadded:: 4.0
  642. The `data_paths` parameter.
  643. .. versionadded:: 4.3
  644. The `strict` parameter.
  645. """
  646. self._init()
  647. self.get_data()
  648. aliases = None
  649. if self.config.paths:
  650. aliases = PathAliases()
  651. for paths in self.config.paths.values():
  652. result = paths[0]
  653. for pattern in paths[1:]:
  654. aliases.add(pattern, result)
  655. self.data_files.combine_parallel_data(
  656. self.data, aliases=aliases, data_paths=data_paths, strict=strict,
  657. )
  658. def get_data(self):
  659. """Get the collected data.
  660. Also warn about various problems collecting data.
  661. Returns a :class:`coverage.CoverageData`, the collected coverage data.
  662. .. versionadded:: 4.0
  663. """
  664. self._init()
  665. if self.collector.save_data(self.data):
  666. self._post_save_work()
  667. return self.data
  668. def _post_save_work(self):
  669. """After saving data, look for warnings, post-work, etc.
  670. Warn about things that should have happened but didn't.
  671. Look for unexecuted files.
  672. """
  673. # If there are still entries in the source_pkgs_unmatched list,
  674. # then we never encountered those packages.
  675. if self._warn_unimported_source:
  676. for pkg in self.source_pkgs_unmatched:
  677. self._warn_about_unmeasured_code(pkg)
  678. # Find out if we got any data.
  679. if not self.data and self._warn_no_data:
  680. self._warn("No data was collected.", slug="no-data-collected")
  681. # Find files that were never executed at all.
  682. for pkg in self.source_pkgs:
  683. if (not pkg in sys.modules or
  684. not hasattr(sys.modules[pkg], '__file__') or
  685. not os.path.exists(sys.modules[pkg].__file__)):
  686. continue
  687. pkg_file = source_for_file(sys.modules[pkg].__file__)
  688. self._find_unexecuted_files(self._canonical_path(pkg_file))
  689. for src in self.source:
  690. self._find_unexecuted_files(src)
  691. if self.config.note:
  692. self.data.add_run_info(note=self.config.note)
  693. def _warn_about_unmeasured_code(self, pkg):
  694. """Warn about a package or module that we never traced.
  695. `pkg` is a string, the name of the package or module.
  696. """
  697. mod = sys.modules.get(pkg)
  698. if mod is None:
  699. self._warn("Module %s was never imported." % pkg, slug="module-not-imported")
  700. return
  701. is_namespace = hasattr(mod, '__path__') and not hasattr(mod, '__file__')
  702. has_file = hasattr(mod, '__file__') and os.path.exists(mod.__file__)
  703. if is_namespace:
  704. # A namespace package. It's OK for this not to have been traced,
  705. # since there is no code directly in it.
  706. return
  707. if not has_file:
  708. self._warn("Module %s has no Python source." % pkg, slug="module-not-python")
  709. return
  710. # The module was in sys.modules, and seems like a module with code, but
  711. # we never measured it. I guess that means it was imported before
  712. # coverage even started.
  713. self._warn(
  714. "Module %s was previously imported, but not measured" % pkg,
  715. slug="module-not-measured",
  716. )
  717. def _find_plugin_files(self, src_dir):
  718. """Get executable files from the plugins."""
  719. for plugin in self.plugins:
  720. for x_file in plugin.find_executable_files(src_dir):
  721. yield x_file, plugin._coverage_plugin_name
  722. def _find_unexecuted_files(self, src_dir):
  723. """Find unexecuted files in `src_dir`.
  724. Search for files in `src_dir` that are probably importable,
  725. and add them as unexecuted files in `self.data`.
  726. """
  727. py_files = ((py_file, None) for py_file in find_python_files(src_dir))
  728. plugin_files = self._find_plugin_files(src_dir)
  729. for file_path, plugin_name in itertools.chain(py_files, plugin_files):
  730. file_path = canonical_filename(file_path)
  731. if self.omit_match and self.omit_match.match(file_path):
  732. # Turns out this file was omitted, so don't pull it back
  733. # in as unexecuted.
  734. continue
  735. self.data.touch_file(file_path, plugin_name)
  736. # Backward compatibility with version 1.
  737. def analysis(self, morf):
  738. """Like `analysis2` but doesn't return excluded line numbers."""
  739. f, s, _, m, mf = self.analysis2(morf)
  740. return f, s, m, mf
  741. def analysis2(self, morf):
  742. """Analyze a module.
  743. `morf` is a module or a file name. It will be analyzed to determine
  744. its coverage statistics. The return value is a 5-tuple:
  745. * The file name for the module.
  746. * A list of line numbers of executable statements.
  747. * A list of line numbers of excluded statements.
  748. * A list of line numbers of statements not run (missing from
  749. execution).
  750. * A readable formatted string of the missing line numbers.
  751. The analysis uses the source file itself and the current measured
  752. coverage data.
  753. """
  754. self._init()
  755. analysis = self._analyze(morf)
  756. return (
  757. analysis.filename,
  758. sorted(analysis.statements),
  759. sorted(analysis.excluded),
  760. sorted(analysis.missing),
  761. analysis.missing_formatted(),
  762. )
  763. def _analyze(self, it):
  764. """Analyze a single morf or code unit.
  765. Returns an `Analysis` object.
  766. """
  767. self.get_data()
  768. if not isinstance(it, FileReporter):
  769. it = self._get_file_reporter(it)
  770. return Analysis(self.data, it)
  771. def _get_file_reporter(self, morf):
  772. """Get a FileReporter for a module or file name."""
  773. plugin = None
  774. file_reporter = "python"
  775. if isinstance(morf, string_class):
  776. abs_morf = abs_file(morf)
  777. plugin_name = self.data.file_tracer(abs_morf)
  778. if plugin_name:
  779. plugin = self.plugins.get(plugin_name)
  780. if plugin:
  781. file_reporter = plugin.file_reporter(abs_morf)
  782. if file_reporter is None:
  783. raise CoverageException(
  784. "Plugin %r did not provide a file reporter for %r." % (
  785. plugin._coverage_plugin_name, morf
  786. )
  787. )
  788. if file_reporter == "python":
  789. file_reporter = PythonFileReporter(morf, self)
  790. return file_reporter
  791. def _get_file_reporters(self, morfs=None):
  792. """Get a list of FileReporters for a list of modules or file names.
  793. For each module or file name in `morfs`, find a FileReporter. Return
  794. the list of FileReporters.
  795. If `morfs` is a single module or file name, this returns a list of one
  796. FileReporter. If `morfs` is empty or None, then the list of all files
  797. measured is used to find the FileReporters.
  798. """
  799. if not morfs:
  800. morfs = self.data.measured_files()
  801. # Be sure we have a list.
  802. if not isinstance(morfs, (list, tuple)):
  803. morfs = [morfs]
  804. file_reporters = []
  805. for morf in morfs:
  806. file_reporter = self._get_file_reporter(morf)
  807. file_reporters.append(file_reporter)
  808. return file_reporters
  809. def report(
  810. self, morfs=None, show_missing=None, ignore_errors=None,
  811. file=None, # pylint: disable=redefined-builtin
  812. omit=None, include=None, skip_covered=None,
  813. ):
  814. """Write a summary report to `file`.
  815. Each module in `morfs` is listed, with counts of statements, executed
  816. statements, missing statements, and a list of lines missed.
  817. `include` is a list of file name patterns. Files that match will be
  818. included in the report. Files matching `omit` will not be included in
  819. the report.
  820. If `skip_covered` is True, don't report on files with 100% coverage.
  821. Returns a float, the total percentage covered.
  822. """
  823. self.get_data()
  824. self.config.from_args(
  825. ignore_errors=ignore_errors, report_omit=omit, report_include=include,
  826. show_missing=show_missing, skip_covered=skip_covered,
  827. )
  828. reporter = SummaryReporter(self, self.config)
  829. return reporter.report(morfs, outfile=file)
  830. def annotate(
  831. self, morfs=None, directory=None, ignore_errors=None,
  832. omit=None, include=None,
  833. ):
  834. """Annotate a list of modules.
  835. Each module in `morfs` is annotated. The source is written to a new
  836. file, named with a ",cover" suffix, with each line prefixed with a
  837. marker to indicate the coverage of the line. Covered lines have ">",
  838. excluded lines have "-", and missing lines have "!".
  839. See :meth:`report` for other arguments.
  840. """
  841. self.get_data()
  842. self.config.from_args(
  843. ignore_errors=ignore_errors, report_omit=omit, report_include=include
  844. )
  845. reporter = AnnotateReporter(self, self.config)
  846. reporter.report(morfs, directory=directory)
  847. def html_report(self, morfs=None, directory=None, ignore_errors=None,
  848. omit=None, include=None, extra_css=None, title=None,
  849. skip_covered=None):
  850. """Generate an HTML report.
  851. The HTML is written to `directory`. The file "index.html" is the
  852. overview starting point, with links to more detailed pages for
  853. individual modules.
  854. `extra_css` is a path to a file of other CSS to apply on the page.
  855. It will be copied into the HTML directory.
  856. `title` is a text string (not HTML) to use as the title of the HTML
  857. report.
  858. See :meth:`report` for other arguments.
  859. Returns a float, the total percentage covered.
  860. """
  861. self.get_data()
  862. self.config.from_args(
  863. ignore_errors=ignore_errors, report_omit=omit, report_include=include,
  864. html_dir=directory, extra_css=extra_css, html_title=title,
  865. skip_covered=skip_covered,
  866. )
  867. reporter = HtmlReporter(self, self.config)
  868. return reporter.report(morfs)
  869. def xml_report(
  870. self, morfs=None, outfile=None, ignore_errors=None,
  871. omit=None, include=None,
  872. ):
  873. """Generate an XML report of coverage results.
  874. The report is compatible with Cobertura reports.
  875. Each module in `morfs` is included in the report. `outfile` is the
  876. path to write the file to, "-" will write to stdout.
  877. See :meth:`report` for other arguments.
  878. Returns a float, the total percentage covered.
  879. """
  880. self.get_data()
  881. self.config.from_args(
  882. ignore_errors=ignore_errors, report_omit=omit, report_include=include,
  883. xml_output=outfile,
  884. )
  885. file_to_close = None
  886. delete_file = False
  887. if self.config.xml_output:
  888. if self.config.xml_output == '-':
  889. outfile = sys.stdout
  890. else:
  891. # Ensure that the output directory is created; done here
  892. # because this report pre-opens the output file.
  893. # HTMLReport does this using the Report plumbing because
  894. # its task is more complex, being multiple files.
  895. output_dir = os.path.dirname(self.config.xml_output)
  896. if output_dir and not os.path.isdir(output_dir):
  897. os.makedirs(output_dir)
  898. open_kwargs = {}
  899. if env.PY3:
  900. open_kwargs['encoding'] = 'utf8'
  901. outfile = open(self.config.xml_output, "w", **open_kwargs)
  902. file_to_close = outfile
  903. try:
  904. reporter = XmlReporter(self, self.config)
  905. return reporter.report(morfs, outfile=outfile)
  906. except CoverageException:
  907. delete_file = True
  908. raise
  909. finally:
  910. if file_to_close:
  911. file_to_close.close()
  912. if delete_file:
  913. file_be_gone(self.config.xml_output)
  914. def sys_info(self):
  915. """Return a list of (key, value) pairs showing internal information."""
  916. import coverage as covmod
  917. self._init()
  918. ft_plugins = []
  919. for ft in self.plugins.file_tracers:
  920. ft_name = ft._coverage_plugin_name
  921. if not ft._coverage_enabled:
  922. ft_name += " (disabled)"
  923. ft_plugins.append(ft_name)
  924. info = [
  925. ('version', covmod.__version__),
  926. ('coverage', covmod.__file__),
  927. ('cover_paths', self.cover_paths),
  928. ('pylib_paths', self.pylib_paths),
  929. ('tracer', self.collector.tracer_name()),
  930. ('plugins.file_tracers', ft_plugins),
  931. ('config_files', self.config.attempted_config_files),
  932. ('configs_read', self.config.config_files),
  933. ('data_path', self.data_files.filename),
  934. ('python', sys.version.replace('\n', '')),
  935. ('platform', platform.platform()),
  936. ('implementation', platform.python_implementation()),
  937. ('executable', sys.executable),
  938. ('cwd', os.getcwd()),
  939. ('path', sys.path),
  940. ('environment', sorted(
  941. ("%s = %s" % (k, v))
  942. for k, v in iitems(os.environ)
  943. if k.startswith(("COV", "PY"))
  944. )),
  945. ('command_line', " ".join(getattr(sys, 'argv', ['???']))),
  946. ]
  947. matcher_names = [
  948. 'source_match', 'source_pkgs_match',
  949. 'include_match', 'omit_match',
  950. 'cover_match', 'pylib_match',
  951. ]
  952. for matcher_name in matcher_names:
  953. matcher = getattr(self, matcher_name)
  954. if matcher:
  955. matcher_info = matcher.info()
  956. else:
  957. matcher_info = '-none-'
  958. info.append((matcher_name, matcher_info))
  959. return info
  960. # FileDisposition "methods": FileDisposition is a pure value object, so it can
  961. # be implemented in either C or Python. Acting on them is done with these
  962. # functions.
  963. def _disposition_init(cls, original_filename):
  964. """Construct and initialize a new FileDisposition object."""
  965. disp = cls()
  966. disp.original_filename = original_filename
  967. disp.canonical_filename = original_filename
  968. disp.source_filename = None
  969. disp.trace = False
  970. disp.reason = ""
  971. disp.file_tracer = None
  972. disp.has_dynamic_filename = False
  973. return disp
  974. def _disposition_debug_msg(disp):
  975. """Make a nice debug message of what the FileDisposition is doing."""
  976. if disp.trace:
  977. msg = "Tracing %r" % (disp.original_filename,)
  978. if disp.file_tracer:
  979. msg += ": will be traced by %r" % disp.file_tracer
  980. else:
  981. msg = "Not tracing %r: %s" % (disp.original_filename, disp.reason)
  982. return msg
  983. def process_startup():
  984. """Call this at Python start-up to perhaps measure coverage.
  985. If the environment variable COVERAGE_PROCESS_START is defined, coverage
  986. measurement is started. The value of the variable is the config file
  987. to use.
  988. There are two ways to configure your Python installation to invoke this
  989. function when Python starts:
  990. #. Create or append to sitecustomize.py to add these lines::
  991. import coverage
  992. coverage.process_startup()
  993. #. Create a .pth file in your Python installation containing::
  994. import coverage; coverage.process_startup()
  995. Returns the :class:`Coverage` instance that was started, or None if it was
  996. not started by this call.
  997. """
  998. cps = os.environ.get("COVERAGE_PROCESS_START")
  999. if not cps:
  1000. # No request for coverage, nothing to do.
  1001. return None
  1002. # This function can be called more than once in a process. This happens
  1003. # because some virtualenv configurations make the same directory visible
  1004. # twice in sys.path. This means that the .pth file will be found twice,
  1005. # and executed twice, executing this function twice. We set a global
  1006. # flag (an attribute on this function) to indicate that coverage.py has
  1007. # already been started, so we can avoid doing it twice.
  1008. #
  1009. # https://bitbucket.org/ned/coveragepy/issue/340/keyerror-subpy has more
  1010. # details.
  1011. if hasattr(process_startup, "coverage"):
  1012. # We've annotated this function before, so we must have already
  1013. # started coverage.py in this process. Nothing to do.
  1014. return None
  1015. cov = Coverage(config_file=cps)
  1016. process_startup.coverage = cov
  1017. cov.start()
  1018. cov._warn_no_data = False
  1019. cov._warn_unimported_source = False
  1020. cov._auto_save = True
  1021. return cov
  1022. def _prevent_sub_process_measurement():
  1023. """Stop any subprocess auto-measurement from writing data."""
  1024. auto_created_coverage = getattr(process_startup, "coverage", None)
  1025. if auto_created_coverage is not None:
  1026. auto_created_coverage._auto_save = False