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

/rsp-dh-invoice/coverage/pytracer.py

https://bitbucket.org/DundiSivaramBhimavarapu/spark-contactcenter
Python | 173 lines | 98 code | 23 blank | 52 comment | 35 complexity | e68757ef097e6a5888c05dc9cc0e2d19 MD5 | raw file
Possible License(s): BSD-3-Clause
  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 atexit
  5. import dis
  6. import sys
  7. from coverage import env
  8. # We need the YIELD_VALUE opcode below, in a comparison-friendly form.
  9. YIELD_VALUE = dis.opmap['YIELD_VALUE']
  10. if env.PY2:
  11. YIELD_VALUE = chr(YIELD_VALUE)
  12. class PyTracer(object):
  13. """Python implementation of the raw data tracer."""
  14. # Because of poor implementations of trace-function-manipulating tools,
  15. # the Python trace function must be kept very simple. In particular, there
  16. # must be only one function ever set as the trace function, both through
  17. # sys.settrace, and as the return value from the trace function. Put
  18. # another way, the trace function must always return itself. It cannot
  19. # swap in other functions, or return None to avoid tracing a particular
  20. # frame.
  21. #
  22. # The trace manipulator that introduced this restriction is DecoratorTools,
  23. # which sets a trace function, and then later restores the pre-existing one
  24. # by calling sys.settrace with a function it found in the current frame.
  25. #
  26. # Systems that use DecoratorTools (or similar trace manipulations) must use
  27. # PyTracer to get accurate results. The command-line --timid argument is
  28. # used to force the use of this tracer.
  29. def __init__(self):
  30. # Attributes set from the collector:
  31. self.data = None
  32. self.trace_arcs = False
  33. self.should_trace = None
  34. self.should_trace_cache = None
  35. self.warn = None
  36. # The threading module to use, if any.
  37. self.threading = None
  38. self.cur_file_dict = []
  39. self.last_line = [0]
  40. self.data_stack = []
  41. self.last_exc_back = None
  42. self.last_exc_firstlineno = 0
  43. self.thread = None
  44. self.stopped = False
  45. self.in_atexit = False
  46. # On exit, self.in_atexit = True
  47. atexit.register(setattr, self, 'in_atexit', True)
  48. def __repr__(self):
  49. return "<PyTracer at {0}: {1} lines in {2} files>".format(
  50. id(self),
  51. sum(len(v) for v in self.data.values()),
  52. len(self.data),
  53. )
  54. def _trace(self, frame, event, arg_unused):
  55. """The trace function passed to sys.settrace."""
  56. if self.stopped:
  57. return
  58. if self.last_exc_back:
  59. if frame == self.last_exc_back:
  60. # Someone forgot a return event.
  61. if self.trace_arcs and self.cur_file_dict:
  62. pair = (self.last_line, -self.last_exc_firstlineno)
  63. self.cur_file_dict[pair] = None
  64. self.cur_file_dict, self.last_line = self.data_stack.pop()
  65. self.last_exc_back = None
  66. if event == 'call':
  67. # Entering a new function context. Decide if we should trace
  68. # in this file.
  69. self.data_stack.append((self.cur_file_dict, self.last_line))
  70. filename = frame.f_code.co_filename
  71. disp = self.should_trace_cache.get(filename)
  72. if disp is None:
  73. disp = self.should_trace(filename, frame)
  74. self.should_trace_cache[filename] = disp
  75. self.cur_file_dict = None
  76. if disp.trace:
  77. tracename = disp.source_filename
  78. if tracename not in self.data:
  79. self.data[tracename] = {}
  80. self.cur_file_dict = self.data[tracename]
  81. # The call event is really a "start frame" event, and happens for
  82. # function calls and re-entering generators. The f_lasti field is
  83. # -1 for calls, and a real offset for generators. Use <0 as the
  84. # line number for calls, and the real line number for generators.
  85. if frame.f_lasti < 0:
  86. self.last_line = -frame.f_code.co_firstlineno
  87. else:
  88. self.last_line = frame.f_lineno
  89. elif event == 'line':
  90. # Record an executed line.
  91. if self.cur_file_dict is not None:
  92. lineno = frame.f_lineno
  93. if self.trace_arcs:
  94. self.cur_file_dict[(self.last_line, lineno)] = None
  95. else:
  96. self.cur_file_dict[lineno] = None
  97. self.last_line = lineno
  98. elif event == 'return':
  99. if self.trace_arcs and self.cur_file_dict:
  100. # Record an arc leaving the function, but beware that a
  101. # "return" event might just mean yielding from a generator.
  102. # Jython seems to have an empty co_code, so just assume return.
  103. code = frame.f_code.co_code
  104. if (not code) or code[frame.f_lasti] != YIELD_VALUE:
  105. first = frame.f_code.co_firstlineno
  106. self.cur_file_dict[(self.last_line, -first)] = None
  107. # Leaving this function, pop the filename stack.
  108. self.cur_file_dict, self.last_line = self.data_stack.pop()
  109. elif event == 'exception':
  110. self.last_exc_back = frame.f_back
  111. self.last_exc_firstlineno = frame.f_code.co_firstlineno
  112. return self._trace
  113. def start(self):
  114. """Start this Tracer.
  115. Return a Python function suitable for use with sys.settrace().
  116. """
  117. self.stopped = False
  118. if self.threading:
  119. if self.thread is None:
  120. self.thread = self.threading.currentThread()
  121. else:
  122. if self.thread.ident != self.threading.currentThread().ident:
  123. # Re-starting from a different thread!? Don't set the trace
  124. # function, but we are marked as running again, so maybe it
  125. # will be ok?
  126. return self._trace
  127. sys.settrace(self._trace)
  128. return self._trace
  129. def stop(self):
  130. """Stop this Tracer."""
  131. self.stopped = True
  132. if self.threading and self.thread.ident != self.threading.currentThread().ident:
  133. # Called on a different thread than started us: we can't unhook
  134. # ourselves, but we've set the flag that we should stop, so we
  135. # won't do any more tracing.
  136. return
  137. if self.warn:
  138. # PyPy clears the trace function before running atexit functions,
  139. # so don't warn if we are in atexit on PyPy and the trace function
  140. # has changed to None.
  141. tf = sys.gettrace()
  142. dont_warn = (env.PYPY and env.PYPYVERSION >= (5, 4) and self.in_atexit and tf is None)
  143. if (not dont_warn) and tf != self._trace:
  144. self.warn("Trace function changed, measurement is likely wrong: %r" % (tf,))
  145. sys.settrace(None)
  146. def get_stats(self):
  147. """Return a dictionary of statistics, or None."""
  148. return None