Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/src/_pytest/debugging.py

raw
1 # mypy: allow-untyped-defs
2 """Interactive debugging with PDB, the Python Debugger."""
3
4 import argparse
5 import functools
6 import sys
7 import types
8 from typing import Any
9 from typing import Callable
10 from typing import Generator
11 from typing import List
12 from typing import Optional
13 from typing import Tuple
14 from typing import Type
15 from typing import TYPE_CHECKING
16 from typing import Union
17 import unittest
18
19 from _pytest import outcomes
20 from _pytest._code import ExceptionInfo
21 from _pytest.config import Config
22 from _pytest.config import ConftestImportFailure
23 from _pytest.config import hookimpl
24 from _pytest.config import PytestPluginManager
25 from _pytest.config.argparsing import Parser
26 from _pytest.config.exceptions import UsageError
27 from _pytest.nodes import Node
28 from _pytest.reports import BaseReport
29
30
31 if TYPE_CHECKING:
32 from _pytest.capture import CaptureManager
33 from _pytest.runner import CallInfo
34
35
36 def _validate_usepdb_cls(value: str) -> Tuple[str, str]:
37 """Validate syntax of --pdbcls option."""
38 try:
39 modname, classname = value.split(":")
40 except ValueError as e:
41 raise argparse.ArgumentTypeError(
42 f"{value!r} is not in the format 'modname:classname'"
43 ) from e
44 return (modname, classname)
45
46
47 def pytest_addoption(parser: Parser) -> None:
48 group = parser.getgroup("general")
49 group._addoption(
50 "--pdb",
51 dest="usepdb",
52 action="store_true",
53 help="Start the interactive Python debugger on errors or KeyboardInterrupt",
54 )
55 group._addoption(
56 "--pdbcls",
57 dest="usepdb_cls",
58 metavar="modulename:classname",
59 type=_validate_usepdb_cls,
60 help="Specify a custom interactive Python debugger for use with --pdb."
61 "For example: --pdbcls=IPython.terminal.debugger:TerminalPdb",
62 )
63 group._addoption(
64 "--trace",
65 dest="trace",
66 action="store_true",
67 help="Immediately break when running each test",
68 )
69
70
71 def pytest_configure(config: Config) -> None:
72 import pdb
73
74 if config.getvalue("trace"):
75 config.pluginmanager.register(PdbTrace(), "pdbtrace")
76 if config.getvalue("usepdb"):
77 config.pluginmanager.register(PdbInvoke(), "pdbinvoke")
78
79 pytestPDB._saved.append(
80 (pdb.set_trace, pytestPDB._pluginmanager, pytestPDB._config)
81 )
82 pdb.set_trace = pytestPDB.set_trace
83 pytestPDB._pluginmanager = config.pluginmanager
84 pytestPDB._config = config
85
86 # NOTE: not using pytest_unconfigure, since it might get called although
87 # pytest_configure was not (if another plugin raises UsageError).
88 def fin() -> None:
89 (
90 pdb.set_trace,
91 pytestPDB._pluginmanager,
92 pytestPDB._config,
93 ) = pytestPDB._saved.pop()
94
95 config.add_cleanup(fin)
96
97
98 class pytestPDB:
99 """Pseudo PDB that defers to the real pdb."""
100
101 _pluginmanager: Optional[PytestPluginManager] = None
102 _config: Optional[Config] = None
103 _saved: List[
104 Tuple[Callable[..., None], Optional[PytestPluginManager], Optional[Config]]
105 ] = []
106 _recursive_debug = 0
107 _wrapped_pdb_cls: Optional[Tuple[Type[Any], Type[Any]]] = None
108
109 @classmethod
110 def _is_capturing(cls, capman: Optional["CaptureManager"]) -> Union[str, bool]:
111 if capman:
112 return capman.is_capturing()
113 return False
114
115 @classmethod
116 def _import_pdb_cls(cls, capman: Optional["CaptureManager"]):
117 if not cls._config:
118 import pdb
119
120 # Happens when using pytest.set_trace outside of a test.
121 return pdb.Pdb
122
123 usepdb_cls = cls._config.getvalue("usepdb_cls")
124
125 if cls._wrapped_pdb_cls and cls._wrapped_pdb_cls[0] == usepdb_cls:
126 return cls._wrapped_pdb_cls[1]
127
128 if usepdb_cls:
129 modname, classname = usepdb_cls
130
131 try:
132 __import__(modname)
133 mod = sys.modules[modname]
134
135 # Handle --pdbcls=pdb:pdb.Pdb (useful e.g. with pdbpp).
136 parts = classname.split(".")
137 pdb_cls = getattr(mod, parts[0])
138 for part in parts[1:]:
139 pdb_cls = getattr(pdb_cls, part)
140 except Exception as exc:
141 value = ":".join((modname, classname))
142 raise UsageError(
143 f"--pdbcls: could not import {value!r}: {exc}"
144 ) from exc
145 else:
146 import pdb
147
148 pdb_cls = pdb.Pdb
149
150 wrapped_cls = cls._get_pdb_wrapper_class(pdb_cls, capman)
151 cls._wrapped_pdb_cls = (usepdb_cls, wrapped_cls)
152 return wrapped_cls
153
154 @classmethod
155 def _get_pdb_wrapper_class(cls, pdb_cls, capman: Optional["CaptureManager"]):
156 import _pytest.config
157
158 class PytestPdbWrapper(pdb_cls):
159 _pytest_capman = capman
160 _continued = False
161
162 def do_debug(self, arg):
163 cls._recursive_debug += 1
164 ret = super().do_debug(arg)
165 cls._recursive_debug -= 1
166 return ret
167
168 def do_continue(self, arg):
169 ret = super().do_continue(arg)
170 if cls._recursive_debug == 0:
171 assert cls._config is not None
172 tw = _pytest.config.create_terminal_writer(cls._config)
173 tw.line()
174
175 capman = self._pytest_capman
176 capturing = pytestPDB._is_capturing(capman)
177 if capturing:
178 if capturing == "global":
179 tw.sep(">", "PDB continue (IO-capturing resumed)")
180 else:
181 tw.sep(
182 ">",
183 "PDB continue (IO-capturing resumed for %s)"
184 % capturing,
185 )
186 assert capman is not None
187 capman.resume()
188 else:
189 tw.sep(">", "PDB continue")
190 assert cls._pluginmanager is not None
191 cls._pluginmanager.hook.pytest_leave_pdb(config=cls._config, pdb=self)
192 self._continued = True
193 return ret
194
195 do_c = do_cont = do_continue
196
197 def do_quit(self, arg):
198 """Raise Exit outcome when quit command is used in pdb.
199
200 This is a bit of a hack - it would be better if BdbQuit
201 could be handled, but this would require to wrap the
202 whole pytest run, and adjust the report etc.
203 """
204 ret = super().do_quit(arg)
205
206 if cls._recursive_debug == 0:
207 outcomes.exit("Quitting debugger")
208
209 return ret
210
211 do_q = do_quit
212 do_exit = do_quit
213
214 def setup(self, f, tb):
215 """Suspend on setup().
216
217 Needed after do_continue resumed, and entering another
218 breakpoint again.
219 """
220 ret = super().setup(f, tb)
221 if not ret and self._continued:
222 # pdb.setup() returns True if the command wants to exit
223 # from the interaction: do not suspend capturing then.
224 if self._pytest_capman:
225 self._pytest_capman.suspend_global_capture(in_=True)
226 return ret
227
228 def get_stack(self, f, t):
229 stack, i = super().get_stack(f, t)
230 if f is None:
231 # Find last non-hidden frame.
232 i = max(0, len(stack) - 1)
233 while i and stack[i][0].f_locals.get("__tracebackhide__", False):
234 i -= 1
235 return stack, i
236
237 return PytestPdbWrapper
238
239 @classmethod
240 def _init_pdb(cls, method, *args, **kwargs):
241 """Initialize PDB debugging, dropping any IO capturing."""
242 import _pytest.config
243
244 if cls._pluginmanager is None:
245 capman: Optional[CaptureManager] = None
246 else:
247 capman = cls._pluginmanager.getplugin("capturemanager")
248 if capman:
249 capman.suspend(in_=True)
250
251 if cls._config:
252 tw = _pytest.config.create_terminal_writer(cls._config)
253 tw.line()
254
255 if cls._recursive_debug == 0:
256 # Handle header similar to pdb.set_trace in py37+.
257 header = kwargs.pop("header", None)
258 if header is not None:
259 tw.sep(">", header)
260 else:
261 capturing = cls._is_capturing(capman)
262 if capturing == "global":
263 tw.sep(">", f"PDB {method} (IO-capturing turned off)")
264 elif capturing:
265 tw.sep(
266 ">",
267 f"PDB {method} (IO-capturing turned off for {capturing})",
268 )
269 else:
270 tw.sep(">", f"PDB {method}")
271
272 _pdb = cls._import_pdb_cls(capman)(**kwargs)
273
274 if cls._pluginmanager:
275 cls._pluginmanager.hook.pytest_enter_pdb(config=cls._config, pdb=_pdb)
276 return _pdb
277
278 @classmethod
279 def set_trace(cls, *args, **kwargs) -> None:
280 """Invoke debugging via ``Pdb.set_trace``, dropping any IO capturing."""
281 frame = sys._getframe().f_back
282 _pdb = cls._init_pdb("set_trace", *args, **kwargs)
283 _pdb.set_trace(frame)
284
285
286 class PdbInvoke:
287 def pytest_exception_interact(
288 self, node: Node, call: "CallInfo[Any]", report: BaseReport
289 ) -> None:
290 capman = node.config.pluginmanager.getplugin("capturemanager")
291 if capman:
292 capman.suspend_global_capture(in_=True)
293 out, err = capman.read_global_capture()
294 sys.stdout.write(out)
295 sys.stdout.write(err)
296 assert call.excinfo is not None
297
298 if not isinstance(call.excinfo.value, unittest.SkipTest):
299 _enter_pdb(node, call.excinfo, report)
300
301 def pytest_internalerror(self, excinfo: ExceptionInfo[BaseException]) -> None:
302 tb = _postmortem_traceback(excinfo)
303 post_mortem(tb)
304
305
306 class PdbTrace:
307 @hookimpl(wrapper=True)
308 def pytest_pyfunc_call(self, pyfuncitem) -> Generator[None, object, object]:
309 wrap_pytest_function_for_tracing(pyfuncitem)
310 return (yield)
311
312
313 def wrap_pytest_function_for_tracing(pyfuncitem):
314 """Change the Python function object of the given Function item by a
315 wrapper which actually enters pdb before calling the python function
316 itself, effectively leaving the user in the pdb prompt in the first
317 statement of the function."""
318 _pdb = pytestPDB._init_pdb("runcall")
319 testfunction = pyfuncitem.obj
320
321 # we can't just return `partial(pdb.runcall, testfunction)` because (on
322 # python < 3.7.4) runcall's first param is `func`, which means we'd get
323 # an exception if one of the kwargs to testfunction was called `func`.
324 @functools.wraps(testfunction)
325 def wrapper(*args, **kwargs):
326 func = functools.partial(testfunction, *args, **kwargs)
327 _pdb.runcall(func)
328
329 pyfuncitem.obj = wrapper
330
331
332 def maybe_wrap_pytest_function_for_tracing(pyfuncitem):
333 """Wrap the given pytestfunct item for tracing support if --trace was given in
334 the command line."""
335 if pyfuncitem.config.getvalue("trace"):
336 wrap_pytest_function_for_tracing(pyfuncitem)
337
338
339 def _enter_pdb(
340 node: Node, excinfo: ExceptionInfo[BaseException], rep: BaseReport
341 ) -> BaseReport:
342 # XXX we re-use the TerminalReporter's terminalwriter
343 # because this seems to avoid some encoding related troubles
344 # for not completely clear reasons.
345 tw = node.config.pluginmanager.getplugin("terminalreporter")._tw
346 tw.line()
347
348 showcapture = node.config.option.showcapture
349
350 for sectionname, content in (
351 ("stdout", rep.capstdout),
352 ("stderr", rep.capstderr),
353 ("log", rep.caplog),
354 ):
355 if showcapture in (sectionname, "all") and content:
356 tw.sep(">", "captured " + sectionname)
357 if content[-1:] == "\n":
358 content = content[:-1]
359 tw.line(content)
360
361 tw.sep(">", "traceback")
362 rep.toterminal(tw)
363 tw.sep(">", "entering PDB")
364 tb = _postmortem_traceback(excinfo)
365 rep._pdbshown = True # type: ignore[attr-defined]
366 post_mortem(tb)
367 return rep
368
369
370 def _postmortem_traceback(excinfo: ExceptionInfo[BaseException]) -> types.TracebackType:
371 from doctest import UnexpectedException
372
373 if isinstance(excinfo.value, UnexpectedException):
374 # A doctest.UnexpectedException is not useful for post_mortem.
375 # Use the underlying exception instead:
376 return excinfo.value.exc_info[2]
377 elif isinstance(excinfo.value, ConftestImportFailure):
378 # A config.ConftestImportFailure is not useful for post_mortem.
379 # Use the underlying exception instead:
380 assert excinfo.value.cause.__traceback__ is not None
381 return excinfo.value.cause.__traceback__
382 else:
383 assert excinfo._excinfo is not None
384 return excinfo._excinfo[2]
385
386
387 def post_mortem(t: types.TracebackType) -> None:
388 p = pytestPDB._init_pdb("post_mortem")
389 p.reset()
390 p.interaction(None, t)
391 if p.quitting:
392 outcomes.exit("Quitting debugger")