Python 单元测试 task.apply_async()

标签 python celery python-unittest django-testing django-tests

使用覆盖率来查看必须测试的内容,并且覆盖率显示旁边必须要测试的内容: send_alert.apply_async()

我知道是celery任务,但是有什么办法可以测试这行代码吗?

理解测试逻辑的其余代码:

class SomeView(GenericAPIView)
    def post(self, request, *args, **kwargs):
        #some code
        if not value:
           send_alert.apply_async()
           # response
        # not if Response

根据第一个答案编写的测试

    @patch('event.views.send_alert')
    def test_send_alert(self, mock_send):
        data = {some data for post}
        response = self.client.post('/api/{0}/mettings/'.format(self.user), data)
        print(response.json())
        self.assertTrue(mock_send.called)

我还检查了在任务 print('Tasks Passed') 之后我看到任务通过的消息,但测试失败并出现错误 AssertionError: False is not true

最佳答案

我假设您正在使用 Django,因为它是这样标记的。

装饰你的测试:

@override_settings(CELERY_EAGER=True)
def test_foo(self):
    # Make your post

或者如果您只是想测试它是否被调用。

from mock import patch

@patch('your_module.your_file.send_alert.apply_async')
def test_foo(self, mock_send):
    # make your post with "value" set to True
    self.assertTrue(mock_send.called)

关于Python 单元测试 task.apply_async(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49982389/

相关文章:

python - 在两个不同的 pandas 数据帧之间搜索和替换值

django - 处理 celery 中的“post_save”信号

python - 我无法让 celery 正常工作(aws elasticbeanstalk)

python - celery Pyramid 周期性任务

python - 重用Mock创建属性模拟unittest.patch

python - 如何使用mockito模拟os.path.join

python - 递归单元测试发现

javascript - cherrypy/jquery CORS 问题

python - 为什么分配给与局部变量同名的类属性会引发 NameError?

python - 将不同类型的对象连接成一个字符串 (Python)