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 hasattr(sys, "monitoring"):
51 MONITORING_EVENTS = {sys.monitoring.events.LINE: "trace_line"}
52
53
54class Tracer:
55 """A super-simple branch coverage tracer."""
56
57 __slots__ = (
58 "_previous_location",
59 "_should_trace",
60 "_tried_and_failed_to_trace",
61 "branches",
62 )
63
64 def __init__(self, *, should_trace: bool) -> None:
65 self.branches: Trace = set()
66 self._previous_location: Optional[Location] = None
67 self._tried_and_failed_to_trace = False
68 self._should_trace = should_trace and self.can_trace()
69
70 @staticmethod
71 def can_trace() -> bool:
72 if PYPY:
73 return False
74 if hasattr(sys, "monitoring"):
75 return sys.monitoring.get_tool(MONITORING_TOOL_ID) is None
76 return sys.gettrace() is None
77
78 def trace(self, frame, event, arg):
79 try:
80 if event == "call":
81 return self.trace
82 elif event == "line":
83 fname = frame.f_code.co_filename
84 if should_trace_file(fname):
85 current_location = (fname, frame.f_lineno)
86 self.branches.add((self._previous_location, current_location))
87 self._previous_location = current_location
88 except RecursionError:
89 pass
90
91 def trace_line(self, code: types.CodeType, line_number: int) -> None:
92 fname = code.co_filename
93 if not should_trace_file(fname):
94 # this function is only called on 3.12+, but we want to avoid an
95 # assertion to that effect for performance.
96 return sys.monitoring.DISABLE # type: ignore
97
98 current_location = (fname, line_number)
99 self.branches.add((self._previous_location, current_location))
100 self._previous_location = current_location
101
102 def __enter__(self):
103 self._tried_and_failed_to_trace = False
104
105 if not self._should_trace:
106 return self
107
108 if not hasattr(sys, "monitoring"):
109 sys.settrace(self.trace)
110 return self
111
112 try:
113 sys.monitoring.use_tool_id(MONITORING_TOOL_ID, "scrutineer")
114 except ValueError:
115 # another thread may have registered a tool for MONITORING_TOOL_ID
116 # since we checked in can_trace.
117 self._tried_and_failed_to_trace = True
118 return self
119
120 for event, callback_name in MONITORING_EVENTS.items():
121 sys.monitoring.set_events(MONITORING_TOOL_ID, event)
122 callback = getattr(self, callback_name)
123 sys.monitoring.register_callback(MONITORING_TOOL_ID, event, callback)
124
125 return self
126
127 def __exit__(self, *args, **kwargs):
128 if not self._should_trace:
129 return
130
131 if not hasattr(sys, "monitoring"):
132 sys.settrace(None)
133 return
134
135 if self._tried_and_failed_to_trace:
136 return
137
138 sys.monitoring.free_tool_id(MONITORING_TOOL_ID)
139 for event in MONITORING_EVENTS:
140 sys.monitoring.register_callback(MONITORING_TOOL_ID, event, None)
141
142
143UNHELPFUL_LOCATIONS = (
144 # There's a branch which is only taken when an exception is active while exiting
145 # a contextmanager; this is probably after the fault has been triggered.
146 # Similar reasoning applies to a few other standard-library modules: even
147 # if the fault was later, these still aren't useful locations to report!
148 # Note: The list is post-processed, so use plain "/" for separator here.
149 "/contextlib.py",
150 "/inspect.py",
151 "/re.py",
152 "/re/__init__.py", # refactored in Python 3.11
153 "/warnings.py",
154 # Quite rarely, the first AFNP line is in Pytest's internals.
155 "/_pytest/**",
156 "/pluggy/_*.py",
157 # used by pytest for failure formatting in the terminal
158 "/pygments/lexer.py",
159 # used by pytest for failure formatting
160 "/difflib.py",
161 "/reprlib.py",
162 "/typing.py",
163 "/conftest.py",
164 "/pprint.py",
165)
166
167
168def _glob_to_re(locs: Iterable[str]) -> str:
169 """Translate a list of glob patterns to a combined regular expression.
170 Only the * and ** wildcards are supported, and patterns including special
171 characters will only work by chance."""
172 # fnmatch.translate is not an option since its "*" consumes path sep
173 return "|".join(
174 loc.replace(".", re.escape("."))
175 .replace("**", r".+")
176 .replace("*", r"[^/]+")
177 .replace("/", re.escape(sep))
178 + r"\Z" # right anchored
179 for loc in locs
180 )
181
182
183def get_explaining_locations(traces):
184 # Traces is a dict[interesting_origin | None, set[frozenset[tuple[str, int]]]]
185 # Each trace in the set might later become a Counter instead of frozenset.
186 if not traces:
187 return {}
188
189 unions = {origin: set().union(*values) for origin, values in traces.items()}
190 seen_passing = {None}.union(*unions.pop(None, set()))
191
192 always_failing_never_passing = {
193 origin: reduce(set.intersection, [set().union(*v) for v in values])
194 - seen_passing
195 for origin, values in traces.items()
196 if origin is not None
197 }
198
199 # Build the observed parts of the control-flow graph for each origin
200 cf_graphs = {origin: defaultdict(set) for origin in unions}
201 for origin, seen_arcs in unions.items():
202 for src, dst in seen_arcs:
203 cf_graphs[origin][src].add(dst)
204 assert cf_graphs[origin][None], "Expected start node with >=1 successor"
205
206 # For each origin, our explanation is the always_failing_never_passing lines
207 # which are reachable from the start node (None) without passing through another
208 # AFNP line. So here's a whatever-first search with early stopping:
209 explanations = defaultdict(set)
210 for origin in unions:
211 queue = {None}
212 seen = set()
213 while queue:
214 assert queue.isdisjoint(seen), f"Intersection: {queue & seen}"
215 src = queue.pop()
216 seen.add(src)
217 if src in always_failing_never_passing[origin]:
218 explanations[origin].add(src)
219 else:
220 queue.update(cf_graphs[origin][src] - seen)
221
222 # The last step is to filter out explanations that we know would be uninformative.
223 # When this is the first AFNP location, we conclude that Scrutineer missed the
224 # real divergence (earlier in the trace) and drop that unhelpful explanation.
225 filter_regex = re.compile(_glob_to_re(UNHELPFUL_LOCATIONS))
226 return {
227 origin: {loc for loc in afnp_locs if not filter_regex.search(loc[0])}
228 for origin, afnp_locs in explanations.items()
229 }
230
231
232# see e.g. https://docs.python.org/3/library/sysconfig.html#posix-user
233# for examples of these path schemes
234STDLIB_DIRS = {
235 Path(sysconfig.get_path("platstdlib")).resolve(),
236 Path(sysconfig.get_path("stdlib")).resolve(),
237}
238SITE_PACKAGES_DIRS = {
239 Path(sysconfig.get_path("purelib")).resolve(),
240 Path(sysconfig.get_path("platlib")).resolve(),
241}
242
243EXPLANATION_STUB = (
244 "Explanation:",
245 " These lines were always and only run by failing examples:",
246)
247
248
249class ModuleLocation(IntEnum):
250 LOCAL = 0
251 SITE_PACKAGES = 1
252 STDLIB = 2
253
254 @classmethod
255 @lru_cache(1024)
256 def from_path(cls, path: str) -> "ModuleLocation":
257 path = Path(path).resolve()
258 # site-packages may be a subdir of stdlib or platlib, so it's important to
259 # check is_relative_to for this before the stdlib.
260 if any(path.is_relative_to(p) for p in SITE_PACKAGES_DIRS):
261 return cls.SITE_PACKAGES
262 if any(path.is_relative_to(p) for p in STDLIB_DIRS):
263 return cls.STDLIB
264 return cls.LOCAL
265
266
267# show local files first, then site-packages, then stdlib
268def _sort_key(path: str, lineno: int) -> tuple[int, str, int]:
269 return (ModuleLocation.from_path(path), path, lineno)
270
271
272def make_report(explanations, *, cap_lines_at=5):
273 report = defaultdict(list)
274 for origin, locations in explanations.items():
275 locations = list(locations)
276 locations.sort(key=lambda v: _sort_key(v[0], v[1]))
277 report_lines = [f" {fname}:{lineno}" for fname, lineno in locations]
278 if len(report_lines) > cap_lines_at + 1:
279 msg = " (and {} more with settings.verbosity >= verbose)"
280 report_lines[cap_lines_at:] = [msg.format(len(report_lines[cap_lines_at:]))]
281 if report_lines: # We might have filtered out every location as uninformative.
282 report[origin] = list(EXPLANATION_STUB) + report_lines
283 return report
284
285
286def explanatory_lines(traces, settings):
287 if Phase.explain in settings.phases and sys.gettrace() and not traces:
288 return defaultdict(list)
289 # Return human-readable report lines summarising the traces
290 explanations = get_explaining_locations(traces)
291 max_lines = 5 if settings.verbosity <= Verbosity.normal else float("inf")
292 return make_report(explanations, cap_lines_at=max_lines)
293
294
295# beware the code below; we're using some heuristics to make a nicer report...
296
297
298@functools.lru_cache
299def _get_git_repo_root() -> Path:
300 try:
301 where = subprocess.run(
302 ["git", "rev-parse", "--show-toplevel"],
303 check=True,
304 timeout=10,
305 capture_output=True,
306 text=True,
307 encoding="utf-8",
308 ).stdout.strip()
309 except Exception: # pragma: no cover
310 return Path().absolute().parents[-1]
311 else:
312 return Path(where)
313
314
315def tractable_coverage_report(trace: Trace) -> dict[str, list[int]]:
316 """Report a simple coverage map which is (probably most) of the user's code."""
317 coverage: dict = {}
318 t = dict(trace)
319 for file, line in set(t.keys()).union(t.values()) - {None}: # type: ignore
320 # On Python <= 3.11, we can use coverage.py xor Hypothesis' tracer,
321 # so the trace will be empty and this line never run under coverage.
322 coverage.setdefault(file, set()).add(line) # pragma: no cover
323 stdlib_fragment = f"{os.sep}lib{os.sep}python3.{sys.version_info.minor}{os.sep}"
324 return {
325 k: sorted(v)
326 for k, v in coverage.items()
327 if stdlib_fragment not in k
328 and (p := Path(k)).is_relative_to(_get_git_repo_root())
329 and "site-packages" not in p.parts
330 }