Skip to content

Commit c1db89a

Browse files
continue fixing
1 parent fdb7238 commit c1db89a

File tree

11 files changed

+80
-56
lines changed

11 files changed

+80
-56
lines changed
Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
1-
from hypothesis import provisional
2-
from hypothesis import strategies as st
3-
from pydantic import AnyHttpUrl, AnyUrl, HttpUrl
4-
51
# FIXME: For now it seems the pydantic hypothesis plugin does not provide strategies for these types.
62
# therefore we currently provide it
7-
st.register_type_strategy(AnyUrl, provisional.urls())
8-
st.register_type_strategy(HttpUrl, provisional.urls())
9-
st.register_type_strategy(AnyHttpUrl, provisional.urls())
3+
# st.register_type_strategy(AnyUrl, provisional.urls())
4+
# st.register_type_strategy(HttpUrl, provisional.urls())
5+
# st.register_type_strategy(AnyHttpUrl, provisional.urls())

services/web/server/src/simcore_service_webserver/notifications/_rabbitmq_exclusive_queue_consumers.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
)
1414
from models_library.socketio import SocketMessageDict
1515
from models_library.users import GroupID
16-
from pydantic import parse_raw_as
16+
from pydantic import TypeAdapter
1717
from servicelib.logging_utils import log_catch, log_context
1818
from servicelib.rabbitmq import RabbitMQClient
1919
from servicelib.utils import logged_gather
@@ -58,17 +58,19 @@ async def _convert_to_node_update_event(
5858
"data": project["workbench"][f"{message.node_id}"],
5959
},
6060
)
61-
_logger.warning("node not found: '%s'", message.dict())
61+
_logger.warning("node not found: '%s'", message.model_dump())
6262
except ProjectNotFoundError:
63-
_logger.warning("project not found: '%s'", message.dict())
63+
_logger.warning("project not found: '%s'", message.model_dump())
6464
return None
6565

6666

6767
async def _progress_message_parser(app: web.Application, data: bytes) -> bool:
6868
rabbit_message: (
6969
ProgressRabbitMessageNode | ProgressRabbitMessageProject
70-
) = parse_raw_as(
71-
ProgressRabbitMessageNode | ProgressRabbitMessageProject, data # type: ignore[arg-type] # from pydantic v2 --> https://github.com/pydantic/pydantic/discussions/4950
70+
) = TypeAdapter(
71+
ProgressRabbitMessageNode | ProgressRabbitMessageProject
72+
).validate_json(
73+
data
7274
)
7375
message: SocketMessageDict | None = None
7476
if isinstance(rabbit_message, ProgressRabbitMessageProject):
@@ -126,7 +128,7 @@ async def _events_message_parser(app: web.Application, data: bytes) -> bool:
126128

127129

128130
async def _osparc_credits_message_parser(app: web.Application, data: bytes) -> bool:
129-
rabbit_message = parse_raw_as(WalletCreditsMessage, data)
131+
rabbit_message = TypeAdapter(WalletCreditsMessage).validate_json(data)
130132
wallet_groups = await wallets_api.list_wallet_groups_with_read_access_by_wallet(
131133
app, wallet_id=rabbit_message.wallet_id
132134
)

services/web/server/src/simcore_service_webserver/projects/_crud_handlers_models.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,13 @@
1818
)
1919
from models_library.workspaces import WorkspaceID
2020
from pydantic import (
21-
TypeAdapter, field_validator, ConfigDict, BaseModel,
21+
BaseModel,
22+
ConfigDict,
2223
Field,
2324
Json,
25+
TypeAdapter,
26+
field_validator,
27+
model_validator,
2428
)
2529
from servicelib.common_headers import (
2630
UNDEFINED_DEFAULT_SIMCORE_USER_AGENT_VALUE,
@@ -65,6 +69,7 @@ def check_parent_valid(cls, values: dict[str, Any]) -> dict[str, Any]:
6569
msg = "Both parent_project_uuid and parent_node_id must be set or both null or both unset"
6670
raise ValueError(msg)
6771
return values
72+
6873
model_config = ConfigDict(populate_by_name=False)
6974

7075

@@ -115,9 +120,9 @@ def search_check_empty_string(cls, v):
115120
return None
116121
return v
117122

118-
_null_or_none_str_to_none_validator = field_validator(
119-
"folder_id", mode="before"
120-
)(null_or_none_str_to_none_validator)
123+
_null_or_none_str_to_none_validator = field_validator("folder_id", mode="before")(
124+
null_or_none_str_to_none_validator
125+
)
121126

122127
_null_or_none_str_to_none_validator2 = field_validator(
123128
"workspace_id", mode="before"
@@ -147,6 +152,7 @@ def validate_order_by_field(cls, v):
147152
msg = f"We do not support ordering by provided field {v.field}"
148153
raise ValueError(msg)
149154
return v
155+
150156
model_config = ConfigDict(extra="forbid")
151157

152158

services/web/server/src/simcore_service_webserver/scicrunch/_rest.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
from typing import Any
1919

2020
from aiohttp import ClientSession
21-
from pydantic import BaseModel, Field
21+
from pydantic import BaseModel, Field, RootModel
2222
from yarl import URL
2323

2424
from .models import ResourceHit
@@ -49,7 +49,7 @@ class ResourceView(BaseModel):
4949

5050
@classmethod
5151
def from_response_payload(cls, payload: dict):
52-
assert payload["success"] == True # nosec
52+
assert payload["success"] is True # nosec
5353
return cls(**payload["data"])
5454

5555
@property
@@ -72,8 +72,8 @@ def get_resource_url(self):
7272
return URL(str(self._get_field("Resource URL")))
7373

7474

75-
class ListOfResourceHits(BaseModel):
76-
__root__: list[ResourceHit]
75+
class ListOfResourceHits(RootModel[list[ResourceHit]]):
76+
...
7777

7878

7979
# REQUESTS
@@ -120,4 +120,4 @@ async def autocomplete_by_name(
120120
) as resp:
121121
body = await resp.json()
122122
assert body.get("success") # nosec
123-
return ListOfResourceHits.parse_obj(body.get("data", []))
123+
return ListOfResourceHits.model_validate(body.get("data", []))

services/web/server/src/simcore_service_webserver/scicrunch/settings.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from aiohttp import web
2-
from pydantic import Field, HttpUrl, SecretStr, parse_obj_as
2+
from pydantic import Field, HttpUrl, SecretStr, TypeAdapter
33
from settings_library.base import BaseCustomSettings
44

55
from .._constants import APP_SETTINGS_KEY
@@ -11,7 +11,7 @@
1111
class SciCrunchSettings(BaseCustomSettings):
1212

1313
SCICRUNCH_API_BASE_URL: HttpUrl = Field(
14-
default=parse_obj_as(HttpUrl, f"{SCICRUNCH_DEFAULT_URL}/api/1"),
14+
default=TypeAdapter(HttpUrl).validate_python(f"{SCICRUNCH_DEFAULT_URL}/api/1"),
1515
description="Base url to scicrunch API's entrypoint",
1616
)
1717

@@ -20,7 +20,9 @@ class SciCrunchSettings(BaseCustomSettings):
2020
SCICRUNCH_API_KEY: SecretStr
2121

2222
SCICRUNCH_RESOLVER_BASE_URL: HttpUrl = Field(
23-
default=parse_obj_as(HttpUrl, f"{SCICRUNCH_DEFAULT_URL}/resolver"),
23+
default=TypeAdapter(HttpUrl).validate_python(
24+
f"{SCICRUNCH_DEFAULT_URL}/resolver"
25+
),
2426
description="Base url to scicrunch resolver entrypoint",
2527
)
2628

services/web/server/src/simcore_service_webserver/storage/schemas.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from typing import Any, TypeAlias
33

44
from models_library.api_schemas_storage import TableSynchronisation
5-
from pydantic import ConfigDict, BaseModel, Field
5+
from pydantic import BaseModel, ConfigDict, Field, RootModel
66

77
# NOTE: storage generates URLs that contain double encoded
88
# slashes, and when applying validation via `StorageFileID`
@@ -24,8 +24,8 @@ class FileLocation(BaseModel):
2424
)
2525

2626

27-
class FileLocationArray(BaseModel):
28-
__root__: list[FileLocation]
27+
class FileLocationArray(RootModel[list[FileLocation]]):
28+
...
2929

3030

3131
class Links(BaseModel):
@@ -70,8 +70,8 @@ class DatasetMetaData(BaseModel):
7070
)
7171

7272

73-
class DatasetMetaDataArray(BaseModel):
74-
__root__: list[DatasetMetaData]
73+
class DatasetMetaDataArray(RootModel[list[DatasetMetaData]]):
74+
...
7575

7676

7777
class FileLocationEnveloped(BaseModel):
@@ -141,8 +141,8 @@ class FileMetaData(BaseModel):
141141
)
142142

143143

144-
class FileMetaDataArray(BaseModel):
145-
__root__: list[FileMetaData]
144+
class FileMetaDataArray(RootModel[list[FileMetaData]]):
145+
...
146146

147147

148148
class FileMetaEnvelope(BaseModel):
@@ -153,9 +153,8 @@ class FileMetaEnvelope(BaseModel):
153153
class PresignedLink(BaseModel):
154154
link: str | None = None
155155

156-
model_config = ConfigDict(
157-
json_schema_extra={"example": {"link": "example_link"}}
158-
)
156+
model_config = ConfigDict(json_schema_extra={"example": {"link": "example_link"}})
157+
159158

160159
class PresignedLinkEnveloped(BaseModel):
161160
data: PresignedLink

services/web/server/src/simcore_service_webserver/tags/schemas.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import re
22
from datetime import datetime
3+
from typing import Annotated
34

45
from models_library.api_schemas_webserver._base import InputSchema, OutputSchema
56
from models_library.users import GroupID, UserID
6-
from pydantic import ConstrainedStr, Field, PositiveInt
7+
from pydantic import Field, PositiveInt, StringConstraints
78
from servicelib.aiohttp.requests_validation import RequestParams, StrictRequestParams
89
from servicelib.request_keys import RQT_USERID_KEY
910
from simcore_postgres_database.utils_tags import TagDict
@@ -17,8 +18,9 @@ class TagPathParams(StrictRequestParams):
1718
tag_id: PositiveInt
1819

1920

20-
class ColorStr(ConstrainedStr):
21-
regex = re.compile(r"^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$")
21+
ColorStr = Annotated[
22+
str, StringConstraints(pattern=re.compile(r"^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$"))
23+
]
2224

2325

2426
class TagUpdate(InputSchema):

services/web/server/src/simcore_service_webserver/utils.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,12 @@
1010
import tracemalloc
1111
from datetime import datetime
1212
from pathlib import Path
13-
from typing import Any, TypedDict, cast
13+
from typing import Any, cast
1414

1515
import orjson
1616
from models_library.basic_types import SHA1Str
1717
from models_library.error_codes import ErrorCodeStr
18+
from typing_extensions import TypedDict
1819

1920
_CURRENT_DIR = (
2021
Path(sys.argv[0] if __name__ == "__main__" else __file__).resolve().parent

services/web/server/tests/unit/isolated/test_dynamic_scheduler.py

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -47,18 +47,23 @@ def mock_rpc_client(
4747

4848
@pytest.fixture
4949
def dynamic_service_start() -> DynamicServiceStart:
50-
return DynamicServiceStart.parse_obj(
51-
DynamicServiceStart.Config.schema_extra["example"]
50+
return DynamicServiceStart.model_validate(
51+
DynamicServiceStart.model_config["json_schema_extra"]["example"]
5252
)
5353

5454

5555
@pytest.mark.parametrize(
5656
"expected_response",
5757
[
58-
*[NodeGet.parse_obj(x) for x in NodeGet.Config.schema_extra["examples"]],
59-
NodeGetIdle.parse_obj(NodeGetIdle.Config.schema_extra["example"]),
60-
DynamicServiceGet.parse_obj(
61-
DynamicServiceGet.Config.schema_extra["examples"][0]
58+
*[
59+
NodeGet.model_validate(x)
60+
for x in NodeGet.model_config["json_schema_extra"]["examples"]
61+
],
62+
NodeGetIdle.model_validate(
63+
NodeGetIdle.model_config["json_schema_extra"]["example"]
64+
),
65+
DynamicServiceGet.model_validate(
66+
DynamicServiceGet.model_config["json_schema_extra"]["examples"][0]
6267
),
6368
],
6469
)
@@ -98,9 +103,12 @@ async def test_get_service_status_raises_rpc_server_error(
98103
@pytest.mark.parametrize(
99104
"expected_response",
100105
[
101-
*[NodeGet.parse_obj(x) for x in NodeGet.Config.schema_extra["examples"]],
102-
DynamicServiceGet.parse_obj(
103-
DynamicServiceGet.Config.schema_extra["examples"][0]
106+
*[
107+
NodeGet.model_validate(x)
108+
for x in NodeGet.model_config["json_schema_extra"]["examples"]
109+
],
110+
DynamicServiceGet.model_validate(
111+
DynamicServiceGet.model_config["json_schema_extra"]["examples"][0]
104112
),
105113
],
106114
)

services/web/server/tests/unit/isolated/test_projects__nodes_resources.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@
1818
"resources",
1919
[
2020
parse_obj_as(ServiceResourcesDict, example)
21-
for example in ServiceResourcesDictHelpers.Config.schema_extra["examples"]
21+
for example in ServiceResourcesDictHelpers.model_config["json_schema_extra"][
22+
"examples"
23+
]
2224
],
2325
)
2426
def test_check_can_update_service_resources_with_same_does_not_raise(
@@ -32,7 +34,9 @@ def test_check_can_update_service_resources_with_same_does_not_raise(
3234
"resources",
3335
[
3436
parse_obj_as(ServiceResourcesDict, example)
35-
for example in ServiceResourcesDictHelpers.Config.schema_extra["examples"]
37+
for example in ServiceResourcesDictHelpers.model_config["json_schema_extra"][
38+
"examples"
39+
]
3640
],
3741
)
3842
def test_check_can_update_service_resources_with_invalid_container_name_raises(
@@ -51,7 +55,9 @@ def test_check_can_update_service_resources_with_invalid_container_name_raises(
5155
"resources",
5256
[
5357
parse_obj_as(ServiceResourcesDict, example)
54-
for example in ServiceResourcesDictHelpers.Config.schema_extra["examples"]
58+
for example in ServiceResourcesDictHelpers.model_config["json_schema_extra"][
59+
"examples"
60+
]
5561
],
5662
)
5763
def test_check_can_update_service_resources_with_invalid_image_name_raises(

0 commit comments

Comments
 (0)