1

I'm new to testing in Django and I was wondering how to write tests for signals.
I went over the documentation but I couldn't find anything helpful.

Let's say a have a simple pre_save signal for Reservation model and I want to change some attribute before saving it to the database.

My code looks like this:

@receiver(pre_save, sender=Reservation)
def set_destination_type(sender, instance, *args, **kwargs):
    points = ['New York', 'Rome', 'Paris']
    if instance.destination in points:
        instance.international = True
    instance.international = False

How would I approach this? Do I just create a reservation and assert that correct value was set? Do I test this function in isolation? I really don't know how to start.

Thanks!

intelis
  • 7,829
  • 14
  • 58
  • 102

1 Answers1

2

The easiest is indeed to create some reservations (where some have destination in points, others not), setting destination to 'foo' (for instance) then save them.

international seems to be a boolean field, so using 'foo' (which is not a boolean) and saving will allows you to check both cases (and as far as instance is not validated/saved you can assign whatever value you want)

"Do I test this function in isolation" => I wouldn't do that, the signals framework is heavily coupled to Django models, to get isolation, you would have to mock a lot of libs making your test code far more difficult than the tested code itself

Raphaël Braud
  • 1,489
  • 10
  • 14
  • This really seems to be the best option.. Thanks – intelis Mar 25 '15 at 23:09
  • 2
    This is a very old question but currently this is not anymore the right answer, there are several way to prevent a unit test from becoming (silently) an integration test due to signals. Interested people can Have a look at [this](https://stackoverflow.com/questions/45320964/how-to-test-signals-when-using-factory-boy-with-muted-signals) and [this](https://stackoverflow.com/questions/18532539/want-to-disable-signals-in-django-testing). – Andrea Citrolo Dec 18 '20 at 14:57