Python 单元测试烧瓶视图模拟芹菜任务
因此,我有一个flask视图,它将芹菜任务添加到队列中,并向用户返回一个200Python 单元测试烧瓶视图模拟芹菜任务,python,unit-testing,mocking,flask,celery,Python,Unit Testing,Mocking,Flask,Celery,因此,我有一个flask视图,它将芹菜任务添加到队列中,并向用户返回一个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_tas
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
问题在于测试以下内容,我不想有芹菜实例等等。我只想知道,在所有验证都正常后,它会将200返回给用户。芹菜launch_task()
将在其他地方测试
因此,我热衷于模拟launch\u task()
调用,这样它基本上什么也不做,使我的unittest独立于芹菜实例
我尝试过以下各种化身:
@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个错误。任何帮助都将不胜感激 我也尝试了任何
@补丁
装饰程序,但都没用
我在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()
@task
装饰器将函数替换为task
对象(请参阅)。如果您模拟任务本身,您将使用MagicMock
替换(有点神奇的)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)