diff --git a/newsfragments/772.bugfix b/newsfragments/772.bugfix new file mode 100644 index 000000000..be6889d36 --- /dev/null +++ b/newsfragments/772.bugfix @@ -0,0 +1 @@ +Do not try to resolve file paths if they are not accessible. diff --git a/src/dxtbx/serialize/filename.py b/src/dxtbx/serialize/filename.py index 8427de4b6..1f60f7720 100644 --- a/src/dxtbx/serialize/filename.py +++ b/src/dxtbx/serialize/filename.py @@ -14,11 +14,15 @@ def resolve_path(path, directory=None): directory (Optional[str]): The local path to resolve relative links Returns: - str: The absolute path to the file to read + str: The absolute path to the file to read if accessible, otherwise + return the original path as provided """ if not path: return "" - path = os.path.expanduser(os.path.expandvars(path)) - if directory and not os.path.isabs(path): - path = os.path.join(directory, path) - return os.path.abspath(path) + trial_path = os.path.expanduser(os.path.expandvars(path)) + if directory and not os.path.isabs(trial_path): + trial_path = os.path.join(directory, trial_path) + if os.path.exists(trial_path): + return os.path.abspath(trial_path) + else: + return path diff --git a/tests/serialize/test_filename.py b/tests/serialize/test_filename.py index 65393fac7..e492d4faf 100644 --- a/tests/serialize/test_filename.py +++ b/tests/serialize/test_filename.py @@ -1,15 +1,30 @@ from __future__ import annotations import os +import uuid from dxtbx.serialize.filename import resolve_path def test_resolve_path(monkeypatch): + # Resolve path + def alwaystrue(path): + return True + + # Set an environment variable monkeypatch.setenv("HELLO_WORLD", "EXPANDED") - new_path = os.path.join("~", "$HELLO_WORLD", "path") + + # First try a path that does not exist + filename = str(uuid.uuid4()) + new_path = os.path.join("~", "$HELLO_WORLD", filename) path = resolve_path(new_path) - assert path == os.path.join(os.path.expanduser("~"), "EXPANDED", "path") - new_path = os.path.join("$HELLO_WORLD", "path") + assert path == new_path + + # Now pretend the path exists + monkeypatch.setattr(os.path, "exists", alwaystrue) + path = resolve_path(new_path) + assert path == os.path.join(os.path.expanduser("~"), "EXPANDED", filename) + + new_path = os.path.join("$HELLO_WORLD", filename) path = resolve_path(new_path) - assert path == os.path.abspath(os.path.join("EXPANDED", "path")) + assert path == os.path.abspath(os.path.join("EXPANDED", filename))