debian-forge/osbuild/testutil/__init__.py
Michael Vogt ad8fd2f532 testutil: extrace new make_fake_tree() helper
Extract a new helper `make_fake_tree()` that generalizes the existing
helper `make_fake_input_tree()`. The later will always create the
content under `{basedir}/tree` which is convinient for input tree
based tests but too specialized when using it in different contexts.

The existing `make_fake_input_tree()` is preserved unchanged and
becomes just a tiny wrapper.
2024-01-03 11:25:48 -08:00

40 lines
1 KiB
Python

"""
Test related utilities
"""
import os
import shutil
def has_executable(executable: str) -> bool:
return shutil.which(executable) is not None
def assert_dict_has(v, keys, expected_value):
for key in keys.split("."):
assert key in v
v = v[key]
assert v == expected_value
def make_fake_tree(basedir, fake_content: dict):
"""Create a directory tree of files with content.
Call it with:
{"filename": "content", "otherfile": "content"}
filename paths will have their parents created as needed, under tmpdir.
"""
for path, content in fake_content.items():
dirp, name = os.path.split(os.path.join(basedir, path.lstrip("/")))
os.makedirs(dirp, exist_ok=True)
with open(os.path.join(dirp, name), "w", encoding="utf-8") as fp:
fp.write(content)
def make_fake_input_tree(tmpdir, fake_content: dict) -> str:
"""
Wrapper around make_fake_tree for "input trees"
"""
basedir = tmpdir / "tree"
make_fake_tree(basedir, fake_content)
return os.fspath(basedir)