polyfactory icon indicating copy to clipboard operation
polyfactory copied to clipboard

Bug: Pydantic Config field `min_anystr_length` not taken into account

Open Leobouloc opened this issue 1 year ago • 3 comments

Description

In a Pydantic model, when using Config field min_anystr_length (to set a minimum length for all strings in the model), Polyfactory does not seem to take it into account which leads to pydantic validation errors during build.

My understanding is that currently, Polyfactory only parses the allow_population_by_field_name (here) from the Config.

Is this assessment correct ? Thank you for your help !

URL to code causing the issue

No response

MCVE

from polyfactory.factories.pydantic_factory import ModelFactory
from pydantic import BaseModel

ModelFactory.seed_random(0)

class TestClass(BaseModel):
    class Config:
        min_anystr_length = 100
    myfield: str

class TestClassFactory(ModelFactory[TestClass]):
    __model__ = TestClass


class TestClassWithoutConfig(BaseModel):
    myfield: str

class TestClassWithoutConfigFactory(ModelFactory[TestClassWithoutConfig]):
    __model__ = TestClassWithoutConfig


print(TestClassWithoutConfigFactory.build()) # OK
print(TestClassFactory.build()) # ERROR

#E   pydantic.error_wrappers.ValidationError: 1 validation error for TestClass
#E   myfield
#E     ensure this value has at least 100 characters (type=value_error.any_str.min_length; #limit_value=100)

Steps to reproduce

Execute the example above (pydantic 1.10)

Screenshots

No response

Logs

E   pydantic.error_wrappers.ValidationError: 1 validation error for TestClass
E   myfield
E     ensure this value has at least 100 characters (type=value_error.any_str.min_length; limit_value=100)

Release Version

2.12.0

Platform

  • [X] Linux
  • [ ] Mac
  • [ ] Windows
  • [ ] Other (Please specify in the description above)

Leobouloc avatar Nov 22 '23 11:11 Leobouloc

@Leobouloc you're right. polyfactory does not currently parse the Config object for constraints and unfortunately, it seems pydantic doesn't inject any of the constraints into the model fields that we do parse :/

vkcku avatar Nov 22 '23 11:11 vkcku

Could this be solved by adding min_length and max_length parameters to from_model_field and from_field_info and passing cls.__model__.__config__.min_anystr_length on to the constraints ? (I see that allow_population_by_field_name is already being parsed from from the model Config) ?

Are there some other constraints I am missing ?

Leobouloc avatar Nov 22 '23 15:11 Leobouloc

I'm so sorry @Leobouloc, I had missed your question!

I think the right way to do this would be to for the from_model_field and from_field_info to consider the values in the config. I'm not sure about all the different constraints that can be set via the config, but all of them should be considered when creating the FieldMeta.

vkcku avatar Jan 21 '24 06:01 vkcku