()
| 156 | |
| 157 | |
| 158 | def test_subclass_custom_encoding(): |
| 159 | class SubDt(datetime): |
| 160 | @classmethod |
| 161 | def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema: |
| 162 | def val(v: datetime) -> SubDt: |
| 163 | return SubDt.fromtimestamp(v.timestamp()) |
| 164 | |
| 165 | return core_schema.no_info_after_validator_function(val, handler(datetime)) |
| 166 | |
| 167 | class SubDelta(timedelta): |
| 168 | @classmethod |
| 169 | def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema: |
| 170 | def val(v: timedelta) -> SubDelta: |
| 171 | return cls(seconds=v.total_seconds()) |
| 172 | |
| 173 | return core_schema.no_info_after_validator_function(val, handler(timedelta)) |
| 174 | |
| 175 | class Model(BaseModel): |
| 176 | a: SubDt |
| 177 | b: SubDelta |
| 178 | |
| 179 | @field_serializer('a', when_used='json') |
| 180 | def serialize_a(self, v: SubDt, _info): |
| 181 | return v.strftime('%a, %d %b %C %H:%M:%S') |
| 182 | |
| 183 | model_config = ConfigDict(ser_json_timedelta='float') |
| 184 | |
| 185 | m = Model(a=SubDt(2032, 1, 1, 1, 1), b=SubDelta(hours=100)) |
| 186 | assert m.model_dump() == {'a': SubDt(2032, 1, 1, 1, 1), 'b': SubDelta(days=4, seconds=14400)} |
| 187 | assert m.model_dump(mode='json') == {'a': 'Thu, 01 Jan 20 01:01:00', 'b': 360000.0} |
| 188 | assert m.model_dump_json() == '{"a":"Thu, 01 Jan 20 01:01:00","b":360000.0}' |
| 189 | |
| 190 | |
| 191 | def test_invalid_model(): |
nothing calls this directly
no test coverage detected