FactoryBoy / factory_boy

A test fixtures replacement for Python
https://factoryboy.readthedocs.io/
MIT License
3.48k stars 392 forks source link

*_batch() methods raise TypeError for models with a 'size' attribute #901

Open adamchainz opened 2 years ago

adamchainz commented 2 years ago

The problem

Take a model with a size attr:

from dataclasses import dataclass

@dataclass
class Container:
    name: str
    size: int

This is a somewhat reasonable/common name.

Unfortunately such a name precludes a factory for making such models in batch, with create_batch() / build_batch() / generate_batch().

With this factory:

import factory

class ContainerFactory(factory.Factory):
    class Meta:
        model = Container

    name = factory.Faker("name")

One gets:

>>> ContainerFactory.create_batch(3, size=10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: BaseFactory.create_batch() got multiple values for argument 'size'

Proposed solution

Change the argument name to something obscure like BATCH_SIZE (mirroring FACTORY_CLASS) or __factory_boy_size.

Extra notes

I think a workaround is possible with other hooks in factory boy?

rbarrois commented 2 years ago

Indeed, a workaround would be possible, the simplest one would be Meta.rename:

class ContainerFactory:
  class Meta:
    model = Container
    rename = {
      "size_": "size"
    }

And then calling ContainerFactory.create_batch(3, size_=5)

Nevertheless, I agree with the initial issue; it would however be somewhat complicated to change, as that pattern (create_batch(size=...) is already used by lots of user code.