Debian Codegraph @

testing/test_debugging.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 import sys
5
6 import _pytest._code
7 from _pytest.debugging import _validate_usepdb_cls
8 from _pytest.monkeypatch import MonkeyPatch
9 from _pytest.pytester import Pytester
10 import pytest
11
12
13 @pytest.fixture(autouse=True)
14 def pdb_env(request):
15 if "pytester" in request.fixturenames:
16 # Disable pdb++ with inner tests.
17 pytester = request.getfixturevalue("pytester")
18 pytester._monkeypatch.setenv("PDBPP_HIJACK_PDB", "0")
19
20
21 def runpdb(pytester: Pytester, source: str):
22 p = pytester.makepyfile(source)
23 return pytester.runpytest_inprocess("--pdb", p)
24
25
26 def runpdb_and_get_stdout(pytester: Pytester, source: str):
27 result = runpdb(pytester, source)
28 return result.stdout.str()
29
30
31 def runpdb_and_get_report(pytester: Pytester, source: str):
32 result = runpdb(pytester, source)
33 reports = result.reprec.getreports("pytest_runtest_logreport")
34 assert len(reports) == 3, reports # setup/call/teardown
35 return reports[1]
36
37
38 @pytest.fixture
39 def custom_pdb_calls() -> list[str]:
40 called = []
41
42 # install dummy debugger class and track which methods were called on it
43 class _CustomPdb:
44 quitting = False
45
46 def __init__(self, *args, **kwargs):
47 called.append("init")
48
49 def reset(self):
50 called.append("reset")
51
52 def interaction(self, *args):
53 called.append("interaction")
54
55 # Methods which we copy docstrings to.
56 def do_debug(self, *args): # pragma: no cover
57 pass
58
59 def do_continue(self, *args): # pragma: no cover
60 pass
61
62 def do_quit(self, *args): # pragma: no cover
63 pass
64
65 _pytest._CustomPdb = _CustomPdb # type: ignore
66 return called
67
68
69 @pytest.fixture
70 def custom_debugger_hook():
71 called = []
72
73 # install dummy debugger class and track which methods were called on it
74 class _CustomDebugger:
75 def __init__(self, *args, **kwargs):
76 called.append("init")
77
78 def reset(self):
79 called.append("reset")
80
81 def interaction(self, *args):
82 called.append("interaction")
83
84 def set_trace(self, frame):
85 print("**CustomDebugger**")
86 called.append("set_trace")
87
88 # Methods which we copy docstrings to.
89 def do_debug(self, *args): # pragma: no cover
90 pass
91
92 def do_continue(self, *args): # pragma: no cover
93 pass
94
95 def do_quit(self, *args): # pragma: no cover
96 pass
97
98 _pytest._CustomDebugger = _CustomDebugger # type: ignore
99 yield called
100 del _pytest._CustomDebugger # type: ignore
101
102
103 class TestPDB:
104 @pytest.fixture
105 def pdblist(self, request):
106 monkeypatch = request.getfixturevalue("monkeypatch")
107 pdblist = []
108
109 def mypdb(*args):
110 pdblist.append(args)
111
112 plugin = request.config.pluginmanager.getplugin("debugging")
113 monkeypatch.setattr(plugin, "post_mortem", mypdb)
114 return pdblist
115
116 def test_pdb_on_fail(self, pytester: Pytester, pdblist) -> None:
117 rep = runpdb_and_get_report(
118 pytester,
119 """
120 def test_func():
121 assert 0
122 """,
123 )
124 assert rep.failed
125 assert len(pdblist) == 1
126 if sys.version_info < (3, 13):
127 tb = _pytest._code.Traceback(pdblist[0][0])
128 else:
129 tb = _pytest._code.Traceback(pdblist[0][0].__traceback__)
130 assert tb[-1].name == "test_func"
131
132 def test_pdb_on_xfail(self, pytester: Pytester, pdblist) -> None:
133 rep = runpdb_and_get_report(
134 pytester,
135 """
136 import pytest
137 @pytest.mark.xfail
138 def test_func():
139 assert 0
140 """,
141 )
142 assert "xfail" in rep.keywords
143 assert not pdblist
144
145 def test_pdb_on_skip(self, pytester, pdblist) -> None:
146 rep = runpdb_and_get_report(
147 pytester,
148 """
149 import pytest
150 def test_func():
151 pytest.skip("hello")
152 """,
153 )
154 assert rep.skipped
155 assert len(pdblist) == 0
156
157 def test_pdb_on_top_level_raise_skiptest(self, pytester, pdblist) -> None:
158 stdout = runpdb_and_get_stdout(
159 pytester,
160 """
161 import unittest
162 raise unittest.SkipTest("This is a common way to skip an entire file.")
163 """,
164 )
165 assert "entering PDB" not in stdout, stdout
166
167 def test_pdb_on_BdbQuit(self, pytester, pdblist) -> None:
168 rep = runpdb_and_get_report(
169 pytester,
170 """
171 import bdb
172 def test_func():
173 raise bdb.BdbQuit
174 """,
175 )
176 assert rep.failed
177 assert len(pdblist) == 0
178
179 def test_pdb_on_KeyboardInterrupt(self, pytester, pdblist) -> None:
180 rep = runpdb_and_get_report(
181 pytester,
182 """
183 def test_func():
184 raise KeyboardInterrupt
185 """,
186 )
187 assert rep.failed
188 assert len(pdblist) == 1
189
190 @staticmethod
191 def flush(child):
192 if child.isalive():
193 # Read if the test has not (e.g. test_pdb_unittest_skip).
194 child.read()
195 child.wait()
196 assert not child.isalive()
197
198 def test_pdb_unittest_postmortem(self, pytester: Pytester) -> None:
199 p1 = pytester.makepyfile(
200 """
201 import unittest
202 class Blub(unittest.TestCase):
203 def tearDown(self):
204 self.filename = None
205 def test_false(self):
206 self.filename = 'debug' + '.me'
207 assert 0
208 """
209 )
210 child = pytester.spawn_pytest(f"--pdb {p1}")
211 child.expect("Pdb")
212 child.sendline("p self.filename")
213 child.sendeof()
214 rest = child.read().decode("utf8")
215 assert "debug.me" in rest
216 self.flush(child)
217
218 def test_pdb_unittest_skip(self, pytester: Pytester) -> None:
219 """Test for issue #2137"""
220 p1 = pytester.makepyfile(
221 """
222 import unittest
223 @unittest.skipIf(True, 'Skipping also with pdb active')
224 class MyTestCase(unittest.TestCase):
225 def test_one(self):
226 assert 0
227 """
228 )
229 child = pytester.spawn_pytest(f"-rs --pdb {p1}")
230 child.expect("Skipping also with pdb active")
231 child.expect_exact("= 1 skipped in")
232 child.sendeof()
233 self.flush(child)
234
235 def test_pdb_print_captured_stdout_and_stderr(self, pytester: Pytester) -> None:
236 p1 = pytester.makepyfile(
237 """
238 def test_1():
239 import sys
240 sys.stderr.write("get\\x20rekt")
241 print("get\\x20rekt")
242 assert False
243
244 def test_not_called_due_to_quit():
245 pass
246 """
247 )
248 child = pytester.spawn_pytest(f"--pdb {p1}")
249 child.expect("captured stdout")
250 child.expect("get rekt")
251 child.expect("captured stderr")
252 child.expect("get rekt")
253 child.expect("traceback")
254 child.expect("def test_1")
255 child.expect("Pdb")
256 child.sendeof()
257 rest = child.read().decode("utf8")
258 assert "Exit: Quitting debugger" in rest
259 assert "= 1 failed in" in rest
260 assert "def test_1" not in rest
261 assert "get rekt" not in rest
262 self.flush(child)
263
264 def test_pdb_dont_print_empty_captured_stdout_and_stderr(
265 self, pytester: Pytester
266 ) -> None:
267 p1 = pytester.makepyfile(
268 """
269 def test_1():
270 assert False
271 """
272 )
273 child = pytester.spawn_pytest(f"--pdb {p1}")
274 child.expect("Pdb")
275 output = child.before.decode("utf8")
276 child.sendeof()
277 assert "captured stdout" not in output
278 assert "captured stderr" not in output
279 self.flush(child)
280
281 @pytest.mark.parametrize("showcapture", ["all", "no", "log"])
282 def test_pdb_print_captured_logs(self, pytester, showcapture: str) -> None:
283 p1 = pytester.makepyfile(
284 """
285 def test_1():
286 import logging
287 logging.warning("get " + "rekt")
288 assert False
289 """
290 )
291 child = pytester.spawn_pytest(f"--show-capture={showcapture} --pdb {p1}")
292 if showcapture in ("all", "log"):
293 child.expect("captured log")
294 child.expect("get rekt")
295 child.expect("Pdb")
296 child.sendeof()
297 rest = child.read().decode("utf8")
298 assert "1 failed" in rest
299 self.flush(child)
300
301 def test_pdb_print_captured_logs_nologging(self, pytester: Pytester) -> None:
302 p1 = pytester.makepyfile(
303 """
304 def test_1():
305 import logging
306 logging.warning("get " + "rekt")
307 assert False
308 """
309 )
310 child = pytester.spawn_pytest(f"--show-capture=all --pdb -p no:logging {p1}")
311 child.expect("get rekt")
312 output = child.before.decode("utf8")
313 assert "captured log" not in output
314 child.expect("Pdb")
315 child.sendeof()
316 rest = child.read().decode("utf8")
317 assert "1 failed" in rest
318 self.flush(child)
319
320 def test_pdb_interaction_exception(self, pytester: Pytester) -> None:
321 p1 = pytester.makepyfile(
322 """
323 import pytest
324 def globalfunc():
325 pass
326 def test_1():
327 with pytest.raises(ValueError):
328 globalfunc()
329 """
330 )
331 child = pytester.spawn_pytest(f"--pdb {p1}")
332 child.expect(".*def test_1")
333 child.expect(r"with pytest.raises\(ValueError\)")
334 child.expect("Pdb")
335 child.sendline("globalfunc")
336 child.expect(".*function")
337 child.sendeof()
338 child.expect("1 failed")
339 self.flush(child)
340
341 def test_pdb_interaction_on_collection_issue181(self, pytester: Pytester) -> None:
342 p1 = pytester.makepyfile(
343 """
344 import pytest
345 xxx
346 """
347 )
348 child = pytester.spawn_pytest(f"--pdb {p1}")
349 # child.expect(".*import pytest.*")
350 child.expect("Pdb")
351 child.sendline("c")
352 child.expect("1 error")
353 self.flush(child)
354
355 def test_pdb_interaction_on_internal_error(self, pytester: Pytester) -> None:
356 pytester.makeconftest(
357 """
358 def pytest_runtest_protocol():
359 0/0
360 """
361 )
362 p1 = pytester.makepyfile("def test_func(): pass")
363 child = pytester.spawn_pytest(f"--pdb {p1}")
364 child.expect("Pdb")
365
366 # INTERNALERROR is only displayed once via terminal reporter.
367 assert (
368 len(
369 [
370 x
371 for x in child.before.decode().splitlines()
372 if x.startswith("INTERNALERROR> Traceback")
373 ]
374 )
375 == 1
376 )
377
378 child.sendeof()
379 self.flush(child)
380
381 def test_pdb_prevent_ConftestImportFailure_hiding_exception(
382 self, pytester: Pytester
383 ) -> None:
384 pytester.makepyfile("def test_func(): pass")
385 sub_dir = pytester.path.joinpath("ns")
386 sub_dir.mkdir()
387 sub_dir.joinpath("conftest").with_suffix(".py").write_text(
388 "import unknown", "utf-8"
389 )
390 sub_dir.joinpath("test_file").with_suffix(".py").write_text(
391 "def test_func(): pass", "utf-8"
392 )
393
394 result = pytester.runpytest_subprocess("--pdb", ".")
395 result.stdout.fnmatch_lines(["-> import unknown"])
396
397 @pytest.mark.xfail(reason="#10042", strict=False)
398 def test_pdb_interaction_capturing_simple(self, pytester: Pytester) -> None:
399 p1 = pytester.makepyfile(
400 """
401 import pytest
402 def test_1():
403 i = 0
404 print("hello17")
405 pytest.set_trace()
406 i == 1
407 assert 0
408 """
409 )
410 child = pytester.spawn_pytest(str(p1))
411 child.expect(r"test_1\(\)")
412 child.expect("i == 1")
413 child.expect("Pdb")
414 child.sendline("c")
415 rest = child.read().decode("utf-8")
416 assert "AssertionError" in rest
417 assert "1 failed" in rest
418 assert "def test_1" in rest
419 assert "hello17" in rest # out is captured
420 self.flush(child)
421
422 def test_pdb_set_trace_kwargs(self, pytester: Pytester) -> None:
423 p1 = pytester.makepyfile(
424 """
425 import pytest
426 def test_1():
427 i = 0
428 print("hello17")
429 pytest.set_trace(header="== my_header ==")
430 x = 3
431 assert 0
432 """
433 )
434 child = pytester.spawn_pytest(str(p1))
435 child.expect("== my_header ==")
436 assert "PDB set_trace" not in child.before.decode()
437 child.expect("Pdb")
438 child.sendline("c")
439 rest = child.read().decode("utf-8")
440 assert "1 failed" in rest
441 assert "def test_1" in rest
442 assert "hello17" in rest # out is captured
443 self.flush(child)
444
445 def test_pdb_set_trace_interception(self, pytester: Pytester) -> None:
446 p1 = pytester.makepyfile(
447 """
448 import pdb
449 def test_1():
450 pdb.set_trace()
451 """
452 )
453 child = pytester.spawn_pytest(str(p1))
454 child.expect("test_1")
455 child.expect("Pdb")
456 child.sendline("q")
457 rest = child.read().decode("utf8")
458 assert "no tests ran" in rest
459 assert "reading from stdin while output" not in rest
460 assert "BdbQuit" not in rest
461 self.flush(child)
462
463 def test_pdb_and_capsys(self, pytester: Pytester) -> None:
464 p1 = pytester.makepyfile(
465 """
466 import pytest
467 def test_1(capsys):
468 print("hello1")
469 pytest.set_trace()
470 """
471 )
472 child = pytester.spawn_pytest(str(p1))
473 child.expect("test_1")
474 child.send("capsys.readouterr()\n")
475 child.expect("hello1")
476 child.sendeof()
477 child.read()
478 self.flush(child)
479
480 def test_pdb_with_caplog_on_pdb_invocation(self, pytester: Pytester) -> None:
481 p1 = pytester.makepyfile(
482 """
483 def test_1(capsys, caplog):
484 import logging
485 logging.getLogger(__name__).warning("some_warning")
486 assert 0
487 """
488 )
489 child = pytester.spawn_pytest(f"--pdb {p1!s}")
490 child.send("caplog.record_tuples\n")
491 child.expect_exact(
492 "[('test_pdb_with_caplog_on_pdb_invocation', 30, 'some_warning')]"
493 )
494 child.sendeof()
495 child.read()
496 self.flush(child)
497
498 def test_set_trace_capturing_afterwards(self, pytester: Pytester) -> None:
499 p1 = pytester.makepyfile(
500 """
501 import pdb
502 def test_1():
503 pdb.set_trace()
504 def test_2():
505 print("hello")
506 assert 0
507 """
508 )
509 child = pytester.spawn_pytest(str(p1))
510 child.expect("test_1")
511 child.send("c\n")
512 child.expect("test_2")
513 child.expect("Captured")
514 child.expect("hello")
515 child.sendeof()
516 child.read()
517 self.flush(child)
518
519 def test_pdb_interaction_doctest(self, pytester: Pytester) -> None:
520 p1 = pytester.makepyfile(
521 """
522 def function_1():
523 '''
524 >>> i = 0
525 >>> assert i == 1
526 '''
527 """
528 )
529 child = pytester.spawn_pytest(f"--doctest-modules --pdb {p1}")
530 child.expect("Pdb")
531
532 assert "UNEXPECTED EXCEPTION: AssertionError()" in child.before.decode("utf8")
533
534 child.sendline("'i=%i.' % i")
535 child.expect("Pdb")
536 assert "\r\n'i=0.'\r\n" in child.before.decode("utf8")
537
538 child.sendeof()
539 rest = child.read().decode("utf8")
540 assert "! _pytest.outcomes.Exit: Quitting debugger !" in rest
541 assert "BdbQuit" not in rest
542 assert "1 failed" in rest
543 self.flush(child)
544
545 def test_doctest_set_trace_quit(self, pytester: Pytester) -> None:
546 p1 = pytester.makepyfile(
547 """
548 def function_1():
549 '''
550 >>> __import__('pdb').set_trace()
551 '''
552 """
553 )
554 # NOTE: does not use pytest.set_trace, but Python's patched pdb,
555 # therefore "-s" is required.
556 child = pytester.spawn_pytest(f"--doctest-modules --pdb -s {p1}")
557 child.expect("Pdb")
558 child.sendline("q")
559 rest = child.read().decode("utf8")
560
561 assert "! _pytest.outcomes.Exit: Quitting debugger !" in rest
562 assert "= no tests ran in" in rest
563 assert "BdbQuit" not in rest
564 assert "UNEXPECTED EXCEPTION" not in rest
565
566 @pytest.mark.xfail(reason="#10042", strict=False)
567 def test_pdb_interaction_capturing_twice(self, pytester: Pytester) -> None:
568 p1 = pytester.makepyfile(
569 """
570 import pytest
571 def test_1():
572 i = 0
573 print("hello17")
574 pytest.set_trace()
575 x = 3
576 print("hello18")
577 pytest.set_trace()
578 x = 4
579 assert 0
580 """
581 )
582 child = pytester.spawn_pytest(str(p1))
583 child.expect(r"PDB set_trace \(IO-capturing turned off\)")
584 child.expect("test_1")
585 child.expect("x = 3")
586 child.expect("Pdb")
587 child.sendline("c")
588 child.expect(r"PDB continue \(IO-capturing resumed\)")
589 child.expect(r"PDB set_trace \(IO-capturing turned off\)")
590 child.expect("x = 4")
591 child.expect("Pdb")
592 child.sendline("c")
593 child.expect("_ test_1 _")
594 child.expect("def test_1")
595 rest = child.read().decode("utf8")
596 assert "Captured stdout call" in rest
597 assert "hello17" in rest # out is captured
598 assert "hello18" in rest # out is captured
599 assert "1 failed" in rest
600 self.flush(child)
601
602 @pytest.mark.xfail(reason="#10042", strict=False)
603 def test_pdb_with_injected_do_debug(self, pytester: Pytester) -> None:
604 """Simulates pdbpp, which injects Pdb into do_debug, and uses
605 self.__class__ in do_continue.
606 """
607 p1 = pytester.makepyfile(
608 mytest="""
609 import pdb
610 import pytest
611
612 count_continue = 0
613
614 class CustomPdb(pdb.Pdb, object):
615 def do_debug(self, arg):
616 import sys
617 import types
618
619 do_debug_func = pdb.Pdb.do_debug
620
621 newglobals = do_debug_func.__globals__.copy()
622 newglobals['Pdb'] = self.__class__
623 orig_do_debug = types.FunctionType(
624 do_debug_func.__code__, newglobals,
625 do_debug_func.__name__, do_debug_func.__defaults__,
626 )
627 return orig_do_debug(self, arg)
628 do_debug.__doc__ = pdb.Pdb.do_debug.__doc__
629
630 def do_continue(self, *args, **kwargs):
631 global count_continue
632 count_continue += 1
633 return super(CustomPdb, self).do_continue(*args, **kwargs)
634
635 def foo():
636 print("print_from_foo")
637
638 def test_1():
639 i = 0
640 print("hello17")
641 pytest.set_trace()
642 x = 3
643 print("hello18")
644
645 assert count_continue == 2, "unexpected_failure: %d != 2" % count_continue
646 pytest.fail("expected_failure")
647 """
648 )
649 child = pytester.spawn_pytest(f"--pdbcls=mytest:CustomPdb {p1!s}")
650 child.expect(r"PDB set_trace \(IO-capturing turned off\)")
651 child.expect(r"\n\(Pdb")
652 child.sendline("debug foo()")
653 child.expect("ENTERING RECURSIVE DEBUGGER")
654 child.expect(r"\n\(\(Pdb")
655 child.sendline("c")
656 child.expect("LEAVING RECURSIVE DEBUGGER")
657 assert b"PDB continue" not in child.before
658 # No extra newline.
659 assert child.before.endswith(b"c\r\nprint_from_foo\r\n")
660
661 # set_debug should not raise outcomes. Exit, if used recursively.
662 child.sendline("debug 42")
663 child.sendline("q")
664 child.expect("LEAVING RECURSIVE DEBUGGER")
665 assert b"ENTERING RECURSIVE DEBUGGER" in child.before
666 assert b"Quitting debugger" not in child.before
667
668 child.sendline("c")
669 child.expect(r"PDB continue \(IO-capturing resumed\)")
670 rest = child.read().decode("utf8")
671 assert "hello17" in rest # out is captured
672 assert "hello18" in rest # out is captured
673 assert "1 failed" in rest
674 assert "Failed: expected_failure" in rest
675 assert "AssertionError: unexpected_failure" not in rest
676 self.flush(child)
677
678 def test_pdb_without_capture(self, pytester: Pytester) -> None:
679 p1 = pytester.makepyfile(
680 """
681 import pytest
682 def test_1():
683 pytest.set_trace()
684 """
685 )
686 child = pytester.spawn_pytest(f"-s {p1}")
687 child.expect(r">>> PDB set_trace >>>")
688 child.expect("Pdb")
689 child.sendline("c")
690 child.expect(r">>> PDB continue >>>")
691 child.expect("1 passed")
692 self.flush(child)
693
694 @pytest.mark.parametrize("capture_arg", ("", "-s", "-p no:capture"))
695 def test_pdb_continue_with_recursive_debug(
696 self, capture_arg, pytester: Pytester
697 ) -> None:
698 """Full coverage for do_debug without capturing.
699
700 This is very similar to test_pdb_interaction_continue_recursive in general,
701 but mocks out ``pdb.set_trace`` for providing more coverage.
702 """
703 p1 = pytester.makepyfile(
704 """
705 try:
706 input = raw_input
707 except NameError:
708 pass
709
710 def set_trace():
711 __import__('pdb').set_trace()
712
713 def test_1(monkeypatch):
714 import _pytest.debugging
715
716 class pytestPDBTest(_pytest.debugging.pytestPDB):
717 @classmethod
718 def set_trace(cls, *args, **kwargs):
719 # Init PytestPdbWrapper to handle capturing.
720 _pdb = cls._init_pdb("set_trace", *args, **kwargs)
721
722 # Mock out pdb.Pdb.do_continue.
723 import pdb
724 pdb.Pdb.do_continue = lambda self, arg: None
725
726 print("===" + " SET_TRACE ===")
727 assert input() == "debug set_trace()"
728
729 # Simulate PytestPdbWrapper.do_debug
730 cls._recursive_debug += 1
731 print("ENTERING RECURSIVE DEBUGGER")
732 print("===" + " SET_TRACE_2 ===")
733
734 assert input() == "c"
735 _pdb.do_continue("")
736 print("===" + " SET_TRACE_3 ===")
737
738 # Simulate PytestPdbWrapper.do_debug
739 print("LEAVING RECURSIVE DEBUGGER")
740 cls._recursive_debug -= 1
741
742 print("===" + " SET_TRACE_4 ===")
743 assert input() == "c"
744 _pdb.do_continue("")
745
746 def do_continue(self, arg):
747 print("=== do_continue")
748
749 monkeypatch.setattr(_pytest.debugging, "pytestPDB", pytestPDBTest)
750
751 import pdb
752 monkeypatch.setattr(pdb, "set_trace", pytestPDBTest.set_trace)
753
754 set_trace()
755 """
756 )
757 child = pytester.spawn_pytest(f"--tb=short {p1} {capture_arg}")
758 child.expect("=== SET_TRACE ===")
759 before = child.before.decode("utf8")
760 if not capture_arg:
761 assert ">>> PDB set_trace (IO-capturing turned off) >>>" in before
762 else:
763 assert ">>> PDB set_trace >>>" in before
764 child.sendline("debug set_trace()")
765 child.expect("=== SET_TRACE_2 ===")
766 before = child.before.decode("utf8")
767 assert "\r\nENTERING RECURSIVE DEBUGGER\r\n" in before
768 child.sendline("c")
769 child.expect("=== SET_TRACE_3 ===")
770
771 # No continue message with recursive debugging.
772 before = child.before.decode("utf8")
773 assert ">>> PDB continue " not in before
774
775 child.sendline("c")
776 child.expect("=== SET_TRACE_4 ===")
777 before = child.before.decode("utf8")
778 assert "\r\nLEAVING RECURSIVE DEBUGGER\r\n" in before
779 child.sendline("c")
780 rest = child.read().decode("utf8")
781 if not capture_arg:
782 assert "> PDB continue (IO-capturing resumed) >" in rest
783 else:
784 assert "> PDB continue >" in rest
785 assert "= 1 passed in" in rest
786
787 def test_pdb_used_outside_test(self, pytester: Pytester) -> None:
788 p1 = pytester.makepyfile(
789 """
790 import pytest
791 pytest.set_trace()
792 x = 5
793 """
794 )
795 if sys.version_info[:2] >= (3, 13):
796 break_line = "pytest.set_trace()"
797 else:
798 break_line = "x = 5"
799 child = pytester.spawn(f"{sys.executable} {p1}")
800 child.expect_exact(break_line)
801 child.expect_exact("Pdb")
802 child.sendeof()
803 self.flush(child)
804
805 def test_pdb_used_in_generate_tests(self, pytester: Pytester) -> None:
806 p1 = pytester.makepyfile(
807 """
808 import pytest
809 def pytest_generate_tests(metafunc):
810 pytest.set_trace()
811 x = 5
812 def test_foo(a):
813 pass
814 """
815 )
816 if sys.version_info[:2] >= (3, 13):
817 break_line = "pytest.set_trace()"
818 else:
819 break_line = "x = 5"
820 child = pytester.spawn_pytest(str(p1))
821 child.expect_exact(break_line)
822 child.expect_exact("Pdb")
823 child.sendeof()
824 self.flush(child)
825
826 def test_pdb_collection_failure_is_shown(self, pytester: Pytester) -> None:
827 p1 = pytester.makepyfile("xxx")
828 result = pytester.runpytest_subprocess("--pdb", p1)
829 result.stdout.fnmatch_lines(
830 ["E NameError: *xxx*", "*! *Exit: Quitting debugger !*"] # due to EOF
831 )
832
833 @pytest.mark.parametrize("post_mortem", (False, True))
834 def test_enter_leave_pdb_hooks_are_called(
835 self, post_mortem, pytester: Pytester
836 ) -> None:
837 pytester.makeconftest(
838 """
839 mypdb = None
840
841 def pytest_configure(config):
842 config.testing_verification = 'configured'
843
844 def pytest_enter_pdb(config, pdb):
845 assert config.testing_verification == 'configured'
846 print('enter_pdb_hook')
847
848 global mypdb
849 mypdb = pdb
850 mypdb.set_attribute = "bar"
851
852 def pytest_leave_pdb(config, pdb):
853 assert config.testing_verification == 'configured'
854 print('leave_pdb_hook')
855
856 global mypdb
857 assert mypdb is pdb
858 assert mypdb.set_attribute == "bar"
859 """
860 )
861 p1 = pytester.makepyfile(
862 """
863 import pytest
864
865 def test_set_trace():
866 pytest.set_trace()
867 assert 0
868
869 def test_post_mortem():
870 assert 0
871 """
872 )
873 if post_mortem:
874 child = pytester.spawn_pytest(str(p1) + " --pdb -s -k test_post_mortem")
875 else:
876 child = pytester.spawn_pytest(str(p1) + " -k test_set_trace")
877 child.expect("enter_pdb_hook")
878 child.sendline("c")
879 if post_mortem:
880 child.expect(r"PDB continue")
881 else:
882 child.expect(r"PDB continue \(IO-capturing resumed\)")
883 child.expect("Captured stdout call")
884 rest = child.read().decode("utf8")
885 assert "leave_pdb_hook" in rest
886 assert "1 failed" in rest
887 self.flush(child)
888
889 def test_pdb_custom_cls(
890 self, pytester: Pytester, custom_pdb_calls: list[str]
891 ) -> None:
892 p1 = pytester.makepyfile("""xxx """)
893 result = pytester.runpytest_inprocess(
894 "--pdb", "--pdbcls=_pytest:_CustomPdb", p1
895 )
896 result.stdout.fnmatch_lines(["*NameError*xxx*", "*1 error*"])
897 assert custom_pdb_calls == ["init", "reset", "interaction"]
898
899 def test_pdb_custom_cls_invalid(self, pytester: Pytester) -> None:
900 result = pytester.runpytest_inprocess("--pdbcls=invalid")
901 result.stderr.fnmatch_lines(
902 [
903 "*: error: argument --pdbcls: 'invalid' is not in the format 'modname:classname'"
904 ]
905 )
906
907 def test_pdb_validate_usepdb_cls(self):
908 assert _validate_usepdb_cls("os.path:dirname.__name__") == (
909 "os.path",
910 "dirname.__name__",
911 )
912
913 assert _validate_usepdb_cls("pdb:DoesNotExist") == ("pdb", "DoesNotExist")
914
915 def test_pdb_custom_cls_without_pdb(
916 self, pytester: Pytester, custom_pdb_calls: list[str]
917 ) -> None:
918 p1 = pytester.makepyfile("""xxx """)
919 result = pytester.runpytest_inprocess("--pdbcls=_pytest:_CustomPdb", p1)
920 result.stdout.fnmatch_lines(["*NameError*xxx*", "*1 error*"])
921 assert custom_pdb_calls == []
922
923 def test_pdb_custom_cls_with_set_trace(
924 self,
925 pytester: Pytester,
926 monkeypatch: MonkeyPatch,
927 ) -> None:
928 pytester.makepyfile(
929 custom_pdb="""
930 class CustomPdb(object):
931 def __init__(self, *args, **kwargs):
932 skip = kwargs.pop("skip")
933 assert skip == ["foo.*"]
934 print("__init__")
935 super(CustomPdb, self).__init__(*args, **kwargs)
936
937 def set_trace(*args, **kwargs):
938 print('custom set_trace>')
939 """
940 )
941 p1 = pytester.makepyfile(
942 """
943 import pytest
944
945 def test_foo():
946 pytest.set_trace(skip=['foo.*'])
947 """
948 )
949 monkeypatch.setenv("PYTHONPATH", str(pytester.path))
950 child = pytester.spawn_pytest(f"--pdbcls=custom_pdb:CustomPdb {p1!s}")
951
952 child.expect("__init__")
953 child.expect("custom set_trace>")
954 self.flush(child)
955
956 @pytest.mark.skipif(
957 sys.version_info < (3, 13),
958 reason="Navigating exception chains was introduced in 3.13",
959 )
960 def test_pdb_exception_chain_navigation(self, pytester: Pytester) -> None:
961 p1 = pytester.makepyfile(
962 """
963 def inner_raise():
964 is_inner = True
965 raise RuntimeError("Woops")
966
967 def outer_raise():
968 is_inner = False
969 try:
970 inner_raise()
971 except RuntimeError:
972 raise RuntimeError("Woopsie")
973
974 def test_1():
975 outer_raise()
976 assert True
977 """
978 )
979 child = pytester.spawn_pytest(f"--pdb {p1}")
980 child.expect("Pdb")
981 child.sendline("is_inner")
982 child.expect_exact("False")
983 child.sendline("exceptions 0")
984 child.sendline("is_inner")
985 child.expect_exact("True")
986 child.sendeof()
987 self.flush(child)
988
989 def test_pdb_wrapped_commands_docstrings(self, pytester: Pytester) -> None:
990 p1 = pytester.makepyfile(
991 """
992 def test_1():
993 assert False
994 """
995 )
996
997 child = pytester.spawn_pytest(f"--pdb {p1}")
998 child.expect("Pdb")
999
1000 # Verify no undocumented commands
1001 child.sendline("help")
1002 child.expect("Documented commands")
1003 assert "Undocumented commands" not in child.before.decode()
1004
1005 child.sendline("help continue")
1006 child.expect("Continue execution")
1007 child.expect("Pdb")
1008
1009 child.sendline("help debug")
1010 child.expect("Enter a recursive debugger")
1011 child.expect("Pdb")
1012
1013 child.sendline("c")
1014 child.sendeof()
1015 self.flush(child)
1016
1017
1018 class TestDebuggingBreakpoints:
1019 @pytest.mark.parametrize("arg", ["--pdb", ""])
1020 def test_sys_breakpointhook_configure_and_unconfigure(
1021 self, pytester: Pytester, arg: str
1022 ) -> None:
1023 """
1024 Test that sys.breakpointhook is set to the custom Pdb class once configured, test that
1025 hook is reset to system value once pytest has been unconfigured
1026 """
1027 pytester.makeconftest(
1028 """
1029 import sys
1030 from pytest import hookimpl
1031 from _pytest.debugging import pytestPDB
1032
1033 def pytest_configure(config):
1034 config.add_cleanup(check_restored)
1035
1036 def check_restored():
1037 assert sys.breakpointhook == sys.__breakpointhook__
1038
1039 def test_check():
1040 assert sys.breakpointhook == pytestPDB.set_trace
1041 """
1042 )
1043 pytester.makepyfile(
1044 """
1045 def test_nothing(): pass
1046 """
1047 )
1048 args = (arg,) if arg else ()
1049 result = pytester.runpytest_subprocess(*args)
1050 result.stdout.fnmatch_lines(["*1 passed in *"])
1051
1052 def test_pdb_custom_cls(
1053 self, pytester: Pytester, custom_debugger_hook, monkeypatch: MonkeyPatch
1054 ) -> None:
1055 monkeypatch.delenv("PYTHONBREAKPOINT", raising=False)
1056 p1 = pytester.makepyfile(
1057 """
1058 def test_nothing():
1059 breakpoint()
1060 """
1061 )
1062 result = pytester.runpytest_inprocess(
1063 "--pdb", "--pdbcls=_pytest:_CustomDebugger", p1
1064 )
1065 result.stdout.fnmatch_lines(["*CustomDebugger*", "*1 passed*"])
1066 assert custom_debugger_hook == ["init", "set_trace"]
1067
1068 @pytest.mark.parametrize("arg", ["--pdb", ""])
1069 def test_environ_custom_class(
1070 self, pytester: Pytester, custom_debugger_hook, arg: str
1071 ) -> None:
1072 pytester.makeconftest(
1073 """
1074 import os
1075 import sys
1076
1077 os.environ['PYTHONBREAKPOINT'] = '_pytest._CustomDebugger.set_trace'
1078
1079 def pytest_configure(config):
1080 config.add_cleanup(check_restored)
1081
1082 def check_restored():
1083 assert sys.breakpointhook == sys.__breakpointhook__
1084
1085 def test_check():
1086 import _pytest
1087 assert sys.breakpointhook is _pytest._CustomDebugger.set_trace
1088 """
1089 )
1090 pytester.makepyfile(
1091 """
1092 def test_nothing(): pass
1093 """
1094 )
1095 args = (arg,) if arg else ()
1096 result = pytester.runpytest_subprocess(*args)
1097 result.stdout.fnmatch_lines(["*1 passed in *"])
1098
1099 def test_sys_breakpoint_interception(
1100 self, pytester: Pytester, monkeypatch: MonkeyPatch
1101 ) -> None:
1102 monkeypatch.delenv("PYTHONBREAKPOINT", raising=False)
1103 p1 = pytester.makepyfile(
1104 """
1105 def test_1():
1106 breakpoint()
1107 """
1108 )
1109 child = pytester.spawn_pytest(str(p1))
1110 child.expect("test_1")
1111 child.expect("Pdb")
1112 child.sendline("quit")
1113 rest = child.read().decode("utf8")
1114 assert "Quitting debugger" in rest
1115 assert "reading from stdin while output" not in rest
1116 TestPDB.flush(child)
1117
1118 @pytest.mark.xfail(reason="#10042", strict=False)
1119 def test_pdb_not_altered(self, pytester: Pytester) -> None:
1120 p1 = pytester.makepyfile(
1121 """
1122 import pdb
1123 def test_1():
1124 pdb.set_trace()
1125 assert 0
1126 """
1127 )
1128 child = pytester.spawn_pytest(str(p1))
1129 child.expect("test_1")
1130 child.expect("Pdb")
1131 child.sendline("c")
1132 rest = child.read().decode("utf8")
1133 assert "1 failed" in rest
1134 assert "reading from stdin while output" not in rest
1135 TestPDB.flush(child)
1136
1137
1138 class TestTraceOption:
1139 def test_trace_sets_breakpoint(self, pytester: Pytester) -> None:
1140 p1 = pytester.makepyfile(
1141 """
1142 def test_1():
1143 assert True
1144
1145 def test_2():
1146 pass
1147
1148 def test_3():
1149 pass
1150 """
1151 )
1152 child = pytester.spawn_pytest("--trace " + str(p1))
1153 child.expect("test_1")
1154 child.expect("Pdb")
1155 child.sendline("c")
1156 child.expect("test_2")
1157 child.expect("Pdb")
1158 child.sendline("c")
1159 child.expect("test_3")
1160 child.expect("Pdb")
1161 child.sendline("q")
1162 child.expect_exact("Exit: Quitting debugger")
1163 rest = child.read().decode("utf8")
1164 assert "= 2 passed in" in rest
1165 assert "reading from stdin while output" not in rest
1166 # Only printed once - not on stderr.
1167 assert "Exit: Quitting debugger" not in child.before.decode("utf8")
1168 TestPDB.flush(child)
1169
1170 def test_trace_with_parametrize_handles_shared_fixtureinfo(
1171 self, pytester: Pytester
1172 ) -> None:
1173 p1 = pytester.makepyfile(
1174 """
1175 import pytest
1176 @pytest.mark.parametrize('myparam', [1,2])
1177 def test_1(myparam, request):
1178 assert myparam in (1, 2)
1179 assert request.function.__name__ == "test_1"
1180 @pytest.mark.parametrize('func', [1,2])
1181 def test_func(func, request):
1182 assert func in (1, 2)
1183 assert request.function.__name__ == "test_func"
1184 @pytest.mark.parametrize('myparam', [1,2])
1185 def test_func_kw(myparam, request, func="func_kw"):
1186 assert myparam in (1, 2)
1187 assert func == "func_kw"
1188 assert request.function.__name__ == "test_func_kw"
1189 """
1190 )
1191 child = pytester.spawn_pytest("--trace " + str(p1))
1192 for func, argname in [
1193 ("test_1", "myparam"),
1194 ("test_func", "func"),
1195 ("test_func_kw", "myparam"),
1196 ]:
1197 child.expect_exact("> PDB runcall (IO-capturing turned off) >")
1198 child.expect_exact(func)
1199 child.expect_exact("Pdb")
1200 child.sendline("args")
1201 child.expect_exact(f"{argname} = 1\r\n")
1202 child.expect_exact("Pdb")
1203 child.sendline("c")
1204 child.expect_exact("Pdb")
1205 child.sendline("args")
1206 child.expect_exact(f"{argname} = 2\r\n")
1207 child.expect_exact("Pdb")
1208 child.sendline("c")
1209 child.expect_exact("> PDB continue (IO-capturing resumed) >")
1210 rest = child.read().decode("utf8")
1211 assert "= 6 passed in" in rest
1212 assert "reading from stdin while output" not in rest
1213 # Only printed once - not on stderr.
1214 assert "Exit: Quitting debugger" not in child.before.decode("utf8")
1215 TestPDB.flush(child)
1216
1217
1218 def test_trace_after_runpytest(pytester: Pytester) -> None:
1219 """Test that debugging's pytest_configure is reentrant."""
1220 p1 = pytester.makepyfile(
1221 """
1222 from _pytest.debugging import pytestPDB
1223
1224 def test_outer(pytester) -> None:
1225 assert len(pytestPDB._saved) == 1
1226
1227 pytester.makepyfile(
1228 \"""
1229 from _pytest.debugging import pytestPDB
1230
1231 def test_inner():
1232 assert len(pytestPDB._saved) == 2
1233 print()
1234 print("test_inner_" + "end")
1235 \"""
1236 )
1237
1238 result = pytester.runpytest("-s", "-k", "test_inner")
1239 assert result.ret == 0
1240
1241 assert len(pytestPDB._saved) == 1
1242 """
1243 )
1244 result = pytester.runpytest_subprocess("-s", "-p", "pytester", str(p1))
1245 result.stdout.fnmatch_lines(["test_inner_end"])
1246 assert result.ret == 0
1247
1248
1249 def test_quit_with_swallowed_SystemExit(pytester: Pytester) -> None:
1250 """Test that debugging's pytest_configure is reentrant."""
1251 p1 = pytester.makepyfile(
1252 """
1253 def call_pdb_set_trace():
1254 __import__('pdb').set_trace()
1255
1256
1257 def test_1():
1258 try:
1259 call_pdb_set_trace()
1260 except SystemExit:
1261 pass
1262
1263
1264 def test_2():
1265 pass
1266 """
1267 )
1268 child = pytester.spawn_pytest(str(p1))
1269 child.expect("Pdb")
1270 child.sendline("q")
1271 child.expect_exact("Exit: Quitting debugger")
1272 rest = child.read().decode("utf8")
1273 assert "no tests ran" in rest
1274 TestPDB.flush(child)
1275
1276
1277 @pytest.mark.parametrize("fixture", ("capfd", "capsys"))
1278 @pytest.mark.xfail(reason="#10042", strict=False)
1279 def test_pdb_suspends_fixture_capturing(pytester: Pytester, fixture: str) -> None:
1280 """Using "-s" with pytest should suspend/resume fixture capturing."""
1281 p1 = pytester.makepyfile(
1282 f"""
1283 def test_inner({fixture}):
1284 import sys
1285
1286 print("out_inner_before")
1287 sys.stderr.write("err_inner_before\\n")
1288
1289 __import__("pdb").set_trace()
1290
1291 print("out_inner_after")
1292 sys.stderr.write("err_inner_after\\n")
1293
1294 out, err = {fixture}.readouterr()
1295 assert out =="out_inner_before\\nout_inner_after\\n"
1296 assert err =="err_inner_before\\nerr_inner_after\\n"
1297 """
1298 )
1299
1300 child = pytester.spawn_pytest(str(p1) + " -s")
1301
1302 child.expect("Pdb")
1303 before = child.before.decode("utf8")
1304 assert (
1305 f"> PDB set_trace (IO-capturing turned off for fixture {fixture}) >" in before
1306 )
1307
1308 # Test that capturing is really suspended.
1309 child.sendline("p 40 + 2")
1310 child.expect("Pdb")
1311 assert "\r\n42\r\n" in child.before.decode("utf8")
1312
1313 child.sendline("c")
1314 rest = child.read().decode("utf8")
1315 assert "out_inner" not in rest
1316 assert "err_inner" not in rest
1317
1318 TestPDB.flush(child)
1319 assert child.exitstatus == 0
1320 assert "= 1 passed in" in rest
1321 assert f"> PDB continue (IO-capturing resumed for fixture {fixture}) >" in rest
1322
1323
1324 def test_pdbcls_via_local_module(pytester: Pytester) -> None:
1325 """It should be imported in pytest_configure or later only."""
1326 p1 = pytester.makepyfile(
1327 """
1328 def test():
1329 print("before_set_trace")
1330 __import__("pdb").set_trace()
1331 """,
1332 mypdb="""
1333 class Wrapped:
1334 class MyPdb:
1335 def set_trace(self, *args):
1336 print("set_trace_called", args)
1337
1338 def runcall(self, *args, **kwds):
1339 print("runcall_called", args, kwds)
1340
1341 # Methods which we copy the docstring over.
1342 def do_debug(self, *args):
1343 pass
1344
1345 def do_continue(self, *args):
1346 pass
1347
1348 def do_quit(self, *args):
1349 pass
1350 """,
1351 )
1352 result = pytester.runpytest(
1353 str(p1), "--pdbcls=really.invalid:Value", syspathinsert=True
1354 )
1355 result.stdout.fnmatch_lines(
1356 [
1357 "*= FAILURES =*",
1358 "E * --pdbcls: could not import 'really.invalid:Value': No module named *really*",
1359 ]
1360 )
1361 assert result.ret == 1
1362
1363 result = pytester.runpytest(
1364 str(p1), "--pdbcls=mypdb:Wrapped.MyPdb", syspathinsert=True
1365 )
1366 assert result.ret == 0
1367 result.stdout.fnmatch_lines(["*set_trace_called*", "* 1 passed in *"])
1368
1369 # Ensure that it also works with --trace.
1370 result = pytester.runpytest(
1371 str(p1), "--pdbcls=mypdb:Wrapped.MyPdb", "--trace", syspathinsert=True
1372 )
1373 assert result.ret == 0
1374 result.stdout.fnmatch_lines(["*runcall_called*", "* 1 passed in *"])
1375
1376
1377 @pytest.mark.xfail(
1378 sys.version_info >= (3, 14),
1379 reason="C-D now quits the test session, rather than failing the test. See https://github.com/python/cpython/issues/124703",
1380 )
1381 def test_raises_bdbquit_with_eoferror(pytester: Pytester) -> None:
1382 """It is not guaranteed that DontReadFromInput's read is called."""
1383 p1 = pytester.makepyfile(
1384 """
1385 def input_without_read(*args, **kwargs):
1386 raise EOFError()
1387
1388 def test(monkeypatch):
1389 import builtins
1390 monkeypatch.setattr(builtins, "input", input_without_read)
1391 __import__('pdb').set_trace()
1392 """
1393 )
1394 result = pytester.runpytest(str(p1))
1395 result.assert_outcomes(failed=1)
1396 result.stdout.fnmatch_lines(["E *BdbQuit", "*= 1 failed in*"])
1397 assert result.ret == 1
1398
1399
1400 def test_pdb_wrapper_class_is_reused(pytester: Pytester) -> None:
1401 p1 = pytester.makepyfile(
1402 """
1403 def test():
1404 __import__("pdb").set_trace()
1405 __import__("pdb").set_trace()
1406
1407 import mypdb
1408 instances = mypdb.instances
1409 assert len(instances) == 2
1410 assert instances[0].__class__ is instances[1].__class__
1411 """,
1412 mypdb="""
1413 instances = []
1414
1415 class MyPdb:
1416 def __init__(self, *args, **kwargs):
1417 instances.append(self)
1418
1419 def set_trace(self, *args):
1420 print("set_trace_called", args)
1421
1422 # Methods which we copy the docstring over.
1423 def do_debug(self, *args):
1424 pass
1425
1426 def do_continue(self, *args):
1427 pass
1428
1429 def do_quit(self, *args):
1430 pass
1431 """,
1432 )
1433 result = pytester.runpytest(str(p1), "--pdbcls=mypdb:MyPdb", syspathinsert=True)
1434 assert result.ret == 0
1435 result.stdout.fnmatch_lines(
1436 ["*set_trace_called*", "*set_trace_called*", "* 1 passed in *"]
1437 )