Skip to content

Commit 0e70f06

Browse files
committed
Printing error when OSError other than FileNotFoundError occurs when deleting persistent history file with history --clear command.
1 parent 7f76e23 commit 0e70f06

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

cmd2/cmd2.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3993,6 +3993,9 @@ def do_history(self, args: argparse.Namespace) -> Optional[bool]:
39933993
os.remove(self.persistent_history_file)
39943994
except FileNotFoundError:
39953995
pass
3996+
except OSError as ex:
3997+
self.pexcept("Error removing history file '{}': {}".format(self.persistent_history_file, ex))
3998+
return
39963999

39974000
if rl_type != RlType.NONE:
39984001
readline.clear_history()

tests/test_history.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -520,7 +520,7 @@ def test_history_run_one_command(base_app):
520520
out2, err2 = run_cmd(base_app, 'history -r 1')
521521
assert out1 == out2
522522

523-
def test_history_clear(hist_file):
523+
def test_history_clear(mocker, hist_file):
524524
# Add commands to history
525525
app = cmd2.Cmd(persistent_history_file=hist_file)
526526
run_cmd(app, 'help')
@@ -538,6 +538,17 @@ def test_history_clear(hist_file):
538538
assert out == []
539539
assert not os.path.exists(hist_file)
540540

541+
# Clear the history again and make sure the FileNotFoundError from trying to delete missing history file is silent
542+
run_cmd(app, 'history --clear')
543+
544+
# Cause os.remove to fail and make sure error gets printed
545+
mock_remove = mocker.patch('os.remove')
546+
mock_remove.side_effect = OSError
547+
548+
out, err = run_cmd(app, 'history --clear')
549+
assert out == []
550+
assert 'Error removing history file' in err[0]
551+
541552
def test_history_verbose_with_other_options(base_app):
542553
# make sure -v shows a usage error if any other options are present
543554
options_to_test = ['-r', '-e', '-o file', '-t file', '-c', '-x']

0 commit comments

Comments
 (0)