/
test_serialize.py
1163 lines (843 loc) · 34.8 KB
/
test_serialize.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
New tests for v2 of serialization logic.
"""
import json
import re
import sys
from enum import Enum
from functools import partial, partialmethod
from typing import Any, Callable, ClassVar, Dict, List, Optional, Pattern, Union
import pytest
from pydantic_core import PydanticSerializationError, core_schema, to_jsonable_python
from typing_extensions import Annotated, TypedDict
from pydantic import (
BaseModel,
Field,
FieldSerializationInfo,
PydanticUserError,
SecretStr,
SerializationInfo,
SerializeAsAny,
SerializerFunctionWrapHandler,
TypeAdapter,
computed_field,
errors,
field_serializer,
model_serializer,
)
from pydantic.config import ConfigDict
from pydantic.functional_serializers import PlainSerializer, WrapSerializer
def test_serialize_extra_allow() -> None:
class Model(BaseModel):
x: int
model_config = ConfigDict(extra='allow')
m = Model(x=1, y=2)
assert m.y == 2
assert m.model_dump() == {'x': 1, 'y': 2}
assert json.loads(m.model_dump_json()) == {'x': 1, 'y': 2}
def test_serialize_extra_allow_subclass_1() -> None:
class Parent(BaseModel):
x: int
class Child(Parent):
model_config = ConfigDict(extra='allow')
class Model(BaseModel):
inner: Parent
m = Model(inner=Child(x=1, y=2))
assert m.inner.y == 2
assert m.model_dump() == {'inner': {'x': 1}}
assert json.loads(m.model_dump_json()) == {'inner': {'x': 1}}
def test_serialize_extra_allow_subclass_2() -> None:
class Parent(BaseModel):
x: int
model_config = ConfigDict(extra='allow')
class Child(Parent):
y: int
class Model(BaseModel):
inner: Parent
m = Model(inner=Child(x=1, y=2))
assert m.inner.y == 2
assert m.model_dump() == {'inner': {'x': 1}}
assert json.loads(m.model_dump_json()) == {'inner': {'x': 1}}
m = Model(inner=Parent(x=1, y=2))
assert m.inner.y == 2
assert m.model_dump() == {'inner': {'x': 1, 'y': 2}}
assert json.loads(m.model_dump_json()) == {'inner': {'x': 1, 'y': 2}}
def test_serializer_annotated_plain_always():
FancyInt = Annotated[int, PlainSerializer(lambda x: f'{x:,}', return_type=str)]
class MyModel(BaseModel):
x: FancyInt
assert MyModel(x=1234).model_dump() == {'x': '1,234'}
assert MyModel(x=1234).model_dump(mode='json') == {'x': '1,234'}
assert MyModel(x=1234).model_dump_json() == '{"x":"1,234"}'
def test_serializer_annotated_plain_json():
FancyInt = Annotated[int, PlainSerializer(lambda x: f'{x:,}', return_type=str, when_used='json')]
class MyModel(BaseModel):
x: FancyInt
assert MyModel(x=1234).model_dump() == {'x': 1234}
assert MyModel(x=1234).model_dump(mode='json') == {'x': '1,234'}
assert MyModel(x=1234).model_dump_json() == '{"x":"1,234"}'
def test_serializer_annotated_wrap_always():
def ser_wrap(v: Any, nxt: SerializerFunctionWrapHandler) -> str:
return f'{nxt(v + 1):,}'
FancyInt = Annotated[int, WrapSerializer(ser_wrap, return_type=str)]
class MyModel(BaseModel):
x: FancyInt
assert MyModel(x=1234).model_dump() == {'x': '1,235'}
assert MyModel(x=1234).model_dump(mode='json') == {'x': '1,235'}
assert MyModel(x=1234).model_dump_json() == '{"x":"1,235"}'
def test_serializer_annotated_wrap_json():
def ser_wrap(v: Any, nxt: SerializerFunctionWrapHandler) -> str:
return f'{nxt(v + 1):,}'
FancyInt = Annotated[int, WrapSerializer(ser_wrap, when_used='json')]
class MyModel(BaseModel):
x: FancyInt
assert MyModel(x=1234).model_dump() == {'x': 1234}
assert MyModel(x=1234).model_dump(mode='json') == {'x': '1,235'}
assert MyModel(x=1234).model_dump_json() == '{"x":"1,235"}'
@pytest.mark.parametrize(
'serializer, func',
[
(PlainSerializer, lambda v: f'{v + 1:,}'),
(WrapSerializer, lambda v, nxt: f'{nxt(v + 1):,}'),
],
)
def test_serializer_annotated_typing_cache(serializer, func):
FancyInt = Annotated[int, serializer(func)]
class FancyIntModel(BaseModel):
x: Optional[FancyInt]
assert FancyIntModel(x=1234).model_dump() == {'x': '1,235'}
def test_serialize_decorator_always():
class MyModel(BaseModel):
x: Optional[int]
@field_serializer('x')
def customise_x_serialization(v, _info) -> str:
return f'{v:,}'
assert MyModel(x=1234).model_dump() == {'x': '1,234'}
assert MyModel(x=1234).model_dump(mode='json') == {'x': '1,234'}
assert MyModel(x=1234).model_dump_json() == '{"x":"1,234"}'
m = MyModel(x=None)
# can't use v:, on None, hence error
error_msg = (
'Error calling function `customise_x_serialization`: '
'TypeError: unsupported format string passed to NoneType.__format__'
)
with pytest.raises(PydanticSerializationError, match=error_msg):
m.model_dump()
with pytest.raises(PydanticSerializationError, match=error_msg):
m.model_dump_json()
def test_serialize_decorator_json():
class MyModel(BaseModel):
x: int
@field_serializer('x', when_used='json')
def customise_x_serialization(v) -> str:
return f'{v:,}'
assert MyModel(x=1234).model_dump() == {'x': 1234}
assert MyModel(x=1234).model_dump(mode='json') == {'x': '1,234'}
assert MyModel(x=1234).model_dump_json() == '{"x":"1,234"}'
def test_serialize_decorator_unless_none():
class MyModel(BaseModel):
x: Optional[int]
@field_serializer('x', when_used='unless-none')
def customise_x_serialization(v):
return f'{v:,}'
assert MyModel(x=1234).model_dump() == {'x': '1,234'}
assert MyModel(x=None).model_dump() == {'x': None}
assert MyModel(x=1234).model_dump(mode='json') == {'x': '1,234'}
assert MyModel(x=None).model_dump(mode='json') == {'x': None}
assert MyModel(x=1234).model_dump_json() == '{"x":"1,234"}'
assert MyModel(x=None).model_dump_json() == '{"x":null}'
def test_annotated_customisation():
def parse_int(s: str, _: Any) -> int:
return int(s.replace(',', ''))
class CommaFriendlyIntLogic:
@classmethod
def __get_pydantic_core_schema__(cls, _source, _handler):
# here we ignore the schema argument (which is just `{'type': 'int'}`) and return our own
return core_schema.with_info_before_validator_function(
parse_int,
core_schema.int_schema(),
serialization=core_schema.format_ser_schema(',', when_used='unless-none'),
)
CommaFriendlyInt = Annotated[int, CommaFriendlyIntLogic]
class MyModel(BaseModel):
x: CommaFriendlyInt
m = MyModel(x='1,000')
assert m.x == 1000
assert m.model_dump(mode='json') == {'x': '1,000'}
assert m.model_dump_json() == '{"x":"1,000"}'
def test_serialize_valid_signatures():
def ser_plain(v: Any, info: SerializationInfo) -> Any:
return f'{v:,}'
def ser_wrap(v: Any, nxt: SerializerFunctionWrapHandler, info: SerializationInfo) -> Any:
return f'{nxt(v):,}'
class MyModel(BaseModel):
f1: int
f2: int
f3: int
f4: int
@field_serializer('f1')
def ser_f1(self, v: Any, info: FieldSerializationInfo) -> Any:
assert self.f1 == 1_000
assert v == 1_000
assert info.field_name == 'f1'
return f'{v:,}'
@field_serializer('f2', mode='wrap')
def ser_f2(self, v: Any, nxt: SerializerFunctionWrapHandler, info: FieldSerializationInfo) -> Any:
assert self.f2 == 2_000
assert v == 2_000
assert info.field_name == 'f2'
return f'{nxt(v):,}'
ser_f3 = field_serializer('f3')(ser_plain)
ser_f4 = field_serializer('f4', mode='wrap')(ser_wrap)
m = MyModel(**{f'f{x}': x * 1_000 for x in range(1, 9)})
assert m.model_dump() == {
'f1': '1,000',
'f2': '2,000',
'f3': '3,000',
'f4': '4,000',
}
assert m.model_dump_json() == '{"f1":"1,000","f2":"2,000","f3":"3,000","f4":"4,000"}'
def test_invalid_signature_no_params() -> None:
with pytest.raises(TypeError, match='Unrecognized field_serializer function signature'):
class _(BaseModel):
x: int
# caught by type checkers
@field_serializer('x')
def no_args() -> Any:
...
def test_invalid_signature_single_params() -> None:
with pytest.raises(TypeError, match='Unrecognized field_serializer function signature'):
class _(BaseModel):
x: int
# not caught by type checkers
@field_serializer('x')
def no_args(self) -> Any:
...
def test_invalid_signature_too_many_params_1() -> None:
with pytest.raises(TypeError, match='Unrecognized field_serializer function signature'):
class _(BaseModel):
x: int
# caught by type checkers
@field_serializer('x')
def no_args(self, value: Any, nxt: Any, info: Any, extra_param: Any) -> Any:
...
def test_invalid_signature_too_many_params_2() -> None:
with pytest.raises(TypeError, match='Unrecognized field_serializer function signature'):
class _(BaseModel):
x: int
# caught by type checkers
@field_serializer('x')
@staticmethod
def no_args(not_self: Any, value: Any, nxt: Any, info: Any) -> Any:
...
def test_invalid_signature_bad_plain_signature() -> None:
with pytest.raises(TypeError, match='Unrecognized field_serializer function signature for'):
class _(BaseModel):
x: int
# caught by type checkers
@field_serializer('x', mode='plain')
def no_args(self, value: Any, nxt: Any, info: Any) -> Any:
...
def test_serialize_ignore_info_plain():
class MyModel(BaseModel):
x: int
@field_serializer('x')
def ser_x(v: Any) -> str:
return f'{v:,}'
assert MyModel(x=1234).model_dump() == {'x': '1,234'}
def test_serialize_ignore_info_wrap():
class MyModel(BaseModel):
x: int
@field_serializer('x', mode='wrap')
def ser_x(v: Any, handler: SerializerFunctionWrapHandler) -> str:
return f'{handler(v):,}'
assert MyModel(x=1234).model_dump() == {'x': '1,234'}
def test_serialize_decorator_self_info():
class MyModel(BaseModel):
x: Optional[int]
@field_serializer('x')
def customise_x_serialization(self, v, info) -> str:
return f'{info.mode}:{v:,}'
assert MyModel(x=1234).model_dump() == {'x': 'python:1,234'}
assert MyModel(x=1234).model_dump(mode='foobar') == {'x': 'foobar:1,234'}
def test_serialize_decorator_self_no_info():
class MyModel(BaseModel):
x: Optional[int]
@field_serializer('x')
def customise_x_serialization(self, v) -> str:
return f'{v:,}'
assert MyModel(x=1234).model_dump() == {'x': '1,234'}
def test_model_serializer_plain():
class MyModel(BaseModel):
a: int
b: bytes
@model_serializer
def _serialize(self):
if self.b == b'custom':
return f'MyModel(a={self.a!r}, b={self.b!r})'
else:
return self.__dict__
m = MyModel(a=1, b='boom')
assert m.model_dump() == {'a': 1, 'b': b'boom'}
assert m.model_dump(mode='json') == {'a': 1, 'b': 'boom'}
assert m.model_dump_json() == '{"a":1,"b":"boom"}'
assert m.model_dump(exclude={'a'}) == {'a': 1, 'b': b'boom'} # exclude is ignored as we used self.__dict__
assert m.model_dump(mode='json', exclude={'a'}) == {'a': 1, 'b': 'boom'}
assert m.model_dump_json(exclude={'a'}) == '{"a":1,"b":"boom"}'
m = MyModel(a=1, b='custom')
assert m.model_dump() == "MyModel(a=1, b=b'custom')"
assert m.model_dump(mode='json') == "MyModel(a=1, b=b'custom')"
assert m.model_dump_json() == '"MyModel(a=1, b=b\'custom\')"'
def test_model_serializer_plain_info():
class MyModel(BaseModel):
a: int
b: bytes
@model_serializer
def _serialize(self, info):
if info.exclude:
return {k: v for k, v in self.__dict__.items() if k not in info.exclude}
else:
return self.__dict__
m = MyModel(a=1, b='boom')
assert m.model_dump() == {'a': 1, 'b': b'boom'}
assert m.model_dump(mode='json') == {'a': 1, 'b': 'boom'}
assert m.model_dump_json() == '{"a":1,"b":"boom"}'
assert m.model_dump(exclude={'a'}) == {'b': b'boom'} # exclude is not ignored
assert m.model_dump(mode='json', exclude={'a'}) == {'b': 'boom'}
assert m.model_dump_json(exclude={'a'}) == '{"b":"boom"}'
def test_model_serializer_wrap():
class MyModel(BaseModel):
a: int
b: bytes
c: bytes = Field(exclude=True)
@model_serializer(mode='wrap')
def _serialize(self, handler):
d = handler(self)
d['extra'] = 42
return d
m = MyModel(a=1, b='boom', c='excluded')
assert m.model_dump() == {'a': 1, 'b': b'boom', 'extra': 42}
assert m.model_dump(mode='json') == {'a': 1, 'b': 'boom', 'extra': 42}
assert m.model_dump_json() == '{"a":1,"b":"boom","extra":42}'
assert m.model_dump(exclude={'a'}) == {'b': b'boom', 'extra': 42}
assert m.model_dump(mode='json', exclude={'a'}) == {'b': 'boom', 'extra': 42}
assert m.model_dump_json(exclude={'a'}) == '{"b":"boom","extra":42}'
def test_model_serializer_wrap_info():
class MyModel(BaseModel):
a: int
b: bytes
c: bytes = Field(exclude=True)
@model_serializer(mode='wrap')
def _serialize(self, handler, info):
d = handler(self)
d['info'] = f'mode={info.mode} exclude={info.exclude}'
return d
m = MyModel(a=1, b='boom', c='excluded')
assert m.model_dump() == {'a': 1, 'b': b'boom', 'info': 'mode=python exclude=None'}
assert m.model_dump(mode='json') == {'a': 1, 'b': 'boom', 'info': 'mode=json exclude=None'}
assert m.model_dump_json() == '{"a":1,"b":"boom","info":"mode=json exclude=None"}'
assert m.model_dump(exclude={'a'}) == {'b': b'boom', 'info': "mode=python exclude={'a'}"}
assert m.model_dump(mode='json', exclude={'a'}) == {'b': 'boom', 'info': "mode=json exclude={'a'}"}
assert m.model_dump_json(exclude={'a'}) == '{"b":"boom","info":"mode=json exclude={\'a\'}"}'
def test_model_serializer_plain_json_return_type():
class MyModel(BaseModel):
a: int
@model_serializer(when_used='json')
def _serialize(self) -> str:
if self.a == 666:
return self.a
else:
return f'MyModel(a={self.a!r})'
m = MyModel(a=1)
assert m.model_dump() == {'a': 1}
assert m.model_dump(mode='json') == 'MyModel(a=1)'
assert m.model_dump_json() == '"MyModel(a=1)"'
m = MyModel(a=666)
assert m.model_dump() == {'a': 666}
with pytest.warns(UserWarning, match='Expected `str` but got `int` - serialized value may not be as expected'):
assert m.model_dump(mode='json') == 666
with pytest.warns(UserWarning, match='Expected `str` but got `int` - serialized value may not be as expected'):
assert m.model_dump_json() == '666'
def test_model_serializer_wrong_args():
m = (
r'Unrecognized model_serializer function signature for '
r'<.+MyModel._serialize at 0x\w+> with `mode=plain`:\(self, x, y, z\)'
)
with pytest.raises(TypeError, match=m):
class MyModel(BaseModel):
a: int
@model_serializer
def _serialize(self, x, y, z):
return self
def test_model_serializer_no_self():
with pytest.raises(TypeError, match='`@model_serializer` must be applied to instance methods'):
class MyModel(BaseModel):
a: int
@model_serializer
def _serialize(slf, x, y, z):
return slf
def test_model_serializer_classmethod():
with pytest.raises(TypeError, match='`@model_serializer` must be applied to instance methods'):
class MyModel(BaseModel):
a: int
@model_serializer
@classmethod
def _serialize(self, x, y, z):
return self
def test_field_multiple_serializer():
m = "Multiple field serializer functions were defined for field 'x', this is not allowed."
with pytest.raises(TypeError, match=m):
class MyModel(BaseModel):
x: int
y: int
@field_serializer('x', 'y')
def serializer1(v) -> str:
return f'{v:,}'
@field_serializer('x')
def serializer2(v) -> str:
return v
def test_field_multiple_serializer_subclass():
class MyModel(BaseModel):
x: int
@field_serializer('x')
def serializer1(v) -> str:
return f'{v:,}'
class MySubModel(MyModel):
@field_serializer('x')
def serializer1(v) -> str:
return f'{v}'
assert MyModel(x=1234).model_dump() == {'x': '1,234'}
assert MySubModel(x=1234).model_dump() == {'x': '1234'}
def int_ser_func_without_info1(v: int, expected: int) -> str:
return f'{v:,}'
def int_ser_func_without_info2(v: int, *, expected: int) -> str:
return f'{v:,}'
def int_ser_func_with_info1(v: int, info: FieldSerializationInfo, expected: int) -> str:
return f'{v:,}'
def int_ser_func_with_info2(v: int, info: FieldSerializationInfo, *, expected: int) -> str:
return f'{v:,}'
def int_ser_instance_method_without_info1(self: Any, v: int, *, expected: int) -> str:
assert self.x == v
return f'{v:,}'
def int_ser_instance_method_without_info2(self: Any, v: int, expected: int) -> str:
assert self.x == v
return f'{v:,}'
def int_ser_instance_method_with_info1(self: Any, v: int, info: FieldSerializationInfo, expected: int) -> str:
assert self.x == v
return f'{v:,}'
def int_ser_instance_method_with_info2(self: Any, v: int, info: FieldSerializationInfo, *, expected: int) -> str:
assert self.x == v
return f'{v:,}'
@pytest.mark.parametrize(
'func',
[
int_ser_func_with_info1,
int_ser_func_with_info2,
int_ser_func_without_info1,
int_ser_func_without_info2,
int_ser_instance_method_with_info1,
int_ser_instance_method_with_info2,
int_ser_instance_method_without_info1,
int_ser_instance_method_without_info2,
],
)
def test_serialize_partial(
func: Any,
):
class MyModel(BaseModel):
x: int
ser = field_serializer('x', return_type=str)(partial(func, expected=1234))
assert MyModel(x=1234).model_dump() == {'x': '1,234'}
@pytest.mark.parametrize(
'func',
[
int_ser_func_with_info1,
int_ser_func_with_info2,
int_ser_func_without_info1,
int_ser_func_without_info2,
int_ser_instance_method_with_info1,
int_ser_instance_method_with_info2,
int_ser_instance_method_without_info1,
int_ser_instance_method_without_info2,
],
)
def test_serialize_partialmethod(
func: Any,
):
class MyModel(BaseModel):
x: int
ser = field_serializer('x', return_type=str)(partialmethod(func, expected=1234))
assert MyModel(x=1234).model_dump() == {'x': '1,234'}
def test_serializer_allow_reuse_inheritance_override():
class Parent(BaseModel):
x: int
@field_serializer('x')
def ser_x(self, _v: int, _info: SerializationInfo) -> str:
return 'parent_encoder'
# overriding a serializer with a function / class var
# of the same name is allowed
# to mimic how inheritance works
# the serializer in the child class replaces the parent
# (without modifying the parent class itself)
class Child1(Parent):
@field_serializer('x')
def ser_x(self, _v: int, _info: SerializationInfo) -> str:
return 'child1_encoder' + ' ' + super().ser_x(_v, _info)
assert Parent(x=1).model_dump_json() == '{"x":"parent_encoder"}'
assert Child1(x=1).model_dump_json() == '{"x":"child1_encoder parent_encoder"}'
# defining an _different_ serializer on the other hand is not allowed
# because they would both "exist" thus causing confusion
# since it's not clear if both or just one will run
msg = 'Multiple field serializer functions were defined ' "for field 'x', this is not allowed."
with pytest.raises(TypeError, match=msg):
class _(Parent):
@field_serializer('x')
def ser_x_other(self, _v: int) -> str:
return 'err'
# the same thing applies if defined on the same class
with pytest.raises(TypeError, match=msg):
class _(BaseModel):
x: int
@field_serializer('x')
def ser_x(self, _v: int) -> str:
return 'parent_encoder'
@field_serializer('x')
def other_func_name(self, _v: int) -> str:
return 'parent_encoder'
def test_serializer_allow_reuse_same_field():
with pytest.warns(UserWarning, match='`ser_x` overrides an existing Pydantic `@field_serializer` decorator'):
class Model(BaseModel):
x: int
@field_serializer('x')
def ser_x(self, _v: int) -> str:
return 'ser_1'
@field_serializer('x')
def ser_x(self, _v: int) -> str:
return 'ser_2'
assert Model(x=1).model_dump() == {'x': 'ser_2'}
def test_serializer_allow_reuse_different_field_1():
with pytest.warns(UserWarning, match='`ser` overrides an existing Pydantic `@field_serializer` decorator'):
class Model(BaseModel):
x: int
y: int
@field_serializer('x')
def ser(self, _v: int) -> str:
return 'x'
@field_serializer('y')
def ser(self, _v: int) -> str:
return 'y'
assert Model(x=1, y=2).model_dump() == {'x': 1, 'y': 'y'}
def test_serializer_allow_reuse_different_field_2():
with pytest.warns(UserWarning, match='`ser_x` overrides an existing Pydantic `@field_serializer` decorator'):
def ser(self: Any, _v: int, _info: Any) -> str:
return 'ser'
class Model(BaseModel):
x: int
y: int
@field_serializer('x')
def ser_x(self, _v: int) -> str:
return 'ser_x'
ser_x = field_serializer('y')(ser)
assert Model(x=1, y=2).model_dump() == {'x': 1, 'y': 'ser'}
def test_serializer_allow_reuse_different_field_3():
with pytest.warns(UserWarning, match='`ser_x` overrides an existing Pydantic `@field_serializer` decorator'):
def ser1(self: Any, _v: int, _info: Any) -> str:
return 'ser1'
def ser2(self: Any, _v: int, _info: Any) -> str:
return 'ser2'
class Model(BaseModel):
x: int
y: int
ser_x = field_serializer('x')(ser1)
ser_x = field_serializer('y')(ser2)
assert Model(x=1, y=2).model_dump() == {'x': 1, 'y': 'ser2'}
def test_serializer_allow_reuse_different_field_4():
def ser(self: Any, _v: int, _info: Any) -> str:
return f'{_v:,}'
class Model(BaseModel):
x: int
y: int
ser_x = field_serializer('x')(ser)
not_ser_x = field_serializer('y')(ser)
assert Model(x=1_000, y=2_000).model_dump() == {'x': '1,000', 'y': '2,000'}
def test_serialize_any_model():
class Model(BaseModel):
m: str
@field_serializer('m')
def ser_m(self, v: str, _info: SerializationInfo) -> str:
return f'custom:{v}'
class AnyModel(BaseModel):
x: Any
m = Model(m='test')
assert m.model_dump() == {'m': 'custom:test'}
assert to_jsonable_python(AnyModel(x=m)) == {'x': {'m': 'custom:test'}}
assert AnyModel(x=m).model_dump() == {'x': {'m': 'custom:test'}}
def test_invalid_field():
msg = (
r'Decorators defined with incorrect fields:'
r' tests.test_serialize.test_invalid_field.<locals>.Model:\d+.customise_b_serialization'
r" \(use check_fields=False if you're inheriting from the model and intended this\)"
)
with pytest.raises(errors.PydanticUserError, match=msg):
class Model(BaseModel):
a: str
@field_serializer('b')
def customise_b_serialization(v):
return v
def test_serialize_with_extra():
class Inner(BaseModel):
a: str = 'a'
class Outer(BaseModel):
# this cause the inner model incorrectly dumpped:
model_config = ConfigDict(extra='allow')
inner: Inner = Field(default_factory=Inner)
m = Outer.model_validate({})
assert m.model_dump() == {'inner': {'a': 'a'}}
def test_model_serializer_nested_models() -> None:
class Model(BaseModel):
x: int
inner: Optional['Model']
@model_serializer(mode='wrap')
def ser_model(self, handler: Callable[['Model'], Dict[str, Any]]) -> Dict[str, Any]:
inner = handler(self)
inner['x'] += 1
return inner
assert Model(x=0, inner=None).model_dump() == {'x': 1, 'inner': None}
assert Model(x=2, inner=Model(x=1, inner=Model(x=0, inner=None))).model_dump() == {
'x': 3,
'inner': {'x': 2, 'inner': {'x': 1, 'inner': None}},
}
def test_pattern_serialize():
ta = TypeAdapter(Pattern[str])
pattern = re.compile('^regex$')
assert ta.dump_python(pattern) == pattern
assert ta.dump_python(pattern, mode='json') == '^regex$'
assert ta.dump_json(pattern) == b'"^regex$"'
def test_custom_return_schema():
class Model(BaseModel):
x: int
@field_serializer('x', return_type=str)
def ser_model(self, v) -> int:
return repr(v)
return_serializer = re.search(r'return_serializer: *\w+', repr(Model.__pydantic_serializer__)).group(0)
assert return_serializer == 'return_serializer: Str'
def test_clear_return_schema():
class Model(BaseModel):
x: int
@field_serializer('x', return_type=Any)
def ser_model(self, v) -> int:
return repr(v)
return_serializer = re.search(r'return_serializer: *\w+', repr(Model.__pydantic_serializer__)).group(0)
assert return_serializer == 'return_serializer: Any'
def test_type_adapter_dump_json():
class Model(TypedDict):
x: int
y: float
@model_serializer(mode='plain')
def ser_model(self) -> Dict[str, Any]:
return {'x': self['x'] * 2, 'y': self['y'] * 3}
ta = TypeAdapter(Model)
assert ta.dump_json(Model({'x': 1, 'y': 2.5})) == b'{"x":2,"y":7.5}'
def test_serialize_as_any() -> None:
class User(BaseModel):
name: str
class UserLogin(User):
password: SecretStr
class OuterModel(BaseModel):
maybe_as_any: Optional[SerializeAsAny[User]] = None
as_any: SerializeAsAny[User]
without: User
user = UserLogin(name='pydantic', password='password')
# insert_assert(json.loads(OuterModel(as_any=user, without=user).model_dump_json()))
assert json.loads(OuterModel(maybe_as_any=user, as_any=user, without=user).model_dump_json()) == {
'maybe_as_any': {'name': 'pydantic', 'password': '**********'},
'as_any': {'name': 'pydantic', 'password': '**********'},
'without': {'name': 'pydantic'},
}
@pytest.mark.parametrize('as_annotation', [True, False])
@pytest.mark.parametrize('mode', ['plain', 'wrap'])
def test_forward_ref_for_serializers(as_annotation, mode):
if mode == 'plain':
def ser_model_func(v) -> 'SomeOtherModel': # noqa F821
return OtherModel(y=v + 1)
def ser_model_method(self, v) -> 'SomeOtherModel': # noqa F821
return ser_model_func(v)
annotation = PlainSerializer(ser_model_func)
else:
def ser_model_func(v, handler) -> 'SomeOtherModel': # noqa F821
return OtherModel(y=v + 1)
def ser_model_method(self, v, handler) -> 'SomeOtherModel': # noqa F821
return ser_model_func(v, handler)
annotation = WrapSerializer(ser_model_func)
class Model(BaseModel):
if as_annotation:
x: Annotated[int, annotation]
else:
x: int
ser_model = field_serializer('x', mode=mode)(ser_model_method)
class OtherModel(BaseModel):
y: int
Model.model_rebuild(_types_namespace={'SomeOtherModel': OtherModel})
assert Model(x=1).model_dump() == {'x': {'y': 2}}
assert Model.model_json_schema(mode='serialization') == {
'$defs': {
'OtherModel': {
'properties': {'y': {'title': 'Y', 'type': 'integer'}},
'required': ['y'],
'title': 'OtherModel',
'type': 'object',
}
},
'properties': {'x': {'allOf': [{'$ref': '#/$defs/OtherModel'}], 'title': 'X'}},
'required': ['x'],
'title': 'Model',
'type': 'object',
}
def test_forward_ref_for_computed_fields():
class Model(BaseModel):
x: int
@computed_field
@property
def two_x(self) -> 'IntAlias': # noqa F821
return self.x * 2
Model.model_rebuild(_types_namespace={'IntAlias': int})
assert Model.model_json_schema(mode='serialization') == {
'properties': {
'two_x': {'readOnly': True, 'title': 'Two X', 'type': 'integer'},
'x': {'title': 'X', 'type': 'integer'},
},
'required': ['x', 'two_x'],
'title': 'Model',
'type': 'object',
}
assert Model(x=1).model_dump() == {'two_x': 2, 'x': 1}
def test_computed_field_custom_serializer():
class Model(BaseModel):
x: int
@computed_field
@property
def two_x(self) -> int:
return self.x * 2
@field_serializer('two_x', when_used='json')
def ser_two_x(self, v):