Skip to content

Commit 6a5ffac

Browse files
authored
♻️ raise ValueError instead of AttributeError on wrong S3Path value (#354)
* ♻️ raise `ValueError` instead of `AttributeError` on wrong `S3Path` value * fix linter warning * fix linters * fix linters * remove deprecated field_name parameter
1 parent 7164efc commit 6a5ffac

File tree

2 files changed

+21
-6
lines changed

2 files changed

+21
-6
lines changed

pydantic_extra_types/s3.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,14 +40,16 @@ class TestModel(BaseModel):
4040
```
4141
"""
4242

43-
patt: ClassVar[str] = r'^s3://([^/]+)/(.*?([^/]+)/?)$'
43+
patt: ClassVar[re.Pattern[str]] = re.compile(r'^s3://([^/]+)/(.*?([^/]+)/?)$')
4444

4545
def __init__(self, value: str) -> None:
4646
self.value = value
47-
groups: tuple[str, str, str] = re.match(self.patt, self.value).groups() # type: ignore
48-
self.bucket: str = groups[0]
49-
self.key: str = groups[1]
50-
self.last_key: str = groups[2]
47+
match = self.patt.match(self.value)
48+
if match is None:
49+
raise ValueError(f'Invalid S3 path: {value!r}')
50+
self.bucket: str = match.group(1)
51+
self.key: str = match.group(2)
52+
self.last_key: str = match.group(3)
5153

5254
def __str__(self) -> str: # pragma: no cover
5355
return self.value
@@ -65,5 +67,4 @@ def __get_pydantic_core_schema__(cls, source: type[Any], handler: GetCoreSchemaH
6567
return core_schema.with_info_after_validator_function(
6668
cls._validate,
6769
core_schema.str_schema(pattern=cls.patt),
68-
field_name=cls.__class__.__name__,
6970
)

tests/test_s3.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,3 +150,17 @@ def test_s3(raw: str, bucket: str, key: str, last_key: str):
150150
def test_wrong_s3():
151151
with pytest.raises(ValidationError):
152152
S3Check(path='s3/ok')
153+
154+
155+
@pytest.mark.parametrize(
156+
'invalid_path',
157+
[
158+
's3/ok',
159+
'not-an-s3-path',
160+
's3://bucket-only',
161+
],
162+
)
163+
def test_wrong_s3_raises_value_error(invalid_path: str):
164+
"""Test that invalid S3 paths raise ValueError."""
165+
with pytest.raises(ValueError, match='Invalid S3 path'):
166+
S3Path(invalid_path)

0 commit comments

Comments
 (0)