Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[MRG] clean up zip error handling for bad zip files #2270

Merged
merged 2 commits into from
Sep 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions src/sourmash/sbt_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,10 +323,14 @@ def load(self, path):
def close(self):
# TODO: this is not ideal; checking for zipfile.fp is looking at
# internal implementation details from CPython...
if self.zipfile is not None or self.bufferzip is not None:
self.flush(keep_closed=True)
self.zipfile.close()
self.zipfile = None

# might not have self.zipfile if was invalid zipfile and __init__
# failed.
if hasattr(self, 'zipfile'):
if self.zipfile is not None or self.bufferzip is not None:
self.flush(keep_closed=True)
self.zipfile.close()
self.zipfile = None

def flush(self, *, keep_closed=False):
# This is a bit complicated, but we have to deal with new data
Expand Down
10 changes: 9 additions & 1 deletion src/sourmash/sourmash_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -1112,7 +1112,15 @@ def open(self):
if os.path.exists(self.location):
do_create = False

storage = ZipStorage(self.location, mode="w")
storage = None
try:
storage = ZipStorage(self.location, mode="w")
except zipfile.BadZipFile:
pass

if storage is None:
raise ValueError(f"File '{self.location}' cannot be opened as a zip file.")

if not storage.subdir:
storage.subdir = 'signatures'

Expand Down
21 changes: 21 additions & 0 deletions tests/test_sourmash_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,27 @@ def test_save_signatures_to_location_1_zip(runtmp):
assert len(saved) == 2


def test_save_signatures_to_location_1_zip_bad(runtmp):
# try saving to bad sigfile.zip
sig2 = utils.get_test_data('2.fa.sig')
ss2 = sourmash.load_one_signature(sig2, ksize=31)
sig47 = utils.get_test_data('47.fa.sig')
ss47 = sourmash.load_one_signature(sig47, ksize=31)

outloc = runtmp.output('foo.zip')

# create bad zip:
with open(outloc, 'wt') as fp:
pass

# now check for error
with pytest.raises(ValueError) as exc:
with sourmash_args.SaveSignaturesToLocation(outloc) as save_sig:
pass

assert 'cannot be opened as a zip file' in str(exc)


def test_save_signatures_to_location_1_zip_dup(runtmp):
# save to sigfile.zip
sig2 = utils.get_test_data('2.fa.sig')
Expand Down