From f801e390f4ed77e014e7d39dcea9a743cb9be89a Mon Sep 17 00:00:00 2001 From: Syed Ahnaf Raza Date: Fri, 27 Nov 2026 01:01:56 +0500 Subject: [PATCH] Raise ValueError in with_name() for '' and '.' --- upath/core.py | 3 ++- upath/tests/cases.py | 6 ++++++ upath/tests/implementations/test_data.py | 7 +++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/upath/core.py b/upath/core.py index 7937f3b7..379fd976 100644 --- a/upath/core.py +++ b/upath/core.py @@ -1186,7 +1186,8 @@ def parts(self) -> Sequence[str]: def with_name(self, name: str) -> Self: """Return a new path with the file name changed.""" split = self.parser.split - if self.parser.sep in name: # `split(name)[0]` + # `self.parser.sep in name` is `split(name)[0]` + if self.parser.sep in name or name in ("", "."): raise ValueError(f"Invalid name {name!r}") _path = self.__vfspath__() _path = _path.removesuffix(split(_path)[1]) + name diff --git a/upath/tests/cases.py b/upath/tests/cases.py index 36c63fe4..71cf6369 100644 --- a/upath/tests/cases.py +++ b/upath/tests/cases.py @@ -77,6 +77,12 @@ def test_with_name(self): path = path.with_name("file.zip") assert path.name == "file.zip" + @pytest.mark.parametrize("name", ["", "."]) + def test_with_name_invalid(self, name): + path = self.path / "file.txt" + with pytest.raises(ValueError, match="Invalid name"): + path.with_name(name) + def test_with_suffix(self): path = self.path / "file.txt" path = path.with_suffix(".zip") diff --git a/upath/tests/implementations/test_data.py b/upath/tests/implementations/test_data.py index a9e69b0e..5f10c346 100644 --- a/upath/tests/implementations/test_data.py +++ b/upath/tests/implementations/test_data.py @@ -55,6 +55,13 @@ def test_with_name(self): with pytest.raises(UnsupportedOperation): self.path.with_name("newname") + @overrides_base + @pytest.mark.parametrize("name", ["", "."]) + def test_with_name_invalid(self, name): + # DataPath does not support name changes + with pytest.raises(UnsupportedOperation): + self.path.with_name(name) + @overrides_base def test_with_suffix(self): # DataPath does not support suffix changes