Skip to content

Commit 7663205

Browse files
fix networks types
1 parent ffd0adc commit 7663205

File tree

2 files changed

+26
-9
lines changed

2 files changed

+26
-9
lines changed
Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,25 @@
11
from typing import Annotated, TypeAlias
22

33
from pydantic import AfterValidator, AnyHttpUrl, AnyUrl, HttpUrl
4+
from pydantic_core import Url
45

56

6-
def _strip_last_slash(url: str) -> str:
7-
return url.rstrip("/")
7+
def _strip_last_slash(url: Url) -> str:
8+
return f"{url}".rstrip("/")
89

910

1011
AnyUrlLegacy: TypeAlias = Annotated[
1112
AnyUrl,
12-
AfterValidator(str),
1313
AfterValidator(_strip_last_slash),
1414
]
1515

1616
AnyHttpUrlLegacy: TypeAlias = Annotated[
1717
AnyHttpUrl,
18-
AfterValidator(str),
1918
AfterValidator(_strip_last_slash),
2019
]
2120

2221

2322
HttpUrlLegacy: TypeAlias = Annotated[
2423
HttpUrl,
25-
AfterValidator(str),
2624
AfterValidator(_strip_last_slash),
2725
]
Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,39 @@
1+
import pytest
12
from common_library.pydantic_networks_extension import AnyHttpUrlLegacy
2-
from pydantic import AnyHttpUrl, TypeAdapter
3+
from pydantic import AnyHttpUrl, BaseModel, TypeAdapter, ValidationError
34
from pydantic_core import Url
45

56

7+
class A(BaseModel):
8+
url: AnyHttpUrlLegacy
9+
10+
611
def test_any_http_url():
712
url = TypeAdapter(AnyHttpUrl).validate_python(
813
"http://backgroud.testserver.io",
914
)
1015

1116
assert isinstance(url, Url)
12-
assert f"{url}" == "http://backgroud.testserver.io/" # NOTE: trailing '/' added in Pydantic v2
17+
assert (
18+
f"{url}" == "http://backgroud.testserver.io/"
19+
) # trailing slash added (in Pydantic v2)
20+
1321

1422
def test_any_http_url_legacy():
1523
url = TypeAdapter(AnyHttpUrlLegacy).validate_python(
16-
"http://backgroud.testserver.io",
24+
"http://backgroud.testserver.io",
1725
)
1826

1927
assert isinstance(url, str)
20-
assert url == "http://backgroud.testserver.io"
28+
assert url == "http://backgroud.testserver.io" # no trailing slash was added
29+
30+
31+
def test_valid_any_http_url_legacy_field():
32+
a = A(url="http://backgroud.testserver.io") # type: ignore
33+
34+
assert a.url == "http://backgroud.testserver.io" # no trailing slash was added
35+
36+
37+
def test_not_valid_any_http_url_legacy_field():
38+
with pytest.raises(ValidationError):
39+
A(url="htttttp://backgroud.testserver.io") # type: ignore

0 commit comments

Comments
 (0)