Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: pydanticfactory_use_construct is not propagated to the nested model. #548

Open
Reskov opened this issue May 13, 2024 · 1 comment · May be fixed by #549
Open

Bug: pydanticfactory_use_construct is not propagated to the nested model. #548

Reskov opened this issue May 13, 2024 · 1 comment · May be fixed by #549
Labels
bug Something isn't working

Comments

@Reskov
Copy link

Reskov commented May 13, 2024

Description

polyfactory always do validation of the nested models, even if factory_use_construct are passed as a build argument.

Possible workaround, but doesn't work well for multiple depth fields
model = NestedFactory.build(factory_use_construct=True, nested={"factory_use_construct": True} )

Is it possible to propagate factory_use_construct to the pydantic model fields by default?

URL to code causing the issue

No response

MCVE

from polyfactory.factories.pydantic_factory import ModelFactory
from pydantic import BaseModel, EmailStr, field_validator


class Person(BaseModel):
    email: EmailStr

    @field_validator('email')
    def validate_email(cls, v):
        if len(v) > 5:
            raise ValueError('email too long')


class PersonFactory(ModelFactory[Person]):
    pass


# # failed email to long, correct
# person = PersonFactory.build()

# works fine
person = PersonFactory.build(factory_use_construct=True)
print(person)

class Nested(BaseModel):
    nested: Person


class NestedFactory(ModelFactory[Nested]):
    pass

# failed email to long, incorrect
nested = NestedFactory.build(factory_use_construct=True)

Steps to reproduce

1. Create a nested model with a `field_validator` or `model_validator`. 
2. Use build(factory_use_construct=True)

Screenshots

No response

Logs

Traceback (most recent call last):
  File "scratch_1.py", line 33, in <module>
    nested = NestedFactory.build(factory_use_construct=True)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/.venv/lib/python3.12/site-packages/polyfactory/factories/pydantic_factory.py", line 392, in build
    processed_kwargs = cls.process_kwargs(**kwargs)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/.venv/lib/python3.12/site-packages/polyfactory/factories/base.py", line 954, in process_kwargs
    field_result = cls.get_field_value(
                   ^^^^^^^^^^^^^^^^^^^^
  File "/.venv/lib/python3.12/site-packages/polyfactory/factories/base.py", line 703, in get_field_value
    return cls._get_or_create_factory(model=unwrapped_annotation).build(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/.venv/lib/python3.12/site-packages/polyfactory/factories/pydantic_factory.py", line 401, in build
    return cls.__model__(**processed_kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/.venv/lib/python3.12/site-packages/pydantic/main.py", line 176, in __init__
    self.__pydantic_validator__.validate_python(data, self_instance=self)
pydantic_core._pydantic_core.ValidationError: 1 validation error for Person
email
  Value error, email too long [type=value_error, input_value='kbutler@hotmail.com', input_type=str]
    For further information visit https://errors.pydantic.dev/2.7/v/value_error


### Release Version

2.15.0

### Platform

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

<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]  
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and 
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.

<a href="https://polar.sh/litestar-org/polyfactory/issues/548">
<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/polyfactory/issues/548/pledge.svg?darkmode=1">
  <img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/polyfactory/issues/548/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
@Reskov Reskov added the bug Something isn't working label May 13, 2024
@guacs
Copy link
Member

guacs commented May 13, 2024

Hey @Reskov thanks for raising the issue! Yeah, this looks like a bug. We should be passing the configured value of factory_use_construct to all the child models as well.

Reskov pushed a commit to Reskov/polyfactory that referenced this issue May 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants