[英]Unit test Flask view mocking out celery tasks
因此,我有一個燒瓶視圖,該視圖將芹菜任務添加到隊列中,並向用戶返回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實例等。我只想知道在所有驗證都OK之后,它會向用戶返回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錯誤退出。 任何援助將不勝感激!
我也嘗試了任何@patch
裝飾器,但它不起作用,我在setUp
發現了模擬:
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
對象,並且它根本不會安排任務。 而是模擬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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.