control.py 45 KB

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