collector.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. """Raw data collector for coverage.py."""
  4. import os
  5. import sys
  6. from coverage import env
  7. from coverage.backward import iitems
  8. from coverage.files import abs_file
  9. from coverage.misc import CoverageException, isolate_module
  10. from coverage.pytracer import PyTracer
  11. os = isolate_module(os)
  12. try:
  13. # Use the C extension code when we can, for speed.
  14. from coverage.tracer import CTracer, CFileDisposition
  15. except ImportError:
  16. # Couldn't import the C extension, maybe it isn't built.
  17. if os.getenv('COVERAGE_TEST_TRACER') == 'c':
  18. # During testing, we use the COVERAGE_TEST_TRACER environment variable
  19. # to indicate that we've fiddled with the environment to test this
  20. # fallback code. If we thought we had a C tracer, but couldn't import
  21. # it, then exit quickly and clearly instead of dribbling confusing
  22. # errors. I'm using sys.exit here instead of an exception because an
  23. # exception here causes all sorts of other noise in unittest.
  24. sys.stderr.write("*** COVERAGE_TEST_TRACER is 'c' but can't import CTracer!\n")
  25. sys.exit(1)
  26. CTracer = None
  27. class FileDisposition(object):
  28. """A simple value type for recording what to do with a file."""
  29. pass
  30. def should_start_context(frame):
  31. """Who-Tests-What hack: Determine whether this frame begins a new who-context."""
  32. fn_name = frame.f_code.co_name
  33. if fn_name.startswith("test"):
  34. return fn_name
  35. class Collector(object):
  36. """Collects trace data.
  37. Creates a Tracer object for each thread, since they track stack
  38. information. Each Tracer points to the same shared data, contributing
  39. traced data points.
  40. When the Collector is started, it creates a Tracer for the current thread,
  41. and installs a function to create Tracers for each new thread started.
  42. When the Collector is stopped, all active Tracers are stopped.
  43. Threads started while the Collector is stopped will never have Tracers
  44. associated with them.
  45. """
  46. # The stack of active Collectors. Collectors are added here when started,
  47. # and popped when stopped. Collectors on the stack are paused when not
  48. # the top, and resumed when they become the top again.
  49. _collectors = []
  50. # The concurrency settings we support here.
  51. SUPPORTED_CONCURRENCIES = set(["greenlet", "eventlet", "gevent", "thread"])
  52. def __init__(self, should_trace, check_include, timid, branch, warn, concurrency):
  53. """Create a collector.
  54. `should_trace` is a function, taking a file name, and returning a
  55. `coverage.FileDisposition object`.
  56. `check_include` is a function taking a file name and a frame. It returns
  57. a boolean: True if the file should be traced, False if not.
  58. If `timid` is true, then a slower simpler trace function will be
  59. used. This is important for some environments where manipulation of
  60. tracing functions make the faster more sophisticated trace function not
  61. operate properly.
  62. If `branch` is true, then branches will be measured. This involves
  63. collecting data on which statements followed each other (arcs). Use
  64. `get_arc_data` to get the arc data.
  65. `warn` is a warning function, taking a single string message argument,
  66. to be used if a warning needs to be issued.
  67. `concurrency` is a list of strings indicating the concurrency libraries
  68. in use. Valid values are "greenlet", "eventlet", "gevent", or "thread"
  69. (the default). Of these four values, only one can be supplied. Other
  70. values are ignored.
  71. """
  72. self.should_trace = should_trace
  73. self.check_include = check_include
  74. self.warn = warn
  75. self.branch = branch
  76. self.threading = None
  77. self.concur_id_func = None
  78. # We can handle a few concurrency options here, but only one at a time.
  79. these_concurrencies = self.SUPPORTED_CONCURRENCIES.intersection(concurrency)
  80. if len(these_concurrencies) > 1:
  81. raise CoverageException("Conflicting concurrency settings: %s" % concurrency)
  82. self.concurrency = these_concurrencies.pop() if these_concurrencies else ''
  83. try:
  84. if self.concurrency == "greenlet":
  85. import greenlet
  86. self.concur_id_func = greenlet.getcurrent
  87. elif self.concurrency == "eventlet":
  88. import eventlet.greenthread # pylint: disable=import-error,useless-suppression
  89. self.concur_id_func = eventlet.greenthread.getcurrent
  90. elif self.concurrency == "gevent":
  91. import gevent # pylint: disable=import-error,useless-suppression
  92. self.concur_id_func = gevent.getcurrent
  93. elif self.concurrency == "thread" or not self.concurrency:
  94. # It's important to import threading only if we need it. If
  95. # it's imported early, and the program being measured uses
  96. # gevent, then gevent's monkey-patching won't work properly.
  97. import threading
  98. self.threading = threading
  99. else:
  100. raise CoverageException("Don't understand concurrency=%s" % concurrency)
  101. except ImportError:
  102. raise CoverageException(
  103. "Couldn't trace with concurrency=%s, the module isn't installed." % (
  104. self.concurrency,
  105. )
  106. )
  107. # Who-Tests-What is just a hack at the moment, so turn it on with an
  108. # environment variable.
  109. self.wtw = int(os.getenv('COVERAGE_WTW', 0))
  110. self.reset()
  111. if timid:
  112. # Being timid: use the simple Python trace function.
  113. self._trace_class = PyTracer
  114. else:
  115. # Being fast: use the C Tracer if it is available, else the Python
  116. # trace function.
  117. self._trace_class = CTracer or PyTracer
  118. if self._trace_class is CTracer:
  119. self.file_disposition_class = CFileDisposition
  120. self.supports_plugins = True
  121. else:
  122. self.file_disposition_class = FileDisposition
  123. self.supports_plugins = False
  124. def __repr__(self):
  125. return "<Collector at 0x%x: %s>" % (id(self), self.tracer_name())
  126. def tracer_name(self):
  127. """Return the class name of the tracer we're using."""
  128. return self._trace_class.__name__
  129. def reset(self):
  130. """Clear collected data, and prepare to collect more."""
  131. # A dictionary mapping file names to dicts with line number keys (if not
  132. # branch coverage), or mapping file names to dicts with line number
  133. # pairs as keys (if branch coverage).
  134. self.data = {}
  135. # A dict mapping contexts to data dictionaries.
  136. self.contexts = {}
  137. self.contexts[None] = self.data
  138. # A dictionary mapping file names to file tracer plugin names that will
  139. # handle them.
  140. self.file_tracers = {}
  141. # The .should_trace_cache attribute is a cache from file names to
  142. # coverage.FileDisposition objects, or None. When a file is first
  143. # considered for tracing, a FileDisposition is obtained from
  144. # Coverage.should_trace. Its .trace attribute indicates whether the
  145. # file should be traced or not. If it should be, a plugin with dynamic
  146. # file names can decide not to trace it based on the dynamic file name
  147. # being excluded by the inclusion rules, in which case the
  148. # FileDisposition will be replaced by None in the cache.
  149. if env.PYPY:
  150. import __pypy__ # pylint: disable=import-error
  151. # Alex Gaynor said:
  152. # should_trace_cache is a strictly growing key: once a key is in
  153. # it, it never changes. Further, the keys used to access it are
  154. # generally constant, given sufficient context. That is to say, at
  155. # any given point _trace() is called, pypy is able to know the key.
  156. # This is because the key is determined by the physical source code
  157. # line, and that's invariant with the call site.
  158. #
  159. # This property of a dict with immutable keys, combined with
  160. # call-site-constant keys is a match for PyPy's module dict,
  161. # which is optimized for such workloads.
  162. #
  163. # This gives a 20% benefit on the workload described at
  164. # https://bitbucket.org/pypy/pypy/issue/1871/10x-slower-than-cpython-under-coverage
  165. self.should_trace_cache = __pypy__.newdict("module")
  166. else:
  167. self.should_trace_cache = {}
  168. # Our active Tracers.
  169. self.tracers = []
  170. def _start_tracer(self):
  171. """Start a new Tracer object, and store it in self.tracers."""
  172. tracer = self._trace_class()
  173. tracer.data = self.data
  174. tracer.trace_arcs = self.branch
  175. tracer.should_trace = self.should_trace
  176. tracer.should_trace_cache = self.should_trace_cache
  177. tracer.warn = self.warn
  178. if hasattr(tracer, 'concur_id_func'):
  179. tracer.concur_id_func = self.concur_id_func
  180. elif self.concur_id_func:
  181. raise CoverageException(
  182. "Can't support concurrency=%s with %s, only threads are supported" % (
  183. self.concurrency, self.tracer_name(),
  184. )
  185. )
  186. if hasattr(tracer, 'file_tracers'):
  187. tracer.file_tracers = self.file_tracers
  188. if hasattr(tracer, 'threading'):
  189. tracer.threading = self.threading
  190. if hasattr(tracer, 'check_include'):
  191. tracer.check_include = self.check_include
  192. if self.wtw:
  193. if hasattr(tracer, 'should_start_context'):
  194. tracer.should_start_context = should_start_context
  195. if hasattr(tracer, 'switch_context'):
  196. tracer.switch_context = self.switch_context
  197. fn = tracer.start()
  198. self.tracers.append(tracer)
  199. return fn
  200. # The trace function has to be set individually on each thread before
  201. # execution begins. Ironically, the only support the threading module has
  202. # for running code before the thread main is the tracing function. So we
  203. # install this as a trace function, and the first time it's called, it does
  204. # the real trace installation.
  205. def _installation_trace(self, frame, event, arg):
  206. """Called on new threads, installs the real tracer."""
  207. # Remove ourselves as the trace function.
  208. sys.settrace(None)
  209. # Install the real tracer.
  210. fn = self._start_tracer()
  211. # Invoke the real trace function with the current event, to be sure
  212. # not to lose an event.
  213. if fn:
  214. fn = fn(frame, event, arg)
  215. # Return the new trace function to continue tracing in this scope.
  216. return fn
  217. def start(self):
  218. """Start collecting trace information."""
  219. if self._collectors:
  220. self._collectors[-1].pause()
  221. # Check to see whether we had a fullcoverage tracer installed. If so,
  222. # get the stack frames it stashed away for us.
  223. traces0 = []
  224. fn0 = sys.gettrace()
  225. if fn0:
  226. tracer0 = getattr(fn0, '__self__', None)
  227. if tracer0:
  228. traces0 = getattr(tracer0, 'traces', [])
  229. try:
  230. # Install the tracer on this thread.
  231. fn = self._start_tracer()
  232. except:
  233. if self._collectors:
  234. self._collectors[-1].resume()
  235. raise
  236. # If _start_tracer succeeded, then we add ourselves to the global
  237. # stack of collectors.
  238. self._collectors.append(self)
  239. # Replay all the events from fullcoverage into the new trace function.
  240. for args in traces0:
  241. (frame, event, arg), lineno = args
  242. try:
  243. fn(frame, event, arg, lineno=lineno)
  244. except TypeError:
  245. raise Exception("fullcoverage must be run with the C trace function.")
  246. # Install our installation tracer in threading, to jump start other
  247. # threads.
  248. if self.threading:
  249. self.threading.settrace(self._installation_trace)
  250. def stop(self):
  251. """Stop collecting trace information."""
  252. assert self._collectors
  253. assert self._collectors[-1] is self, (
  254. "Expected current collector to be %r, but it's %r" % (self, self._collectors[-1])
  255. )
  256. self.pause()
  257. self.tracers = []
  258. # Remove this Collector from the stack, and resume the one underneath
  259. # (if any).
  260. self._collectors.pop()
  261. if self._collectors:
  262. self._collectors[-1].resume()
  263. def pause(self):
  264. """Pause tracing, but be prepared to `resume`."""
  265. for tracer in self.tracers:
  266. tracer.stop()
  267. stats = tracer.get_stats()
  268. if stats:
  269. print("\nCoverage.py tracer stats:")
  270. for k in sorted(stats.keys()):
  271. print("%20s: %s" % (k, stats[k]))
  272. if self.threading:
  273. self.threading.settrace(None)
  274. def resume(self):
  275. """Resume tracing after a `pause`."""
  276. for tracer in self.tracers:
  277. tracer.start()
  278. if self.threading:
  279. self.threading.settrace(self._installation_trace)
  280. else:
  281. self._start_tracer()
  282. def switch_context(self, new_context):
  283. """Who-Tests-What hack: switch to a new who-context."""
  284. # Make a new data dict, or find the existing one, and switch all the
  285. # tracers to use it.
  286. data = self.contexts.setdefault(new_context, {})
  287. for tracer in self.tracers:
  288. tracer.data = data
  289. def save_data(self, covdata):
  290. """Save the collected data to a `CoverageData`.
  291. Also resets the collector.
  292. """
  293. def abs_file_dict(d):
  294. """Return a dict like d, but with keys modified by `abs_file`."""
  295. return dict((abs_file(k), v) for k, v in iitems(d))
  296. if self.branch:
  297. covdata.add_arcs(abs_file_dict(self.data))
  298. else:
  299. covdata.add_lines(abs_file_dict(self.data))
  300. covdata.add_file_tracers(abs_file_dict(self.file_tracers))
  301. if self.wtw:
  302. # Just a hack, so just hack it.
  303. import pprint
  304. out_file = "coverage_wtw_{:06}.py".format(os.getpid())
  305. with open(out_file, "w") as wtw_out:
  306. pprint.pprint(self.contexts, wtw_out)
  307. self.reset()