litestar-org / polyfactory

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

Bug: ModelFactory can not generate list of classes with a Pydantic field alias #494

Closed keviloper closed 7 months ago

keviloper commented 7 months ago

Description

I am trying to generate a list of classes but an error is thrown:

pydantic_core._pydantic_core.ValidationError: 1 validation error for Status
cardstatus.0
  Input should be a valid dictionary or instance of CardStatus [type=model_type, input_value=[CardStatus(link_id=5265,...ture=-12651701372362.7)], input_type=list]
    For further information visit https://errors.pydantic.dev/2.5/v/model_type

This error only occurs when I define a field alias. Without a field alias it works.

URL to code causing the issue

No response

MCVE

from typing import Optional, Union
from polyfactory import Use
from polyfactory.factories.pydantic_factory import ModelFactory
from pydantic import BaseModel, Field, conlist, StrictInt, StrictFloat

class CardStatus(BaseModel):
    link_id: Optional[StrictInt] = Field(None, alias="linkId")
    temperature: Optional[Union[StrictFloat, StrictInt]] = None
    __properties = ["linkId", "temperature"]

class CardsFactory(ModelFactory):
    __model__ = CardStatus
    __allow_none_optionals__ = False

class Status(BaseModel):
    # cellular_cards: Optional[conlist(CardStatus)] = Field(None)  # working
    card_status: Optional[conlist(CardStatus)] = Field(None, alias="cardstatus")  # not working

class StatusFactory(ModelFactory):
    __model__ = Status
    __randomize_collection_length__ = True
    __min_collection_length__ = 2
    __max_collection_length__ = 5
    __allow_none_optionals__ = False
    cellular_cards = Use(CardsFactory.batch, size=3)

if __name__ == '__main__':
    gen = StatusFactory()
    e: Status = gen.build()
    print(e.model_dump())

Steps to reproduce

1. Run MCVE

Screenshots

No response

Logs

No response

Release Version

Python 3.11 pydantic==2.5.3 pydantic-settings==2.1.0 polyfactory==2.14.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

guacs commented 7 months ago

@kevininf this is a duplicate of #493. For the time being, you'll have to downgrade to 2.14.0.