From 6c94b75172850b45654162e2eca3f20271350300 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 26 Dec 2024 15:22:23 +0100 Subject: [PATCH] chore: improve zip loading errorhandling --- freqtrade/data/btanalysis.py | 14 ++++++++++---- tests/data/test_btanalysis.py | 21 +++++++++++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/freqtrade/data/btanalysis.py b/freqtrade/data/btanalysis.py index fe85b08ea..7b0109fa9 100644 --- a/freqtrade/data/btanalysis.py +++ b/freqtrade/data/btanalysis.py @@ -414,11 +414,17 @@ def load_file_from_zip(zip_path: Path, filename: str) -> bytes: """ try: with zipfile.ZipFile(zip_path) as zipf: - with zipf.open(filename) as file: - return file.read() + try: + with zipf.open(filename) as file: + return file.read() + except KeyError: + logger.error(f"File {filename} not found in zip: {zip_path}") + raise ValueError(f"File {filename} not found in zip: {zip_path}") from None + except FileNotFoundError: + raise ValueError(f"Zip file {zip_path} not found.") except zipfile.BadZipFile: - logger.exception(f"Bad zip file: {zip_path}") - raise ValueError(f"Bad zip file: {zip_path}") from None + logger.error(f"Bad zip file: {zip_path}.") + raise ValueError(f"Bad zip file: {zip_path}.") from None def load_backtest_analysis_data(backtest_dir: Path, name: str): diff --git a/tests/data/test_btanalysis.py b/tests/data/test_btanalysis.py index 9b79983af..1c901bc16 100644 --- a/tests/data/test_btanalysis.py +++ b/tests/data/test_btanalysis.py @@ -1,6 +1,7 @@ from datetime import datetime, timedelta, timezone from pathlib import Path from unittest.mock import MagicMock +from zipfile import ZipFile import pytest from pandas import DataFrame, DateOffset, Timestamp, to_datetime @@ -15,6 +16,7 @@ from freqtrade.data.btanalysis import ( get_latest_hyperopt_file, load_backtest_data, load_backtest_metadata, + load_file_from_zip, load_trades, load_trades_from_db, ) @@ -569,3 +571,22 @@ def test_calculate_max_drawdown_abs(profits, relative, highd, lowdays, result, r assert drawdown.high_value > drawdown.low_value assert drawdown.drawdown_abs == result assert pytest.approx(drawdown.relative_account_drawdown) == result_rel + + +def test_load_file_from_zip(tmp_path): + with pytest.raises(ValueError, match=r"Zip file .* not found\."): + load_file_from_zip(tmp_path / "test.zip", "testfile.txt") + + (tmp_path / "testfile.zip").touch() + with pytest.raises(ValueError, match=r"Bad zip file.*"): + load_file_from_zip(tmp_path / "testfile.zip", "testfile.txt") + + zip_file = tmp_path / "testfile2.zip" + with ZipFile(zip_file, "w") as zipf: + zipf.writestr("testfile.txt", "testfile content") + + content = load_file_from_zip(zip_file, "testfile.txt") + assert content.decode("utf-8") == "testfile content" + + with pytest.raises(ValueError, match=r"File .* not found in zip.*"): + load_file_from_zip(zip_file, "testfile55.txt")