单元测试Flask视图模拟Celery任务

10

我有一个Flask视图,它将一个celery任务添加到队列中,并向用户返回200。

from flask.views import MethodView
from app.tasks import launch_task

class ExampleView(MethodView):
    def post(self):
        # Does some verification of the incoming request, if all good:
        launch_task(task, arguments)
        return 'Accepted', 200

问题在于测试以下内容,我不想必须拥有celery实例等等。我只想知道在所有验证都通过之后,它向用户返回200。 celery launch_task()将在其他地方进行测试。

因此,我很想模拟掉launch_task()调用,使其本质上什么也不做,使我的单元测试与celery实例无关。

我尝试过各种化身:

@mock.patch('app.views.launch_task.delay'):
def test_launch_view(self, mock_launch_task):
    mock_launch_task.return_value = None
    # post a correct dictionary to the view
    correct_data = {'correct': 'params'}
    rs.self.app.post('/launch/', data=correct_data)
    self.assertEqual(rs.status_code, 200)

@mock.patch('app.views.launch_task'):
def test_launch_view(self, mock_launch_task):
    mock_launch_task.return_value = None
    # post a correct dictionary to the view
    correct_data = {'correct': 'params'}
    rs.self.app.post('/launch/', data=correct_data)
    self.assertEqual(rs.status_code, 200)

但似乎无法使其工作,我的视图只是以500错误退出。如果有任何帮助将不胜感激!

2个回答

4

我尝试使用任何@patch装饰器,但它都没有起作用。后来我在setUp中找到了mock的用法:

import unittest
from mock import patch
from mock import MagicMock

class TestLaunchTask(unittest.TestCase):
    def setUp(self):
        self.patcher_1 = patch('app.views.launch_task')
        mock_1 = self.patcher_1.start()

        launch_task = MagicMock()
        launch_task.as_string = MagicMock(return_value = 'test')
        mock_1.return_value = launch_task

    def tearDown(self):
        self.patcher_1.stop()

1
< p > @task 装饰器将函数替换为 Task 对象(参见 documentation)。如果你模拟任务本身,你将使用 MagicMock 替换(有点神奇的)Task 对象,并且根本不会安排任务。相反,要模拟 Task 对象的 run() 方法,像这样:

# With CELERY_ALWAYS_EAGER=True
@patch('monitor.tasks.monitor_user.run')
def test_monitor_all(self, monitor_user):
    """
    Test monitor.all task
    """

    user = ApiUserFactory()
    tasks.monitor_all.delay()
    monitor_user.assert_called_once_with(user.key)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接