diff --git a/newsfragments/+suffix-separators.bugfix.rst b/newsfragments/+suffix-separators.bugfix.rst new file mode 100644 index 0000000..05411ed --- /dev/null +++ b/newsfragments/+suffix-separators.bugfix.rst @@ -0,0 +1 @@ +Reject directory separators in ``Path.with_suffix`` so replacing an extension cannot change the parent directory. Use the path's configured module to distinguish Windows and POSIX separators. diff --git a/path/__init__.py b/path/__init__.py index 731e88e..371c06c 100644 --- a/path/__init__.py +++ b/path/__init__.py @@ -331,6 +331,8 @@ def suffix(self) -> Self: def with_suffix(self, suffix: str) -> Self: """Return a new path with the file suffix changed (or added, if none) + The suffix must start with a dot and contain no directory separators. + >>> Path('/home/guido/python.tar.gz').with_suffix(".foo") Path('/home/guido/python.tar.foo') @@ -342,7 +344,10 @@ def with_suffix(self, suffix: str) -> Self: ... ValueError: Invalid suffix 'zip' """ - if not suffix.startswith('.'): + separators = (self.module.sep, self.module.altsep) + if not suffix.startswith('.') or any( + sep and sep in suffix for sep in separators + ): raise ValueError(f"Invalid suffix {suffix!r}") return self.stripext() + suffix diff --git a/tests/test_path.py b/tests/test_path.py index 55d733c..8bcd163 100644 --- a/tests/test_path.py +++ b/tests/test_path.py @@ -169,6 +169,34 @@ def test_explicit_module_classes(self): assert nt_path is Path.using_module(ntpath) assert nt_path.__name__ == 'Path_ntpath' + @pytest.mark.parametrize('module', [posixpath, ntpath]) + @pytest.mark.parametrize('suffix', ['.txt/child', './child', '.txt/']) + def test_with_suffix_rejects_directory_separator(self, module, suffix): + filename = Path.using_module(module)('archive.tar.gz') + with pytest.raises(ValueError, match='Invalid suffix'): + filename.with_suffix(suffix) + + @pytest.mark.parametrize('suffix', [r'.txt\child', '.\\child', '.txt\\']) + def test_with_suffix_rejects_windows_separator(self, suffix): + filename = Path.using_module(ntpath)('archive.tar.gz') + with pytest.raises(ValueError, match='Invalid suffix'): + filename.with_suffix(suffix) + + def test_with_suffix_preserves_posix_backslash(self): + filename = Path.using_module(posixpath)('archive.tar.gz') + result = filename.with_suffix(r'.txt\child') + assert result == r'archive.tar.txt\child' + assert isinstance(result, type(filename)) + + @pytest.mark.parametrize('module', [posixpath, ntpath]) + @pytest.mark.parametrize('suffix', ['.txt', '.tar.gz']) + def test_with_suffix_preserves_directory(self, module, suffix): + path_cls = Path.using_module(module) + filename = path_cls('directory') / 'archive.tar.gz' + result = filename.with_suffix(suffix) + assert result == path_cls('directory') / ('archive.tar' + suffix) + assert isinstance(result, path_cls) + def test_joinpath_on_instance(self): res = Path('foo') foo_bar = res.joinpath('bar')