Debian Codegraph @

src/_pytest/debugging.py

raw
1 # mypy: allow-untyped-defs
2 # ruff: noqa: T100
3 """Interactive debugging with PDB, the Python Debugger."""
4
5 from __future__ import annotations
6
7 import argparse
8 from collections.abc import Callable
9 from collections.abc import Generator
10 import functools
11 import importlib
12 import sys
13 import types
14 from typing import Any
15
16 from _pytest import outcomes
17 from _pytest._code import ExceptionInfo
18 from _pytest.capture import CaptureManager
19 from _pytest.config import Config
20 from _pytest.config import ConftestImportFailure
21 from _pytest.config import hookimpl
22 from _pytest.config import PytestPluginManager
23 from _pytest.config.argparsing import Parser
24 from _pytest.config.exceptions import UsageError
25 from _pytest.nodes import Node
26 from _pytest.reports import BaseReport
27 from _pytest.runner import CallInfo
28
29
30 def _validate_usepdb_cls(value: str) -> tuple[str, str]:
31 """Validate syntax of --pdbcls option."""
32 try:
33 modname, classname = value.split(":")
34 except ValueError as e:
35 raise argparse.ArgumentTypeError(
36 f"{value!r} is not in the format 'modname:classname'"
37 ) from e
38 return (modname, classname)
39
40
41 def pytest_addoption(parser: Parser) -> None:
42 group = parser.getgroup("general")
43 group.addoption(
44 "--pdb",
45 dest="usepdb",
46 action="store_true",
47 help="Start the interactive Python debugger on errors or KeyboardInterrupt",
48 )
49 group.addoption(
50 "--pdbcls",
51 dest="usepdb_cls",
52 metavar="modulename:classname",
53 type=_validate_usepdb_cls,
54 help="Specify a custom interactive Python debugger for use with --pdb."
55 "For example: --pdbcls=IPython.terminal.debugger:TerminalPdb",
56 )
57 group.addoption(
58 "--trace",
59 dest="trace",
60 action="store_true",
61 help="Immediately break when running each test",
62 )
63
64
65 def pytest_configure(config: Config) -> None:
66 import pdb
67
68 if config.getvalue("trace"):
69 config.pluginmanager.register(PdbTrace(), "pdbtrace")
70 if config.getvalue("usepdb"):
71 config.pluginmanager.register(PdbInvoke(), "pdbinvoke")
72
73 pytestPDB._saved.append(
74 (pdb.set_trace, pytestPDB._pluginmanager, pytestPDB._config)
75 )
76 pdb.set_trace = pytestPDB.set_trace
77 pytestPDB._pluginmanager = config.pluginmanager
78 pytestPDB._config = config
79
80 # NOTE: not using pytest_unconfigure, since it might get called although
81 # pytest_configure was not (if another plugin raises UsageError).
82 def fin() -> None:
83 (
84 pdb.set_trace,
85 pytestPDB._pluginmanager,
86 pytestPDB._config,
87 ) = pytestPDB._saved.pop()
88
89 config.add_cleanup(fin)
90
91
92 class pytestPDB:
93 """Pseudo PDB that defers to the real pdb."""
94
95 _pluginmanager: PytestPluginManager | None = None
96 _config: Config | None = None
97 _saved: list[
98 tuple[Callable[..., None], PytestPluginManager | None, Config | None]
99 ] = []
100 _recursive_debug = 0
101 _wrapped_pdb_cls: tuple[type[Any], type[Any]] | None = None
102
103 @classmethod
104 def _is_capturing(cls, capman: CaptureManager | None) -> str | bool:
105 if capman:
106 return capman.is_capturing()
107 return False
108
109 @classmethod
110 def _import_pdb_cls(cls, capman: CaptureManager | None):
111 if not cls._config:
112 import pdb
113
114 # Happens when using pytest.set_trace outside of a test.
115 return pdb.Pdb
116
117 usepdb_cls = cls._config.getvalue("usepdb_cls")
118
119 if cls._wrapped_pdb_cls and cls._wrapped_pdb_cls[0] == usepdb_cls:
120 return cls._wrapped_pdb_cls[1]
121
122 if usepdb_cls:
123 modname, classname = usepdb_cls
124
125 try:
126 mod = importlib.import_module(modname)
127
128 # Handle --pdbcls=pdb:pdb.Pdb (useful e.g. with pdbpp).
129 parts = classname.split(".")
130 pdb_cls = getattr(mod, parts[0])
131 for part in parts[1:]:
132 pdb_cls = getattr(pdb_cls, part)
133 except Exception as exc:
134 value = ":".join((modname, classname))
135 raise UsageError(
136 f"--pdbcls: could not import {value!r}: {exc}"
137 ) from exc
138 else:
139 import pdb
140
141 pdb_cls = pdb.Pdb
142
143 wrapped_cls = cls._get_pdb_wrapper_class(pdb_cls, capman)
144 cls._wrapped_pdb_cls = (usepdb_cls, wrapped_cls)
145 return wrapped_cls
146
147 @classmethod
148 def _get_pdb_wrapper_class(cls, pdb_cls, capman: CaptureManager | None):
149 import _pytest.config
150
151 class PytestPdbWrapper(pdb_cls):
152 _pytest_capman = capman
153 _continued = False
154
155 def do_debug(self, arg):
156 cls._recursive_debug += 1
157 ret = super().do_debug(arg)
158 cls._recursive_debug -= 1
159 return ret
160
161 if hasattr(pdb_cls, "do_debug"):
162 do_debug.__doc__ = pdb_cls.do_debug.__doc__
163
164 def do_continue(self, arg):
165 ret = super().do_continue(arg)
166 if cls._recursive_debug == 0:
167 assert cls._config is not None
168 tw = _pytest.config.create_terminal_writer(cls._config)
169 tw.line()
170
171 capman = self._pytest_capman
172 capturing = pytestPDB._is_capturing(capman)
173 if capturing:
174 if capturing == "global":
175 tw.sep(">", "PDB continue (IO-capturing resumed)")
176 else:
177 tw.sep(
178 ">",
179 f"PDB continue (IO-capturing resumed for {capturing})",
180 )
181 assert capman is not None
182 capman.resume()
183 else:
184 tw.sep(">", "PDB continue")
185 assert cls._pluginmanager is not None
186 cls._pluginmanager.hook.pytest_leave_pdb(config=cls._config, pdb=self)
187 self._continued = True
188 return ret
189
190 if hasattr(pdb_cls, "do_continue"):
191 do_continue.__doc__ = pdb_cls.do_continue.__doc__
192
193 do_c = do_cont = do_continue
194
195 def do_quit(self, arg):
196 # Raise Exit outcome when quit command is used in pdb.
197 #
198 # This is a bit of a hack - it would be better if BdbQuit
199 # could be handled, but this would require to wrap the
200 # whole pytest run, and adjust the report etc.
201 ret = super().do_quit(arg)
202
203 if cls._recursive_debug == 0:
204 outcomes.exit("Quitting debugger")
205
206 return ret
207
208 if hasattr(pdb_cls, "do_quit"):
209 do_quit.__doc__ = pdb_cls.do_quit.__doc__
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: CaptureManager | None = 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 _enter_pdb(node, call.excinfo, report)
298
299 def pytest_internalerror(self, excinfo: ExceptionInfo[BaseException]) -> None:
300 exc_or_tb = _postmortem_exc_or_tb(excinfo)
301 post_mortem(exc_or_tb)
302
303
304 class PdbTrace:
305 @hookimpl(wrapper=True)
306 def pytest_pyfunc_call(self, pyfuncitem) -> Generator[None, object, object]:
307 wrap_pytest_function_for_tracing(pyfuncitem)
308 return (yield)
309
310
311 def wrap_pytest_function_for_tracing(pyfuncitem) -> None:
312 """Change the Python function object of the given Function item by a
313 wrapper which actually enters pdb before calling the python function
314 itself, effectively leaving the user in the pdb prompt in the first
315 statement of the function."""
316 _pdb = pytestPDB._init_pdb("runcall")
317 testfunction = pyfuncitem.obj
318
319 # we can't just return `partial(pdb.runcall, testfunction)` because (on
320 # python < 3.7.4) runcall's first param is `func`, which means we'd get
321 # an exception if one of the kwargs to testfunction was called `func`.
322 @functools.wraps(testfunction)
323 def wrapper(*args, **kwargs) -> None:
324 func = functools.partial(testfunction, *args, **kwargs)
325 _pdb.runcall(func)
326
327 pyfuncitem.obj = wrapper
328
329
330 def maybe_wrap_pytest_function_for_tracing(pyfuncitem) -> None:
331 """Wrap the given pytestfunct item for tracing support if --trace was given in
332 the command line."""
333 if pyfuncitem.config.getvalue("trace"):
334 wrap_pytest_function_for_tracing(pyfuncitem)
335
336
337 def _enter_pdb(
338 node: Node, excinfo: ExceptionInfo[BaseException], rep: BaseReport
339 ) -> BaseReport:
340 # XXX we reuse the TerminalReporter's terminalwriter
341 # because this seems to avoid some encoding related troubles
342 # for not completely clear reasons.
343 tw = node.config.pluginmanager.getplugin("terminalreporter")._tw
344 tw.line()
345
346 showcapture = node.config.option.showcapture
347
348 for sectionname, content in (
349 ("stdout", rep.capstdout),
350 ("stderr", rep.capstderr),
351 ("log", rep.caplog),
352 ):
353 if showcapture in (sectionname, "all") and content:
354 tw.sep(">", "captured " + sectionname)
355 if content[-1:] == "\n":
356 content = content[:-1]
357 tw.line(content)
358
359 tw.sep(">", "traceback")
360 rep.toterminal(tw)
361 tw.sep(">", "entering PDB")
362 tb_or_exc = _postmortem_exc_or_tb(excinfo)
363 rep._pdbshown = True # type: ignore[attr-defined]
364 post_mortem(tb_or_exc)
365 return rep
366
367
368 def _postmortem_exc_or_tb(
369 excinfo: ExceptionInfo[BaseException],
370 ) -> types.TracebackType | BaseException:
371 from doctest import UnexpectedException
372
373 get_exc = sys.version_info >= (3, 13)
374 if isinstance(excinfo.value, UnexpectedException):
375 # A doctest.UnexpectedException is not useful for post_mortem.
376 # Use the underlying exception instead:
377 underlying_exc = excinfo.value
378 if get_exc:
379 return underlying_exc.exc_info[1]
380
381 return underlying_exc.exc_info[2]
382 elif isinstance(excinfo.value, ConftestImportFailure):
383 # A config.ConftestImportFailure is not useful for post_mortem.
384 # Use the underlying exception instead:
385 cause = excinfo.value.cause
386 if get_exc:
387 return cause
388
389 assert cause.__traceback__ is not None
390 return cause.__traceback__
391 else:
392 assert excinfo._excinfo is not None
393 if get_exc:
394 return excinfo._excinfo[1]
395
396 return excinfo._excinfo[2]
397
398
399 def post_mortem(tb_or_exc: types.TracebackType | BaseException) -> None:
400 p = pytestPDB._init_pdb("post_mortem")
401 p.reset()
402 p.interaction(None, tb_or_exc)
403 if p.quitting:
404 outcomes.exit("Quitting debugger")