In FactoryBoy, how do I setup my factory with an empty many-to-many member field?

Viewed 1040

I'm using Django 3 with Python 3.8. I have the following model ...

class Coop(models.Model):
    objects = CoopManager()
    name = models.CharField(max_length=250, null=False)
    types = models.ManyToManyField(CoopType, blank=False)
    addresses = models.ManyToManyField(Address)
    enabled = models.BooleanField(default=True, null=False)
    phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone')
    email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email')
    web_site = models.TextField()

I have created the following factory (using Factory boy) to attempt create the model in a test ...

class CoopFactory(factory.DjangoModelFactory):
    """
        Define Coop Factory
    """
    class Meta:
        model = Coop

    name = "test model"
    enabled = True
    phone = factory.SubFactory(PhoneContactMethodFactory)
    email = factory.SubFactory(EmailContactMethodFactory)
    web_site = "http://www.hello.com"

    @factory.post_generation
    def addresses(self, create, extracted, **kwargs):
        if not create:
            # Simple build, do nothing.
            return

        if extracted:
            # A list of types were passed in, use them
            for address in extracted:
                self.addresses.add(address)
        else:
            address = AddressFactory()
            self.addresses.add( address )

    @factory.post_generation
    def types(self, create, extracted, **kwargs):
        if not create:
            # Simple build, do nothing.
            return

        if extracted:
            # A list of types were passed in, use them
            for type in extracted:
                self.types.add(type)
        else:
            print("Creating type ...\n")
            type = CoopTypeFactory()
            self.types.add( type )

but I'm having trouble creating a factory with a many-to-many field (types) that is empty. I tried the below

@pytest.mark.django_db
def test_coop_create_with_no_types(self):
    """ Test customer model """    # create customer model instance
    coop = CoopFactory.create(types=[])
    print("size: ", coop.types.all().count())
    self.assertIsNotNone(coop)
    self.assertIsNotNone( coop.id )

but the value of types.all().count() is always equal to 1. How do I properly setup a factory with an empty many-to-many field?

Edit: In response to the answer given, what's the right way to pass in the member field to be used by the factory? I tried

@pytest.mark.django_db
def test_coop_create_with_existing_type(self):
    """ Test customer model """    # create customer model instance
    coop_from_factory = CoopFactory()
    self.assertIsNotNone(coop_from_factory)

    coop_types = coop_from_factory.types
    coop = CoopFactory.create(types=[coop_types.all().first()], addresses=coop_from_factory.addresses.all())
    self.assertIsNotNone(coop)

but got this error, for the line "for _ in range(extracted):" line ...

Traceback (most recent call last):
  File "/Users/davea/Documents/workspace/chicommons/maps/web/tests/test_models.py", line 48, in test_coop_create_with_existing_type
    coop = CoopFactory.create(types=coop_types, addresses=coop_from_factory.addresses.all())
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/factory/base.py", line 564, in create
    return cls._generate(enums.CREATE_STRATEGY, kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/factory/django.py", line 141, in _generate
    return super(DjangoModelFactory, cls)._generate(strategy, params)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/factory/base.py", line 501, in _generate
    return step.build()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/factory/builder.py", line 296, in build
    postgen_results[declaration_name] = declaration.declaration.call(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/factory/declarations.py", line 622, in call
    return self.function(
  File "/Users/davea/Documents/workspace/chicommons/maps/web/tests/factories.py", line 128, in types
    for _ in range(extracted):
TypeError: 'ManyRelatedManager' object cannot be interpreted as an integer
2 Answers

The fix is to change if extracted to if extracted is not None.

Explanation

In Python, an empty list is falsey1 but is not None.

coop = CoopFactory.create(types=[])

The empty list [] is passed to the post-generation hook types, as the parameter extracted.

@factory.post_generation
def types(self, create, extracted, **kwargs):
    if not create:
        # Simple build, do nothing.
        return

    if extracted:
        # A list of types were passed in, use them
        for type in extracted:
            self.types.add(type)
    else:
        print("Creating type ...\n")
        type = CoopTypeFactory()
        self.types.add( type )

Since if extracted is a truth value test1, the falsey empty list falls to the else block where a type is created. So, the value of types.all().count() is equal to 1.

1 https://docs.python.org/3/library/stdtypes.html#truth-value-testing

Skip the

        else:
            print("Creating type ...\n")
            type = CoopTypeFactory()
            self.types.add( type )

Which always will create CoopType as default.

One thing that may not be clear from documentation is @factory.post_generation hooks are always called. That means that the else statements in all the post_generation hooks in the example code will always be called.

More info: Simple Many-to-many relationship

Pattern I use often if I want to create default values directly is adding a function to the factory, which in this example, would translate to:

@factory.post_generation
def create_types(self, create, extracted, **kwargs):
    if not create:
        # Simple build, do nothing.
        return

    if extracted:
        for _ in range(extracted):
            self.types.add(CoopTypeFactory())

Enables to use CoopFactory(create_types=3).

Here's my full example:

@factory.post_generation
def types(self, create, extracted, **kwargs):
    if not create:
        # Simple build, do nothing.
        return

    if extracted:
        # A list of types were passed in, use them
        for type in extracted:
            self.types.add(type)
    # Removed this because it always creates 1 CoopType as default and
    # it may not be the desired behaviour for all tests.
    # else:
    #     print("Creating type ...\n")
    #     type = CoopTypeFactory()
    #     self.types.add( type )

# Adding this function to have a simple way of just adding default CoopTypes
@factory.post_generation
def create_types(self, create, extracted, **kwargs):
    if not create:
        # Simple build, do nothing.
        return

    if extracted: # This must be an integer
        for _ in range(extracted):
            self.types.add(CoopTypeFactory())

This gives the optional usages:

CoopFactory(create_types=3) will call the create_types and put int 3 in param extracted and create 3 default CoopTypes. (This enables simple use)

CoopFactory(types=[CoopTypeFactory()]) will call the types and put a list of 1 CoopType in param extracted. (This enables more control over how CoopTypes are created if those objects needs some specific values)

Related