Skip to content

Commit

Permalink
tests for file_utils.normalize_path
Browse files Browse the repository at this point in the history
  • Loading branch information
dmichaels-harvard committed May 6, 2024
1 parent 33e1edf commit 09d6f2f
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 10 deletions.
16 changes: 8 additions & 8 deletions dcicutils/file_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,25 +79,25 @@ def search_for_file(file: str,
return None if single is True else []


def normalize_path(value: Union[str, pathlib.Path], absolute: bool = False, home: Optional[bool] = None) -> str:
def normalize_path(value: Union[str, pathlib.Path], absolute: bool = False, expand_home: Optional[bool] = None) -> str:
"""
Normalizes the given path value and returns the result; does things like remove redundant
consecutive directory separators and redundant parent paths. If the given absolute argument
is True than converts the path to an absolute path. If the given home argument is True and
if the path can reasonably be represented with a home directory indicator (i.e. "~"), then
converts it to such. If the home argument is False and path starts with the home directory
indicator then expands it to the actual (absolute) home path. If the given value is not
actually even a string (or pathlib.Path) then returns an empty string.
is True than converts the path to an absolute path. If the given expand_home argument is False
and if the path can reasonably be represented with a home directory indicator (i.e. "~"), then
converts it to such. If the expand_home argument is True and path starts with the home directory
indicator (i.e. "~") then expands it to the actual (absolute) home path of the caller. If the
given path value is not actually even a string (or pathlib.Path) then returns an empty string.
"""
if isinstance(value, pathlib.Path):
value = str(value)
elif not isinstance(value, str):
return ""
if not (value := value.strip()) or not (value := os.path.normpath(value)):
return ""
if home is False:
if expand_home is True:
value = os.path.expanduser(value)
elif (home is True) and (os.name == "posix") and value.startswith(home := HOME_DIRECTORY + os.sep):
elif (expand_home is False) and (os.name == "posix") and value.startswith(home := HOME_DIRECTORY + os.sep):
value = "~/" + value[len(home):]
if absolute is True:
value = os.path.abspath(value)
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "dcicutils"
version = "8.8.4.1b22" # TODO: To become 8.8.5
version = "8.8.4.1b23" # TODO: To become 8.8.5
description = "Utility package for interacting with the 4DN Data Portal and other 4DN resources"
authors = ["4DN-DCIC Team <support@4dnucleome.org>"]
license = "MIT"
Expand Down
43 changes: 42 additions & 1 deletion test/test_file_utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
import importlib
import pytest
import os
from dcicutils.file_utils import search_for_file
from dcicutils.file_utils import normalize_path, search_for_file
from dcicutils.tmpfile_utils import temporary_directory

HOME_DIRECTORY = "/Some/HomeDirectory"
CURRENT_DIRECTORY = os.path.abspath(os.path.curdir)


@pytest.fixture(autouse=True)
def monkey_path_home_directory(monkeypatch):
monkeypatch.setenv("HOME", HOME_DIRECTORY)
file_utils_module = importlib.import_module("dcicutils.file_utils")
save_home_directory = file_utils_module.HOME_DIRECTORY
file_utils_module.HOME_DIRECTORY = HOME_DIRECTORY
yield
file_utils_module = save_home_directory


def test_search_for_file():

Expand Down Expand Up @@ -38,3 +53,29 @@ def test_search_for_file():
assert (set(search_for_file(filename, location=topdirname, recursive=True)) ==
set([filepath, subfilepath]))
assert search_for_file(filename, location=topdirname, recursive=False) == []


def test_normalize_path():
assert os.environ["HOME"] == HOME_DIRECTORY
assert normalize_path(None) == ""
assert normalize_path("") == ""
assert normalize_path(123) == ""
assert normalize_path("///") == "/"
assert normalize_path(".") == "."
assert normalize_path(".//") == "."
assert normalize_path("/") == "/"
assert normalize_path("/.") == "/"
assert normalize_path("./abc") == "abc"
assert normalize_path("./abc", absolute=True) == f"{CURRENT_DIRECTORY}/abc"
assert normalize_path("/abc/def") == "/abc/def"
assert normalize_path("/abc/def/") == "/abc/def"
assert normalize_path("/abc///def") == "/abc/def"
assert normalize_path("///abc///def") == "/abc/def"
assert normalize_path("~///Ghi//Jkl//") == "~/Ghi/Jkl"
assert normalize_path("~///Ghi//Jkl/", expand_home=False, absolute=False) == "~/Ghi/Jkl"
assert normalize_path("~///Ghi//Jkl/", absolute=True) == f"{CURRENT_DIRECTORY}/~/Ghi/Jkl"
assert normalize_path("~///Ghi//Jkl/", expand_home=True, absolute=True) == f"{HOME_DIRECTORY}/Ghi/Jkl"
assert normalize_path("~///Ghi//Jkl/", expand_home=True, absolute=False) == f"{HOME_DIRECTORY}/Ghi/Jkl"
assert normalize_path("~///Ghi//Jkl/", expand_home=False, absolute=True) == f"{CURRENT_DIRECTORY}/~/Ghi/Jkl"
assert normalize_path("~///Ghi//Jkl/", expand_home=True) == f"{HOME_DIRECTORY}/Ghi/Jkl"
assert normalize_path(f"{HOME_DIRECTORY}/Ghi//Jkl/", expand_home=False) == "~/Ghi/Jkl"

0 comments on commit 09d6f2f

Please sign in to comment.