@@ -2293,6 +2293,38 @@ class Config:
22932293 expected_detail = "Check validator" ,
22942294 )
22952295
2296+ async def test_field_validator_can_change_value (self ):
2297+ class UserSchemaWithValidator (BaseModel ):
2298+ name : str
2299+
2300+ @validator ("name" )
2301+ def fix_title (cls , v ):
2302+ return v .title ()
2303+
2304+ class Config :
2305+ orm_mode = True
2306+
2307+ attrs = {"name" : "john doe" }
2308+ create_user_body = {"data" : {"attributes" : attrs }}
2309+
2310+ app = self .build_app (UserSchemaWithValidator )
2311+ async with AsyncClient (app = app , base_url = "http://test" ) as client :
2312+ url = app .url_path_for (f"get_{ self .resource_type } _list" )
2313+ res = await client .post (url , json = create_user_body )
2314+ assert res .status_code == status .HTTP_201_CREATED , res .text
2315+
2316+ res_json = res .json ()
2317+ assert res_json ["data" ]
2318+ assert res_json ["data" ].pop ("id" )
2319+ assert res_json == {
2320+ "data" : {
2321+ "attributes" : {"name" : "John Doe" },
2322+ "type" : "validator" ,
2323+ },
2324+ "jsonapi" : {"version" : "1.0" },
2325+ "meta" : None ,
2326+ }
2327+
22962328 @mark .parametrize (
22972329 ("name" , "expected_detail" ),
22982330 [
@@ -2346,5 +2378,38 @@ class Config:
23462378 expected_detail = expected_detail ,
23472379 )
23482380
2381+ async def test_root_validator_can_change_value (self ):
2382+ class UserSchemaWithValidator (BaseModel ):
2383+ name : str
2384+
2385+ @root_validator
2386+ def fix_title (cls , v ):
2387+ v ["name" ] = v ["name" ].title ()
2388+ return v
2389+
2390+ class Config :
2391+ orm_mode = True
2392+
2393+ attrs = {"name" : "john doe" }
2394+ create_user_body = {"data" : {"attributes" : attrs }}
2395+
2396+ app = self .build_app (UserSchemaWithValidator )
2397+ async with AsyncClient (app = app , base_url = "http://test" ) as client :
2398+ url = app .url_path_for (f"get_{ self .resource_type } _list" )
2399+ res = await client .post (url , json = create_user_body )
2400+ assert res .status_code == status .HTTP_201_CREATED , res .text
2401+
2402+ res_json = res .json ()
2403+ assert res_json ["data" ]
2404+ assert res_json ["data" ].pop ("id" )
2405+ assert res_json == {
2406+ "data" : {
2407+ "attributes" : {"name" : "John Doe" },
2408+ "type" : "validator" ,
2409+ },
2410+ "jsonapi" : {"version" : "1.0" },
2411+ "meta" : None ,
2412+ }
2413+
23492414
23502415# todo: test errors
0 commit comments