Skip to content

Commit a84bf52

Browse files
hermankoldenbkueng
authored andcommitted
fix: allow closed file handles in calc_sha256sum
Since we tend to allow filenames and file handles interchangably in this code base, we might run into the edge case of a closed file handle being input to calc_sha256sum. We should then open the file before getting the hash.
1 parent 8bcee7b commit a84bf52

2 files changed

Lines changed: 16 additions & 6 deletions

File tree

‎pyulog/db.py‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -114,15 +114,16 @@ def calc_sha256sum(log_file):
114114
if log_file is None:
115115
return None
116116
if isinstance(log_file, str):
117-
log_file = open(log_file, 'rb') # pylint: disable=consider-using-with
118-
log_context = log_file
117+
file_context = open(log_file, 'rb') # pylint: disable=consider-using-with
118+
elif log_file.closed:
119+
file_context = open(log_file.name, 'rb')
119120
else:
120-
log_context = contextlib.nullcontext()
121+
file_context = contextlib.nullcontext(log_file)
121122

122123
file_hash = hashlib.sha256()
123-
with log_context:
124+
with file_context as open_file:
124125
while True:
125-
block = log_file.read(4096)
126+
block = open_file.read(4096)
126127
file_hash.update(block)
127128
if block == b'':
128129
break

‎test/test_db.py‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,8 @@ def test_unapplied_migrations(self):
142142
@data('sample_log_small')
143143
def test_sha256sum(self, test_case):
144144
'''
145-
Verify that the sha256sum set on save can be used to find the same file again.
145+
Verify that the sha256sum set on save can be used to find the same file
146+
again, using any of the approved file input methods.
146147
'''
147148

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

155+
test_file_handle = open(test_file, 'rb') # pylint: disable=consider-using-with
156+
open_digest = DatabaseULog.calc_sha256sum(test_file_handle)
157+
self.assertEqual(digest, open_digest)
158+
159+
test_file_handle.close()
160+
closed_digest = DatabaseULog.calc_sha256sum(test_file_handle)
161+
self.assertEqual(digest, closed_digest)
162+
154163
pk_from_digest = DatabaseULog.primary_key_from_sha256sum(self.db_handle, digest)
155164
self.assertEqual(pk_from_digest, dbulog.primary_key)
156165

0 commit comments

Comments
 (0)