python - 如何模拟 django 信号处理程序?

标签 python django mocking signals django-signals

我有一个通过装饰器连接的 signal_handler,就像这个非常简单的:

@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,一切都按预期工作。

最佳答案

可能更好的主意是模拟信号处理程序内部的功能,而不是处理程序本身。使用 OP 的代码:

@receiver(post_save, sender=User, dispatch_uid='myfile.signal_handler_post_save_user')
def signal_handler_post_save_user(sender, *args, **kwargs):
  do_stuff()  # <-- mock this

def do_stuff():
   ... do stuff in here

然后模拟do_stuff:

with mock.patch('myapp.myfile.do_stuff') as mocked_handler:
    self.assert_equal(mocked_handler.call_count, 1)

关于python - 如何模拟 django 信号处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13112302/

相关文章:

python - Scrapy:在 __init__ 中设置的规则被 CrawlSpider 忽略

python - <back space> 在 shell 中的 python 和 ipython 中不起作用

c# - 我将如何进行单元测试?

python - pyodbc连接字符串sql server身份验证

python - 在 Python 2.6 中使用 JSON?

python - Django ORM 不同查询,其中顺序由带注释的字段完成,您需要不同的 ('id' )

php - 将遗留 mySQL 数据库集成到新的 Django ORM 支持的数据结构中

python - Django 按多个字段分组

Python 修补现有类

Python模拟postgres数据库