How do I mock a django signal handler?

后端 未结 7 1632
走了就别回头了
走了就别回头了 2020-12-14 00:22

I have a signal_handler connected through a decorator, something like this very simple one:

@receiver(post_save, sender=User, 
          dispatch_uid=\'myfil         


        
7条回答
  •  情书的邮戳
    2020-12-14 00:48

    So, I ended up with a kind-of solution: mocking a signal handler simply means to connect the mock itself to the signal, so this exactly is what I did:

    def test_cache():
        with mock.patch('myapp.myfile.signal_handler_post_save_user', autospec=True) as mocked_handler:
            post_save.connect(mocked_handler, sender=User, dispatch_uid='test_cache_mocked_handler')
            # do stuff that will call the post_save of User
        self.assertEquals(mocked_handler.call_count, 1)  # standard django
        # self.assert_equal(mocked_handler.call_count, 1)  # when using django-nose
    

    Notice that autospec=True in mock.patch is required in order to make post_save.connect to correctly work on a MagicMock, otherwise django will raise some exceptions and the connection will fail.

提交回复
热议问题