Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix serialization of LazyObject #320

Merged
merged 1 commit into from
May 15, 2024
Merged
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
5 changes: 5 additions & 0 deletions reactivated/serialization/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from django.conf import settings
from django.db import models
from django.forms.models import ModelChoiceIteratorValue
from django.utils.functional import LazyObject
from django.utils.module_loading import import_string

from reactivated import fields, stubs, utils
Expand Down Expand Up @@ -1135,6 +1136,10 @@ def serialize(
if value is None:
return None

# If value is a lazy object, resolve it before continuing.
if isinstance(value, LazyObject):
value = value.__reduce__()[1][0]

serializer: Serializer
serializer_path = schema.schema.get("serializer", None)

Expand Down
9 changes: 9 additions & 0 deletions tests/__snapshots__/serialization.ambr
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,15 @@
'type': 'object',
})
# ---
# name: test_serialize_lazy_object
Thing(
definitions=dict({
}),
schema=dict({
'type': 'string',
}),
)
# ---
# name: test_simple_union
Thing(
definitions=dict({
Expand Down
8 changes: 8 additions & 0 deletions tests/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from django.db import models as django_models
from django.db.models import IntegerField, Model, UUIDField
from django.forms.models import ModelChoiceIteratorValue
from django.utils.functional import SimpleLazyObject
from django.utils.translation import gettext, gettext_lazy
from jsonschema import validate

Expand Down Expand Up @@ -245,6 +246,12 @@ def test_serialization():
convert_to_json_and_validate(serialized, generated_schema)


def test_serialize_lazy_object(snapshot):
schema = create_schema(str, {})
assert serialize(SimpleLazyObject(lambda: "hello"), schema) == "hello"
assert schema == snapshot


@pytest.mark.skip
def test_form():
generated_schema = create_schema(forms.OperaForm, {})
Expand Down Expand Up @@ -608,6 +615,7 @@ def test_simple_union(snapshot):
assert serialize(["1", "2", "3"], schema) == ["1", "2", "3"]
assert serialize((5, "hello"), schema) == [5, "hello"]
assert serialize(True, schema) is True
assert serialize(SimpleLazyObject(lambda: "hello"), schema) == "hello"
assert schema == snapshot


Expand Down
Loading