summaryrefslogtreecommitdiff
path: root/test/utils/destination.py
blob: ad767d1c4737a7f5e864130e46fcb807361484d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import enum
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path, PurePath
from typing import IO, Callable, Generator, Optional, TextIO, Union

DestParmType = Union[Path, PurePath, str, IO[bytes], TextIO]


@dataclass(frozen=True)
class DestRef:
    param: DestParmType
    path: Path


class DestinationType(str, enum.Enum):
    RETURN = enum.auto()
    PATH = enum.auto()
    PURE_PATH = enum.auto()
    STR_PATH = enum.auto()
    FILE_URI = enum.auto()
    BINARY_IO = enum.auto()
    TEXT_IO = enum.auto()

    @contextmanager
    def make_ref(
        self,
        tmp_path: Path,
        encoding: Optional[str] = None,
        path_factory: Callable[[Path, "DestinationType", Optional[str]], Path] = (
            lambda tmp_path, type, encoding: tmp_path / f"file-{type.name}-{encoding}"
        ),
    ) -> Generator[Optional[DestRef], None, None]:
        path = path_factory(tmp_path, self, encoding)
        # path = tmp_path / f"file-{self.name}"
        if self is DestinationType.RETURN:
            yield None
        elif self is DestinationType.PATH:
            yield DestRef(path, path)
        elif self is DestinationType.PURE_PATH:
            yield DestRef(PurePath(path), path)
        elif self is DestinationType.STR_PATH:
            yield DestRef(f"{path}", path)
        elif self is DestinationType.FILE_URI:
            yield DestRef(path.as_uri(), path)
        elif self is DestinationType.BINARY_IO:
            with path.open("wb") as bfh:
                yield DestRef(bfh, path)
        elif self is DestinationType.TEXT_IO:
            assert encoding is not None
            with path.open("w", encoding=encoding) as fh:
                yield DestRef(fh, path)
        else:
            raise ValueError(f"unsupported type {type!r}")