MCPcopy
hub / github.com/pydantic/pydantic / test_subclass_encoding

Function test_subclass_encoding

tests/test_json.py:140–155  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

138
139
140def test_subclass_encoding():
141 class SubDate(datetime):
142 @classmethod
143 def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
144 def val(v: datetime) -> SubDate:
145 return SubDate.fromtimestamp(v.timestamp())
146
147 return core_schema.no_info_after_validator_function(val, handler(datetime))
148
149 class Model(BaseModel):
150 a: datetime
151 b: SubDate
152
153 m = Model(a=datetime(2032, 1, 1, 1, 1), b=SubDate(2020, 2, 29, 12, 30))
154 assert m.model_dump() == {'a': datetime(2032, 1, 1, 1, 1), 'b': SubDate(2020, 2, 29, 12, 30)}
155 assert m.model_dump_json() == '{"a":"2032-01-01T01:01:00","b":"2020-02-29T12:30:00"}'
156
157
158def test_subclass_custom_encoding():

Callers

nothing calls this directly

Calls 4

SubDateClass · 0.85
model_dump_jsonMethod · 0.80
ModelClass · 0.70
model_dumpMethod · 0.45

Tested by

no test coverage detected