@@ -150,13 +150,27 @@ def test_exclude_none():
150
150
151
151
152
152
def test_exclude_default ():
153
+ class TestComparison :
154
+ def __init__ (self , val : Any ):
155
+ self .val = val
156
+
157
+ def __eq__ (self , other ):
158
+ return self .val == other .val
159
+
153
160
v = SchemaSerializer (
154
161
core_schema .typed_dict_schema (
155
162
{
156
163
'foo' : core_schema .typed_dict_field (core_schema .nullable_schema (core_schema .int_schema ())),
157
164
'bar' : core_schema .typed_dict_field (
158
165
core_schema .with_default_schema (core_schema .bytes_schema (), default = b'[default]' )
159
166
),
167
+ 'foobar' : core_schema .typed_dict_field (
168
+ core_schema .with_default_schema (
169
+ core_schema .any_schema (),
170
+ default = TestComparison (val = 1 ),
171
+ default_comparison = lambda value , default : value .val == - 1 * default .val ,
172
+ )
173
+ ),
160
174
}
161
175
)
162
176
)
@@ -165,9 +179,19 @@ def test_exclude_default():
165
179
assert v .to_python ({'foo' : 1 , 'bar' : b'[default]' }, exclude_defaults = True ) == {'foo' : 1 }
166
180
assert v .to_python ({'foo' : 1 , 'bar' : b'[default]' }, mode = 'json' ) == {'foo' : 1 , 'bar' : '[default]' }
167
181
assert v .to_python ({'foo' : 1 , 'bar' : b'[default]' }, exclude_defaults = True , mode = 'json' ) == {'foo' : 1 }
168
-
169
182
assert v .to_json ({'foo' : 1 , 'bar' : b'[default]' }) == b'{"foo":1,"bar":"[default]"}'
170
183
assert v .to_json ({'foo' : 1 , 'bar' : b'[default]' }, exclude_defaults = True ) == b'{"foo":1}'
184
+ # Note that due to the custom comparison operator foobar must be excluded
185
+ assert v .to_python ({'foo' : 1 , 'bar' : b'x' , 'foobar' : TestComparison (val = - 1 )}, exclude_defaults = True ) == {
186
+ 'foo' : 1 ,
187
+ 'bar' : b'x' ,
188
+ }
189
+ # foobar here must be included
190
+ assert v .to_python ({'foo' : 1 , 'bar' : b'x' , 'foobar' : TestComparison (val = 1 )}, exclude_defaults = True ) == {
191
+ 'foo' : 1 ,
192
+ 'bar' : b'x' ,
193
+ 'foobar' : TestComparison (val = 1 ),
194
+ }
171
195
172
196
173
197
def test_function_plain_field_serializer_to_python ():
0 commit comments