polyfactory
polyfactory copied to clipboard
Enhance batch Method to Accept fields_list for Custom Field Values
Description:
I propose adding an additional argument, fields_list, of type list[dict[str, typing.Any]], to the batch method in the BaseFactory.
Here is the modified implementation I suggest:
@classmethod
def batch(
cls,
*_: Any,
fields_list: list[dict[str, Any]] | None = None,
size: int,
**kwargs: Any,
) -> list[T]:
if size <= 0:
return []
fields_list = fields_list or [{}] * size
if len(fields_list) != size:
raise InvalidSizeException()
fields = [kwargs | field for field in fields_list]
return [cls.build(**field) for field in fields]
# Example
class InnerExampleModel(pydantic.BaseModel):
example_field: str
class ExampleModel(pydantic.BaseModel):
example_field: str
inner_fields: list[InnerExampleModel]
@register_fixture(name="example_model_factory")
class ExampleModelFactory(ModelFactory[ExampleModel]): ...
@register_fixture(name="example_inner_model_factory")
class InnerExampleModelFactory(ModelFactory[InnerExampleModel]): ...
# The example may not be very good, but it just shows how it will look with the implemented functionality.
@pytest.mark.parametrize("example_field_value", [("test_value1", "test_value2"), ("test_value3", "test_value4")])
def test_example(
example_field_values: tuple[str],
example_model_factory: ExampleModelFactory,
example_inner_model_factory: InnerExampleModelFactory,
) -> None:
example_inner_models = example_inner_model_factory.batch(
size: len(example_field_values),
fields_list=[
{"example_field": example_field_values[0]},
{"example_field": example_field_values[1]},
]
)
example_model = example_model_factory.build(inner_fields=example_inner_models)
...
Motivation:
The proposed enhancement allows for the creation of a specific number of objects with varying field values during testing. While kwargs can set common fields, fields_list enables individual elements to have distinct values, which is particularly useful when values are derived from test parameterization in pytest. This implementation eliminates the need for workarounds or boilerplate code, streamlining the process of object creation and improving test management efficiency.