litestar-org / polyfactory

Simple and powerful factories for mock data generation
https://polyfactory.litestar.dev/
MIT License
988 stars 78 forks source link

Bug: `ModelFactory._create_model` not handling `_build_context = None` #563

Closed sam-or closed 3 weeks ago

sam-or commented 1 month ago

Description

I'm getting errors from the ModelFactory._create_model function which is not handling when the passed in build context is None: https://github.com/litestar-org/polyfactory/pull/549/files#diff-58f44001d9e3d42e5c8fc55d621181dc66f78b37b46a414bb1bf6b6dd1d2bcbbR504

Should that line be:

if cls._get_build_context(_build_context).get("factory_use_construct"):

On another note, it seems this issue has highlighted the fact that the build context isn't being passed down to factories for models in collection fields when using .coverage() (see traceback for the snippet in the mcve)

EDIT: Reading the PR that introduced this... Seems like this has already been raised.

@guacs @Reskov

MCVE

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

class T(BaseModel):
    i: int

class L(BaseModel):
    l: list[T]

list(ModelFactory.create_factory(L).coverage())

Logs

@classmethod
    def _create_model(cls, _build_context: PydanticBuildContext, **kwargs: Any) -> T:
        """Create an instance of the factory's __model__

        :param _build_context: BuildContext instance.
        :param kwargs: Model kwargs.

        :returns: An instance of type T.

        """
>       if _build_context.get("factory_use_construct"):
E       AttributeError: 'NoneType' object has no attribute 'get'

.venv/lib/python3.10/site-packages/polyfactory/factories/pydantic_factory.py:504: AttributeError

Release Version

2.16.1

Platform


[!NOTE]
While we are open for sponsoring on GitHub Sponsors and OpenCollective, we also utilize Polar.sh to engage in pledge-based sponsorship.

Check out all issues funded or available for funding on our Polar.sh dashboard

  • 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.

Fund with Polar

adhtruong commented 3 weeks ago

Fixed in https://github.com/litestar-org/polyfactory/pull/564