Unit test Flask view mocking out celery tasks Unit test Flask view mocking out celery tasks flask flask

Unit test Flask view mocking out celery tasks


I tried also any @patch decorator and it didn't workAnd I found mock in setUp like:

import unittestfrom mock import patchfrom mock import MagicMockclass 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()


The @task decorator replaces the function with a Task object (see documentation). If you mock the task itself you'll replace the (somewhat magic) Task object with a MagicMock and it won't schedule the task at all. Instead mock the Task object's run() method, like so:

# 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)