Skip to content
Advertisement

Proper way to test Django signals

I’m trying to test sent signal and it’s providing_args. Signal triggered inside contact_question_create view just after form submission.

My TestCase is something like:

    def test_form_should_post_proper_data_via_signal(self):
        form_data = {'name': 'Jan Nowak'}
        signals.question_posted.send(sender='test', form_data=form_data)
        @receiver(signals.question_posted, sender='test')
        def question_posted_listener(sender, form_data):
            self.name = form_data['name']
        eq_(self.name, 'Jan Nowak')

Is this the proper way to test this signal? Any better ideas?

Advertisement

Answer

I’ve resolved the problem by myself. I think that the best solution is following:

    def test_form_should_post_proper_data_via_signal(self):
        # define the local listener
        def question_posted_listener(sender, form_data, **kwargs):
            self.name = form_data['name']

        # prepare fake data
        form_data = {'name': 'Jan Nowak'}

        # connect & send the signal
        signals.question_posted.connect(question_posted_listener, sender='test')
        signals.question_posted.send(sender='test', form_data=form_data)

        # check results
        eq_(self.name, 'Jan Nowak')
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement