Coverage.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. """
  2. A Cython plugin for coverage.py
  3. Requires the coverage package at least in version 4.0 (which added the plugin API).
  4. """
  5. from __future__ import absolute_import
  6. import re
  7. import os.path
  8. import sys
  9. from collections import defaultdict
  10. from coverage.plugin import CoveragePlugin, FileTracer, FileReporter # requires coverage.py 4.0+
  11. from coverage.files import canonical_filename
  12. from .Utils import find_root_package_dir, is_package_dir, open_source_file
  13. from . import __version__
  14. C_FILE_EXTENSIONS = ['.c', '.cpp', '.cc', '.cxx']
  15. MODULE_FILE_EXTENSIONS = set(['.py', '.pyx', '.pxd'] + C_FILE_EXTENSIONS)
  16. def _find_c_source(base_path):
  17. file_exists = os.path.exists
  18. for ext in C_FILE_EXTENSIONS:
  19. file_name = base_path + ext
  20. if file_exists(file_name):
  21. return file_name
  22. return None
  23. def _find_dep_file_path(main_file, file_path, relative_path_search=False):
  24. abs_path = os.path.abspath(file_path)
  25. if not os.path.exists(abs_path) and (file_path.endswith('.pxi') or
  26. relative_path_search):
  27. # files are looked up relative to the main source file
  28. rel_file_path = os.path.join(os.path.dirname(main_file), file_path)
  29. if os.path.exists(rel_file_path):
  30. abs_path = os.path.abspath(rel_file_path)
  31. # search sys.path for external locations if a valid file hasn't been found
  32. if not os.path.exists(abs_path):
  33. for sys_path in sys.path:
  34. test_path = os.path.realpath(os.path.join(sys_path, file_path))
  35. if os.path.exists(test_path):
  36. return canonical_filename(test_path)
  37. return canonical_filename(abs_path)
  38. class Plugin(CoveragePlugin):
  39. # map from traced file paths to absolute file paths
  40. _file_path_map = None
  41. # map from traced file paths to corresponding C files
  42. _c_files_map = None
  43. # map from parsed C files to their content
  44. _parsed_c_files = None
  45. def sys_info(self):
  46. return [('Cython version', __version__)]
  47. def file_tracer(self, filename):
  48. """
  49. Try to find a C source file for a file path found by the tracer.
  50. """
  51. # TODO We need to pxd-files to the include map. For more info see pybuild.py
  52. # Currently skip such files, because they are not supported in Arcadia pybuild with coverage.
  53. if os.path.splitext(filename)[-1] not in ('.pyx', '.pxi'):
  54. return None
  55. if filename.startswith('<') or filename.startswith('memory:'):
  56. return None
  57. c_file = py_file = None
  58. filename = canonical_filename(filename)
  59. if self._c_files_map and filename in self._c_files_map:
  60. c_file = self._c_files_map[filename][0]
  61. if c_file is None:
  62. c_file, py_file = self._find_source_files(filename)
  63. if not c_file:
  64. return None # unknown file
  65. # parse all source file paths and lines from C file
  66. # to learn about all relevant source files right away (pyx/pxi/pxd)
  67. # FIXME: this might already be too late if the first executed line
  68. # is not from the main .pyx file but a file with a different
  69. # name than the .c file (which prevents us from finding the
  70. # .c file)
  71. _, code = self._read_source_lines(c_file, filename)
  72. if code is None:
  73. return None # no source found
  74. if self._file_path_map is None:
  75. self._file_path_map = {}
  76. return CythonModuleTracer(filename, py_file, c_file, self._c_files_map, self._file_path_map)
  77. def file_reporter(self, filename):
  78. # TODO: let coverage.py handle .py files itself
  79. #ext = os.path.splitext(filename)[1].lower()
  80. #if ext == '.py':
  81. # from coverage.python import PythonFileReporter
  82. # return PythonFileReporter(filename)
  83. filename = canonical_filename(filename)
  84. if self._c_files_map and filename in self._c_files_map:
  85. c_file, rel_file_path, code = self._c_files_map[filename]
  86. else:
  87. c_file, _ = self._find_source_files(filename)
  88. if not c_file:
  89. if standalone():
  90. raise AssertionError(filename)
  91. return None # unknown file
  92. rel_file_path, code = self._read_source_lines(c_file, filename)
  93. if code is None:
  94. if standalone():
  95. raise AssertionError(filename)
  96. return None # no source found
  97. return CythonModuleReporter(c_file, filename, rel_file_path, code)
  98. def _find_source_files(self, filename):
  99. basename, ext = os.path.splitext(filename)
  100. ext = ext.lower()
  101. if ext in MODULE_FILE_EXTENSIONS:
  102. pass
  103. elif ext == '.pyd':
  104. # Windows extension module
  105. platform_suffix = re.search(r'[.]cp[0-9]+-win[_a-z0-9]*$', basename, re.I)
  106. if platform_suffix:
  107. basename = basename[:platform_suffix.start()]
  108. elif ext == '.so':
  109. # Linux/Unix/Mac extension module
  110. platform_suffix = re.search(r'[.](?:cpython|pypy)-[0-9]+[-_a-z0-9]*$', basename, re.I)
  111. if platform_suffix:
  112. basename = basename[:platform_suffix.start()]
  113. elif ext == '.pxi':
  114. # if we get here, it means that the first traced line of a Cython module was
  115. # not in the main module but in an include file, so try a little harder to
  116. # find the main source file
  117. self._find_c_source_files(os.path.dirname(filename), filename)
  118. if filename in self._c_files_map:
  119. return self._c_files_map[filename][0], None
  120. if standalone():
  121. raise AssertionError(filename)
  122. else:
  123. # none of our business
  124. return None, None
  125. c_file = filename if ext in C_FILE_EXTENSIONS else _find_c_source(basename)
  126. if c_file is None:
  127. # a module "pkg/mod.so" can have a source file "pkg/pkg.mod.c"
  128. package_root = find_root_package_dir.uncached(filename)
  129. package_path = os.path.relpath(basename, package_root).split(os.path.sep)
  130. if len(package_path) > 1:
  131. test_basepath = os.path.join(os.path.dirname(filename), '.'.join(package_path))
  132. c_file = _find_c_source(test_basepath)
  133. py_source_file = None
  134. if c_file:
  135. py_source_file = os.path.splitext(c_file)[0] + '.py'
  136. if not os.path.exists(py_source_file):
  137. py_source_file = None
  138. try:
  139. with OpenFile(c_file) as f:
  140. if '/* Generated by Cython ' not in f.read(30):
  141. return None, None # not a Cython file
  142. except (IOError, OSError):
  143. c_file = None
  144. return c_file, py_source_file
  145. def _find_c_source_files(self, dir_path, source_file):
  146. """
  147. Desperately parse all C files in the directory or its package parents
  148. (not re-descending) to find the (included) source file in one of them.
  149. """
  150. if standalone():
  151. if os.environ.get('PYTHON_COVERAGE_CYTHON_BUILD_ROOT'):
  152. broot = os.environ['PYTHON_COVERAGE_CYTHON_BUILD_ROOT']
  153. iter_files = lambda: (os.path.join(root, filename) for root, _, files in os.walk(broot) for filename in files)
  154. else:
  155. import library.python.resource
  156. iter_files = library.python.resource.resfs_files
  157. for c_file in iter_files():
  158. if os.path.splitext(c_file)[1] in C_FILE_EXTENSIONS:
  159. self._read_source_lines(c_file, source_file)
  160. if source_file in self._c_files_map:
  161. return
  162. raise AssertionError((source_file, os.environ.get('PYTHON_COVERAGE_CYTHON_BUILD_ROOT')))
  163. if not os.path.isdir(dir_path):
  164. return
  165. splitext = os.path.splitext
  166. for filename in os.listdir(dir_path):
  167. ext = splitext(filename)[1].lower()
  168. if ext in C_FILE_EXTENSIONS:
  169. self._read_source_lines(os.path.join(dir_path, filename), source_file)
  170. if source_file in self._c_files_map:
  171. return
  172. # not found? then try one package up
  173. if is_package_dir(dir_path):
  174. self._find_c_source_files(os.path.dirname(dir_path), source_file)
  175. def _read_source_lines(self, c_file, sourcefile):
  176. """
  177. Parse a Cython generated C/C++ source file and find the executable lines.
  178. Each executable line starts with a comment header that states source file
  179. and line number, as well as the surrounding range of source code lines.
  180. """
  181. if self._parsed_c_files is None:
  182. self._parsed_c_files = {}
  183. if c_file in self._parsed_c_files:
  184. code_lines = self._parsed_c_files[c_file]
  185. else:
  186. code_lines = self._parse_cfile_lines(c_file)
  187. self._parsed_c_files[c_file] = code_lines
  188. if self._c_files_map is None:
  189. self._c_files_map = {}
  190. for filename, code in code_lines.items():
  191. abs_path = _find_dep_file_path(c_file, filename,
  192. relative_path_search=True)
  193. self._c_files_map[abs_path] = (c_file, filename, code)
  194. if sourcefile not in self._c_files_map:
  195. return (None,) * 2 # e.g. shared library file
  196. return self._c_files_map[sourcefile][1:]
  197. def _parse_cfile_lines(self, c_file):
  198. """
  199. Parse a C file and extract all source file lines that generated executable code.
  200. """
  201. match_source_path_line = re.compile(r' */[*] +"(.*)":([0-9]+)$').match
  202. match_current_code_line = re.compile(r' *[*] (.*) # <<<<<<+$').match
  203. match_comment_end = re.compile(r' *[*]/$').match
  204. match_trace_line = re.compile(r' *__Pyx_TraceLine\(([0-9]+),').match
  205. not_executable = re.compile(
  206. r'\s*c(?:type)?def\s+'
  207. r'(?:(?:public|external)\s+)?'
  208. r'(?:struct|union|enum|class)'
  209. r'(\s+[^:]+|)\s*:'
  210. ).match
  211. code_lines = defaultdict(dict)
  212. executable_lines = defaultdict(set)
  213. current_filename = None
  214. with OpenFile(c_file) as lines:
  215. lines = iter(lines)
  216. for line in lines:
  217. match = match_source_path_line(line)
  218. if not match:
  219. if '__Pyx_TraceLine(' in line and current_filename is not None:
  220. trace_line = match_trace_line(line)
  221. if trace_line:
  222. executable_lines[current_filename].add(int(trace_line.group(1)))
  223. continue
  224. filename, lineno = match.groups()
  225. current_filename = filename
  226. lineno = int(lineno)
  227. for comment_line in lines:
  228. match = match_current_code_line(comment_line)
  229. if match:
  230. code_line = match.group(1).rstrip()
  231. if not_executable(code_line):
  232. break
  233. code_lines[filename][lineno] = code_line
  234. break
  235. elif match_comment_end(comment_line):
  236. # unexpected comment format - false positive?
  237. break
  238. # Remove lines that generated code but are not traceable.
  239. for filename, lines in code_lines.items():
  240. dead_lines = set(lines).difference(executable_lines.get(filename, ()))
  241. for lineno in dead_lines:
  242. del lines[lineno]
  243. return code_lines
  244. class CythonModuleTracer(FileTracer):
  245. """
  246. Find the Python/Cython source file for a Cython module.
  247. """
  248. def __init__(self, module_file, py_file, c_file, c_files_map, file_path_map):
  249. super(CythonModuleTracer, self).__init__()
  250. self.module_file = module_file
  251. self.py_file = py_file
  252. self.c_file = c_file
  253. self._c_files_map = c_files_map
  254. self._file_path_map = file_path_map
  255. def has_dynamic_source_filename(self):
  256. return True
  257. def dynamic_source_filename(self, filename, frame):
  258. """
  259. Determine source file path. Called by the function call tracer.
  260. """
  261. source_file = frame.f_code.co_filename
  262. try:
  263. return self._file_path_map[source_file]
  264. except KeyError:
  265. pass
  266. if standalone():
  267. abs_path = self.module_file
  268. else:
  269. abs_path = _find_dep_file_path(filename, source_file)
  270. if self.py_file and source_file[-3:].lower() == '.py':
  271. # always let coverage.py handle this case itself
  272. self._file_path_map[source_file] = self.py_file
  273. return self.py_file
  274. assert self._c_files_map is not None
  275. if abs_path not in self._c_files_map:
  276. self._c_files_map[abs_path] = (self.c_file, source_file, None)
  277. self._file_path_map[source_file] = abs_path
  278. return abs_path
  279. class CythonModuleReporter(FileReporter):
  280. """
  281. Provide detailed trace information for one source file to coverage.py.
  282. """
  283. def __init__(self, c_file, source_file, rel_file_path, code):
  284. super(CythonModuleReporter, self).__init__(source_file)
  285. self.name = rel_file_path
  286. self.c_file = c_file
  287. self._code = code
  288. self._abs_filename = self._find_abs_filename()
  289. def lines(self):
  290. """
  291. Return set of line numbers that are possibly executable.
  292. """
  293. return set(self._code)
  294. def _iter_source_tokens(self):
  295. current_line = 1
  296. for line_no, code_line in sorted(self._code.items()):
  297. while line_no > current_line:
  298. yield []
  299. current_line += 1
  300. yield [('txt', code_line)]
  301. current_line += 1
  302. def source(self):
  303. """
  304. Return the source code of the file as a string.
  305. """
  306. if os.path.exists(self._abs_filename):
  307. with open_source_file(self._abs_filename) as f:
  308. return f.read()
  309. else:
  310. return '\n'.join(
  311. (tokens[0][1] if tokens else '')
  312. for tokens in self._iter_source_tokens())
  313. def source_token_lines(self):
  314. """
  315. Iterate over the source code tokens.
  316. """
  317. if os.path.exists(self._abs_filename):
  318. with open_source_file(self._abs_filename) as f:
  319. for line in f:
  320. yield [('txt', line.rstrip('\n'))]
  321. else:
  322. for line in self._iter_source_tokens():
  323. yield line
  324. def _find_abs_filename(self):
  325. for root in [
  326. os.environ.get('PYTHON_COVERAGE_ARCADIA_SOURCE_ROOT'),
  327. os.environ.get('PYTHON_COVERAGE_CYTHON_BUILD_ROOT'),
  328. ]:
  329. if root:
  330. abs_path = os.path.join(root, self.filename)
  331. if root and os.path.exists(abs_path):
  332. return abs_path
  333. return self.filename
  334. def coverage_init(reg, options):
  335. reg.add_file_tracer(Plugin())
  336. # ========================== Arcadia specific =================================
  337. def standalone():
  338. return getattr(sys, 'is_standalone_binary', False)
  339. class OpenFile(object):
  340. def __init__(self, filename, mode='r'):
  341. assert 'r' in mode, ('Read-only', mode)
  342. self.filename = filename
  343. self.mode = mode
  344. self.file = None
  345. self.build_root = os.environ.get('PYTHON_COVERAGE_CYTHON_BUILD_ROOT')
  346. def __enter__(self):
  347. # See redefined _find_c_source() description for more info
  348. if self.build_root:
  349. self.file = open(os.path.join(self.build_root, self.filename), self.mode)
  350. return self.file
  351. elif standalone():
  352. import library.python.resource
  353. from six import StringIO
  354. content = library.python.resource.resfs_read(self.filename, builtin=True)
  355. assert content, (self.filename, os.environ.items())
  356. return StringIO(content.decode())
  357. else:
  358. self.file = open(self.filename, self.mode)
  359. return self.file
  360. def __exit__(self, exc_type, exc_val, exc_tb):
  361. if self.file:
  362. self.file.close()
  363. # ======================= Redefine some methods ===============================
  364. if standalone():
  365. import itertools
  366. import json
  367. CYTHON_INCLUDE_MAP = {'undef': True}
  368. def _find_c_source(base_path):
  369. '''
  370. There are two different coverage stages when c source file might be required:
  371. * trace - python calls c_tracefunc on every line and CythonModuleTracer needs to match
  372. pyd and pxi files with source files. This is test's runtime and tests' clean environment might
  373. doesn't contain required sources and generated files (c, cpp), that's why we get files from resfs_src.
  374. * report - coverage data contains only covered data and CythonModuleReporter needs to
  375. parse source files to obtain missing lines and branches. This is test_tool's resolve/build_report step.
  376. test_tools doesn't have compiled in sources, however, it can extract required files
  377. from binary and set PYTHON_COVERAGE_CYTHON_BUILD_ROOT to guide coverage.
  378. '''
  379. if os.environ.get('PYTHON_COVERAGE_CYTHON_BUILD_ROOT'):
  380. # Report stage (resolve)
  381. def exists(filename):
  382. return os.path.exists(os.path.join(os.environ['PYTHON_COVERAGE_CYTHON_BUILD_ROOT'], filename))
  383. else:
  384. # Trace stage (test's runtime)
  385. def exists(filename):
  386. import library.python.resource
  387. return library.python.resource.resfs_src(filename, resfs_file=True)
  388. if os.environ.get('PYTHON_COVERAGE_CYTHON_INCLUDE_MAP'):
  389. if CYTHON_INCLUDE_MAP.get('undef'):
  390. with open(os.environ['PYTHON_COVERAGE_CYTHON_INCLUDE_MAP']) as afile:
  391. data = json.load(afile)
  392. data = {os.path.splitext(k)[0]: v for k, v in data.items()}
  393. CYTHON_INCLUDE_MAP.clear()
  394. CYTHON_INCLUDE_MAP.update(data)
  395. if base_path in CYTHON_INCLUDE_MAP:
  396. # target file was included and should be sought inside another pyx file
  397. base_path = CYTHON_INCLUDE_MAP[base_path]
  398. # TODO (', '.py3', '.py2') -> ('.py3', '.py2'), when https://a.yandex-team.ru/review/3511262 is merged
  399. suffixes = [''.join(x) for x in itertools.product(('.pyx',), ('', '.py3', '.py2'), ('.cpp', '.c'))]
  400. suffixes += C_FILE_EXTENSIONS
  401. for suffix in suffixes:
  402. if exists(base_path + suffix):
  403. return base_path + suffix
  404. return None
  405. def _find_dep_file_path(main_file, file_path, relative_path_search=False):
  406. # file_path is already arcadia root relative
  407. return canonical_filename(file_path)