diff --git a/CHANGELOG.md b/CHANGELOG.md index e8f30f407..16f4313dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,8 @@ ## 4.5.0 (TBD) - Bug Fixes + - Invalid UTF-8 and malformed JSON values in persistent history files now produce a warning and + start with empty history instead of preventing application startup. - Rich theme styles now display `white` and `bright_white` correctly in prompt-toolkit. Previously, `white` appeared bright white, and using `bright_white` raised a `ValueError` when cmd2 applied the theme. The fix covers both foreground and background colors. diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 27ad738e6..77dac2d28 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -5862,7 +5862,7 @@ def _initialize_history(self, hist_file: str) -> None: try: import lzma as decompress_lib - decompress_exceptions: tuple[type[Exception], ...] = (decompress_lib.LZMAError,) + decompress_exceptions: tuple[type[Exception], ...] = (decompress_lib.LZMAError, UnicodeDecodeError) except ModuleNotFoundError: # pragma: no cover import bz2 as decompress_lib # type: ignore[no-redef] @@ -5882,7 +5882,7 @@ def _initialize_history(self, hist_file: str) -> None: try: self.history = History.from_json(history_json) - except (json.JSONDecodeError, KeyError, ValueError) as ex: + except (json.JSONDecodeError, KeyError, TypeError, ValueError) as ex: self.perror( f"Error processing persistent history data '{hist_file}': {ex}\n" f"The history file will be recreated when this application exits." diff --git a/tests/test_history.py b/tests/test_history.py index 405f162d4..3716f71e8 100644 --- a/tests/test_history.py +++ b/tests/test_history.py @@ -1747,19 +1747,29 @@ def test_history_file_bad_compression(capsys, tmp_path) -> None: assert "Error decompressing persistent history data" in err -def test_history_file_bad_json(capsys, tmp_path) -> None: +@pytest.mark.parametrize( + ("data", "error"), + [ + (b"THIS IS NOT JSON", "Error processing persistent history data"), + (b"[]", "Error processing persistent history data"), + (b"null", "Error processing persistent history data"), + (b"42", "Error processing persistent history data"), + (b"\xff", "Error decompressing persistent history data"), + ], +) +def test_history_file_bad_json(capsys, tmp_path, data, error) -> None: import lzma - data = b"THIS IS NOT JSON" compressed_data = lzma.compress(data) history_file = tmp_path / "doesntmatter" history_file.write_bytes(compressed_data) - cmd2.Cmd(persistent_history_file=str(history_file)) + app = cmd2.Cmd(persistent_history_file=str(history_file)) out, err = capsys.readouterr() assert not out - assert "Error processing persistent history data" in err + assert error in err + assert len(app.history) == 0 def test_history_populates_pt(hist_file) -> None: