Skip to content

Commit 6c94b75

Browse files
committed
chore: improve zip loading errorhandling
1 parent 7a61959 commit 6c94b75

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

freqtrade/data/btanalysis.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -414,11 +414,17 @@ def load_file_from_zip(zip_path: Path, filename: str) -> bytes:
414414
"""
415415
try:
416416
with zipfile.ZipFile(zip_path) as zipf:
417-
with zipf.open(filename) as file:
418-
return file.read()
417+
try:
418+
with zipf.open(filename) as file:
419+
return file.read()
420+
except KeyError:
421+
logger.error(f"File {filename} not found in zip: {zip_path}")
422+
raise ValueError(f"File {filename} not found in zip: {zip_path}") from None
423+
except FileNotFoundError:
424+
raise ValueError(f"Zip file {zip_path} not found.")
419425
except zipfile.BadZipFile:
420-
logger.exception(f"Bad zip file: {zip_path}")
421-
raise ValueError(f"Bad zip file: {zip_path}") from None
426+
logger.error(f"Bad zip file: {zip_path}.")
427+
raise ValueError(f"Bad zip file: {zip_path}.") from None
422428

423429

424430
def load_backtest_analysis_data(backtest_dir: Path, name: str):

tests/data/test_btanalysis.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from datetime import datetime, timedelta, timezone
22
from pathlib import Path
33
from unittest.mock import MagicMock
4+
from zipfile import ZipFile
45

56
import pytest
67
from pandas import DataFrame, DateOffset, Timestamp, to_datetime
@@ -15,6 +16,7 @@
1516
get_latest_hyperopt_file,
1617
load_backtest_data,
1718
load_backtest_metadata,
19+
load_file_from_zip,
1820
load_trades,
1921
load_trades_from_db,
2022
)
@@ -569,3 +571,22 @@ def test_calculate_max_drawdown_abs(profits, relative, highd, lowdays, result, r
569571
assert drawdown.high_value > drawdown.low_value
570572
assert drawdown.drawdown_abs == result
571573
assert pytest.approx(drawdown.relative_account_drawdown) == result_rel
574+
575+
576+
def test_load_file_from_zip(tmp_path):
577+
with pytest.raises(ValueError, match=r"Zip file .* not found\."):
578+
load_file_from_zip(tmp_path / "test.zip", "testfile.txt")
579+
580+
(tmp_path / "testfile.zip").touch()
581+
with pytest.raises(ValueError, match=r"Bad zip file.*"):
582+
load_file_from_zip(tmp_path / "testfile.zip", "testfile.txt")
583+
584+
zip_file = tmp_path / "testfile2.zip"
585+
with ZipFile(zip_file, "w") as zipf:
586+
zipf.writestr("testfile.txt", "testfile content")
587+
588+
content = load_file_from_zip(zip_file, "testfile.txt")
589+
assert content.decode("utf-8") == "testfile content"
590+
591+
with pytest.raises(ValueError, match=r"File .* not found in zip.*"):
592+
load_file_from_zip(zip_file, "testfile55.txt")

0 commit comments

Comments
 (0)