Skip to content

Commit

Permalink
kernelci.api.models: fix pydantic warnings for url fields
Browse files Browse the repository at this point in the history
Fix the below pydantic v2 warnings:
```
Expected `url` but got `str` with value - serialized value may not be as expected
```
This is due to fields such as `artifacts` and `revision.url`
expect pydantic `Url` type and afterwards convert the values
to `str` to store it in mongo DB and for json response.
Change field types to `str` and use `TypeAdapter` to validate
`Url` values before validating them as strings.

Discussion thread for the issue:
pydantic/pydantic#6395

Signed-off-by: Jeny Sadadia <[email protected]>
  • Loading branch information
Jeny Sadadia authored and nuclearcat committed Nov 27, 2024
1 parent 3e3317c commit fa656f1
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions kernelci/api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,21 @@
from pydantic import (
AnyHttpUrl,
AnyUrl,
AfterValidator,
BaseModel,
BeforeValidator,
Field,
FileUrl,
field_validator,
StrictInt,
TypeAdapter,
)
from .models_base import (
PyObjectId,
DatabaseModel,
)

any_url_adapter = TypeAdapter(AnyUrl)
any_http_url_adapter = TypeAdapter(AnyHttpUrl)


class StateValues(str, enum.Enum):
"""Enumeration to declare values to be used for Node.state"""
Expand Down Expand Up @@ -117,7 +120,8 @@ class Revision(BaseModel):
tree: str = Field(
description="git tree of the revision"
)
url: Annotated[AnyUrl | FileUrl, AfterValidator(str)] = Field(
url: Annotated[str, BeforeValidator(
lambda value: str(any_url_adapter.validate_python(value)))] = Field(
description="git URL of the revision"
)
branch: str = Field(
Expand Down Expand Up @@ -205,7 +209,8 @@ class Node(DatabaseModel):
default=None,
description="Result of node",
)
artifacts: Optional[Dict[str, Annotated[AnyHttpUrl, AfterValidator(str)]]] = Field(
artifacts: Optional[Dict[str, Annotated[str, BeforeValidator(
lambda value: str(any_http_url_adapter.validate_python(value)))]]] = Field(
description="Artifacts associated with the node (binaries, logs...)",
default=None
)
Expand Down Expand Up @@ -506,7 +511,8 @@ class TestData(BaseModel):
default=None
)
# [TODO] Specify the source code file/function too?
test_source: Optional[Annotated[AnyUrl, AfterValidator(str)]] = Field(
test_source: Optional[Annotated[str, BeforeValidator(
lambda value: str(any_url_adapter.validate_python(value)))]] = Field(
description="Repository containing the test source code",
default=None
)
Expand Down

0 comments on commit fa656f1

Please sign in to comment.