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

1"""This module contains functions for hashing files.""" 

2 

3import hashlib as _hashlib 

4import sys as _sys 

5 

6if _sys.version_info >= (3, 9): 

7 import functools as _functools 

8 

9from io import BufferedReader as _BufferedReader 

10 

11from . import tools as _tools 

12 

13 

14def hash_fileobj(fileobj: _BufferedReader) -> bytes: 

15 """Compute a non-security relevant md5 hash of a fileobj. 

16 

17 Args: 

18 fileobj (str): The fileobj to hash. 

19 

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() 

29 

30 

31def hash_file(path: str) -> bytes: 

32 """Compute a non-security relevant md5 hash of a file. 

33 

34 Args: 

35 path (str): The path to the file. 

36 

37 Returns: 

38 bytes: The digest. 

39 """ 

40 with open(path, "rb") as ifi: 

41 return hash_fileobj(ifi)