mirror of
https://github.com/pre-commit/pre-commit-hooks.git
synced 2026-04-06 12:06:53 +00:00
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
This commit is contained in:
parent
72ad6dc953
commit
f4cd1ba0d6
813 changed files with 66015 additions and 58839 deletions
|
|
@ -1,9 +1,12 @@
|
|||
# mypy: allow-untyped-defs
|
||||
"""Interactive debugging with PDB, the Python Debugger."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import functools
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from typing import Any
|
||||
from typing import Callable
|
||||
from typing import Generator
|
||||
|
|
@ -13,7 +16,6 @@ from typing import Tuple
|
|||
from typing import Type
|
||||
from typing import TYPE_CHECKING
|
||||
from typing import Union
|
||||
import unittest
|
||||
|
||||
from _pytest import outcomes
|
||||
from _pytest._code import ExceptionInfo
|
||||
|
|
@ -32,51 +34,51 @@ if TYPE_CHECKING:
|
|||
from _pytest.runner import CallInfo
|
||||
|
||||
|
||||
def _validate_usepdb_cls(value: str) -> Tuple[str, str]:
|
||||
def _validate_usepdb_cls(value: str) -> tuple[str, str]:
|
||||
"""Validate syntax of --pdbcls option."""
|
||||
try:
|
||||
modname, classname = value.split(":")
|
||||
modname, classname = value.split(':')
|
||||
except ValueError as e:
|
||||
raise argparse.ArgumentTypeError(
|
||||
f"{value!r} is not in the format 'modname:classname'"
|
||||
f"{value!r} is not in the format 'modname:classname'",
|
||||
) from e
|
||||
return (modname, classname)
|
||||
|
||||
|
||||
def pytest_addoption(parser: Parser) -> None:
|
||||
group = parser.getgroup("general")
|
||||
group = parser.getgroup('general')
|
||||
group._addoption(
|
||||
"--pdb",
|
||||
dest="usepdb",
|
||||
action="store_true",
|
||||
help="Start the interactive Python debugger on errors or KeyboardInterrupt",
|
||||
'--pdb',
|
||||
dest='usepdb',
|
||||
action='store_true',
|
||||
help='Start the interactive Python debugger on errors or KeyboardInterrupt',
|
||||
)
|
||||
group._addoption(
|
||||
"--pdbcls",
|
||||
dest="usepdb_cls",
|
||||
metavar="modulename:classname",
|
||||
'--pdbcls',
|
||||
dest='usepdb_cls',
|
||||
metavar='modulename:classname',
|
||||
type=_validate_usepdb_cls,
|
||||
help="Specify a custom interactive Python debugger for use with --pdb."
|
||||
"For example: --pdbcls=IPython.terminal.debugger:TerminalPdb",
|
||||
help='Specify a custom interactive Python debugger for use with --pdb.'
|
||||
'For example: --pdbcls=IPython.terminal.debugger:TerminalPdb',
|
||||
)
|
||||
group._addoption(
|
||||
"--trace",
|
||||
dest="trace",
|
||||
action="store_true",
|
||||
help="Immediately break when running each test",
|
||||
'--trace',
|
||||
dest='trace',
|
||||
action='store_true',
|
||||
help='Immediately break when running each test',
|
||||
)
|
||||
|
||||
|
||||
def pytest_configure(config: Config) -> None:
|
||||
import pdb
|
||||
|
||||
if config.getvalue("trace"):
|
||||
config.pluginmanager.register(PdbTrace(), "pdbtrace")
|
||||
if config.getvalue("usepdb"):
|
||||
config.pluginmanager.register(PdbInvoke(), "pdbinvoke")
|
||||
if config.getvalue('trace'):
|
||||
config.pluginmanager.register(PdbTrace(), 'pdbtrace')
|
||||
if config.getvalue('usepdb'):
|
||||
config.pluginmanager.register(PdbInvoke(), 'pdbinvoke')
|
||||
|
||||
pytestPDB._saved.append(
|
||||
(pdb.set_trace, pytestPDB._pluginmanager, pytestPDB._config)
|
||||
(pdb.set_trace, pytestPDB._pluginmanager, pytestPDB._config),
|
||||
)
|
||||
pdb.set_trace = pytestPDB.set_trace
|
||||
pytestPDB._pluginmanager = config.pluginmanager
|
||||
|
|
@ -97,29 +99,29 @@ def pytest_configure(config: Config) -> None:
|
|||
class pytestPDB:
|
||||
"""Pseudo PDB that defers to the real pdb."""
|
||||
|
||||
_pluginmanager: Optional[PytestPluginManager] = None
|
||||
_config: Optional[Config] = None
|
||||
_saved: List[
|
||||
Tuple[Callable[..., None], Optional[PytestPluginManager], Optional[Config]]
|
||||
_pluginmanager: PytestPluginManager | None = None
|
||||
_config: Config | None = None
|
||||
_saved: list[
|
||||
tuple[Callable[..., None], PytestPluginManager | None, Config | None]
|
||||
] = []
|
||||
_recursive_debug = 0
|
||||
_wrapped_pdb_cls: Optional[Tuple[Type[Any], Type[Any]]] = None
|
||||
_wrapped_pdb_cls: tuple[type[Any], type[Any]] | None = None
|
||||
|
||||
@classmethod
|
||||
def _is_capturing(cls, capman: Optional["CaptureManager"]) -> Union[str, bool]:
|
||||
def _is_capturing(cls, capman: CaptureManager | None) -> str | bool:
|
||||
if capman:
|
||||
return capman.is_capturing()
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def _import_pdb_cls(cls, capman: Optional["CaptureManager"]):
|
||||
def _import_pdb_cls(cls, capman: CaptureManager | None):
|
||||
if not cls._config:
|
||||
import pdb
|
||||
|
||||
# Happens when using pytest.set_trace outside of a test.
|
||||
return pdb.Pdb
|
||||
|
||||
usepdb_cls = cls._config.getvalue("usepdb_cls")
|
||||
usepdb_cls = cls._config.getvalue('usepdb_cls')
|
||||
|
||||
if cls._wrapped_pdb_cls and cls._wrapped_pdb_cls[0] == usepdb_cls:
|
||||
return cls._wrapped_pdb_cls[1]
|
||||
|
|
@ -132,14 +134,14 @@ class pytestPDB:
|
|||
mod = sys.modules[modname]
|
||||
|
||||
# Handle --pdbcls=pdb:pdb.Pdb (useful e.g. with pdbpp).
|
||||
parts = classname.split(".")
|
||||
parts = classname.split('.')
|
||||
pdb_cls = getattr(mod, parts[0])
|
||||
for part in parts[1:]:
|
||||
pdb_cls = getattr(pdb_cls, part)
|
||||
except Exception as exc:
|
||||
value = ":".join((modname, classname))
|
||||
value = ':'.join((modname, classname))
|
||||
raise UsageError(
|
||||
f"--pdbcls: could not import {value!r}: {exc}"
|
||||
f'--pdbcls: could not import {value!r}: {exc}',
|
||||
) from exc
|
||||
else:
|
||||
import pdb
|
||||
|
|
@ -151,7 +153,7 @@ class pytestPDB:
|
|||
return wrapped_cls
|
||||
|
||||
@classmethod
|
||||
def _get_pdb_wrapper_class(cls, pdb_cls, capman: Optional["CaptureManager"]):
|
||||
def _get_pdb_wrapper_class(cls, pdb_cls, capman: CaptureManager | None):
|
||||
import _pytest.config
|
||||
|
||||
# Type ignored because mypy doesn't support "dynamic"
|
||||
|
|
@ -176,18 +178,18 @@ class pytestPDB:
|
|||
capman = self._pytest_capman
|
||||
capturing = pytestPDB._is_capturing(capman)
|
||||
if capturing:
|
||||
if capturing == "global":
|
||||
tw.sep(">", "PDB continue (IO-capturing resumed)")
|
||||
if capturing == 'global':
|
||||
tw.sep('>', 'PDB continue (IO-capturing resumed)')
|
||||
else:
|
||||
tw.sep(
|
||||
">",
|
||||
"PDB continue (IO-capturing resumed for %s)"
|
||||
'>',
|
||||
'PDB continue (IO-capturing resumed for %s)'
|
||||
% capturing,
|
||||
)
|
||||
assert capman is not None
|
||||
capman.resume()
|
||||
else:
|
||||
tw.sep(">", "PDB continue")
|
||||
tw.sep('>', 'PDB continue')
|
||||
assert cls._pluginmanager is not None
|
||||
cls._pluginmanager.hook.pytest_leave_pdb(config=cls._config, pdb=self)
|
||||
self._continued = True
|
||||
|
|
@ -205,7 +207,7 @@ class pytestPDB:
|
|||
ret = super().do_quit(arg)
|
||||
|
||||
if cls._recursive_debug == 0:
|
||||
outcomes.exit("Quitting debugger")
|
||||
outcomes.exit('Quitting debugger')
|
||||
|
||||
return ret
|
||||
|
||||
|
|
@ -231,7 +233,7 @@ class pytestPDB:
|
|||
if f is None:
|
||||
# Find last non-hidden frame.
|
||||
i = max(0, len(stack) - 1)
|
||||
while i and stack[i][0].f_locals.get("__tracebackhide__", False):
|
||||
while i and stack[i][0].f_locals.get('__tracebackhide__', False):
|
||||
i -= 1
|
||||
return stack, i
|
||||
|
||||
|
|
@ -243,9 +245,9 @@ class pytestPDB:
|
|||
import _pytest.config
|
||||
|
||||
if cls._pluginmanager is None:
|
||||
capman: Optional[CaptureManager] = None
|
||||
capman: CaptureManager | None = None
|
||||
else:
|
||||
capman = cls._pluginmanager.getplugin("capturemanager")
|
||||
capman = cls._pluginmanager.getplugin('capturemanager')
|
||||
if capman:
|
||||
capman.suspend(in_=True)
|
||||
|
||||
|
|
@ -255,20 +257,20 @@ class pytestPDB:
|
|||
|
||||
if cls._recursive_debug == 0:
|
||||
# Handle header similar to pdb.set_trace in py37+.
|
||||
header = kwargs.pop("header", None)
|
||||
header = kwargs.pop('header', None)
|
||||
if header is not None:
|
||||
tw.sep(">", header)
|
||||
tw.sep('>', header)
|
||||
else:
|
||||
capturing = cls._is_capturing(capman)
|
||||
if capturing == "global":
|
||||
tw.sep(">", f"PDB {method} (IO-capturing turned off)")
|
||||
if capturing == 'global':
|
||||
tw.sep('>', f'PDB {method} (IO-capturing turned off)')
|
||||
elif capturing:
|
||||
tw.sep(
|
||||
">",
|
||||
f"PDB {method} (IO-capturing turned off for {capturing})",
|
||||
'>',
|
||||
f'PDB {method} (IO-capturing turned off for {capturing})',
|
||||
)
|
||||
else:
|
||||
tw.sep(">", f"PDB {method}")
|
||||
tw.sep('>', f'PDB {method}')
|
||||
|
||||
_pdb = cls._import_pdb_cls(capman)(**kwargs)
|
||||
|
||||
|
|
@ -280,15 +282,15 @@ class pytestPDB:
|
|||
def set_trace(cls, *args, **kwargs) -> None:
|
||||
"""Invoke debugging via ``Pdb.set_trace``, dropping any IO capturing."""
|
||||
frame = sys._getframe().f_back
|
||||
_pdb = cls._init_pdb("set_trace", *args, **kwargs)
|
||||
_pdb = cls._init_pdb('set_trace', *args, **kwargs)
|
||||
_pdb.set_trace(frame)
|
||||
|
||||
|
||||
class PdbInvoke:
|
||||
def pytest_exception_interact(
|
||||
self, node: Node, call: "CallInfo[Any]", report: BaseReport
|
||||
self, node: Node, call: CallInfo[Any], report: BaseReport,
|
||||
) -> None:
|
||||
capman = node.config.pluginmanager.getplugin("capturemanager")
|
||||
capman = node.config.pluginmanager.getplugin('capturemanager')
|
||||
if capman:
|
||||
capman.suspend_global_capture(in_=True)
|
||||
out, err = capman.read_global_capture()
|
||||
|
|
@ -316,7 +318,7 @@ def wrap_pytest_function_for_tracing(pyfuncitem):
|
|||
wrapper which actually enters pdb before calling the python function
|
||||
itself, effectively leaving the user in the pdb prompt in the first
|
||||
statement of the function."""
|
||||
_pdb = pytestPDB._init_pdb("runcall")
|
||||
_pdb = pytestPDB._init_pdb('runcall')
|
||||
testfunction = pyfuncitem.obj
|
||||
|
||||
# we can't just return `partial(pdb.runcall, testfunction)` because (on
|
||||
|
|
@ -333,35 +335,35 @@ def wrap_pytest_function_for_tracing(pyfuncitem):
|
|||
def maybe_wrap_pytest_function_for_tracing(pyfuncitem):
|
||||
"""Wrap the given pytestfunct item for tracing support if --trace was given in
|
||||
the command line."""
|
||||
if pyfuncitem.config.getvalue("trace"):
|
||||
if pyfuncitem.config.getvalue('trace'):
|
||||
wrap_pytest_function_for_tracing(pyfuncitem)
|
||||
|
||||
|
||||
def _enter_pdb(
|
||||
node: Node, excinfo: ExceptionInfo[BaseException], rep: BaseReport
|
||||
node: Node, excinfo: ExceptionInfo[BaseException], rep: BaseReport,
|
||||
) -> BaseReport:
|
||||
# XXX we re-use the TerminalReporter's terminalwriter
|
||||
# because this seems to avoid some encoding related troubles
|
||||
# for not completely clear reasons.
|
||||
tw = node.config.pluginmanager.getplugin("terminalreporter")._tw
|
||||
tw = node.config.pluginmanager.getplugin('terminalreporter')._tw
|
||||
tw.line()
|
||||
|
||||
showcapture = node.config.option.showcapture
|
||||
|
||||
for sectionname, content in (
|
||||
("stdout", rep.capstdout),
|
||||
("stderr", rep.capstderr),
|
||||
("log", rep.caplog),
|
||||
('stdout', rep.capstdout),
|
||||
('stderr', rep.capstderr),
|
||||
('log', rep.caplog),
|
||||
):
|
||||
if showcapture in (sectionname, "all") and content:
|
||||
tw.sep(">", "captured " + sectionname)
|
||||
if content[-1:] == "\n":
|
||||
if showcapture in (sectionname, 'all') and content:
|
||||
tw.sep('>', 'captured ' + sectionname)
|
||||
if content[-1:] == '\n':
|
||||
content = content[:-1]
|
||||
tw.line(content)
|
||||
|
||||
tw.sep(">", "traceback")
|
||||
tw.sep('>', 'traceback')
|
||||
rep.toterminal(tw)
|
||||
tw.sep(">", "entering PDB")
|
||||
tw.sep('>', 'entering PDB')
|
||||
tb = _postmortem_traceback(excinfo)
|
||||
rep._pdbshown = True # type: ignore[attr-defined]
|
||||
post_mortem(tb)
|
||||
|
|
@ -386,8 +388,8 @@ def _postmortem_traceback(excinfo: ExceptionInfo[BaseException]) -> types.Traceb
|
|||
|
||||
|
||||
def post_mortem(t: types.TracebackType) -> None:
|
||||
p = pytestPDB._init_pdb("post_mortem")
|
||||
p = pytestPDB._init_pdb('post_mortem')
|
||||
p.reset()
|
||||
p.interaction(None, t)
|
||||
if p.quitting:
|
||||
outcomes.exit("Quitting debugger")
|
||||
outcomes.exit('Quitting debugger')
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue