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
55
56
57
58
59
60
|
from __future__ import annotations
import dataclasses as dc
import json
from pathlib import Path
from typing import Any, Literal, TypeVar, overload
import pytest
DATADIR = Path(__file__).parent.parent / "data"
B = TypeVar("B", bound=bool)
@dc.dataclass
class Finder:
root: Path # type: ignore[annotation-unchecked]
subdirs: list[Path] = dc.field(default_factory=list)
@overload
def lookup(self, path: Path | str, abort: Literal[True] = True) -> Path: ...
@overload
def lookup(self, path: Path | str, abort: Literal[False]) -> None: ...
@overload
def lookup(self, path: Path | str, abort: B) -> Path | None: ...
def lookup(self, path: Path | str, abort: bool = True) -> Path | None:
candidates = [
self.root / path,
*self.subdirs,
]
for candidate in reversed(candidates):
if candidate.exists():
return candidate
if abort:
raise FileNotFoundError(f"cannot find {path}", candidates)
return None
def load(self, path: Path, mode: str | None = None) -> Any:
source = self.lookup(path)
mode = mode or source.suffix.strip(".")
if mode == "json":
return json.loads(source.read_text())
elif mode == "raw":
return source.read_bytes()
else:
return source.read_text()
@pytest.fixture(scope="session")
def finder(request):
yield Finder(DATADIR)
@pytest.fixture(scope="module")
def mfinder(request):
path = Path(request.module.__file__).parent
yield Finder(DATADIR, subdirs=[path, path / "data"])
|