Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ def __init__(self, model: type[BaseModel]):

def to_dict(self, data: BaseModel) -> dict:
# The result is stored as JSON, so dump JSON-compatible values; from_dict validates them back into the model.
return data.model_dump(mode="json")
# Dump with aliases so the stored dict is what model_validate() accepts for models with field aliases.
return data.model_dump(mode="json", by_alias=True)

def from_dict(self, data: dict) -> BaseModel:
return self.__model.model_validate(data)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
from uuid import UUID

import pytest
from pydantic import BaseModel
from pydantic import BaseModel, ConfigDict, Field
from pydantic.alias_generators import to_camel
from pytest_mock import MockerFixture

from aws_lambda_powertools.utilities.idempotency import (
Expand Down Expand Up @@ -304,6 +305,42 @@ def test_pydantic_serializer_round_trips_non_json_types(payment_receipt: Payment
assert serializer.from_dict(json.loads(stored)) == payment_receipt


class AliasedOrder(BaseModel):
order_id: str = Field(alias="orderId")


class CamelOrder(BaseModel):
model_config = ConfigDict(alias_generator=to_camel)

order_id: str
customer_name: str


class PopulateByNameOrder(BaseModel):
model_config = ConfigDict(populate_by_name=True)

order_id: str = Field(alias="orderId")


@pytest.mark.parametrize(
"model, order",
[
(AliasedOrder, AliasedOrder(orderId="abc")),
(CamelOrder, CamelOrder(orderId="abc", customerName="ada")),
(PopulateByNameOrder, PopulateByNameOrder(orderId="abc")),
],
)
def test_pydantic_serializer_round_trips_field_aliases(model, order):
# GIVEN a serializer for a model with field aliases
serializer = PydanticSerializer(model=model)

# WHEN the model is stored as JSON, the same way the persistence layer saves a result
stored = json_serialize(serializer.to_dict(order))

# THEN reading it back returns the same model
assert serializer.from_dict(json.loads(stored)) == order


@pytest.mark.parametrize("output_serializer_type", ["explicit", "deduced"])
def test_idempotent_function_serialization_pydantic_with_non_json_types(
output_serializer_type: str,
Expand Down