diff --git a/pyulog/db.py b/pyulog/db.py index 0c40b34..91f50b3 100644 --- a/pyulog/db.py +++ b/pyulog/db.py @@ -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 diff --git a/test/test_db.py b/test/test_db.py index 53c2429..06e9ef7 100644 --- a/test/test_db.py +++ b/test/test_db.py @@ -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') @@ -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)