1
1
from __future__ import annotations
2
2
3
3
import uuid
4
- from typing import Any , Generic
4
+ from typing import Any , Generic , TypeVar
5
5
6
6
import pytest
7
7
from pydantic import BaseModel , Field
@@ -22,12 +22,21 @@ class SampleModel(BaseModel):
22
22
value : int = Field (description = "Value field for testing" )
23
23
24
24
25
- class ComplexModel (BaseModel ):
25
+ class SampleModelSubclass (SampleModel ):
26
+ """Subclass of SampleModel for testing."""
27
+
28
+ extra_field : str
29
+
30
+
31
+ SampleModelT = TypeVar ("SampleModelT" , bound = SampleModel )
32
+
33
+
34
+ class ComplexModel (BaseModel , Generic [SampleModelT ]):
26
35
"""Complex Pydantic model for testing."""
27
36
28
37
items : list [str ] = Field (default_factory = list )
29
38
metadata : dict [str , Any ] = Field (default_factory = dict )
30
- nested : SampleModel | None = Field (default = None )
39
+ nested : SampleModelT | None = Field (default = None )
31
40
32
41
33
42
class TestMessageEncoding :
@@ -508,3 +517,23 @@ def test_dynamic_import_load_pydantic(self, monkeypatch):
508
517
inst .pydantic_registry .clear ()
509
518
restored = inst .from_dict (dumped )
510
519
assert restored == sample
520
+
521
+ @pytest .mark .sanity
522
+ @pytest .mark .parametrize (
523
+ "declared_type" ,
524
+ [
525
+ ComplexModel ,
526
+ ComplexModel [SampleModelSubclass ],
527
+ ],
528
+ )
529
+ def test_generic_model_handling (self , declared_type ):
530
+ inst = Serializer ("dict" )
531
+ inst .register_pydantic (ComplexModel [SampleModelSubclass ])
532
+ nested = declared_type (
533
+ items = ["i1" , "i2" ],
534
+ metadata = {"m" : 1 },
535
+ nested = SampleModelSubclass (name = "nested" , value = 10 , extra_field = "extra" ),
536
+ )
537
+ dumped = inst .to_dict (nested )
538
+ restored = inst .from_dict (dumped )
539
+ assert restored == nested
0 commit comments