diff --git a/src/pyprojroot/root.py b/src/pyprojroot/root.py index d2a5377..2260764 100644 --- a/src/pyprojroot/root.py +++ b/src/pyprojroot/root.py @@ -6,7 +6,7 @@ """ from pathlib import Path -from typing import Union, Tuple +from typing import Union, Tuple, Optional from .criterion import ( as_root_criterion as _as_root_criterion, @@ -15,13 +15,11 @@ ) -def as_start_path(start: Union[None, _PathType]) -> Path: - if start is None: - return Path.cwd() - if not isinstance(start, Path): - start = Path(start) - # TODO: consider `start = start.resolve()` - return start +def as_start_path(start: Optional[_PathType]) -> Path: + """Convert path argument into normalised Path object.""" + if start is not None: + return Path(start).expanduser().resolve() + return Path.cwd().resolve() def find_root_with_reason( @@ -39,7 +37,6 @@ def find_root_with_reason( # Prepare inputs criterion = _as_root_criterion(criterion) start = as_start_path(start) - # Check start if start.is_dir() and criterion(start): return start, "Pass" diff --git a/tests/test_root.py b/tests/test_root.py new file mode 100644 index 0000000..17b0e58 --- /dev/null +++ b/tests/test_root.py @@ -0,0 +1,60 @@ +import os + +import pytest + +from pyprojroot.root import as_start_path, find_root + +MARKER = ".here" + + +@pytest.fixture +def temp_dir_structure(tmp_path): + """ + Create a pytest temp path for testing: + + tmp_path/ + └── dir1/ + ├── .here <-- marker file + └── dir2/ + """ + dir1 = tmp_path / "dir1" + dir2 = dir1 / "dir2" + os.makedirs(dir1 / MARKER) + os.makedirs(dir2) + return dir1, dir2 + + +def test_as_start_path_normalized_path(): + result01 = as_start_path("~") # Home + assert result01.is_dir() + + result02 = as_start_path("~/.") # Still at Home + assert result02.is_dir() + assert result01 == result02 + + result03 = as_start_path("~/..") # One directory below Home + assert result03.is_dir() + assert result03 != result02 + + +def test_find_root_marker_in_child(temp_dir_structure): + """Marker is in child folder, checking the parent should raise.""" + dir1, _ = temp_dir_structure + + os.chdir(dir1) + result = find_root(MARKER, start=".") + assert result.is_dir() + + with pytest.raises(RuntimeError, match="Project root not found."): + find_root(MARKER, start="..") + + +def test_find_root_marker_in_parent(temp_dir_structure): + """Marker in parent - child and parent should successfully find a root.""" + _, dir2 = temp_dir_structure + os.chdir(dir2) + result01 = find_root(MARKER, start=".") + assert result01.is_dir() + + result02 = find_root(MARKER, start="..") + assert result02.is_dir()