polyfactory
polyfactory copied to clipboard
Allow partial attributes factory for child factories (randomly generating only missing fields for child models)
Given the following Pydantic models and Factory:
from pydantic_factories import ModelFactory
from pydantic import BaseModel
class Pet(BaseModel):
name: str
age: int
class Person(BaseModel):
name: str
pets: list[Pet]
age: int
class PersonFactory(ModelFactory[Person]):
__model__ = Person
When trying to build:
data = {
'name': 'John',
'pets': [
{'name': 'dog'},
{'name': 'cat'},
],
}
PersonFactory.build(**data)
Then the following exception is raised:
ValidationError: 2 validation errors for Person
pets -> 0 -> age
field required (type=value_error.missing)
pets -> 1 -> age
field required (type=value_error.missing)
We see that the age is missing in the data, so the factory is not able to construct the model.
If we add the age to the data:
data = {
'name': 'John',
'pets': [
{'name': 'dog', 'age': 3},
{'name': 'cat', 'age': 4},
],
}
PersonFactory.build(**data)
The factory will construct the model instance:
Person(name='John', pets=[Pet(name='dog', age=3), Pet(name='cat', age=4)], age=5978)
Note: only the age of the Pets (child model) is necessary, ModelFactory handles to randomly fill the age of Person.
It would be great to have the same behaviour of Factory Boy. If we pass only part of the attributes of a child model, then the factory will generate the missing attributes for us.
Can we work on this feature?
Sure, go ahead
Great, I'll work on a PR.
any updates? @pedro-prose
Hi, I didn't had the time this last week. I'll work on it this week.
released
released
Thank you!