@@ -1212,7 +1212,7 @@ class Model:
1212
1212
m : Model
1213
1213
1214
1214
m = val .validate_python ({'x' : 123 })
1215
- assert m == Model (x = 1 )
1215
+ assert m == Model (x = 123 )
1216
1216
1217
1217
with pytest .raises (ValidationError ):
1218
1218
val .validate_python ({'x' : 'abc' })
@@ -1222,3 +1222,71 @@ class Model:
1222
1222
1223
1223
with pytest .raises (ValidationError ):
1224
1224
val .validate_assignment (m , 'x' , 'abc' )
1225
+
1226
+
1227
+ def test_dataclass_slots_field_before_validator ():
1228
+ kwargs = {'slots' : True }
1229
+
1230
+ @dataclasses .dataclass (** kwargs )
1231
+ class Foo :
1232
+ a : int
1233
+ b : str
1234
+
1235
+ @classmethod
1236
+ def validate_b (cls , v : bytes , info : core_schema .FieldValidationInfo ) -> bytes :
1237
+ assert v == b'hello'
1238
+ assert info .field_name == 'b'
1239
+ assert info .data == {'a' : 1 }
1240
+ return b'hello world!'
1241
+
1242
+ schema = core_schema .dataclass_schema (
1243
+ Foo ,
1244
+ core_schema .dataclass_args_schema (
1245
+ 'Foo' ,
1246
+ [
1247
+ core_schema .dataclass_field (name = 'a' , schema = core_schema .int_schema ()),
1248
+ core_schema .dataclass_field (
1249
+ name = 'b' ,
1250
+ schema = core_schema .field_before_validator_function (Foo .validate_b , core_schema .str_schema ()),
1251
+ ),
1252
+ ],
1253
+ ),
1254
+ )
1255
+
1256
+ v = SchemaValidator (schema )
1257
+ foo = v .validate_python ({'a' : 1 , 'b' : b'hello' })
1258
+ assert dataclasses .asdict (foo ) == {'a' : 1 , 'b' : 'hello world!' }
1259
+
1260
+
1261
+ def test_dataclass_slots_field_after_validator ():
1262
+ kwargs = {'slots' : True }
1263
+
1264
+ @dataclasses .dataclass (** kwargs )
1265
+ class Foo :
1266
+ a : int
1267
+ b : str
1268
+
1269
+ @classmethod
1270
+ def validate_b (cls , v : str , info : core_schema .FieldValidationInfo ) -> str :
1271
+ assert v == 'hello'
1272
+ assert info .field_name == 'b'
1273
+ assert info .data == {'a' : 1 }
1274
+ return 'hello world!'
1275
+
1276
+ schema = core_schema .dataclass_schema (
1277
+ Foo ,
1278
+ core_schema .dataclass_args_schema (
1279
+ 'Foo' ,
1280
+ [
1281
+ core_schema .dataclass_field (name = 'a' , schema = core_schema .int_schema ()),
1282
+ core_schema .dataclass_field (
1283
+ name = 'b' ,
1284
+ schema = core_schema .field_after_validator_function (Foo .validate_b , core_schema .str_schema ()),
1285
+ ),
1286
+ ],
1287
+ ),
1288
+ )
1289
+
1290
+ v = SchemaValidator (schema )
1291
+ foo = v .validate_python ({'a' : 1 , 'b' : b'hello' })
1292
+ assert dataclasses .asdict (foo ) == {'a' : 1 , 'b' : 'hello world!' }
0 commit comments