factory_boy icon indicating copy to clipboard operation
factory_boy copied to clipboard

SubFactory should preserve signal muting behaviour of the factory used

Open kristaps opened this issue 7 years ago • 5 comments

It appears that using SubFactory bypasses any signal muting attached to the factory used, which seems counter-intuitive.

Is it possible to keep the muting defined on the factory, or to allow controlling the signal muting when invoking SubFactory?

An example to demonstrate the problem:

import factory
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver


class SomeModel(models.Model):
    pass

class OtherModel(models.Model):
    some = models.ForeignKey(SomeModel)

@receiver(post_save, sender=SomeModel)
def mess_stuff_up(instance, created, raw, **kwargs):
    raise Exception("BOOM!")


@factory.django.mute_signals(post_save)
class SomeModelFactory(factory.DjangoModelFactory):
    class Meta:
        model = SomeModel

class OtherModelFactory(factory.DjangoModelFactory):
    class Meta:
        model = OtherModel

    some = factory.SubFactory(SomeModelFactory)


# Signal handler not triggered, as expected from the mute_signals use
SomeModelFactory()

# SubFactory(SomeModelFactory) triggers the post_save receiver, despite
# the post_save signal being muted on SomeModelFactory
OtherModelFactory()

kristaps avatar Oct 09 '17 10:10 kristaps

This actually works in versions <2.9. I found this issue when I upgraded my packages and a bunch of tests started failing with IntegrityErrors.

ErwinJunge avatar Oct 19 '17 14:10 ErwinJunge

Would be nice to get some clarity on this. There's a point to be made about muting signals in the first place, but having the functionality there and not having it muted in SubFactories does seem counter-intuitive.

If someone could point me in the right direction to restore this behaviour (if desired) I would be happy to make a PR for this.

chuckoy avatar Jul 19 '18 06:07 chuckoy

It would be nice to have this behavior back indeed! In the mean time, the workaround proposed for muting specific receivers can be used here as well (muting the signal altogether): https://github.com/FactoryBoy/factory_boy/issues/505#issuecomment-436316484

arthurio avatar Feb 08 '19 23:02 arthurio

Any updates on a fix to this?

pfcodes avatar Jul 07 '23 12:07 pfcodes

The fix is merged, will be available in the next release. (You can try using git version)

last-partizan avatar Jul 10 '23 05:07 last-partizan