Coverage for src/pytest_samples/tools/_iotools.py: 100%

13 statements  

« prev     ^ index     » next       coverage.py v7.4.2, created at 2024-02-20 19:47 +0000

1import shutil as _shutil 

2 

3from dataclasses import dataclass as _dataclass 

4from typing import Any as _Any, Callable as _Callable, IO as _IO 

5 

6 

7WriteFunction = _Callable[[bytes], _Any] 

8"""Function signature of an io "write" function.""" 

9 

10 

11@_dataclass(frozen=True) 

12class _MockTargetFileobj: 

13 """An object mocking a fileobj with a "write" function.""" 

14 

15 __slots__ = ("write",) 

16 

17 write: WriteFunction 

18 """The write function.""" 

19 

20 

21def copy_fileobj_to_func( 

22 fileobj: _IO[bytes], 

23 func: _Callable[[bytes], _Any], 

24 length: int = 0 

25): 

26 """Copy a fileobj to a function accepting bytes. This imitates 

27 `shutil.copyfileobj` for function targets. 

28 

29 Args: 

30 fileobj (IO[bytes]): The fileobj to copy. 

31 func (Callable[[bytes], Any]): The function to write to. 

32 length (int, optional): The number of bytes to write. Defaults 

33 to 0, which will write all bytes. 

34 """ 

35 target = _MockTargetFileobj(func) 

36 _shutil.copyfileobj(fileobj, target, length)