Skip to content
Myr

test_abort_interrupt.py

This file

Path

tests/test_abort_interrupt.py

179 lines · 5.2 KiB · Python

Last changed by

Stable (#3851)Rowlando13before adoption6aabf09

History of this file

Take it

Stable (#3851)Rowlando13before adoption6aabf09

lines 1–179why, one step back
1"""A second Ctrl-C while ``Command.main()`` reported an abort or an error used
2to escape as an unhandled traceback: the message and the exit both ran in3``except`` clauses, outside every ``try`` that caught ``KeyboardInterrupt``.4https://github.com/pallets/click/issues/380256The fix holds one policy, the one the pager has followed since7https://github.com/pallets/click/pull/351: a late interrupt must not replace8the intended outcome. In standalone mode the collected exit code wins, for9aborts, errors and success alike, and the message is best effort. Without10standalone mode the interrupt propagates to the caller. Two settled contracts11stay in place: the first interrupt reaches a non-standalone caller as12``Abort`` (https://github.com/pallets/click/pull/2380), and the ``Aborted!``13message stays as it is (declined in14https://github.com/pallets/click/issues/1447 and15https://github.com/pallets/click/issues/2584).16"""1718import sys1920import pytest2122import click232425class RecordingStderr:26 """A stderr stand-in that records what is written to it.2728 With ``interrupt_at=N``, the ``N``-th ``isatty()`` call raises29 ``KeyboardInterrupt``. ``echo()`` calls ``isatty()`` before writing, which30 is where the traceback in issue #3802 ended.31 """3233 def __init__(self, interrupt_at=None):34 self.text = ""35 self.interrupt_at = interrupt_at36 self.isatty_calls = 03738 def isatty(self):39 self.isatty_calls += 14041 if self.isatty_calls == self.interrupt_at:42 raise KeyboardInterrupt4344 return False4546 def write(self, value):47 self.text += value48 return len(value)4950 def flush(self):51 pass525354def _interrupt_prompt(text):55 """Stand in for ``input()`` when the user presses Ctrl-C at a prompt."""56 raise KeyboardInterrupt575859def _prompting_command():60 @click.command()61 @click.option("--name", prompt="Name")62 def cli(name):63 click.echo(name)6465 return cli666768def _interrupting_command():69 @click.command()70 def cli():71 raise KeyboardInterrupt7273 return cli747576def _exit_code(cli, stderr, monkeypatch):77 """Run *cli* in standalone mode and return its exit code."""78 monkeypatch.setattr(sys, "stderr", stderr)7980 try:81 cli.main([], "cli")82 except SystemExit as e:83 return e.code84 except KeyboardInterrupt:85 pytest.fail("KeyboardInterrupt escaped Command.main()")8687 pytest.fail("Command.main() returned without exiting")888990@pytest.mark.parametrize(91 ("source", "interrupt_at"),92 [("prompt", None), ("prompt", 1), ("body", None), ("body", 1), ("body", 2)],93)94def test_interrupt_while_reporting_abort(monkeypatch, source, interrupt_at):95 """Exit code 1 survives a second Ctrl-C; the message may not.9697 The counted ``isatty`` picks the window. A prompt converts the interrupt98 to ``Abort`` itself, so the only window left in ``Command.main()`` is the99 ``Aborted!`` message (``1``). An interrupt from the command body goes100 through the conversion in ``Command.main()``, which writes a blank line101 first (``1``), before the message (``2``).102 """103 if source == "prompt":104 monkeypatch.setattr("click.termui.visible_prompt_func", _interrupt_prompt)105 cli = _prompting_command()106 else:107 cli = _interrupting_command()108109 stderr = RecordingStderr(interrupt_at=interrupt_at)110111 assert _exit_code(cli, stderr, monkeypatch) == 1112113 if interrupt_at is None:114 assert "Aborted!" in stderr.text115116117def test_interrupt_while_reporting_error(monkeypatch):118 """A Ctrl-C while Click writes an error keeps the error's exit code."""119120 class InterruptedReport(click.ClickException):121 exit_code = 3122123 def show(self, file=None):124 raise KeyboardInterrupt125126 @click.command()127 def cli():128 raise InterruptedReport("boom")129130 assert _exit_code(cli, RecordingStderr(), monkeypatch) == 3131132133def test_late_interrupt_with_disabled_standalone_mode(monkeypatch):134 """Without standalone mode, a late interrupt reaches the caller, not exit 1.135136 The patched ``Abort`` raises a second ``KeyboardInterrupt`` from its137 constructor: it lands on the ``raise Abort() from e`` statement that138 ``Command.main()`` only runs for non-standalone callers.139 """140141 class InterruptedAbort(click.Abort):142 def __init__(self):143 raise KeyboardInterrupt144145 monkeypatch.setattr(click.core, "Abort", InterruptedAbort)146 cli = _interrupting_command()147 monkeypatch.setattr(sys, "stderr", RecordingStderr())148149 with pytest.raises(KeyboardInterrupt):150 cli.main([], "cli", standalone_mode=False)151152153def test_interrupt_while_exiting_after_success(monkeypatch):154 """A Ctrl-C while a successful exit propagates keeps exit code 0.155156 The uniform policy: the run completed before the interrupt arrived, so the157 intended outcome wins for success exactly as it does for aborts and158 errors.159 """160161 @click.command()162 def cli():163 click.echo("done")164165 real_exit = sys.exit166 codes = []167168 def interrupted_exit(code=None):169 codes.append(code)170171 if len(codes) == 1:172 raise KeyboardInterrupt173174 real_exit(code)175176 monkeypatch.setattr(sys, "exit", interrupted_exit)177178 assert _exit_code(cli, RecordingStderr(), monkeypatch) == 0179 assert codes == [0, 0]