Skip to content

Commit 8d611e0

Browse files
committed
Add unit tests for Ctrl-C stopping scripts/transcripts
1 parent 662a784 commit 8d611e0

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

tests/test_cmd2.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,28 @@ def test_runcmds_plus_hooks(base_app, request):
376376
out, err = run_cmd(base_app, 'history -s')
377377
assert out == normalize(expected)
378378

379+
def test_runcmds_plus_hooks_ctrl_c(base_app, capsys):
380+
"""Test Ctrl-C while in runcmds_plus_hooks"""
381+
import types
382+
383+
def do_keyboard_interrupt(self, _):
384+
raise KeyboardInterrupt('Interrupting this command')
385+
setattr(base_app, 'do_keyboard_interrupt', types.MethodType(do_keyboard_interrupt, base_app))
386+
387+
# Default behavior is to stop command loop on Ctrl-C
388+
base_app.history.clear()
389+
base_app.runcmds_plus_hooks(['help', 'keyboard_interrupt', 'shortcuts'])
390+
out, err = capsys.readouterr()
391+
assert err.startswith("Interrupting this command")
392+
assert len(base_app.history) == 2
393+
394+
# Ctrl-C should not stop command loop in this case
395+
base_app.history.clear()
396+
base_app.runcmds_plus_hooks(['help', 'keyboard_interrupt', 'shortcuts'], stop_on_keyboard_interrupt=False)
397+
out, err = capsys.readouterr()
398+
assert not err
399+
assert len(base_app.history) == 3
400+
379401
def test_relative_run_script(base_app, request):
380402
test_dir = os.path.dirname(request.module.__file__)
381403
filename = os.path.join(test_dir, 'script.txt')

tests/test_transcript.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,9 @@ def do_nothing(self, statement):
8181
"""Do nothing and output nothing"""
8282
pass
8383

84+
def do_keyboard_interrupt(self, _):
85+
raise KeyboardInterrupt('Interrupting this command')
86+
8487

8588
def test_commands_at_invocation():
8689
testargs = ["prog", "say hello", "say Gracie", "quit"]
@@ -235,6 +238,12 @@ def test_generate_transcript_stop(capsys):
235238
_, err = capsys.readouterr()
236239
assert err.startswith("Command 2 triggered a stop")
237240

241+
# keyboard_interrupt command should stop the loop and not run the third command
242+
commands = ['help', 'keyboard_interrupt', 'set']
243+
app._generate_transcript(commands, transcript_fname)
244+
_, err = capsys.readouterr()
245+
assert err.startswith("Interrupting this command\nCommand 2 triggered a stop")
246+
238247

239248
@pytest.mark.parametrize('expected, transformed', [
240249
# strings with zero or one slash or with escaped slashes means no regular

0 commit comments

Comments
 (0)