hendrikschneider
hendrikschneider

Reputation: 1846

Django factory boy mock model method in factory

My model's save method is calling an api after saving. To test my application I am using DjangoModelFactory to generate objects for testing. However, the api still being called.

class MyClass(models.Model):
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        self.call_api()

I have tried mocking the method but it is not working

#...
from .models import MyModel

@pytest.mark.django_db
@patch("MyModel.call_api")
class MyModelFactory(factory.django.DjangoModelFactory, factory.base.BaseFactory):
    class Meta:
        model = MyModel

My Question is, how can I use mock methods when I use it with factories?

Upvotes: 0

Views: 1861

Answers (1)

Xelnor
Xelnor

Reputation: 3589

The proper extension point is Factory._create:

class MyModelFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = MyModel

    @classmethod
    def _create(cls, model_class, *args, **kwargs):
        with patch("MyModel.call_api"):
            return super()._create(model_class, *args, **kwargs)

Just a quick note: you don't need to inherit from factory.base.Factory in addition to factory.django.DjangoModelFactory, the latter is already a subclass of the former.

Upvotes: 6

Related Questions