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

fix: allow closed file handles in calc_sha256sum #97

Merged
merged 1 commit into from
Jul 4, 2024
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
11 changes: 6 additions & 5 deletions pyulog/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,15 +114,16 @@ def calc_sha256sum(log_file):
if log_file is None:
return None
if isinstance(log_file, str):
log_file = open(log_file, 'rb') # pylint: disable=consider-using-with
log_context = log_file
file_context = open(log_file, 'rb') # pylint: disable=consider-using-with
elif log_file.closed:
file_context = open(log_file.name, 'rb')
else:
log_context = contextlib.nullcontext()
file_context = contextlib.nullcontext(log_file)

file_hash = hashlib.sha256()
with log_context:
with file_context as open_file:
while True:
block = log_file.read(4096)
block = open_file.read(4096)
file_hash.update(block)
if block == b'':
break
Expand Down
11 changes: 10 additions & 1 deletion test/test_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,8 @@ def test_unapplied_migrations(self):
@data('sample_log_small')
def test_sha256sum(self, test_case):
'''
Verify that the sha256sum set on save can be used to find the same file again.
Verify that the sha256sum set on save can be used to find the same file
again, using any of the approved file input methods.
'''

test_file = os.path.join(TEST_PATH, f'{test_case}.ulg')
Expand All @@ -151,6 +152,14 @@ def test_sha256sum(self, test_case):
digest = DatabaseULog.calc_sha256sum(test_file)
self.assertEqual(digest, dbulog.sha256sum)

test_file_handle = open(test_file, 'rb') # pylint: disable=consider-using-with
open_digest = DatabaseULog.calc_sha256sum(test_file_handle)
self.assertEqual(digest, open_digest)

test_file_handle.close()
closed_digest = DatabaseULog.calc_sha256sum(test_file_handle)
self.assertEqual(digest, closed_digest)

pk_from_digest = DatabaseULog.primary_key_from_sha256sum(self.db_handle, digest)
self.assertEqual(pk_from_digest, dbulog.primary_key)

Expand Down
Loading