Skip to content
Myr

Patch `pdb` in `CliRunner` to allow debugger interactions in tests

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Fixes #654, #824, #843 and #951

authored by Kevin Deldycke · committed by Kevin Deldycke · parent 1339fd3 · Browse files · 4 files+100 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+100 added−0 removed

  • tests:+50 added−0 removed
  • other:+50 added−0 removed

4 files+100 added−0 removed

modified:src/click/testing.py+45 added
2 unmodified lines
3import collections.abc as cabc4import contextlib5import io6import os7import pdb8import shlex9import sys10import tempfile11import typing as t
378 unmodified lines
390 old_hidden_prompt_func = termui.hidden_prompt_func391 old__getchar_func = termui._getchar392 old_should_strip_ansi = utils.should_strip_ansi # type: ignore393 old__compat_should_strip_ansi = _compat.should_strip_ansi394 old_pdb_init = pdb.Pdb.__init__395 termui.visible_prompt_func = visible_input396 termui.hidden_prompt_func = hidden_input397 termui._getchar = _getchar398 utils.should_strip_ansi = should_strip_ansi # type: ignore399 _compat.should_strip_ansi = should_strip_ansi400401 def _patched_pdb_init(402 self: pdb.Pdb,403 completekey: str = "tab",404 stdin: t.IO[str] | None = None,405 stdout: t.IO[str] | None = None,406 **kwargs: t.Any,407 ) -> None:408 """Default ``pdb.Pdb`` to real terminal streams during409 ``CliRunner`` isolation.410411 Without this patch, ``pdb.Pdb.__init__`` inherits from412 ``cmd.Cmd`` which falls back to ``sys.stdin``/``sys.stdout``413 when no explicit streams are provided. During isolation414 those are ``BytesIO``-backed wrappers, so the debugger415 reads from an empty buffer and writes to captured output,416 making interactive debugging impossible.417418 By defaulting to ``sys.__stdin__``/``sys.__stdout__`` (the419 original terminal streams Python preserves regardless of420 redirection), debuggers can interact with the user while421 ``click.echo`` output is still captured normally.422423 This covers ``pdb.set_trace()``, ``breakpoint()``,424 ``pdb.post_mortem()``, and debuggers that subclass425 ``pdb.Pdb`` (ipdb, pdbpp). Explicit ``stdin``/``stdout``426 arguments are honored and not overridden. Debuggers that427 do not subclass ``pdb.Pdb`` (pudb, debugpy) are not428 covered.429430 See: https://github.com/pallets/click/issues/654 and431 https://github.com/pallets/click/issues/824432 """433 if stdin is None:434 stdin = sys.__stdin__435 if stdout is None:436 stdout = sys.__stdout__437 old_pdb_init(438 self, completekey=completekey, stdin=stdin, stdout=stdout, **kwargs439 )440441 pdb.Pdb.__init__ = _patched_pdb_init # type: ignore[assignment]442443 old_env = {}444 try:445 for key, value in env.items():446 old_env[key] = os.environ.get(key)
22 unmodified lines
469 termui._getchar = old__getchar_func470 utils.should_strip_ansi = old_should_strip_ansi # type: ignore471 _compat.should_strip_ansi = old__compat_should_strip_ansi472 formatting.FORCED_WIDTH = old_forced_width473 pdb.Pdb.__init__ = old_pdb_init # type: ignore[method-assign]474475 def invoke(476 self,477 cli: Command,
142 unmodified lines
modified:tests/test_testing.py+50 added
1import os2import pdb3import sys4from io import BytesIO56import pytest
462 unmodified lines
469 print("gyarados gyarados gyarados", file=sys.stderr, end="", flush=False)470471 result = runner.invoke(cli)472 assert result.stderr == "gyarados gyarados gyarados"473474475def test_pdb_uses_real_streams():476 """``pdb.Pdb()`` inside ``CliRunner`` defaults to real terminal streams477 so that interactive debuggers work instead of reading from the478 captured ``BytesIO`` stdin.479 """480481 @click.command()482 def cli():483 debugger = pdb.Pdb()484 assert debugger.stdin is sys.__stdin__485 assert debugger.stdout is sys.__stdout__486 click.echo("after debugger")487488 runner = CliRunner()489 result = runner.invoke(cli, catch_exceptions=False)490 assert result.output == "after debugger\n"491492493def test_pdb_explicit_streams_honored():494 """Explicit ``stdin``/``stdout`` arguments to ``pdb.Pdb()`` are not495 overridden by the ``CliRunner`` patch.496 """497498 @click.command()499 def cli():500 custom_in = sys.stdin501 custom_out = sys.stdout502 debugger = pdb.Pdb(stdin=custom_in, stdout=custom_out)503 assert debugger.stdin is custom_in504 assert debugger.stdout is custom_out505506 runner = CliRunner()507 runner.invoke(cli, catch_exceptions=False)508509510def test_pdb_init_restored_after_invoke():511 """``pdb.Pdb.__init__`` is restored to its original after invoke."""512 original = pdb.Pdb.__init__513514 @click.command()515 def cli():516 pass517518 runner = CliRunner()519 runner.invoke(cli)520521 assert pdb.Pdb.__init__ is original
modified:.pre-commit-config.yaml+1 added
modified:CHANGES.rst+4 added
11 unmodified lines
12 an object that doesn't support equality comparison with strings, such as13 ``semver.Version``. :issue:`3298` :pr:`3299`14- Fix pager test pollution under parallel execution by using pytest's15 ``tmp_path`` fixture instead of a shared temporary file path. :pr:`3238`16- Patch ``pdb.Pdb`` in ``CliRunner`` isolation so ``pdb.set_trace()``,17 ``breakpoint()``, and debuggers subclassing ``pdb.Pdb`` (ipdb, pdbpp) can18 interact with the real terminal instead of the captured I/O streams.19 :issue:`654` :issue:`824` :issue:`843` :pr:`951` :pr:`3235`2021Version 8.3.222-------------23
1323 unmodified lines