Search code examples
pythondjangotestingdjango-testing

Basics of testing signals in Django


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!


Solution

  • 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