使用模拟在Django单元测试中修补芹菜任务 [英] Using mock to patch a celery task in Django unit tests

查看:75
本文介绍了使用模拟在Django单元测试中修补芹菜任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用python模拟库修补在将模型保存在我的Django应用中时运行的Celery任务,以查看其是否被正确调用.

I'm trying to use the python mock library to patch a Celery task that is run when a model is saved in my django app, to see that it's being called correctly.

基本上,任务是在myapp.tasks内部定义的,并像下面这样导入到我的models.py文件的顶部:

Basically, the task is defined inside myapp.tasks, and is imported at the top of my models.py-file like so:

from .tasks import mytask

...,然后使用mytask.delay(foo, bar)在模型内的save()上运行.到目前为止,一切都很好-当我实际运行Celeryd等时,效果很好.

...and then runs on save() inside the model using mytask.delay(foo, bar). So far so good - works out fine when I'm actually running Celeryd etc.

我想构建一个模拟任务的单元测试,只是为了检查是否使用正确的参数调用了它,并且实际上并没有尝试过运行Celery任务.

I want to construct a unit test that mocks the task, just to check that it gets called with the correct arguments, and doesn't actually try to run the Celery task ever.

因此,在测试文件中,我在标准TestCase中有类似的内容:

So in the test file, I've got something like this inside of a standard TestCase:

from mock import patch # at the top of the file

# ...then later
def test_celery_task(self):
    with patch('myapp.models.mytask.delay') as mock_task:
        # ...create an instance of the model and save it etc
        self.assertTrue(mock_task.called)

...但是它永远不会被调用/总是错误的.我已经尝试了各种化身(改为修补myapp.models.mytask,并检查是否改为调用mock_task.delay.我从模拟文档中收集到导入路径至关重要,并且谷歌搜索告诉我它应该是该路径)可以在被测模块内部看到(如果我正确理解的话,它应该是myapp.models.mytask.delay而不是myapp.tasks.mytask.delay).

...but it never gets called/is always false. I've tried various incarnations (patching myapp.models.mytask instead, and checking if mock_task.delay was called instead. I've gathered from the mock docs that the import path is crucial, and googling tells me that it should be the path as it is seen inside the module under tests (which would be myapp.models.mytask.delay rather than myapp.tasks.mytask.delay, if I understand it correctly).

我在哪里错了?在修补Celery任务方面有一些特定的困难吗?我可以打补丁celery.task(用作mytask的装饰器)吗?

Where am I going wrong here? Is there some specific difficulties in patching Celery tasks? Could I patch celery.task (which is used as a decorator to mytask) instead?

推荐答案

您遇到的问题与这是Celery任务无关.您恰好正在修补错误的东西. ;)

The issue that you are having is unrelated to the fact that this is a Celery task. You just happen to be patching the wrong thing. ;)

具体来说,您需要找出哪个视图或其他文件正在导入"mytask"并将其修补在那里,因此相关行应如下所示:

Specifically, you need to find out which view or other file is importing "mytask" and patch it over there, so the relevant line would look like this:

with patch('myapp.myview.mytask.delay') as mock_task:

这里还有一些其他风味:

There is some more flavor to this here:

http://www.voidspace.org. uk/python/mock/patch.html#where-to-patch

这篇关于使用模拟在Django单元测试中修补芹菜任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆