From 218e098b4e32f11991cad501ecdfbfbdbfaa78df Mon Sep 17 00:00:00 2001 From: Antti Kaihola <13725+akaihola@users.noreply.github.com> Date: Sat, 16 Nov 2024 20:40:04 +0200 Subject: [PATCH] feat: factory fixture for creating temporary copies of directory trees --- setup.cfg | 1 + src/darkgraylib/testtools/temp_copy.py | 31 ++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 src/darkgraylib/testtools/temp_copy.py diff --git a/setup.cfg b/setup.cfg index c34247b0..7a08168b 100644 --- a/setup.cfg +++ b/setup.cfg @@ -48,6 +48,7 @@ pygments.lexers = pytest11 = pytest_git_repo = darkgraylib.testtools.git_repo_plugin pytest_clear_black_cache = darkgraylib.testtools.clear_black_cache_plugin + pytest_temp_copy = darkgraylib.testtools.temp_copy pytest_patching = darkgraylib.testtools.patching [options.extras_require] diff --git a/src/darkgraylib/testtools/temp_copy.py b/src/darkgraylib/testtools/temp_copy.py new file mode 100644 index 00000000..32cbb417 --- /dev/null +++ b/src/darkgraylib/testtools/temp_copy.py @@ -0,0 +1,31 @@ +"""Pytest fixture factory for making temporary copies of directory trees.""" + +from __future__ import annotations + +import re +from contextlib import contextmanager +from shutil import copytree +from typing import TYPE_CHECKING, Callable, ContextManager + +import pytest + +if TYPE_CHECKING: + from pathlib import Path + from typing import Generator + + +@pytest.fixture +def make_temp_copy( + request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory +) -> Callable[[Path], ContextManager[Path]]: + """Pytest fixture to create a temporary clone of a directory structure.""" + + @contextmanager + def temp_copy_factory(path: Path) -> Generator[Path]: + max_len = 30 + name = re.sub(r"\W", "_", f"clone_{request.node.name}")[:max_len] + clone = tmp_path_factory.mktemp(name, numbered=True) / path.name + copytree(path, clone) + yield clone + + return temp_copy_factory