Skip to content

Commit

Permalink
test(copier): add tests for Copier class methods
Browse files Browse the repository at this point in the history
  • Loading branch information
entelecheia committed May 4, 2023
1 parent 62ba225 commit 7ae60c3
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
3 changes: 3 additions & 0 deletions src/hyfi/utils/copier.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ def __post_init__(self):
self.path_spec = PathSpec.from_lines("gitwildmatch", self.exclude)
self.dst_path_existed = self.dst_path.exists()

def __enter__(self):
return self

def __exit__(self, exc_type, exc_value, traceback):
"""Exit the context manager, handling cleanup if needed."""
if exc_type is not None and not self.dst_path_existed and self.cleanup_on_error:
Expand Down
1 change: 0 additions & 1 deletion src/hyfi/utils/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import colorama
from pydantic import StrictBool


colorama.init()

IntSeq = Sequence[int]
Expand Down
56 changes: 56 additions & 0 deletions tests/hyfi/utils/test_copier.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import os
import shutil
from pathlib import Path

import pytest

from hyfi.utils.copier import Copier


def test_files_are_copied(tmp_path):
# source path is under src/hyfi/conf
src_path = Path("src/hyfi/conf")
assert src_path.exists()
dst_path = tmp_path / "output"

with Copier(src_path=src_path, dst_path=dst_path, verbose=False) as worker:
worker.run_copy()

for root, _, files in os.walk(src_path):
for filename in files:
if filename.endswith(".yaml"):
src_file = Path(root, filename)
dst_file = dst_path / src_file.relative_to(src_path)
assert dst_file.exists()


def test_cleanup_on_error(tmp_path):
src_path = Path("src/hyfi/conf")
assert src_path.exists()
dst_path = tmp_path / "output"

with pytest.raises(Exception):
with Copier(src_path=src_path, dst_path=dst_path, verbose=False) as worker:
worker.run_copy()
raise Exception("Simulated error")

assert not dst_path.exists()


def test_no_cleanup_on_error_if_dst_existed(tmp_path):
src_path = Path("src/hyfi/conf")
assert src_path.exists()
dst_path = tmp_path / "output"
dst_path.mkdir(parents=True, exist_ok=True)

with pytest.raises(Exception):
with Copier(src_path=src_path, dst_path=dst_path, verbose=False) as worker:
worker.run_copy()
raise Exception("Simulated error")

assert dst_path.exists()
shutil.rmtree(dst_path)


if __name__ == "__main__":
pytest.main(["-v", "test_copier.py"])

0 comments on commit 7ae60c3

Please sign in to comment.