How do I mock a django signal handler?

后端 未结 7 1628
走了就别回头了
走了就别回头了 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:34

    As you mentioned, mock.patch('myapp.myfile._support_function') is correct but mock.patch('myapp.myfile.signal_handler_post_save_user') is wrong.

    I think the reason is:

    When init you test, some file import the signal's realization python file, then @receive decorator create a new signal connection.

    In the test, mock.patch('myapp.myfile._support_function') will create another signal connection, so the original signal handler is called even if mocked.

    Try to disconnect the signal connection before mock.patch('myapp.myfile._support_function'), like

    post_save.disconnect(signal_handler_post_save_user)
    with mock.patch("review.signals. signal_handler_post_save_user", autospec=True) as handler:
        #do stuff
    

提交回复
热议问题