Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/hypothesis/internal/scrutineer.py: 35%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

152 statements  

1# This file is part of Hypothesis, which may be found at 

2# https://github.com/HypothesisWorks/hypothesis/ 

3# 

4# Copyright the Hypothesis Authors. 

5# Individual contributors are listed in AUTHORS.rst and the git log. 

6# 

7# This Source Code Form is subject to the terms of the Mozilla Public License, 

8# v. 2.0. If a copy of the MPL was not distributed with this file, You can 

9# obtain one at https://mozilla.org/MPL/2.0/. 

10 

11import functools 

12import os 

13import re 

14import subprocess 

15import sys 

16import sysconfig 

17import types 

18from collections import defaultdict 

19from collections.abc import Iterable 

20from enum import IntEnum 

21from functools import lru_cache, reduce 

22from os import sep 

23from pathlib import Path 

24from typing import TYPE_CHECKING, Optional 

25 

26from hypothesis._settings import Phase, Verbosity 

27from hypothesis.internal.compat import PYPY 

28from hypothesis.internal.escalation import is_hypothesis_file 

29 

30if TYPE_CHECKING: 

31 from typing import TypeAlias 

32 

33Location: "TypeAlias" = tuple[str, int] 

34Branch: "TypeAlias" = tuple[Optional[Location], Location] 

35Trace: "TypeAlias" = set[Branch] 

36 

37 

38@functools.cache 

39def should_trace_file(fname: str) -> bool: 

40 # fname.startswith("<") indicates runtime code-generation via compile, 

41 # e.g. compile("def ...", "<string>", "exec") in e.g. attrs methods. 

42 return not (is_hypothesis_file(fname) or fname.startswith("<")) 

43 

44 

45# where possible, we'll use 3.12's new sys.monitoring module for low-overhead 

46# coverage instrumentation; on older python versions we'll use sys.settrace. 

47# tool_id = 1 is designated for coverage, but we intentionally choose a 

48# non-reserved tool id so we can co-exist with coverage tools. 

49MONITORING_TOOL_ID = 3 

50if sys.version_info[:2] >= (3, 12): 

51 MONITORING_EVENTS = {sys.monitoring.events.LINE: "trace_line"} 

52 

53 

54class Tracer: 

55 """A super-simple branch coverage tracer.""" 

56 

57 __slots__ = ("_previous_location", "_should_trace", "branches") 

58 

59 def __init__(self, *, should_trace: bool) -> None: 

60 self.branches: Trace = set() 

61 self._previous_location: Optional[Location] = None 

62 self._should_trace = should_trace and self.can_trace() 

63 

64 @staticmethod 

65 def can_trace() -> bool: 

66 return ( 

67 (sys.version_info[:2] < (3, 12) and sys.gettrace() is None) 

68 or ( 

69 sys.version_info[:2] >= (3, 12) 

70 and sys.monitoring.get_tool(MONITORING_TOOL_ID) is None 

71 ) 

72 ) and not PYPY 

73 

74 def trace(self, frame, event, arg): 

75 try: 

76 if event == "call": 

77 return self.trace 

78 elif event == "line": 

79 fname = frame.f_code.co_filename 

80 if should_trace_file(fname): 

81 current_location = (fname, frame.f_lineno) 

82 self.branches.add((self._previous_location, current_location)) 

83 self._previous_location = current_location 

84 except RecursionError: 

85 pass 

86 

87 def trace_line(self, code: types.CodeType, line_number: int) -> None: 

88 fname = code.co_filename 

89 if not should_trace_file(fname): 

90 # this function is only called on 3.12+, but we want to avoid an 

91 # assertion to that effect for performance. 

92 return sys.monitoring.DISABLE # type: ignore 

93 

94 current_location = (fname, line_number) 

95 self.branches.add((self._previous_location, current_location)) 

96 self._previous_location = current_location 

97 

98 def __enter__(self): 

99 if not self._should_trace: 

100 return self 

101 

102 if sys.version_info[:2] < (3, 12): 

103 sys.settrace(self.trace) 

104 return self 

105 

106 sys.monitoring.use_tool_id(MONITORING_TOOL_ID, "scrutineer") 

107 for event, callback_name in MONITORING_EVENTS.items(): 

108 sys.monitoring.set_events(MONITORING_TOOL_ID, event) 

109 callback = getattr(self, callback_name) 

110 sys.monitoring.register_callback(MONITORING_TOOL_ID, event, callback) 

111 

112 return self 

113 

114 def __exit__(self, *args, **kwargs): 

115 if not self._should_trace: 

116 return 

117 

118 if sys.version_info[:2] < (3, 12): 

119 sys.settrace(None) 

120 return 

121 

122 sys.monitoring.free_tool_id(MONITORING_TOOL_ID) 

123 for event in MONITORING_EVENTS: 

124 sys.monitoring.register_callback(MONITORING_TOOL_ID, event, None) 

125 

126 

127UNHELPFUL_LOCATIONS = ( 

128 # There's a branch which is only taken when an exception is active while exiting 

129 # a contextmanager; this is probably after the fault has been triggered. 

130 # Similar reasoning applies to a few other standard-library modules: even 

131 # if the fault was later, these still aren't useful locations to report! 

132 # Note: The list is post-processed, so use plain "/" for separator here. 

133 "/contextlib.py", 

134 "/inspect.py", 

135 "/re.py", 

136 "/re/__init__.py", # refactored in Python 3.11 

137 "/warnings.py", 

138 # Quite rarely, the first AFNP line is in Pytest's internals. 

139 "/_pytest/**", 

140 "/pluggy/_*.py", 

141 # used by pytest for failure formatting in the terminal 

142 "/pygments/lexer.py", 

143 # used by pytest for failure formatting 

144 "/difflib.py", 

145 "/reprlib.py", 

146 "/typing.py", 

147 "/conftest.py", 

148 "/pprint.py", 

149) 

150 

151 

152def _glob_to_re(locs: Iterable[str]) -> str: 

153 """Translate a list of glob patterns to a combined regular expression. 

154 Only the * and ** wildcards are supported, and patterns including special 

155 characters will only work by chance.""" 

156 # fnmatch.translate is not an option since its "*" consumes path sep 

157 return "|".join( 

158 loc.replace(".", re.escape(".")) 

159 .replace("**", r".+") 

160 .replace("*", r"[^/]+") 

161 .replace("/", re.escape(sep)) 

162 + r"\Z" # right anchored 

163 for loc in locs 

164 ) 

165 

166 

167def get_explaining_locations(traces): 

168 # Traces is a dict[interesting_origin | None, set[frozenset[tuple[str, int]]]] 

169 # Each trace in the set might later become a Counter instead of frozenset. 

170 if not traces: 

171 return {} 

172 

173 unions = {origin: set().union(*values) for origin, values in traces.items()} 

174 seen_passing = {None}.union(*unions.pop(None, set())) 

175 

176 always_failing_never_passing = { 

177 origin: reduce(set.intersection, [set().union(*v) for v in values]) 

178 - seen_passing 

179 for origin, values in traces.items() 

180 if origin is not None 

181 } 

182 

183 # Build the observed parts of the control-flow graph for each origin 

184 cf_graphs = {origin: defaultdict(set) for origin in unions} 

185 for origin, seen_arcs in unions.items(): 

186 for src, dst in seen_arcs: 

187 cf_graphs[origin][src].add(dst) 

188 assert cf_graphs[origin][None], "Expected start node with >=1 successor" 

189 

190 # For each origin, our explanation is the always_failing_never_passing lines 

191 # which are reachable from the start node (None) without passing through another 

192 # AFNP line. So here's a whatever-first search with early stopping: 

193 explanations = defaultdict(set) 

194 for origin in unions: 

195 queue = {None} 

196 seen = set() 

197 while queue: 

198 assert queue.isdisjoint(seen), f"Intersection: {queue & seen}" 

199 src = queue.pop() 

200 seen.add(src) 

201 if src in always_failing_never_passing[origin]: 

202 explanations[origin].add(src) 

203 else: 

204 queue.update(cf_graphs[origin][src] - seen) 

205 

206 # The last step is to filter out explanations that we know would be uninformative. 

207 # When this is the first AFNP location, we conclude that Scrutineer missed the 

208 # real divergence (earlier in the trace) and drop that unhelpful explanation. 

209 filter_regex = re.compile(_glob_to_re(UNHELPFUL_LOCATIONS)) 

210 return { 

211 origin: {loc for loc in afnp_locs if not filter_regex.search(loc[0])} 

212 for origin, afnp_locs in explanations.items() 

213 } 

214 

215 

216# see e.g. https://docs.python.org/3/library/sysconfig.html#posix-user 

217# for examples of these path schemes 

218STDLIB_DIRS = { 

219 Path(sysconfig.get_path("platstdlib")).resolve(), 

220 Path(sysconfig.get_path("stdlib")).resolve(), 

221} 

222SITE_PACKAGES_DIRS = { 

223 Path(sysconfig.get_path("purelib")).resolve(), 

224 Path(sysconfig.get_path("platlib")).resolve(), 

225} 

226 

227EXPLANATION_STUB = ( 

228 "Explanation:", 

229 " These lines were always and only run by failing examples:", 

230) 

231 

232 

233class ModuleLocation(IntEnum): 

234 LOCAL = 0 

235 SITE_PACKAGES = 1 

236 STDLIB = 2 

237 

238 @classmethod 

239 @lru_cache(1024) 

240 def from_path(cls, path: str) -> "ModuleLocation": 

241 path = Path(path).resolve() 

242 # site-packages may be a subdir of stdlib or platlib, so it's important to 

243 # check is_relative_to for this before the stdlib. 

244 if any(path.is_relative_to(p) for p in SITE_PACKAGES_DIRS): 

245 return cls.SITE_PACKAGES 

246 if any(path.is_relative_to(p) for p in STDLIB_DIRS): 

247 return cls.STDLIB 

248 return cls.LOCAL 

249 

250 

251# show local files first, then site-packages, then stdlib 

252def _sort_key(path: str, lineno: int) -> tuple[int, str, int]: 

253 return (ModuleLocation.from_path(path), path, lineno) 

254 

255 

256def make_report(explanations, *, cap_lines_at=5): 

257 report = defaultdict(list) 

258 for origin, locations in explanations.items(): 

259 locations = list(locations) 

260 locations.sort(key=lambda v: _sort_key(v[0], v[1])) 

261 report_lines = [f" {fname}:{lineno}" for fname, lineno in locations] 

262 if len(report_lines) > cap_lines_at + 1: 

263 msg = " (and {} more with settings.verbosity >= verbose)" 

264 report_lines[cap_lines_at:] = [msg.format(len(report_lines[cap_lines_at:]))] 

265 if report_lines: # We might have filtered out every location as uninformative. 

266 report[origin] = list(EXPLANATION_STUB) + report_lines 

267 return report 

268 

269 

270def explanatory_lines(traces, settings): 

271 if Phase.explain in settings.phases and sys.gettrace() and not traces: 

272 return defaultdict(list) 

273 # Return human-readable report lines summarising the traces 

274 explanations = get_explaining_locations(traces) 

275 max_lines = 5 if settings.verbosity <= Verbosity.normal else float("inf") 

276 return make_report(explanations, cap_lines_at=max_lines) 

277 

278 

279# beware the code below; we're using some heuristics to make a nicer report... 

280 

281 

282@functools.lru_cache 

283def _get_git_repo_root() -> Path: 

284 try: 

285 where = subprocess.run( 

286 ["git", "rev-parse", "--show-toplevel"], 

287 check=True, 

288 timeout=10, 

289 capture_output=True, 

290 text=True, 

291 encoding="utf-8", 

292 ).stdout.strip() 

293 except Exception: # pragma: no cover 

294 return Path().absolute().parents[-1] 

295 else: 

296 return Path(where) 

297 

298 

299def tractable_coverage_report(trace: Trace) -> dict[str, list[int]]: 

300 """Report a simple coverage map which is (probably most) of the user's code.""" 

301 coverage: dict = {} 

302 t = dict(trace) 

303 for file, line in set(t.keys()).union(t.values()) - {None}: # type: ignore 

304 # On Python <= 3.11, we can use coverage.py xor Hypothesis' tracer, 

305 # so the trace will be empty and this line never run under coverage. 

306 coverage.setdefault(file, set()).add(line) # pragma: no cover 

307 stdlib_fragment = f"{os.sep}lib{os.sep}python3.{sys.version_info.minor}{os.sep}" 

308 return { 

309 k: sorted(v) 

310 for k, v in coverage.items() 

311 if stdlib_fragment not in k 

312 and (p := Path(k)).is_relative_to(_get_git_repo_root()) 

313 and "site-packages" not in p.parts 

314 }