Skip to content

Commit

Permalink
Use mode=json for get_prep_value during field value serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
surenkov committed Mar 30, 2024
1 parent ef706b5 commit 15562af
Show file tree
Hide file tree
Showing 5 changed files with 25 additions and 13 deletions.
2 changes: 1 addition & 1 deletion django_pydantic_field/v2/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def validate_json(self, value: str | bytes, *, strict: bool | None = None) -> ST

def dump_python(self, value: ty.Any, **override_kwargs: ty.Unpack[ExportKwargs]) -> ty.Any:
"""Dump the value to a Python object."""
union_kwargs = ChainMap(override_kwargs, self._dump_python_kwargs) # type: ignore
union_kwargs = ChainMap(override_kwargs, self._dump_python_kwargs, {"mode": "json"}) # type: ignore
return self.type_adapter.dump_python(value, **union_kwargs)

def dump_json(self, value: ty.Any, **override_kwargs: ty.Unpack[ExportKwargs]) -> bytes:
Expand Down
17 changes: 14 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import typing as t
from datetime import date
from syrupy.extensions.json import JSONSnapshotExtension

import pydantic
import pytest

from django.conf import settings
from pydantic.dataclasses import dataclass

from rest_framework.test import APIRequestFactory
from syrupy.extensions.json import JSONSnapshotExtension

from django_pydantic_field.compat import PYDANTIC_V2


class InnerSchema(pydantic.BaseModel):
Expand All @@ -28,6 +28,17 @@ class SampleDataclass:
stub_int: int = 1


class SchemaWithCustomTypes(pydantic.BaseModel):
url: pydantic.HttpUrl = "http://localhost/"
uid: pydantic.UUID4 = "367388a6-9b3b-4ef0-af84-a27d61a05bc7"
crd: pydantic.PaymentCardNumber = "4111111111111111"

if PYDANTIC_V2:
b64: pydantic.Base64Str = "YmFzZTY0"
model_config = dict(validate_default=True) # type: ignore



@pytest.fixture
def request_factory():
return APIRequestFactory()
Expand Down
3 changes: 2 additions & 1 deletion tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from django_pydantic_field import fields
from django_pydantic_field.compat.pydantic import PYDANTIC_V1, PYDANTIC_V2

from .conftest import InnerSchema, SampleDataclass # noqa
from .conftest import InnerSchema, SampleDataclass, SchemaWithCustomTypes # noqa
from .sample_app.models import Building
from .test_app.models import SampleForwardRefModel, SampleModel, SampleSchema

Expand Down Expand Up @@ -113,6 +113,7 @@ class Meta:
fields.PydanticSchemaField(schema=ty.Optional[SampleRootModel], default=[""]),
fields.PydanticSchemaField(schema=ty.Optional[SampleRootModel], null=True, default=None),
fields.PydanticSchemaField(schema=ty.Optional[SampleRootModel], null=True, blank=True),
fields.PydanticSchemaField(schema=SchemaWithCustomTypes, default={}),
pytest.param(
fields.PydanticSchemaField(schema=ty.Optional[SampleRootModel], default=SampleRootModel.parse_obj([])),
marks=pytest.mark.xfail(
Expand Down
4 changes: 2 additions & 2 deletions tests/v2/rest_framework/test_e2e_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ def test_end_to_end_api_view(view, request_factory):
def test_end_to_end_list_create_api_view(request_factory):
field_data = InnerSchema(stub_str="abc", stub_list=[date(2022, 7, 1)]).json()
expected_result = {
"sample_field": {"stub_str": "abc", "stub_list": [date(2022, 7, 1)], "stub_int": 1},
"sample_list": [{"stub_str": "abc", "stub_list": [date(2022, 7, 1)], "stub_int": 1}],
"sample_field": {"stub_str": "abc", "stub_list": ["2022-07-01"], "stub_int": 1},
"sample_list": [{"stub_str": "abc", "stub_list": ["2022-07-01"], "stub_int": 1}],
"sample_seq": [],
}

Expand Down
12 changes: 6 additions & 6 deletions tests/v2/rest_framework/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def test_schema_field():
expected_encoded = {
"stub_str": "abc",
"stub_int": 1,
"stub_list": [date(2022, 7, 1)],
"stub_list": ["2022-07-01"],
}

assert field.to_representation(existing_instance) == expected_encoded
Expand All @@ -53,7 +53,7 @@ def test_schema_field():
def test_field_schema_with_custom_config():
field = rest_framework.SchemaField(InnerSchema, allow_null=True, exclude={"stub_int"})
existing_instance = InnerSchema(stub_str="abc", stub_list=[date(2022, 7, 1)])
expected_encoded = {"stub_str": "abc", "stub_list": [date(2022, 7, 1)]}
expected_encoded = {"stub_str": "abc", "stub_list": ["2022-07-01"]}

assert field.to_representation(existing_instance) == expected_encoded
assert field.to_internal_value(expected_encoded) == existing_instance
Expand All @@ -63,7 +63,7 @@ def test_field_schema_with_custom_config():

def test_serializer_marshalling_with_schema_field():
existing_instance = {"field": [InnerSchema(stub_str="abc", stub_list=[date(2022, 7, 1)])], "annotated_field": []}
expected_data = {"field": [{"stub_str": "abc", "stub_int": 1, "stub_list": [date(2022, 7, 1)]}], "annotated": []}
expected_data = {"field": [{"stub_str": "abc", "stub_int": 1, "stub_list": ["2022-07-01"]}], "annotated": []}
expected_validated_data = {"field": [InnerSchema(stub_str="abc", stub_list=[date(2022, 7, 1)])], "annotated": []}

serializer = SampleSerializer(instance=existing_instance)
Expand All @@ -83,9 +83,9 @@ def test_model_serializer_marshalling_with_schema_field():
serializer = SampleModelSerializer(instance)

expected_data = {
"sample_field": {"stub_str": "abc", "stub_int": 1, "stub_list": [date(2022, 7, 1)]},
"sample_list": [{"stub_str": "abc", "stub_int": 2, "stub_list": [date(2022, 7, 1)]}] * 2,
"sample_seq": [{"stub_str": "abc", "stub_int": 3, "stub_list": [date(2022, 7, 1)]}] * 3,
"sample_field": {"stub_str": "abc", "stub_int": 1, "stub_list": ["2022-07-01"]},
"sample_list": [{"stub_str": "abc", "stub_int": 2, "stub_list": ["2022-07-01"]}] * 2,
"sample_seq": [{"stub_str": "abc", "stub_int": 3, "stub_list": ["2022-07-01"]}] * 3,
}
assert serializer.data == expected_data

Expand Down

0 comments on commit 15562af

Please sign in to comment.