我有一个通过装饰器连接的信号处理程序,就像这个非常简单的:
@receiver(post_save, sender=User,
dispatch_uid='myfile.signal_handler_post_save_user')
def signal_handler_post_save_user(sender, *args, **kwargs):
# do stuff
我想要做的是在测试中使用模拟库http://www.voidspace.org.uk/python/mock/模拟它,以检查 django 调用它的次数。我现在的代码是这样的:
def test_cache():
with mock.patch('myapp.myfile.signal_handler_post_save_user') as mocked_handler:
# do stuff that will call the post_save of User
self.assert_equal(mocked_handler.call_count, 1)
这里的问题是即使模拟了原始信号处理程序也会被调用,很可能是因为@receiver
装饰器在某处存储了信号处理程序的副本,所以我模拟了错误的代码。
所以问题是:我如何模拟我的信号处理程序以使我的测试工作?
请注意,如果我将信号处理程序更改为:
def _support_function(*args, **kwargs):
# do stuff
@receiver(post_save, sender=User,
dispatch_uid='myfile.signal_handler_post_save_user')
def signal_handler_post_save_user(sender, *args, **kwargs):
_support_function(*args, **kwargs)
而我嘲笑_support_function
,一切都按预期工作。