Python unittest task.apply_async()

时间:2018-04-23 13:27:58

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

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

我知道这是芹菜任务,但有没有办法测试代码行?

其余代码用于理解测试逻辑:

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

1 个答案:

答案 0 :(得分:3)

我假设您正在使用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)