Skip to content

Commit

Permalink
feat: factory fixture for creating temporary copies of directory trees
Browse files Browse the repository at this point in the history
  • Loading branch information
akaihola committed Nov 17, 2024
1 parent 9007892 commit 218e098
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
31 changes: 31 additions & 0 deletions src/darkgraylib/testtools/temp_copy.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 218e098

Please sign in to comment.