Skip to content

Commit a5f9ac8

Browse files
committed
add test
1 parent 1839d3b commit a5f9ac8

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

tests/serializers/test_model.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -565,6 +565,42 @@ def ser_x(self, v: Any, _) -> str:
565565
assert json.loads(s.to_json(Model(x=1000))) == {'x': '1_000'}
566566

567567

568+
def test_function_plain_field_serializer_with_computed_field():
569+
@dataclasses.dataclass
570+
class Model:
571+
x: int
572+
573+
@property
574+
def computed_field_x(self) -> int:
575+
return self.x + 200
576+
577+
def ser_func(self, v: Any, serializer: core_schema.FieldSerializationInfo) -> str:
578+
return str(v * 2)
579+
580+
field_str_with_field_serializer = core_schema.str_schema(
581+
serialization=core_schema.plain_serializer_function_ser_schema(
582+
Model.ser_func,
583+
is_field_serializer=True,
584+
info_arg=True,
585+
return_schema=core_schema.any_schema(),
586+
)
587+
)
588+
589+
s = SchemaSerializer(
590+
core_schema.model_schema(
591+
Model,
592+
core_schema.model_fields_schema(
593+
{'x': core_schema.model_field(field_str_with_field_serializer)},
594+
computed_fields=[
595+
core_schema.computed_field('computed_field_x', field_str_with_field_serializer),
596+
],
597+
),
598+
)
599+
)
600+
assert json.loads(s.to_json(Model(x=1000))) == {'x': '2000', 'computed_field_x': '2400'}
601+
assert s.to_python(Model(x=2000)) == {'x': '4000', 'computed_field_x': '4400'}
602+
603+
568604
def test_function_wrap_field_serializer_to_json():
569605
@dataclasses.dataclass
570606
class Model:

0 commit comments

Comments
 (0)