【问题标题】:Python unittest task.apply_async()Python unittest task.apply_async()
【发布时间】:2018-10-03 13:49:52
【问题描述】:

使用覆盖率来查看必须测试的内容,覆盖率表明接下来必须测试: 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

【问题讨论】:

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


    【解决方案1】:

    我假设您使用的是 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)
    

    【讨论】:

    • 它可以工作,但是如何在测试后视图中集成它,例如如果值不是True,则调用此任务。并测试它是否被调用
    • 因为当某些值(收到的内容)不正确时,此任务在 post 方法中的视图中应用。
    • 更新了答案。带有模拟的第二个版本应该适用于您的用例。
    • Edit question with test code and error that task is not called, but to be called because after task I see print.
    • 你在正确的地方打补丁吗? send_alertcomponent.message.tasks.send_alert 中。但是你的补丁应该指向<view module>.<view file>.send_alert。您需要修补它导入的名称空间。
    猜你喜欢
    • 2013-07-09
    • 2022-08-22
    • 2013-12-14
    • 1970-01-01
    • 2017-05-04
    • 2023-03-05
    • 2021-04-12
    • 2011-05-18
    • 2015-02-02
    相关资源
    最近更新 更多