Skip to content

Commit cd398e2

Browse files
authored
Merge pull request #5920 from blueyed/lazy-import-pdb
Allow for "pdb" module to be rewritten
2 parents b847d57 + 07f20cc commit cd398e2

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

src/_pytest/debugging.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
""" interactive debugging with PDB, the Python Debugger. """
22
import argparse
3-
import pdb
43
import sys
5-
from doctest import UnexpectedException
64

75
from _pytest import outcomes
86
from _pytest.config import hookimpl
@@ -45,6 +43,8 @@ def pytest_addoption(parser):
4543

4644

4745
def pytest_configure(config):
46+
import pdb
47+
4848
if config.getvalue("trace"):
4949
config.pluginmanager.register(PdbTrace(), "pdbtrace")
5050
if config.getvalue("usepdb"):
@@ -87,6 +87,8 @@ def _is_capturing(cls, capman):
8787
@classmethod
8888
def _import_pdb_cls(cls, capman):
8989
if not cls._config:
90+
import pdb
91+
9092
# Happens when using pytest.set_trace outside of a test.
9193
return pdb.Pdb
9294

@@ -113,6 +115,8 @@ def _import_pdb_cls(cls, capman):
113115
"--pdbcls: could not import {!r}: {}".format(value, exc)
114116
)
115117
else:
118+
import pdb
119+
116120
pdb_cls = pdb.Pdb
117121

118122
wrapped_cls = cls._get_pdb_wrapper_class(pdb_cls, capman)
@@ -313,6 +317,8 @@ def _enter_pdb(node, excinfo, rep):
313317

314318

315319
def _postmortem_traceback(excinfo):
320+
from doctest import UnexpectedException
321+
316322
if isinstance(excinfo.value, UnexpectedException):
317323
# A doctest.UnexpectedException is not useful for post_mortem.
318324
# Use the underlying exception instead:

testing/acceptance_test.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1238,3 +1238,40 @@ def test_3():
12381238
assert (
12391239
result.stdout.str().count("async def functions are not natively supported") == 1
12401240
)
1241+
1242+
1243+
def test_pdb_can_be_rewritten(testdir):
1244+
testdir.makepyfile(
1245+
**{
1246+
"conftest.py": """
1247+
import pytest
1248+
pytest.register_assert_rewrite("pdb")
1249+
""",
1250+
"__init__.py": "",
1251+
"pdb.py": """
1252+
def check():
1253+
assert 1 == 2
1254+
""",
1255+
"test_pdb.py": """
1256+
def test():
1257+
import pdb
1258+
assert pdb.check()
1259+
""",
1260+
}
1261+
)
1262+
# Disable debugging plugin itself to avoid:
1263+
# > INTERNALERROR> AttributeError: module 'pdb' has no attribute 'set_trace'
1264+
result = testdir.runpytest_subprocess("-p", "no:debugging", "-vv")
1265+
result.stdout.fnmatch_lines(
1266+
[
1267+
" def check():",
1268+
"> assert 1 == 2",
1269+
"E assert 1 == 2",
1270+
"E -1",
1271+
"E +2",
1272+
"",
1273+
"pdb.py:2: AssertionError",
1274+
"*= 1 failed in *",
1275+
]
1276+
)
1277+
assert result.ret == 1

0 commit comments

Comments
 (0)