Passed
Push — main ( 2b775d...83a9fb )
by Douglas
04:59 queued 02:43
created

MandosResources.a_file()   A

Complexity

Conditions 2

Size

Total Lines 13
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 11
nop 3
dl 0
loc 13
rs 9.85
c 0
b 0
f 0
1
import os
0 ignored issues
show
introduced by
Missing module docstring
Loading history...
2
import typing
3
from pathlib import Path
4
from typing import Union, Optional, MutableMapping
5
6
import orjson
0 ignored issues
show
introduced by
Unable to import 'orjson'
Loading history...
7
from pocketutils.core.dot_dict import NestedDotDict
0 ignored issues
show
introduced by
Unable to import 'pocketutils.core.dot_dict'
Loading history...
8
from pocketutils.core.exceptions import (
0 ignored issues
show
Unused Code introduced by
Unused DirDoesNotExistError imported from pocketutils.core.exceptions
Loading history...
introduced by
Unable to import 'pocketutils.core.exceptions'
Loading history...
9
    FileDoesNotExistError,
10
    DirDoesNotExistError,
11
    MissingResourceError,
12
    PathExistsError,
13
)
14
from pocketutils.core.hashers import Hasher
0 ignored issues
show
introduced by
Unable to import 'pocketutils.core.hashers'
Loading history...
15
from pocketutils.tools.common_tools import CommonTools
0 ignored issues
show
introduced by
Unable to import 'pocketutils.tools.common_tools'
Loading history...
16
17
from mandos.model.utils.misc_utils import MiscUtils
18
19
20
class MandosResources:
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
21
22
    start_time = MiscUtils.utc()
23
    start_time_local = start_time.astimezone()
24
    start_timestamp = start_time.isoformat(timespec="milliseconds")
25
    start_timestamp_filesys = start_time_local.strftime("%Y-%m-%d_%H-%M-%S")
26
    hasher: Hasher = Hasher("sha256", buffer_size=16 * 1024)
27
    resource_dir = Path(__file__).parent.parent.parent
28
29
    @classmethod
30
    def contains(cls, *nodes: Union[Path, str], suffix: Optional[str] = None) -> bool:
31
        """Returns whether a resource file (or dir) exists."""
32
        return cls.path(*nodes, suffix=suffix).exists()
33
34
    @classmethod
35
    def path(
36
        cls, *nodes: Union[Path, str], suffix: Optional[str] = None, exists: bool = True
0 ignored issues
show
Unused Code introduced by
The argument exists seems to be unused.
Loading history...
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
37
    ) -> Path:
38
        """Gets a path of a test resource file under ``resources/``."""
39
        path = Path(cls.resource_dir, "resources", *nodes)
40
        path = path.with_suffix(path.suffix if suffix is None else suffix)
41
        if not path.exists():
42
            raise MissingResourceError(f"Resource {path} missing")
43
        return path
44
45
    @classmethod
46
    def file(cls, *nodes: Union[Path, str], suffix: Optional[str] = None) -> Path:
47
        """Gets a path of a test resource file under ``resources/``."""
48
        path = cls.path(*nodes, suffix=suffix)
49
        if not path.is_file():
50
            raise PathExistsError(f"Resource {path} is not a file!")
51
        if not os.access(path, os.R_OK):
52
            raise FileDoesNotExistError(f"Resource {path} is not readable")
53
        return path
54
55
    @classmethod
56
    def dir(cls, *nodes: Union[Path, str]) -> Path:
57
        """Gets a path of a test resource file under ``resources/``."""
58
        path = cls.path(*nodes)
59
        if not path.is_dir() and not path.is_mount():
60
            raise PathExistsError(f"Resource {path} is not a directory!")
61
        return path
62
63
    @classmethod
64
    def a_file(cls, *nodes: Union[Path, str], suffixes: Optional[typing.Set[str]] = None) -> Path:
65
        """Gets a path of a test resource file under ``resources/``, ignoring suffix."""
66
        path = Path(cls.resource_dir, "resources", *nodes)
67
        options = [
68
            p
69
            for p in path.parent.glob(path.stem + "*")
70
            if p.is_file() and (suffixes is None or p.suffix in suffixes)
71
        ]
72
        try:
73
            return CommonTools.only(options)
74
        except LookupError:
75
            raise MissingResourceError(f"Resource {path} missing") from None
76
77
    @classmethod
78
    def json(cls, *nodes: Union[Path, str], suffix: Optional[str] = None) -> NestedDotDict:
79
        """Reads a JSON file under ``resources/``."""
80
        path = cls.path(*nodes, suffix=suffix)
81
        data = orjson.loads(Path(path).read_text(encoding="utf8"))
82
        return NestedDotDict(data)
83
84
    @classmethod
85
    def json_dict(cls, *nodes: Union[Path, str], suffix: Optional[str] = None) -> MutableMapping:
86
        """Reads a JSON file under ``resources/``."""
87
        path = cls.path(*nodes, suffix=suffix)
88
        data = orjson.loads(Path(path).read_text(encoding="utf8"))
89
        return data
90
91
    strings = None
92
93
94
MandosResources.strings = {
95
    k.partition(":")[2]: v for k, v in MandosResources.json("strings.json").items()
96
}
97
98
99
__all__ = ["MandosResources"]
100