Coverage for src/pytest_samples/_hashing.py: 100%
16 statements
« prev ^ index » next coverage.py v7.4.2, created at 2024-02-20 19:47 +0000
« prev ^ index » next coverage.py v7.4.2, created at 2024-02-20 19:47 +0000
1"""This module contains functions for hashing files."""
3import hashlib as _hashlib
4import sys as _sys
6if _sys.version_info >= (3, 9):
7 import functools as _functools
9from io import BufferedReader as _BufferedReader
11from . import tools as _tools
14def hash_fileobj(fileobj: _BufferedReader) -> bytes:
15 """Compute a non-security relevant md5 hash of a fileobj.
17 Args:
18 fileobj (str): The fileobj to hash.
20 Returns:
21 bytes: The digest.
22 """
23 generator = _hashlib.md5
24 if _sys.version_info >= (3, 9):
25 generator = _functools.partial(generator, usedforsecurity=False)
26 md5 = generator()
27 _tools.copy_fileobj_to_func(fileobj, md5.update)
28 return md5.digest()
31def hash_file(path: str) -> bytes:
32 """Compute a non-security relevant md5 hash of a file.
34 Args:
35 path (str): The path to the file.
37 Returns:
38 bytes: The digest.
39 """
40 with open(path, "rb") as ifi:
41 return hash_fileobj(ifi)