Skip to content

Commit ba6c5ed

Browse files
committed
Cleanup some history tests
1 parent 297af34 commit ba6c5ed

File tree

2 files changed

+41
-25
lines changed

2 files changed

+41
-25
lines changed

cmd2/cmd2.py

Lines changed: 38 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,10 @@ def __init__(self, completekey: str = 'tab', stdin=None, stdout=None, persistent
403403
self.hidden_commands = ['eof', 'eos', '_relative_load']
404404

405405
# Commands to exclude from the history command
406+
# initialize history
407+
self.persistent_history_file = persistent_history_file
408+
self.persistent_history_length = persistent_history_length
409+
self._initialize_history()
406410
self.exclude_from_history = '''history edit eof eos'''.split()
407411

408412
# Command aliases and macros
@@ -463,9 +467,6 @@ def __init__(self, completekey: str = 'tab', stdin=None, stdout=None, persistent
463467
# If this string is non-empty, then this warning message will print if a broken pipe error occurs while printing
464468
self.broken_pipe_warning = ''
465469

466-
# initialize history
467-
self._initialize_history(persistent_history_file, persistent_history_length)
468-
469470
# If a startup script is provided, then add it in the queue to load
470471
if startup_script is not None:
471472
startup_script = os.path.expanduser(startup_script)
@@ -3447,8 +3448,8 @@ def do_history(self, args: argparse.Namespace) -> None:
34473448
for hi in history:
34483449
self.poutput(hi.pr(script=args.script, expanded=args.expanded, verbose=args.verbose))
34493450

3450-
def _initialize_history(self, histfile, maxlen):
3451-
"""Initialize history with optional persistence and maximum length
3451+
def _initialize_history(self):
3452+
"""Initialize history using history related attributes
34523453
34533454
This function can determine whether history is saved in the prior text-based
34543455
format (one line of input is stored as one line in the file), or the new-as-
@@ -3461,38 +3462,57 @@ def _initialize_history(self, histfile, maxlen):
34613462
"""
34623463
self.history = History()
34633464
# with no persistent history, nothing else in this method is relevant
3464-
if not histfile:
3465+
if not self.persistent_history_file:
34653466
return
34663467

3467-
histfile = os.path.expanduser(histfile)
3468+
self.persistent_history_file = os.path.expanduser(self.persistent_history_file)
34683469

34693470
# first we try and unpickle the history file
34703471
history = History()
34713472
try:
3472-
with open(histfile, 'rb') as fobj:
3473+
with open(self.persistent_history_file, 'rb') as fobj:
34733474
history = pickle.load(fobj)
34743475
except (FileNotFoundError, KeyError, EOFError):
34753476
pass
3477+
except IsADirectoryError:
3478+
msg = "persistent history file '{}' is a directory"
3479+
self.perror(msg.format(self.persistent_history_file))
34763480
except OSError as ex:
34773481
msg = "can not read persistent history file '{}': {}"
3478-
self.perror(msg.format(histfile, ex), traceback_war=False)
3482+
self.perror(msg.format(self.persistent_history_file, ex), traceback_war=False)
3483+
3484+
self.history = history
34793485

34803486
# trim history to length and ensure it's writable
3481-
history.truncate(maxlen)
3482-
try:
3483-
# open with append so it doesn't truncate the file
3484-
with open(histfile, 'ab') as fobj:
3485-
self.persistent_history_file = histfile
3486-
except OSError as ex:
3487-
msg = "can not write persistent history file '{}': {}"
3488-
self.perror(msg.format(histfile, ex), traceback_war=False)
3487+
# history.truncate(maxlen)
3488+
# try:
3489+
# # open with append so it doesn't truncate the file
3490+
# with open(histfile, 'ab') as fobj:
3491+
# self.persistent_history_file = histfile
3492+
# except OSError as ex:
3493+
# msg = "can not write persistent history file '{}': {}"
3494+
# self.perror(msg.format(histfile, ex), traceback_war=False)
34893495

34903496
# register a function to write history at save
34913497
# if the history file is in plain text format from 0.9.12 or lower
34923498
# this will fail, and the history in the plain text file will be lost
34933499

34943500
#import atexit
3495-
#atexit.register(readline.write_history_file, self.persistent_history_file)
3501+
#atexit.register(self._persist_history_on_exit)
3502+
3503+
def _persist_history_on_exit(self):
3504+
"""write history out to the history file"""
3505+
if not self.persistent_history_file:
3506+
return
3507+
3508+
self.history.truncate(self.persistent_history_length)
3509+
try:
3510+
with open(self.persistent_history_file, 'wb') as fobj:
3511+
pickle.dump(self.history, fobj)
3512+
3513+
except OSError as ex:
3514+
msg = "can not write persistent history file '{}': {}"
3515+
self.perror(msg.format(self.persistent_history_file, ex), traceback_war=False)
34963516

34973517
def _generate_transcript(self, history: List[Union[HistoryItem, str]], transcript_file: str) -> None:
34983518
"""Generate a transcript file from a given history of commands."""

tests/test_history.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -398,8 +398,6 @@ def hist_file():
398398
pass
399399

400400
def test_existing_history_file(hist_file, capsys):
401-
import atexit
402-
import readline
403401

404402
# Create the history file before making cmd2 app
405403
with open(hist_file, 'w'):
@@ -416,11 +414,9 @@ def test_existing_history_file(hist_file, capsys):
416414
## TODO atexit.unregister(readline.write_history_file)
417415

418416
# Remove created history file
419-
os.remove(hist_file)
417+
#os.remove(hist_file)
420418

421419
def test_new_history_file(hist_file, capsys):
422-
import atexit
423-
import readline
424420

425421
# Remove any existing history file
426422
try:
@@ -439,7 +435,7 @@ def test_new_history_file(hist_file, capsys):
439435
### TODO atexit.unregister(readline.write_history_file)
440436

441437
# Remove created history file
442-
os.remove(hist_file)
438+
#os.remove(hist_file)
443439

444440
def test_bad_history_file_path(capsys, request):
445441
# Use a directory path as the history file
@@ -449,7 +445,7 @@ def test_bad_history_file_path(capsys, request):
449445
cmd2.Cmd(persistent_history_file=test_dir)
450446
_, err = capsys.readouterr()
451447

452-
assert 'can not write' in err
448+
assert 'is a directory' in err
453449

454450
def test_history_file_conversion_no_truncate_on_init(hist_file, capsys):
455451
# test the code that converts a plain text history file to a pickle binary

0 commit comments

Comments
 (0)