Skip to content

Commit

Permalink
✨ Added chdir_context context manager for testing with relative paths
Browse files Browse the repository at this point in the history
  • Loading branch information
s-weigand committed Dec 18, 2022
1 parent b5698b8 commit ad96e6f
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 2 deletions.
33 changes: 33 additions & 0 deletions glotaran/utils/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from collections.abc import Mapping
from collections.abc import MutableMapping
from collections.abc import Sequence
from contextlib import contextmanager
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
Expand All @@ -19,6 +20,7 @@
from glotaran.typing.types import DatasetMappable

if TYPE_CHECKING:
from collections.abc import Generator
from collections.abc import Iterator

import pandas as pd
Expand Down Expand Up @@ -190,6 +192,37 @@ def load_datasets(dataset_mappable: DatasetMappable) -> DatasetMapping:
return DatasetMapping.loader(dataset_mappable)


@contextmanager
def chdir_context(folder_path: StrOrPath) -> Generator[Path, None, None]:
"""Context manager to change directory to ``folder_path``.
Parameters
----------
folder_path: StrOrPath
Path to change to.
Yields
------
Generator[Path, None, None]
Resolved path of ``folder_path``.
Raises
------
ValueError
If ``folder_path`` is an existing file.
"""
original_dir = Path(os.curdir).resolve()
folder_path = Path(folder_path)
if folder_path.is_file() is True:
raise ValueError("Value of 'folder_path' needs to be a folder but was an existing file.")
folder_path.mkdir(parents=True, exist_ok=True)
try:
os.chdir(folder_path)
yield folder_path.resolve()
finally:
os.chdir(original_dir)


def relative_posix_path(source_path: StrOrPath, base_path: StrOrPath | None = None) -> str:
"""Ensure that ``source_path`` is a posix path, relative to ``base_path`` if defined.
Expand Down
38 changes: 36 additions & 2 deletions glotaran/utils/test/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from __future__ import annotations

import html
import os
import sys
from pathlib import Path

Expand All @@ -19,6 +20,7 @@
from glotaran.testing.simulated_data.sequential_spectral_decay import SCHEME
from glotaran.testing.simulated_data.shared_decay import SPECTRAL_AXIS
from glotaran.utils.io import DatasetMapping
from glotaran.utils.io import chdir_context
from glotaran.utils.io import create_clp_guide_dataset
from glotaran.utils.io import load_datasets
from glotaran.utils.io import relative_posix_path
Expand Down Expand Up @@ -196,11 +198,43 @@ def test_relative_posix_path(tmp_path: Path, rel_file_path: str):

assert rel_result_path == rel_file_path

rel_result_no_coomon = relative_posix_path(
rel_result_no_common = relative_posix_path(
(tmp_path / f"../{rel_file_path}").resolve().as_posix(), str(tmp_path)
)

assert rel_result_no_coomon == f"../{rel_file_path}"
assert rel_result_no_common == f"../{rel_file_path}"


def test_chdir_context(tmp_path: Path):
"""Original Path is restored even after exception is thrown."""
original_dir = Path(os.curdir).resolve()
with chdir_context(tmp_path) as curdir:
assert curdir == tmp_path.resolve()
assert tmp_path.resolve() == Path(os.curdir).resolve()
assert Path("test.txt").resolve() == (tmp_path / "test.txt").resolve()

assert Path(os.curdir).resolve() == original_dir

with pytest.raises(ValueError):
with chdir_context(tmp_path):
raise ValueError("Original path will be restored after I raise.")

assert Path(os.curdir).resolve() == original_dir


def test_chdir_context_exception(tmp_path: Path):
"""Raise error if ``folder_path`` is an existing file instead of a folder."""
file_path = tmp_path / "test.txt"
file_path.touch()

with pytest.raises(ValueError) as excinfo:
with chdir_context(file_path):
pass

assert (
str(excinfo.value)
== "Value of 'folder_path' needs to be a folder but was an existing file."
)


@pytest.mark.skipif(not sys.platform.startswith("win32"), reason="Only needed for Windows")
Expand Down

0 comments on commit ad96e6f

Please sign in to comment.