Debian Codegraph @

tests/common.py

raw symbols SCIP
1 """Common test utilities."""
2
3 import logging
4 import os
5 import pathlib
6 from io import StringIO
7 from typing import Any, LiteralString
8 from unittest.mock import patch
9
10 from annotatedyaml import loader as yaml_loader
11
12 _LOGGER = logging.getLogger(__name__)
13 YAML_CONFIG_FILE = "test.yaml"
14
15
16 def get_test_config_dir(*add_path: Any) -> LiteralString | str | bytes:
17 """Return a path to a test config dir."""
18 return os.path.join(os.path.dirname(__file__), "testing_config", *add_path)
19
20
21 def patch_yaml_files(files_dict, endswith=True) -> Any:
22 """Patch load_yaml with a dictionary of yaml files."""
23 # match using endswith, start search with longest string
24 matchlist = sorted(files_dict.keys(), key=len) if endswith else []
25
26 def mock_open_f(fname: str | pathlib.Path, **_: Any) -> StringIO:
27 """Mock open() in the yaml module, used by load_yaml."""
28 # Return the mocked file on full match
29 if isinstance(fname, pathlib.Path):
30 fname = str(fname)
31
32 if fname in files_dict:
33 _LOGGER.debug("patch_yaml_files match %s", fname)
34 res = StringIO(files_dict[fname])
35 res.name = fname
36 return res
37
38 # Match using endswith
39 for ends in matchlist:
40 if fname.endswith(ends):
41 _LOGGER.debug("patch_yaml_files end match %s: %s", ends, fname)
42 res = StringIO(files_dict[ends])
43 res.name = fname
44 return res
45
46 # Not found
47 msg = f"File not found: {fname}"
48 raise FileNotFoundError(msg)
49
50 return patch.object(yaml_loader, "open", mock_open_f, create=True)