Skip to content

Commit 95e6dfa

Browse files
committed
Added unit tests for persistent history file
1 parent 5d2133a commit 95e6dfa

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

tests/test_cmd2.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1825,3 +1825,66 @@ def test_onecmd_raw_str_quit(base_app):
18251825
assert stop
18261826
assert out == ''
18271827

1828+
1829+
def test_existing_history_file(capsys, request):
1830+
import atexit
1831+
import readline
1832+
1833+
# Create path to a history file
1834+
test_dir = os.path.dirname(request.module.__file__)
1835+
hist_file = os.path.join(test_dir, 'hist_file')
1836+
1837+
# Create the history file before making cmd2 app
1838+
with open(hist_file, 'w'):
1839+
pass
1840+
1841+
# Create a new cmd2 app
1842+
app = cmd2.Cmd(persistent_history_file=hist_file)
1843+
out, err = capsys.readouterr()
1844+
1845+
# Unregister the call to write_history_file that cmd2 did
1846+
atexit.unregister(readline.write_history_file)
1847+
1848+
# Remove created history file and make sure there were no errors
1849+
os.remove(hist_file)
1850+
assert err == ''
1851+
1852+
def test_new_history_file(capsys, request):
1853+
import atexit
1854+
import readline
1855+
1856+
# Create path to a history file
1857+
test_dir = os.path.dirname(request.module.__file__)
1858+
hist_file = os.path.join(test_dir, 'hist_file')
1859+
1860+
# Remove any existing history file
1861+
try:
1862+
os.remove(hist_file)
1863+
except OSError:
1864+
pass
1865+
1866+
# Create a new cmd2 app
1867+
app = cmd2.Cmd(persistent_history_file=hist_file)
1868+
out, err = capsys.readouterr()
1869+
1870+
# Unregister the call to write_history_file that cmd2 did
1871+
atexit.unregister(readline.write_history_file)
1872+
1873+
# Remove created history file and make sure there were no errors
1874+
os.remove(hist_file)
1875+
assert err == ''
1876+
1877+
def test_bad_history_file_path(capsys, request):
1878+
# Use a directory path as the history file
1879+
test_dir = os.path.dirname(request.module.__file__)
1880+
1881+
# Create a new cmd2 app
1882+
app = cmd2.Cmd(persistent_history_file=test_dir)
1883+
out, err = capsys.readouterr()
1884+
1885+
if sys.platform == 'win32':
1886+
# pyreadline masks the read exception. Therefore the bad path error occurs when trying to write the file.
1887+
assert 'readline cannot write' in err
1888+
else:
1889+
# GNU readline raises an exception upon trying to read the directory as a file
1890+
assert 'readline cannot read' in err

0 commit comments

Comments
 (0)