@@ -281,7 +281,7 @@ class Config:
281
281
assert m .json () == '{\n "a": 1,\n "b": "foo"\n }'
282
282
283
283
284
- def test_json_nested_encode ():
284
+ def test_json_nested_encode_models ():
285
285
class Phone (BaseModel ):
286
286
manufacturer : str
287
287
number : int
@@ -314,8 +314,58 @@ class Config:
314
314
315
315
timon .friend = pumbaa
316
316
317
- assert iphone .json () == '{"manufacturer": "Apple", "number": 18002752273}'
317
+ assert iphone .json (models_as_dict = False ) == '{"manufacturer": "Apple", "number": 18002752273}'
318
318
assert (
319
- pumbaa .json () == '{"name": "Pumbaa", "SSN": 234, "birthday": 737424000.0, "phone": 18007267864, "friend": null}'
319
+ pumbaa .json (models_as_dict = False )
320
+ == '{"name": "Pumbaa", "SSN": 234, "birthday": 737424000.0, "phone": 18007267864, "friend": null}'
320
321
)
321
- assert timon .json () == '{"name": "Timon", "SSN": 123, "birthday": 738892800.0, "phone": 18002752273, "friend": 234}'
322
+ assert (
323
+ timon .json (models_as_dict = False )
324
+ == '{"name": "Timon", "SSN": 123, "birthday": 738892800.0, "phone": 18002752273, "friend": 234}'
325
+ )
326
+
327
+
328
+ def test_custom_encode_fallback_basemodel ():
329
+ class MyExoticType :
330
+ pass
331
+
332
+ def custom_encoder (o ):
333
+ if isinstance (o , MyExoticType ):
334
+ return 'exo'
335
+ raise TypeError ('not serialisable' )
336
+
337
+ class Foo (BaseModel ):
338
+ x : MyExoticType
339
+
340
+ class Config :
341
+ arbitrary_types_allowed = True
342
+
343
+ class Bar (BaseModel ):
344
+ foo : Foo
345
+
346
+ assert Bar (foo = Foo (x = MyExoticType ())).json (encoder = custom_encoder ) == '{"foo": {"x": "exo"}}'
347
+
348
+
349
+ def test_custom_encode_error ():
350
+ class MyExoticType :
351
+ pass
352
+
353
+ def custom_encoder (o ):
354
+ raise TypeError ('not serialisable' )
355
+
356
+ class Foo (BaseModel ):
357
+ x : MyExoticType
358
+
359
+ class Config :
360
+ arbitrary_types_allowed = True
361
+
362
+ with pytest .raises (TypeError , match = 'not serialisable' ):
363
+ Foo (x = MyExoticType ()).json (encoder = custom_encoder )
364
+
365
+
366
+ def test_recursive ():
367
+ class Model (BaseModel ):
368
+ value : Optional [str ]
369
+ nested : Optional [BaseModel ]
370
+
371
+ assert Model (value = None , nested = Model (value = None )).json (exclude_none = True ) == '{"nested": {}}'
0 commit comments