Skip to content

Commit 0d83b84

Browse files
committed
Add absolute path check for filename validation
1 parent 3e55596 commit 0d83b84

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

pathvalidate/_file.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,8 @@ def validate(self, value: PathType) -> None:
223223
unicode_filename = preprocess(value)
224224
value_len = len(unicode_filename)
225225

226+
self.__validate_abspath(unicode_filename)
227+
226228
if value_len > self.max_len:
227229
raise InvalidLengthError(
228230
"filename is too long: expected<={:d}, actual={:d}".format(self.max_len, value_len)
@@ -239,6 +241,14 @@ def validate(self, value: PathType) -> None:
239241
else:
240242
self.__validate_unix_filename(unicode_filename)
241243

244+
def __validate_abspath(self, value: str) -> None:
245+
if any([ntpath.isabs(value), posixpath.isabs(value)]):
246+
raise ValidationError(
247+
description="found an absolute path ({}), expected a filename".format(value),
248+
platform=self.platform,
249+
reason=ErrorReason.FOUND_ABS_PATH,
250+
)
251+
242252
def __validate_unix_filename(self, unicode_filename: str) -> None:
243253
match = self.__RE_INVALID_FILENAME.findall(unicode_filename)
244254
if match:

test/test_filename.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,13 @@
1111
import pytest
1212

1313
from pathvalidate import (
14+
ErrorReason,
1415
InvalidCharError,
1516
InvalidLengthError,
1617
NullNameError,
1718
Platform,
1819
ReservedNameError,
20+
ValidationError,
1921
is_valid_filename,
2022
sanitize_filename,
2123
validate_filename,
@@ -281,8 +283,9 @@ def test_exception_reserved_name(self, value, platform, expected):
281283
],
282284
)
283285
def test_exception_filepath(self, value, platform):
284-
with pytest.raises(InvalidCharError):
286+
with pytest.raises(ValidationError) as e:
285287
validate_filename(value, platform=platform)
288+
assert e.value.reason in [ErrorReason.FOUND_ABS_PATH, ErrorReason.INVALID_CHARACTER]
286289
assert not is_valid_filename(value, platform=platform)
287290

288291
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)